body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<h1>Enter risk!</h1> <p>This program will roll dice for the game of Risk. The initial input is two numbers separated by a space and if the attackers wish to do a blitz they can add one more space and an &quot;!&quot; to get a positive attack modifier but are committed for an all or nothing fight.</p> <pre><code>package riskdieroll; import java.awt.Component; import java.util.Arrays; import java.util.Collections; import javax.swing.JOptionPane; public class RiskDieRoll { private static Component frame; public static void main(String[] args) { int spcCnt, atck1, dfnc1, rollCnt, atck2 = 0, dfnc2 = 0, valHold, atckMod; String intInpt, Lsr; while(true) { boolean k = false; Lsr = &quot;&quot;; intInpt = JOptionPane.showInputDialog(&quot;Please enter the a&quot; + &quot;mount of attackers then the number of\ndefenders separa&quot; + &quot;ted by a space.&quot;, atck2 + &quot; &quot; + dfnc2); spcCnt = rollCnt = 0; valHold = intInpt.length(); atckMod = 6; if(&quot;0 0&quot;.equals(intInpt)) { break; } for(int i = 0; intInpt.charAt(i) != ' '; i++) { spcCnt++; } atck2 = atck1 = (int)Double.parseDouble(intInpt.substring(0 , spcCnt)); if(intInpt.charAt(valHold - 1) == '!') { k = true; atckMod = 7; valHold -= 2; } dfnc2 = dfnc1 = (int)Double.parseDouble(intInpt.substring(spcCnt + 1 , valHold)); Integer[] z = new Integer[3], y = new Integer[2]; if(atck1 &lt; 2) { JOptionPane.showMessageDialog(frame, &quot;INVALID ATTACK! You need&quot; + &quot; at least two armys to make an attack!&quot;); atck2 = dfnc2 = 0; } else if(dfnc1 &lt; 1) { JOptionPane.showMessageDialog(frame, &quot;INVALID INPUT! There must&quot; + &quot; be at least one defending army!&quot;); atck2 = dfnc2 = 0; } else { do { rollCnt = 0; for(int i = 0; i &lt; 3; i++) { z[i] = (int)Math.ceil(Math.random() * atckMod); } for(int i = 0; i &lt; 2; i++) { y[i] = (int)Math.ceil(Math.random() * 6); } Arrays.sort(z, Collections.reverseOrder()); Arrays.sort(y, Collections.reverseOrder()); while(dfnc2 &gt; 0 &amp;&amp; rollCnt &lt; 2 &amp;&amp; atck2 &gt; 1) { if(y[rollCnt] &gt;= z[rollCnt]) { atck2--; } else { dfnc2--; } rollCnt++; } }while(k &amp;&amp; (dfnc2 &gt; 0 &amp;&amp; atck2 &gt; 1)); if(dfnc2 &lt; 1) { Lsr = &quot;\n\nDefenders have lost!!&quot;; } else if(atck2 &lt; 2) { Lsr = &quot;\n\nAttackers have been repelled!!!&quot;; } JOptionPane.showMessageDialog(frame, &quot;Attacking force now at &quot; + atck2 + &quot; (Lost &quot; + (atck1 - atck2) + &quot;)&quot; + &quot;\nDefence force now &quot; + &quot;at &quot; + dfnc2 + &quot; (Lost &quot; + (dfnc1 - dfnc2) + &quot;)&quot; + Lsr); if(!&quot;&quot;.equals(Lsr)) { atck2 = dfnc2 = 0; } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:29:00.320", "Id": "60170", "Score": "4", "body": "`\"Please enter the a\" + \"mount [...] separa\" + \"ted by a space.\"`?! I thought splitting the string on multiple lines was supposed to **improve** readability!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:30:18.953", "Id": "60172", "Score": "0", "body": "@retailcoder - while funny, not constructive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:34:38.053", "Id": "60174", "Score": "0", "body": "@Max sorry I didn't mean to offend anyone - it's just one of the point's I'd raise if I were to review this code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:34:53.757", "Id": "60175", "Score": "0", "body": "@retailcoder Didn't think of that when I did that, ah well. I'll fix it. No harm done. Edit: There we go! All for your reading pleasure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:37:20.310", "Id": "60176", "Score": "0", "body": "@retailcoder - oh, I wasn't offended. Yes, it's one of the *many* points I'd raise, too, but OP might appreciate a constructive response over a funny one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:37:56.350", "Id": "60177", "Score": "2", "body": "I'd upvote, but [I'm out of ammo](http://meta.codereview.stackexchange.com/questions/999/call-of-duty-were-on-a-mission)... will come back at 12AM UTC for sure :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:32:22.957", "Id": "60193", "Score": "4", "body": "I took the liberty to roll the edit back, please do not change the code after posting it. This would invalidate existing answers and is unnecessary. If it was a hiccup while posting, you can alwazs comment and tell people that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:44:10.813", "Id": "60250", "Score": "0", "body": "@200_success If you look closely you can see that my program does vary the number of dice it rolls based on the number of army on each side." } ]
[ { "body": "<pre><code>package riskdieroll;\n</code></pre>\n\n<p>Package names are used to associate developers/companies with the code. They normally look like this:</p>\n\n<pre><code>package com.company.yourpackage;\npackage com.gmail.username.yourpackage;\n</code></pre>\n\n<p>This is not a problem if this is only a test of some sorts, the moment you release code into the wild you should assign a correct package to it.</p>\n\n<hr>\n\n<pre><code>public static void main(String[] args) \n {\n</code></pre>\n\n<p>Java uses a modified <a href=\"http://en.wikipedia.org/wiki/Indent_style#Variant%3a_1TBS\" rel=\"nofollow\">K&amp;R style</a> for braces, keeping opening braces on the same line:</p>\n\n<pre><code>function name() {\n if (variable) {\n // Code\n } else {\n // No Code\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>int spcCnt, atck1, dfnc1, rollCnt, atck2 = 0, dfnc2 = 0, valHold, atckMod;\n</code></pre>\n\n<p>Avoid initializing multiple variables in the same line, it just gets messy and unreadable. If you initialize many variables in the same line, it can be that someone who quickly reads your code misses these variables, which leads to confusion. If you have so many variables that even initializing them line by line seems messy, there's something wrong with your code and it should most likely be restructured.</p>\n\n<hr>\n\n<pre><code>boolean k = false;\n</code></pre>\n\n<p>Here is one of the ultimate rules for programming:</p>\n\n<blockquote>\n <p>Use correct, accurate and easy to remember names for all your stuff.</p>\n</blockquote>\n\n<p><code>k</code> is not a good name, the name should tell me what the variable is supposed to do or what it is used for. Quick, can you tell me what these variables are used for?</p>\n\n<ul>\n<li>k</li>\n<li>u</li>\n<li>isRunning</li>\n<li>nothingFound</li>\n<li>counter</li>\n<li>mmmmm</li>\n<li>__mmmmm</li>\n</ul>\n\n<hr>\n\n<pre><code>Lsr = \"\";\n</code></pre>\n\n<p>This variable is declared outside of the loop, yet it is cleared each iteration, therefor it's scope is limited to the loop, therefor it should be declared inside the loop to make it obvious that this variable is not persistent over iterations.</p>\n\n<hr>\n\n<pre><code>intInpt = JOptionPane.showInputDialog(\"Please enter the a\"\n + \"mount of attackers then the number of\\ndefenders separa\"\n + \"ted by a space.\", atck2 + \" \" + dfnc2);\n</code></pre>\n\n<p>Even if violating the 80/120 column rule, format your strings in a way that keeps them readable.</p>\n\n<pre><code>intInpt = JOptionPane.showInputDialog(\"Please enter the amount of attackers then the number of\\n\"\n + \"defenders separated by a space.\", atck2 + \" \" + dfnc2);\n</code></pre>\n\n<hr>\n\n<pre><code>spcCnt = rollCnt = 0;\n</code></pre>\n\n<p>Try to avoid multiple assignments on one line unless it is kinda necessary, for the same reasons as above. Also, names.</p>\n\n<hr>\n\n<pre><code>atck2 = atck1 = (int)Double.parseDouble(intInpt.substring(0 , spcCnt));\n</code></pre>\n\n<p>Why are you parsing a <code>Double</code> if you want an <code>int</code>?</p>\n\n<hr>\n\n<pre><code>if(atck1 &lt; 2)\n</code></pre>\n\n<p>Try to avoid <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\" rel=\"nofollow\">magic numbers and strings</a> at all costs! Use constants and enums to give them names. Compare these two snippets:</p>\n\n<pre><code>if (e &lt; 5) {\n\n// Somewhere in the class\nprivate static final int MIN_VALUE = 5;\n\n// Down in the function\nif (value &lt; MIN_VALUE) {\n</code></pre>\n\n<hr>\n\n<pre><code>JOptionPane.showMessageDialog(frame, \"Attacking force now at \" \n + atck2 + \" (Lost \" + (atck1 - atck2) + \")\" + \"\\nDefence force now \"\n + \"at \" + dfnc2 + \" (Lost \" + (dfnc1 - dfnc2) + \")\" + Lsr);\n</code></pre>\n\n<p>Consider if <code>String.format()</code> might be a better options for formatting strings with many variables.</p>\n\n<hr>\n\n<pre><code>if(!\"\".equals(Lsr))\n</code></pre>\n\n<p>It's called \"<a href=\"https://en.wikipedia.org/wiki/Yoda_conditions\" rel=\"nofollow\">Yoda conditions</a>\". It comes up from the dark days of C/C++ when you could accidentally do this:</p>\n\n<pre><code>if (x = 5) {\n</code></pre>\n\n<p>Today, all compilers warn you about such things and in statically typed languages (like Java) it even does not compile at all. The difference between these two</p>\n\n<ul>\n<li><code>if(!\"\".equals(Lsr))</code></li>\n<li><code>if(!lsr.equals(\"\"))</code></li>\n</ul>\n\n<p>is a mere aesthetic one, but it's the difference between reading these two</p>\n\n<ul>\n<li>If an empty string is not equal to lsr</li>\n<li>If lsr is not equal to an empty string</li>\n</ul>\n\n<p>Not to mention that you should test strings for emptiness by testing their length, it's faster and easier to read:</p>\n\n<pre><code>if (Lsr.length() &gt;= 0) {\n</code></pre>\n\n<p>Or even better:</p>\n\n<pre><code>if (!Lsr.isEmpty()) {\n</code></pre>\n\n<p>This does not cover the possibility that the string is <code>null</code>, which will yield a <code>NullPointerException</code> when trying to invoke instance methods. If it is possible that the string is <code>null</code>, an additional check would be required with this method:</p>\n\n<pre><code>if (Lsr != null &amp;&amp; !Lsr.isEmpty()) {\n</code></pre>\n\n<p>If that is acceptable depends on many things.</p>\n\n<hr>\n\n<p>When it comes to Object Orientation, your program is not at all Object Oriented. It would benefit greatly from abstracting the logic for calculating the dice rolls into a separate class. Same goes for input and output. Consider the following</p>\n\n<blockquote>\n <p>Your main loop should not contain how your program works, it should tell you what it does.</p>\n</blockquote>\n\n<p>Start by separating this main-loop into separate functions. See what can stand on it's own and what you need to do to make it stand on it's own. Hint: The moment you want to use <code>public static</code>/<a href=\"https://en.wikipedia.org/wiki/Global_variables\" rel=\"nofollow\">global variables</a> variables to connect these functions, you're doing something wrong.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:29:49.407", "Id": "60183", "Score": "0", "body": "@ variable name \"k\" I forgot to rename that to something better didn't I? I'll get that sorted! bltz should be a better name. 1/?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:29:55.460", "Id": "60184", "Score": "6", "body": "Great review... one (really) small nitpick ... `if(!\"\".equals(Lsr)) ...` is not the same as `!Lsr.equals(\"\")`... Sometimes people (including me) use `\"constant\".equals(val)` to avoid possible NullPointerExceptions with the alternative. Otherwise, great!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:32:05.683", "Id": "60185", "Score": "0", "body": "@ Lsr, sounds good. I'll fix that.\n@ bad strings, I did fix that, you must have started that answer before I did. \n2/?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:34:44.163", "Id": "60186", "Score": "0", "body": "@ Multiple assignments, I thought that it was a nice time saver and would be acceptable. What is wrong with doing it this way? \n@ Double instead of int, I am still a newbie and did not know how to do this until a recent google\n3/?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:36:39.893", "Id": "60187", "Score": "0", "body": "@ Magic numbers/strings, What do you mean by this? I have never heard of what your saying.\n@ String.format(), Don't know what that is, I'll look into it.\n4/?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:39:46.657", "Id": "60188", "Score": "0", "body": "@ Yoda conditions, same thing as Magic numbers/strings\n@ Testing string emptiness, alright, I'll try that out.\n@ Object Orientation, Not too sure what you mean by this. Could you elaborate?\n5/6" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:40:53.023", "Id": "60189", "Score": "0", "body": "@public static, Again, not sure what you mean by that.\nI am very sorry for my ignorance. I'm still learning\n6/6" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:41:30.100", "Id": "60194", "Score": "2", "body": "@lukeb28: I'll not go into details about Object Oriented programming and abstraction, that's what good books are for and it it's out of scope for Code Review. It's basically about how your program has no real structure compared to what Java allows you to do. I've also extended my answer with some links which should answer most of your questions. Otherwise no need to apologize, as along as you're willing to learn it's okay to make mistakes and ask questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:45:08.690", "Id": "60197", "Score": "1", "body": "@lukeb28: Also good names are not shortened. It's okay if your variables are named `counterForAllFailedAttempts` if it describes what the variable is for. Don't be afraid of long variable names. Always ask yourself \"would somebody else understand what I mean with this?\", good code is readable and clearly structured, it eases working with it and allows for easier changing it later on. Always go for readability first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:46:01.807", "Id": "60251", "Score": "0", "body": "@Bobby Thanks for the help! I'll use those links!" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:57:25.527", "Id": "36646", "ParentId": "36643", "Score": "13" } }, { "body": "<p>To reiterate Bobby's point about using <em>meaningful</em> names, please consider spelling words with all their vowels in tact. This has several benefits:</p>\n\n<ul>\n<li>The code is <em>much</em> easier to read.</li>\n<li>You improve your prose typing skills.</li>\n<li>You avoid building muscle memory of misspelled words.</li>\n</ul>\n\n<p>And seriously, you're not saving yourself any time by omitting vowels at random. In fact, it probably takes longer as you have to keep correcting yourself when you type <code>iAttack</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:49:51.643", "Id": "60199", "Score": "0", "body": "Minor nitpick: Please spell all words with vowels, there's no point in shortening variable names at all (the compiler does not care, the JVM does not care, your harddisk most likely also not...who *will* care is the next coder who needs to change something in that code)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T18:19:03.020", "Id": "60203", "Score": "0", "body": "@Bobby - I removed \"short\" and \"variable\" so it applies to all words. Is this what you meant?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T19:10:12.797", "Id": "60214", "Score": "0", "body": "Kinda, I meant that you should never omit vowels from variable names, no matter if short or long." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:47:39.893", "Id": "60252", "Score": "0", "body": "@Bobby \"no point in shortening variable names at all (the compiler does not care\" Didn't know that. I thought it did help. I will keep this in mind for future projects" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:49:47.777", "Id": "60434", "Score": "0", "body": "@lukeb28 With high CPU speeds and massive amounts of memory, you don't have to worry about optimizing for the compiler on today's PCs--most especially while learning to program. Developer time is far more valuable than hardware." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:13:12.347", "Id": "60817", "Score": "0", "body": "@lukeb28: Always go for readability first, and for speed *after* you've run a profiler." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:45:10.793", "Id": "36651", "ParentId": "36643", "Score": "4" } }, { "body": "<p>This code turned out to be a great exercise in <a href=\"http://refactoring.com/\">refactoring</a>, primarily using</p>\n\n<ul>\n<li><a href=\"http://refactoring.com/catalog/extractMethod.html\">Extract Method</a></li>\n<li><a href=\"http://refactoring.com/catalog/reduceScopeOfVariable.html\">Reduce Scope of Variable</a></li>\n<li><a href=\"http://refactoring.com/catalog/extractClass.html\">Extract Class</a></li>\n<li><a href=\"http://refactoring.com/catalog/introduceExplainingVariable.html\">Introduce Explaining Variable</a></li>\n<li><a href=\"http://refactoring.com/catalog/selfEncapsulateField.html\">Self Encapsulate Field</a></li>\n</ul>\n\n<p>Here's my goal:</p>\n\n<pre><code>public class RiskDieRoller\n{\n //////////////////////////////////////////////////////////////////////\n\n private static class Strength\n {\n public int attack;\n public int defence;\n public int attackMod = 6;\n\n public Strength() {}\n\n public Strength(Strength other)\n {\n this.attack = other.attack;\n this.defence = other.defence;\n this.attackMod = other.attackMod;\n }\n\n public void blitz()\n {\n this.attackMod = 7;\n }\n\n public boolean isBlitz()\n {\n return this.attackMod == 7;\n }\n\n public String toString()\n {\n return \"Attack \" + this.attack +\n \" Defence \" + this.defence +\n \" AttackMod \" + this.attackMod;\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n // …\n\n public static void main(String[] args) \n {\n RiskDieRoller roller = new RiskDieRoller();\n\n Strength before = new Strength();\n while (null != (before = roller.prompt(before)))\n {\n Strength after = roller.play(before);\n boolean isDecisive = roller.report(before, after);\n before = isDecisive ? new Strength() : after;\n }\n }\n}\n</code></pre>\n\n<p>I've renamed the class to <code>RiskDieRoller</code> and introduced a <code>Strength</code> class to help tame the proliferation of variables. The <code>main()</code> function just outlines how the program flows.</p>\n\n<p>It's now just a simple matter of filling in the blanks. ☺︎</p>\n\n<hr>\n\n<h3>Prompt</h3>\n\n<p>You failed to handle the \"Cancel\" button — a <code>NullPointerException</code> occurs. You handle <code>\"0 0\"</code> as a special case, but what if there is gratuitous extra whitespace? Also, if the exclamation mark is not preceded by a space, then <code>Double.parseDouble()</code> barfs. Anyway, you should be calling <code>Integer.parseInt()</code> instead.</p>\n\n<p>In any case, analyzing the string character by character is tedious, error prone, and unforgiving of variations in the user-provided input. Just use a regular expression.</p>\n\n<pre><code>private static final Pattern INPUT_RE =\n Pattern.compile(\"^\\\\s*(\\\\d+)\\\\s+(\\\\d+)\\\\s*(!)?\\\\s*$\");\n\npublic Strength prompt(Strength before)\n{\n do\n {\n String input = JOptionPane.showInputDialog(\"Please enter the \"\n + \"number of attackers then the number of\\ndefenders \"\n + \"separated by a space.\",\n before.attack + \" \" + before.defence);\n if (null == input)\n {\n return null;\n }\n\n Matcher matcher = INPUT_RE.matcher(input);\n if (matcher.matches())\n {\n Strength s = new Strength();\n s.attack = Integer.parseInt(matcher.group(1));\n s.defence = Integer.parseInt(matcher.group(2));\n if (null != matcher.group(3))\n {\n s.blitz();\n }\n\n if (s.attack == 0 &amp;&amp; s.defence == 0)\n {\n return null;\n }\n if (s.attack &lt;= 1)\n {\n output(\"INVALID ATTACK! You need\"\n + \" at least two armies to make an attack!\");\n }\n else if (s.defence &lt;= 0)\n {\n output(\"INVALID INPUT! There must\"\n + \" be at least one defending army!\");\n }\n else\n {\n return s;\n }\n }\n } while (true); // Repeat until input passes validation\n}\n\nprivate void output(String message)\n{\n JOptionPane.showMessageDialog(null, message);\n}\n</code></pre>\n\n<p>It's not necessary to have a null <code>Component</code> instance variable; you can just pass a literal null to <code>.showMessageDialog()</code>.</p>\n\n<hr>\n\n<h3>Play</h3>\n\n<p>This part of the code is more or less the same as before, but with nicer variable names. I've changed <code>(int)Math.ceil(Math.random() * …)</code> to <code>Random.nextInt()</code>.</p>\n\n<pre><code>private Random random = new Random();\n\npublic Strength play(Strength before)\n{\n Strength s = new Strength(before); // Return a copy\n Integer[] attackRolls = new Integer[3],\n defenceRolls = new Integer[2];\n\n do\n {\n for (int i = 0; i &lt; 3; i++)\n {\n attackRolls[i] = 1 + random.nextInt(s.attackMod);\n }\n for (int i = 0; i &lt; 2; i++)\n {\n defenceRolls[i] = 1 + random.nextInt(6);\n }\n Arrays.sort(attackRolls, Collections.reverseOrder());\n Arrays.sort(defenceRolls, Collections.reverseOrder());\n\n for (int rollCnt = 0; rollCnt &lt; 2; rollCnt++)\n {\n if (s.defence &lt;= 0 || s.attack &lt;= 1)\n {\n return s;\n }\n if (defenceRolls[rollCnt] &gt;= attackRolls[rollCnt])\n {\n s.attack--;\n }\n else\n {\n s.defence--;\n }\n }\n } while (s.isBlitz())\n return s;\n}\n</code></pre>\n\n<p>Strictly speaking, you don't have to add 1 to <code>.nextInt()</code>, but it's more human-friendly to do so.</p>\n\n<hr>\n\n<h3>Report</h3>\n\n<p>Again, the main difference is in the management of variables. This function now has to return <code>true</code> if the battle was decisive. Arguably, that violates the single-responsibility principle, and could be improved further.</p>\n\n<p>In your original code, you checked for <code>dfnc2 &gt; 0</code> to continue the battle and <code>dfnc2 &lt; 1</code> to report annihilation of the defenders. I've changed this to <code>s.defence &lt;= 0</code> to check for termination of the battle and <code>after.defence &lt;= 0</code> to report annihilation, so that the similarity is apparent.</p>\n\n<p>I think <code>String.format()</code> is more readable than concatenation.</p>\n\n<pre><code>public boolean report(Strength before, Strength after)\n{\n String verdict = (after.defence &lt;= 0) ?\n \"\\n\\nDefenders have lost!!\" :\n (after.attack &lt;= 1) ?\n \"\\n\\nAttackers have been repelled!!!\" : \"\";\n\n output(String.format(\"Attacking force now at %d (Lost %d)\\n\" +\n \"Defence force now at %d (Lost %d)\" +\n \"%s\",\n after.attack,\n before.attack - after.attack,\n after.defence,\n before.defence - after.defence,\n verdict));\n\n return !verdict.isEmpty();\n}\n</code></pre>\n\n<hr>\n\n<h3>Nitpicks</h3>\n\n<ul>\n<li>\"armys\" → \"armies\"</li>\n<li>\"a\" + \"mount of attackers\" → \"number of attackers\" (because it's a countable noun)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T02:18:52.463", "Id": "60275", "Score": "0", "body": "Wow, just wow. This is just, amazing! It's going to take me a few hours with Google to understand some of the things you have done but it should be well worth it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:01:44.757", "Id": "60278", "Score": "0", "body": "One question: how does the before.attack and after.attack work? I can never see where \"after\" comes in except at the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:42:31.037", "Id": "60284", "Score": "0", "body": "In `main()` — `Strength after = roller.play(before)`. That means that `before` represents the pre-battle state, and `after` represents the post-battle state." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T08:21:08.930", "Id": "60298", "Score": "0", "body": "Are those lines of slashes really necessary?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T08:23:05.320", "Id": "60299", "Score": "0", "body": "@Bobby I just find it very helpful to demarcate inner classes clearly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T08:46:15.163", "Id": "60301", "Score": "0", "body": "@Bobby, @200_success - no they are not necessary and `Strength` shouldn't be an inner static class. I understand it may be an inner class for demonstration purposes, but it should be its own class." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:41:22.753", "Id": "36659", "ParentId": "36643", "Score": "16" } }, { "body": "<p>Besides the stylistic issues, I think you may have made two fundamental mistakes in implementing the rules of Risk.</p>\n\n<h3>Number of dice rolled</h3>\n\n<p>According to <a href=\"http://www.hasbro.com/common/instruct/risk.pdf\">Hasbro's rules</a>…</p>\n\n<blockquote>\n <ul>\n <li>You, the attacker, will roll 1, 2 or 3 red dice: You must have at least one more army in your territory than the number of dice you roll. Hint: The more dice you roll, the greater your odds of winning. Yet the more dice you roll, the more armies you may lose, or be required to move into a captured territory.</li>\n <li>The defender will roll either 1 or 2 white dice: To roll 2 dice, he or she must have at least 2 armies on the territory under attack. Hint: The more dice the defender rolls, the greater his or her odds of winning-but the more armies he or she may lose.</li>\n </ul>\n</blockquote>\n\n<p>The main issue is that in your implementation, the probabilities don't reflect the army strengths. In your code, the attacker rolls three virtual dice:</p>\n\n<blockquote>\n<pre><code>for(int i = 0; i &lt; 3; i++)\n{\n z[i] = (int)Math.ceil(Math.random() * atckMod);\n}\n</code></pre>\n</blockquote>\n\n<p>… and similarly, the defender rolls two virtual dice. Then you sort them in descending order and decide the fate of each unit based on the top two dice of each side, stopping early if either side is annihilated. According to the rules, though, each side should only roll as many dice as the number of units involved in the battle.</p>\n\n<p>The game is designed to mimic the effect of units reinforcing each other. The probabilities are not nearly the same! The expected value of one die throw is</p>\n\n<blockquote>\n <p>1/6 (6 + 5 + 4 + 3 + 2 + 1) = 3.5</p>\n</blockquote>\n\n<p>The expected value of the maximum of two dice is</p>\n\n<blockquote>\n <p>1/6<sup>2</sup> (6 (6<sup>2</sup> - 5<sup>2</sup>) + 5 (5<sup>2</sup> - 4<sup>2</sup>) + 4 (4<sup>2</sup> - 3<sup>2</sup>) + 3 (3<sup>2</sup> - 2<sup>2</sup>) + 2 (2<sup>2</sup> - 1<sup>2</sup>) + 1) ≈ 4.4722</p>\n</blockquote>\n\n<p>The expected value of the maximum of three dice is</p>\n\n<blockquote>\n <p>1/6<sup>3</sup> (6 (6<sup>3</sup> - 5<sup>3</sup>) + 5 (5<sup>3</sup> - 4<sup>3</sup>) + 4 (4<sup>3</sup> - 3<sup>3</sup>) + 3 (3<sup>3</sup> - 2<sup>3</sup>) + 2 (2<sup>3</sup> - 1<sup>3</sup>) + 1) ≈ 4.95833</p>\n</blockquote>\n\n<p>The minor issue is that you haven't implemented an option to battle with only some of the available units, which would involve more complex prompting.</p>\n\n<h3>Blitz</h3>\n\n<p>The attacker's die rolls are simulated using</p>\n\n<blockquote>\n<pre><code>(int)Math.ceil(Math.random() * atckMod)\n</code></pre>\n</blockquote>\n\n<p>where <code>atckMod</code> is 7 instead of 6 in blitz mode. That would be a simulation of a seven-sided die, which <a href=\"http://en.wikipedia.org/wiki/Platonic_solid\">shouldn't physically exist</a>. Maybe you meant to add 1 bonus point to each die roll instead? (Blitz mode isn't mentioned in the rules I referenced above; perhaps it's a house rule you have.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T02:27:37.553", "Id": "60276", "Score": "0", "body": "Thanks for pointing those rule errors out, no one else noticed and I didn't either. I used to have it work properly but I guess when I re-coded some of it (The code I show here is the result of about a week playing around with it) I got rid of that functionality without knowing. As for the Blitz mode, that's more of a balancing factor that I think would work well in the real world as if your committing to an all or nothing attack you should have an ace up your sleeve. I know a 7 sided die does not exist, it just that anything else that does would be too great a multiplier for it to be fair." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T02:45:29.923", "Id": "60277", "Score": "0", "body": "Fixed that by adding \"&& i < atck1\" in the for loop's conditional." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T01:00:21.093", "Id": "36674", "ParentId": "36643", "Score": "7" } } ]
{ "AcceptedAnswerId": "36659", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:22:18.070", "Id": "36643", "Score": "21", "Tags": [ "java", "game", "dice", "battle-simulation" ], "Title": "Possible improvements to Risk board game?" }
36643
<p>I'm trying out a new approach to SASS stylesheets, which I'm hoping will make them more organizined, maintainable, and readable. </p> <p>I often feel like there is a thin line between code that is well structured and code that is entirely convoluted. I would appreciate any thoughts as to which side of the line this code falls. </p> <p>I don't want to tell you too much more about what these styles are intended to produce -- my hope is that the code will explain this for itself. Also note that this is part of a larger project, so don't worry about missing dependencies, etc.</p> <h3>Questions for review</h3> <ol> <li>How would you make this code easier to read/maintain? </li> <li>Can you understand what these styles are trying to produce?</li> <li>Is the purpose of the mixins/placeholders clear?</li> </ol> <h3>File structure:</h3> <pre><code>theme/sass/partials/ widget/ collapsable/ _appendicon.scss _closeall.scss _toggleswitch.scss collapsable.scss collapsablered.scss _button.scss </code></pre> <h3>collapsable.scss</h3> <pre><code>/** * Collapsable widget. * * The widget has "open" and "closed" states. * The widget has a Toggle Switch, which is visible in * both open and closed states. * All other content is hidden in the closed state. */ @mixin setOpenState { &amp;, &amp;.state-open { @content; } } @mixin setClosedState { &amp;.state-closed { @content; } } @mixin setToggleSwitchStyles { &amp;&gt;h1:first-child, .collapseableToggle { @content; } } @import "collapsable/closeall"; @import "collapsable/appendicon"; @import "collapsable/toggleswitch"; %collapsable { @include setOpenState { @include setToggleSwitchStyles { @extend %toggleSwitch; } } @include setClosedState { @extend %closeAllExceptToggle; @include setToggleSwitchStyles { @extend %toggleSwitchClosed; } } } </code></pre> <h3>collapsablered.scss</h3> <pre><code>@import "collapsable"; @import "../button"; %collapsableRed { @extend %collapsable; @include setOpenState { @include setToggleSwitchStyles { @extend %buttonWithRedBg; } } @include setClosedState { @include setToggleSwitchStyles { @extend %buttonWithDarkBg; } } } </code></pre> <h3>collapsable/_closeall.scss</h3> <pre><code>%closeAllChildren { * { display: none; } } %closeAllExceptToggle { @extend %closeAllChildren; @include setToggleSwitchStyles { display: block; .icon-sprite { display: inline-block; } } } </code></pre> <h3>collapsable/_appendicon.scss</h3> <pre><code>@import "compass/utilities/general/clearfix"; @import "../../icon"; @mixin appendIcon { @include pie-clearfix; .icon-sprite { margin-right: 5px; vertical-align: -3px; } &amp;:after { content: ''; position: relative; top: 2px; float: right; @content; } } %withCloseIcon { @include appendIcon { @extend .icon-close; // defined in _icon.scss } } %withOpenIcon { @include appendIcon { @extend .icon-rChevronDk; // defined in _icon.scss top: 1px; } } </code></pre> <h3>collapsable/_toggleswitch.scss</h3> <pre><code>%toggleSwitch { cursor: pointer; @extend %withCloseIcon; } %toggleSwitchClosed { @extend %toggleSwitch; @extend %withOpenIcon; } </code></pre> <h3>partials/_button.scss</h3> <pre><code>@import "typography"; %buttonWithRedBg { @extend %textOnRedBg; // defined in _typography.scss cursor: pointer; &amp;:hover { background-color: $redDk; } &amp;:active { background-color: $black; } } %buttonWithDarkBg { @extend %textOnDarkBg; // defined in _typography.scss cursor: pointer; &amp;:hover { background-color: #000; } &amp;:active { background-color: $redDk; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:12:15.740", "Id": "60180", "Score": "1", "body": "There appears to be a CSS error in your icon-sprite class. You have `vertical-align: -3px`, but the vertical-align property only takes specific values like top/bottom/middle/text-top/etc. Also, is this code intended to be portable (Compass extension)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:26:36.710", "Id": "60280", "Score": "0", "body": "As I said, this is a component of a larger project, not a portable extension -- though I am concerned with modularity and reusability. Also, I'm looking for comments on readability/structure/etc., not syntax errors -- [though vertical-align does take px arguments](http://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align), for the record." } ]
[ { "body": "<p>Overall, your naming conventions are pretty good. I don't feel like I need to go look at mixins themselves to figure out what their purpose is. The extensive use of extends does concern me, since it can lead to larger CSS rather than smaller like you might expect (see: <a href=\"https://codereview.stackexchange.com/questions/26003/mixin-extend-or-silent-class\">Mixin, @extend or (silent) class?</a>).</p>\n\n<p>Your <code>%textOnDarkBg</code> and <code>%textOnRedBg</code> extend classes might be redundant. If you're not already using Compass, you might want to take a look at it. It offers a function as well as a mixin for setting a good contrasting color against your desired background color (see: <a href=\"http://compass-style.org/reference/compass/utilities/color/contrast/\" rel=\"nofollow noreferrer\">http://compass-style.org/reference/compass/utilities/color/contrast/</a>). Highly useful if your project is intended to be themed.</p>\n\n<p>Generally speaking, using colors for class names isn't very clear unless the content is about color (eg. a color wheel or a rainbow). What is <em>red</em> for? Is it for <em>errors</em>? Or maybe a <em>call to action</em>? The same thing goes for <em>dark</em>. Using <em>inverted</em> or <em>closed</em> might be better choices. If the site's design is already dark, a <em>dark</em> button probably doesn't make much sense.</p>\n\n<p>Your code only allows the user to have exactly 2 colors (default and <em>red</em>), which seems more limited than it needs to be. You could easily make it very flexible by making use of lists (or maps, which will be in the next version of Sass). Here's an example from my own project:</p>\n\n<pre><code>// name dark light\n$dialog-help: #2E3192 #B9C2E1 !default; // purple\n$dialog-info: #005FB4 #BDE5F8 !default; // blue\n$dialog-success: #6F7D03 #DFE5B0 !default; // green\n$dialog-warning: #A0410D #EFBBA0 !default; // orange\n$dialog-error: #C41616 #F8AAAA !default; // red\n\n$dialog-attributes:\n ( help nth($dialog-help, 1) nth($dialog-help, 2)\n , info nth($dialog-info, 1) nth($dialog-info, 2)\n , success nth($dialog-success, 1) nth($dialog-success, 2)\n , warning nth($dialog-warning, 1) nth($dialog-warning, 2)\n , error nth($dialog-error, 1) nth($dialog-error, 2)\n ) !default;\n\n@each $a in $dialog-attributes {\n $name: nth($a, 1);\n $color: nth($a, 2);\n $bg: nth($a, 3);\n\n %dialog-colors.#{$name} {\n color: $color;\n background-color: $bg;\n }\n\n %dialog-colors-inverted.#{$name} {\n color: $bg;\n background-color: $color;\n }\n\n %badge-colors.#{$name} {\n background-color: $color;\n color: $background-color;\n }\n\n %button-colors.#{$name} {\n @include button($base: $bg) {\n @include button-text($color, inset);\n\n @include button-states;\n }\n }\n\n %button-colors-inverted.#{$name} {\n @include button($base: $color) {\n @include button-text($bg, inset);\n\n @include button-states;\n }\n }\n\n %button-colors-faded.#{$name} {\n @include button($base: fade($bg, 10%)) {\n color: #CCC;\n\n @include button-states;\n }\n }\n}\n</code></pre>\n\n<p>In case you're wondering why I'm using multiple classes, I've setup a short demo: <a href=\"http://sassmeister.com/gist/7792677\" rel=\"nofollow noreferrer\">http://sassmeister.com/gist/7792677</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:18:18.050", "Id": "60398", "Score": "0", "body": "I'm glad the structure and use of the mixins is easy to grok. The use of `@extend` vs `@mixin` is still a bit of a mystery to me, though I've been trying to use `@extend` to denote a type of style (_noun_), and `@include` to do something to a style (_verb_).\nI think you're right about the color naming. I split out `collapsableRed` because I wanted to make it easy to extend the base `collapsable` widget for different themes. It would probably be better to use a named theme instead of a color name (eg `myAwesomeThemeCollapsable`). I wouldn't use `.42pxWideHeader` instead of `.sidebarHeader`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:23:04.023", "Id": "60400", "Score": "0", "body": "And yes, I am using Compass. The `%textOnWhateverColorBg` runs into the same problem as `%collapsableWhateverColor` -- I shouldn't be naming a class with a specific style value. I'll have to think of a better name. Maybe `%textColorsActive` and `%textColorsInactive` would be more descriptive." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T18:28:49.733", "Id": "36652", "ParentId": "36647", "Score": "4" } } ]
{ "AcceptedAnswerId": "36652", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T16:01:02.750", "Id": "36647", "Score": "3", "Tags": [ "css", "sass" ], "Title": "SASS Code Structure / Readability" }
36647
<p>Though I have heard about the magic method <code>__autload</code>, I still prefer to use this code:</p> <pre><code>function autoload($array) { foreach ($array as $value) { switch ($value) { case 'database' : include ROOT_DIR.'/core/database.php'; break ; case 'user' : include ROOT_DIR.'/core/user_class.php'; break ; case 'error_handler' : include ROOT_DIR.'/core/error_class.php'; break ; case 'template' : include ROOT_DIR.'/template/rain.tpl.class.php'; break ; case 'email' : include ROOT_DIR.'/core/email_class.php'; break ; } } } </code></pre> <p>I'm not exactly sure if this is a good option. Should I switch to the magic method <code>__autoload</code> or keep using my simple <code>switch case</code>? If you propose that I need to use the magic method instead, is it due to a performance-wise factor? If not, why are you suggesting it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:03:16.800", "Id": "60253", "Score": "1", "body": "For reference, this wouldn't be nearly as messy if you stuck to a naming convention. You could easily handle just the odd cases, and let everything else be handled by code that understands your naming scheme. Course, at that point, you're about 80% of the way to a true autoloader anyway..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:10:00.763", "Id": "60257", "Score": "1", "body": "Also, no one uses `__autoload` directly anymore. You can (and should!) use `spl_autoload_register` to set up class autoloaders. Among other things, it lets you have more than one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T10:21:13.030", "Id": "60309", "Score": "0", "body": "@cHao Thank you very much, i'll look into spl_autoload .." } ]
[ { "body": "<p>It depends if this is for OOP or procedural code. I am assuming OOP as you use class in some of your file names.</p>\n\n<h2>Procedural</h2>\n\n<p>If this is for procedural code then it should be renamed to <code>load</code> as there is nothing auto about it (see the OOP review).</p>\n\n<h2>OOP</h2>\n\n<p>If this is for OOP then it is not a good option. <code>spl_autoload_register</code> to register a standard autoload function is better.</p>\n\n<h2>Your Solution</h2>\n\n<ul>\n<li>There is a hardcoded entry that needs to be maintained for each class that you want to include. This does not scale well with hundreds or thousands of entries to look through.</li>\n<li>If the value is not recognized you ignore it silently because you don't have a <code>default</code> entry in your <code>switch</code> statement.</li>\n<li>You have to manually autoload the classes that you want (this takes the auto out of autoload).</li>\n</ul>\n\n<h2>Advantages of spl_autoload_register</h2>\n\n<ul>\n<li><p><code>spl_autoload_register</code> is a true automatic loader.</p>\n\n<pre><code>// We just need one call to register an autoload function, this registers the\n// autoloading for the lifetime of the program.\nspl_autoload_register();\n$exampleObject = new Example_Object;\n\n// In the file autoloaded for class Example_Object:\nclass Example_Object\n{\n // Type hinting works to load the class for Another_Object.\n public exampleMethod(Another_Object $another)\n {\n // Autoloading works here too.\n $lastObject = new Last_Object;\n }\n}\n</code></pre></li>\n</ul>\n\n<p>The autoloader only needs to be registered once and continues to load files for classes right throughout the program.</p>\n\n<ul>\n<li>A stack of autoload functions can be provided allowing for flexibility in the logic used to load classes.</li>\n<li>Because files are loaded lazily only what is required is loaded no matter how much you edit the other files.</li>\n<li>Using logic to load your class files helps you to organize them logically. It makes your logic simpler if you name your class files logically. This helps when you have hundreds or thousands of files that have been named in a consistent manner.</li>\n</ul>\n\n<h2>What not to use an autoloader for</h2>\n\n<p>An autoloader is for loading the file needed to define a class. You should not use it to load functions or templates. These should still be included manually.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:24:00.890", "Id": "36661", "ParentId": "36654", "Score": "3" } }, { "body": "<p>I think there is merit in this approach for reasons I'll not go into. Instead I'll simply share the core workings of my \"magic\" class:</p>\n\n<pre><code>&lt;?php\nclass Magic{\n /** INSTANTIATION\n *\n * Define the paths to the classes\n */\n public $paths;\n public function __construct(){\n // Define our paths\n $this-&gt;paths = array(\n 'one' =&gt; dirname(__FILE__) . '/one.php',\n 'two' =&gt; dirname(__FILE__) . '/two.php',\n 'three' =&gt; dirname(__FILE__) . '/three.php'\n );\n }\n /** __GET :: MAGIC METHOD\n *\n * PHP hits this when trying to access a non-existent classes\n *\n * We can use it to \"autoload\" and insantiate on-demand\n */\n public function __get($name){\n // Do we have a path defined?\n if(isset($this-&gt;paths[$name])){\n // Hotload the library...\n require_once($this-&gt;paths[$name]);\n // What to do?\n if(class_exists($name)){\n // Instantiate the class\n $this-&gt;$name = new $name($this);\n return $this-&gt;$name;\n }\n }\n // Assume the worst\n return false;\n }\n}\n$magic = new Magic();\n\n// Usage\n$magic-&gt;one-&gt;stuff();\n$magic-&gt;two-&gt;methods();\n$magic-&gt;three();\n</code></pre>\n\n<p>You should be able to deduce that the moment you request an object, the __get magic method is called, at this point we load and instantiate the class making it instantly available. For me this is desirable as I store settings in the Magic object which can be used by the loaded classes during creation.</p>\n\n<p>I too have never been overly keen on using spl_autoload_register; but then I'm guilty of writing tightly coupled code. These are my faults and I do well to be aware of them!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:50:47.410", "Id": "36665", "ParentId": "36654", "Score": "1" } } ]
{ "AcceptedAnswerId": "36661", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T19:07:12.940", "Id": "36654", "Score": "1", "Tags": [ "php5" ], "Title": "Simple PHP Autoloader alternative" }
36654
<blockquote> <p>You have to find a path through which the rat move from the starting position (0,0) to the final position where cheese is (n,n). List the total no of possible paths which the rat can take to reach the cheese.</p> </blockquote> <p>Sample Input:</p> <pre><code>7 0 0 1 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 1 0 1 1 0 1 0 1 0 0 0 0 1 0 1 1 1 1 0 0 0 </code></pre> <p>Sample Output:</p> <pre><code>4 </code></pre> <p>My code:</p> <pre><code>import java.util.*; class maze { static int n; static int[][] a; static int path; public static void main(String[] ar) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n][n]; for(int i = 0; i &lt; n; i++) { for(int j = 0; j &lt; n; j++) { a[i][j] = sc.nextInt(); } } search(0,0); System.out.println(path); } public static void search(int i, int j) { if(!exist(i,j) || a[i][j] == 1) return; if(i == n-1 &amp;&amp; j == n-1) { path++; return; } a[i][j] = 1; search(i+1,j); search(i-1,j); search(i,j+1); search(i,j-1); a[i][j] = 0; } public static boolean exist(int i, int j) { return i&gt;=0 &amp;&amp; j &gt;=0 &amp;&amp; i &lt; n &amp;&amp; j &lt; n; } } </code></pre> <p>Can anybody recommend a better solution than this or if there are any, please point out the mistakes in this. I made it using simple logic and I don't know much about graph theory. Is this DFS or BFS?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-19T19:05:06.860", "Id": "253481", "Score": "0", "body": "There's no input about where the cheese is." } ]
[ { "body": "<p>There are not many things to criticize here ... the basic algorithm in general looks good.</p>\n\n<p>The three items I would caution you on are:</p>\n\n<ol>\n<li>you are keeping track of the path-count in the <code>paths</code> static variable. This is a pattern that, although works, is not very 'pretty', there's a better way... I'll explain.</li>\n<li>you modify the source array. This can be OK, but, in general, when you want to modify the source data you should instead work off a copy of the data.</li>\n<li>all your other variables (the maze itself and the size of the maze) are static.</li>\n</ol>\n\n<p>With a slight shift in the way you think of your search method, instead of updating the number of paths, you should instead think 'how many paths <strong>from here</strong>?'</p>\n\n<p>Also, lets fix the static variable issues too (we will need two methods for this):</p>\n\n<pre><code>public static final int search(int[][] data) {\n int[] mymap = new int[data.length][];\n for (int i = 0; i &lt; data.length; i++) {\n mymap[i] = Arrays.copyOf(data[i], data[i].length);\n }\n return search(mymap, 0, 0);\n}\n</code></pre>\n\n<p>Now, the <code>search(...)</code> recursive method should return an <code>int</code>, and it takes the maze as input, not from a static variable.</p>\n\n<p>To avoud the use of the 'n' variable, we use the basic information from the maze. The following is a copy/paste of your code with slight modifications:</p>\n\n<ol>\n<li>it returns <code>int</code></li>\n<li>return-statements inside return a value now</li>\n<li>the input includes the 'maze' (instead of being a static variable)</li>\n<li>there are no references to <code>n</code>, just to the <code>a</code> array</li>\n<li>it has an internal <code>paths</code> variable</li>\n<li>it changes how it calls <code>exist(...)</code></li>\n</ol>\n\n\n\n<pre><code>public static int search(int[][] a, int i, int j)\n{\n if(!exist(i,j) || a[i][j] == 1)\n return 0; // no path here.\n if(i == a.length - 1 &amp;&amp; j == a[i].length - 1)\n {\n return 1; // 1 path here.\n }\n a[i][j] = 1; // mark that we have seen this spot here\n int paths = 0; // introduce a counter...\n paths += search(a, i+1,j); // add the additional paths as we find them\n paths += search(a, i-1,j);\n paths += search(a, i,j+1);\n paths += search(a, i,j-1);\n a[i][j] = 0;\n return paths; // return the number of paths available from this point.\n}\n</code></pre>\n\n<p>The <code>exist()</code> function will also need to change:</p>\n\n<pre><code>public static boolean exist(int[][] a, int i, int j)\n{\n return i&gt;=0 &amp;&amp; j &gt;=0 &amp;&amp; i &lt; a.length &amp;&amp; j &lt; a[i].length;\n} \n</code></pre>\n\n<p>Note that this no longer references the <code>n</code> static variable either.</p>\n\n<p>Finally, with these changes (and, really, in the scheme of things they are 'small'), your main method simply becomes:</p>\n\n<pre><code> Scanner sc = new Scanner(System.in);\n int n = sc.nextInt();\n int[][] a = new int[n][n];\n for(int i = 0; i &lt; n; i++)\n {\n for(int j = 0; j &lt; n; j++)\n {\n a[i][j] = sc.nextInt();\n }\n }\n System.out.println(search(a));\n</code></pre>\n\n<p>For this, the <code>a</code> does not need to be static either.</p>\n\n<p>If you code the process like I suggest then the methods become much more generic, and you have other advantages like:</p>\n\n<ol>\n<li>the methods are all thread-safe now (you can find many paths in parallel using the same methods).</li>\n<li>the data and the logic are both self-contained.</li>\n<li>there are no static variables.</li>\n</ol>\n\n<p>Finally, the variable names you have chosen are really short..... consider renaming the <code>a</code> variable at least.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T19:58:19.730", "Id": "36658", "ParentId": "36655", "Score": "4" } }, { "body": "<p>Your recursive search is fine, as long as the paths through the maze are short enough not to overflow the stack. Since you have to find all paths, an exhaustive search is necessary, so I don't think you need to use any fancier algorithms. (Recursion generally results in depth-first search behaviour.)</p>\n\n<p>I agree with @rolfl that static variables should be avoided, and that modifying the input matrix is naughty. However, I recommend a different remedy: make a <code>Maze</code> object. (By the way, class names should be <code>UpperCaseLikeThis</code> in Java.)</p>\n\n<p>Once your <code>Maze</code> object has copied the maze definition into a private instance variable, it's free to do whatever it wants with the array, including modifying it with temporary roadblocks.</p>\n\n<p>I've renamed <code>search()</code> to <code>pathsFrom()</code> to clarify the meaning of its parameters. I've also renamed <code>exist()</code> to <code>isInBounds()</code> for clarity.</p>\n\n<p>The count of the number of paths is <em>not</em> part of the state of the maze, so it should not be an instance variable or a class variable. It should just be returned from the <code>pathsFrom()</code> method.</p>\n\n<pre><code>import java.util.*;\n\nclass Maze\n{\n private int n;\n private int[][] a;\n\n /**\n * Array is a square matrix, whose elements are 0 for paths and 1 for walls.\n */\n public Maze(int[][] array)\n {\n // Copy the array, assuming that it is a square matrix\n n = array.length;\n a = new int[n][];\n for (int i = n - 1; i &gt;= 0; i--)\n {\n a[i] = Arrays.copyOf(array[i], n);\n }\n }\n\n public int pathsFrom(int i, int j)\n {\n if(!isInBounds(i,j) || a[i][j] == 1)\n {\n return 0;\n }\n if(i == n-1 &amp;&amp; j == n-1)\n {\n return 1;\n }\n try\n {\n a[i][j] = 1;\n return pathsFrom(i+1,j) +\n pathsFrom(i-1,j) +\n pathsFrom(i,j+1) +\n pathsFrom(i,j-1);\n }\n finally\n {\n // Restore the state of the maze before returning\n a[i][j] = 0;\n }\n }\n\n private boolean isInBounds(int i, int j)\n {\n return i&gt;=0 &amp;&amp; j &gt;=0 &amp;&amp; i &lt; n &amp;&amp; j &lt; n;\n }\n\n public static void main(String[] ar)\n {\n Scanner sc = new Scanner(System.in);\n int n = sc.nextInt();\n int[][] a = new int[n][n];\n for(int i = 0; i &lt; n; i++)\n {\n for(int j = 0; j &lt; n; j++)\n {\n a[i][j] = sc.nextInt();\n }\n }\n Maze m = new Maze(a);\n System.out.println(m.pathsFrom(0, 0));\n }\n\n}\n</code></pre>\n\n<p>In the implementation of <code>pathsFrom()</code> above, I've used a slick language trick to sneak in a statement before returning. That code is equivalent to</p>\n\n<pre><code> a[i][j] = 1;\n int paths = pathsFrom(i+1,j) +\n pathsFrom(i-1,j) +\n pathsFrom(i,j+1) +\n pathsFrom(i,j-1);\n a[i][j] = 0;\n return paths;\n</code></pre>\n\n<p>… except that the version using <code>finally</code> restores the state of the matrix even if an exception is thrown.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:46:55.707", "Id": "36663", "ParentId": "36655", "Score": "3" } } ]
{ "AcceptedAnswerId": "36658", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T19:07:49.777", "Id": "36655", "Score": "4", "Tags": [ "java", "recursion", "pathfinding" ], "Title": "Count possible paths through a maze" }
36655
<p>I have the input image <code>in</code>, and the mask image <code>lev</code> (which label each pixel as a number from 1 to <code>nlevels</code>, <code>nlevels</code>=4). I need to get image out, which from each region <code>in==lev</code> will be replaced by its average value.</p> <p>Here is my brute force approach. I'm wondering if there is any better way of doing it.</p> <pre><code>Mat ACA::global_average(Mat in, const Mat &amp;lev) { // in: CV_32F // lev: CV_32S int M=in.rows; int N=in.cols; in.convertTo(in, CV_32FC3); // vector holds average value for each category vector&lt;float&gt; count(nlevels,0); vector&lt;Vec3f&gt; average(nlevels); int pixlev; for (int i=0; i &lt; M; i++) for (int j=0; j &lt; N; j++) { pixlev = lev.at&lt;int&gt;(i,j); assert (pixlev&lt;nlevels); average[pixlev] += in.at&lt;Vec3f&gt;(i,j); count[pixlev]++; } for (int i=0; i&lt;nlevels; i++) average[i] /=count[i]; Mat out=Mat::zeros(M,N,CV_32FC3); for (int i=0; i&lt;M; i++) for (int j=0; j&lt;N; j++) { pixlev = lev.at&lt;int&gt;(i,j); out.at&lt;Vec3f&gt;(i,j)=average[pixlev]; } return out; } </code></pre> <p>P/S:</p> <p>Here is an example. </p> <p>Input Image:</p> <p><img src="https://i.stack.imgur.com/KgXSl.jpg" alt="Original Image"> Mask image, it is basically a matrix labelling the pixels into one of 4 categories</p> <p><img src="https://i.stack.imgur.com/T45X4.png" alt="Mask Image"></p> <p>Output picture is the average of input image, for each category of pixels. For example, at first I find all pixels has category 1, find their average, and replace all those pixels by the average value.</p> <p><img src="https://i.stack.imgur.com/q6NHt.png" alt="Output picture"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T04:55:23.437", "Id": "60292", "Score": "0", "body": "I don't really follow your description, especially what average you are taking. Could you provide a simple input / lev / output example? Also if you could comment your code I guess it will help people help you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T08:01:18.170", "Id": "60297", "Score": "0", "body": "Thanks for the update. It's clear to me now. I'll check it out when I have time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:17:31.340", "Id": "60346", "Score": "0", "body": "Apart from few missing {} on the outer for loops, it looks good to me" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T07:24:04.360", "Id": "60459", "Score": "0", "body": "I also don't see any particular inefficiencies in it. Did you have some ideas that you weren't able to implement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T06:11:33.373", "Id": "60610", "Score": "0", "body": "I'm thinking of using convolution to perform averaging ( and convolution can be calculated through FFT(n logn). But nevermind, this should be good enough as you guys point out." } ]
[ { "body": "<h1>Algorithm</h1>\n\n<p>You will benefit greatly from using OpenCV's built-in functionality rather than performing this operation yourself. OpenCV supports masked operations, which will only apply to pixels where the mask is nonzero.</p>\n\n<pre><code>cv::Mat global_average(const cv::Mat&amp; input, const cv::Mat&amp; levels)\n{\n assert(levels.channels() == 1);\n cv::Mat output(input.size(), input.type());\n for (int level = 0; level &lt; nlevels; ++level)\n {\n const cv::Mat mask = levels == level;\n const cv::Scalar avg = cv::mean(input, mask);\n output.setTo(avg, mask);\n }\n return output;\n}\n</code></pre>\n\n<p>Using functionality already present in OpenCV is not only clearer and shorter (by a factor of 3), but also allows the code to be more flexible. You will notice:</p>\n\n<ul>\n<li>There is no explicit type conversion or array indexing occurring, which is safer.</li>\n<li>This code is also more flexible: you do not need to convert your images to floating-point or integers.</li>\n<li>It can operate on 8-bit images as well, which can give a significant speedup, since most of the time in the algorithm will be spent on memory access. Simply using the raw 8-bit images gives a ~15% speedup in my tests.</li>\n<li>It is also possible that OpenCV functions may benefit from hardware and parallelism optimizations, which could make them faster than raw loops.</li>\n</ul>\n\n<h1>Code Style</h1>\n\n<h3>Whitespace</h3>\n\n<p>Put spaces around your assignments and comparisons: <code>int i=0; i&lt;m;</code> is harder to read than <code>int i = 0; i &lt; M;</code>. Also, be consistent. Sometimes you do this already, but most of the time you do not.</p>\n\n<h3>Braces</h3>\n\n<p>You have nested <code>for</code> loops, but only the inner loop has braces. Both loops should have braces surrounding the body for consistency.</p>\n\n<h3>Precondition Checking</h3>\n\n<p>Although it is good that you leave comments indicating the data types you expect from <code>in</code> and <code>lev</code>, it is better to verify this in code. Adding assertions about these conditions makes it easier to debug if a wrong parameter is passed:</p>\n\n<pre><code>assert(in.depth() == CV_32F);\nassert(lev.depth() == CV_32S);\n</code></pre>\n\n<h3>Use <code>const</code> when you can</h3>\n\n<p>Both <code>M</code> and <code>N</code> do not change during the function evaluation. They can be declared as <code>const int</code> to allow the compiler to perform checks that they are never accidentally modified. Additionally, you can reduce the scope of <code>pixlev</code> by declaring it inside each of the loops. Then it too can be made <code>const</code>:</p>\n\n<pre><code>const int pixlev = lev.at&lt;int&gt;(i,j); // or use auto to reduce type duplication\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-29T18:41:17.890", "Id": "58430", "ParentId": "36656", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T19:51:30.370", "Id": "36656", "Score": "6", "Tags": [ "c++", "algorithm", "image", "opencv" ], "Title": "Replace subimage by its average value" }
36656
<p>I have previous revisions of my deck of cards project, but I may not need to link them here since the emphasis is on the use of templates.</p> <p>I've never used them before until now, and I like how intuitive my implementation has become. However, I'm also aware that there are many pitfalls in C++ templates. Although I don't think this implementation uses them heavily, I'd still like to know if I'm at a good start before I use them again.</p> <p>I'm also a bit unsure about some of my naming now, considering this is a template class. For instance, I've changed <code>add()</code>'s parameter from <code>card</code> to <code>item</code> because it cannot be assumed that the user will only use cards. Although it makes sense to just use cards (or anything representing cards), it would not seem practical to limit the implementation to just that usage. I would prefer this to be reusable.</p> <p>Of course, I'm okay with any other improvements that can be made.</p> <p><strong>Deck.hpp</strong></p> <pre><code>#ifndef DECK_HPP #define DECK_HPP #include &lt;algorithm&gt; #include &lt;stdexcept&gt; #include &lt;vector&gt; template &lt;class T&gt; class Deck { private: std::vector&lt;T&gt; original; std::vector&lt;T&gt; playable; public: typedef typename std::vector&lt;T&gt;::size_type SizeType; void add(T const&amp;); T draw(); void reset(); void shuffle(); SizeType size() const { return playable.size(); } bool empty() const { return playable.empty(); } }; template &lt;class T&gt; void Deck&lt;T&gt;::add(T const&amp; item) { original.push_back(item); playable.push_back(item); } template &lt;class T&gt; T Deck&lt;T&gt;::draw() { if (playable.empty()) { throw std::out_of_range("deck empty"); } T top(playable.back()); playable.pop_back(); return top; } template &lt;class T&gt; void Deck&lt;T&gt;::reset() { playable = original; } template &lt;class T&gt; void Deck&lt;T&gt;::shuffle() { if (!playable.empty()) { std::random_shuffle(playable.begin(), playable.end()); } } #endif </code></pre>
[]
[ { "body": "<p>The usage of a template parameter named <code>T</code> is generally idiomatic when there are no restrictions on what you can use when instantiating the template; for example, when using container classes <code>T</code> is used as it could potentially be anything. If the parameter is more limited however, you should give it a more descriptive name. In this example, an obvious choice would be <code>Card</code>:</p>\n\n<pre><code>template &lt;typename Card&gt;\nclass Deck\n{\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:50:57.840", "Id": "60286", "Score": "0", "body": "Good point. I suppose there will be confusion if the user uses, say, `int`s, but that it inevitable with templates." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T09:08:47.960", "Id": "60464", "Score": "0", "body": "I disagree. The templatized parameter are generic they can be anything thus trying to name this counterproductive. I generally use `T` for a normal type or `I` for an iterator." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T01:51:46.763", "Id": "36676", "ParentId": "36657", "Score": "6" } }, { "body": "<p>Bottom line: your code here is focused and solid. It's a well-written introductory use of templates. However I'm not sure it's a great scenario in which to use them. First I'll talk about ways to improve its reusability, and then I'll say more about why I think it's a questionable scenario.</p>\n<p>As you start trying to implement your own templatized data structure, there are a lot of concerns to think about. Above all else you need to consider how your data structure will be used; what operations will consumers of it expect, what limitations will they have to put up with, and whether any of the data structure's implementation choices lock them into bad patterns. In general I would say you would do well to follow the lead of the STL data structures unless you have specific reasons not to. Here are a few of the places where you currently differ:</p>\n<h3><code>void Deck&lt;T&gt;::add(T const &amp;)</code></h3>\n<p>This one actually is pretty much spot on. But I want to talk about the implications of how it's implemented. You are requiring <code>T</code> to be copyable. Thus if a consumer of this class needs to compare cards, <code>T</code> will need to compare itself through means other than by its address. This isn't particularly unusual, but I just wanted to be clear that comparing <code>T</code> instances by address is invalidated by <code>Deck&lt;T&gt;</code>'s implementation.</p>\n<p>The biggest question mark here is the lack of a range insertion, perhaps via constructor or <code>add(InputIterator first, InputIterator last)</code>. Similarly there's no index-based insertion, but that wouldn't mix well with the two vectors that are often out of sync.</p>\n<h3><code>T Deck&lt;T&gt;::draw()</code></h3>\n<p>Before C++11 introduced move semantics, there was not necessarily a low cost way to examine and remove an item from a data structure. This is why vector and other data structures let you examine the front or back, but don't return the removed item on a pop_back(). While it's perfectly good to wrap the functionality of the underlying storage, as the cost of copying T goes up, so does the cost of this implementation of <code>draw()</code>. Implementing it in some other fashion (typically as two separate methods for peeking and removing) is suggested before C++11.</p>\n<blockquote>\n<p>Taking into account what Corbin and Loki Astari point out, it's more relevant to consider weak and strong exception guarantees (essentially the ability to reason about correctness in unusual situations) instead of the cost of copying (thanks especially to RVO). Whether you need to care about either is still completely dependent on your use case in practice, and thus only of extreme importance in general purpose data structures, or in ones you know need to offer it.</p>\n</blockquote>\n<h3>Inside <code>draw()</code></h3>\n<p>Your implementation of <code>draw()</code> verifies that the playable deck has items remaining. This is certainly good for catching errors, but leads to repeated checks for the same data. Either the calling code will look like <code>while (true) { ::: draw(); ::: }</code> and will have to use a <code>try/catch</code> to find out when the deck was empty, or it will look like <code>while (!deck.empty()) { ::: draw(); ::: }</code>. The former is a questionable way to use exceptions, as an empty deck is hardly an unexpected condition, but the latter means both the caller and callee are repeating the empty check. It's also possible that the caller knows this in other ways, such as having put 52 cards in the deck and then looping 52 times to empty it.</p>\n<p>As an aside, it can still be useful to have this sort of check available by another name (consider the difference between <code>vector&lt;T&gt;::operator[]</code> and <code>vector&lt;T&gt;::at</code>), or available through a compile-time option (such as a <code>DEBUG</code> build). But it's typically good to make an unchecked version available (vector's operator[] case).</p>\n<h3><code>void Deck&lt;T&gt;::reset()</code></h3>\n<p>I'm lumping a couple comments in here, and this is less about following the STL's lead. Like in <code>draw()</code>, as the cost of copying <code>T</code> goes up or the size of your deck goes up, so does the cost of <code>reset()</code>; is it possible that you don't need to save the original order? If you don't, then perhaps it would be better to consider a different implementation:\none <code>vector&lt;T&gt;</code> containing the order of the deck, one <code>vector&lt;T&gt;::const_iterator</code> or <code>vector&lt;T&gt;::size_type</code> containing the index/iterator through which you've already played. This would have a lot of repercussions, so I'm going to show the methods that it would impact, assuming the class has a <code>size_type deck_top</code>, and that we remove <code>original</code>. I like the shorter code, but that has less to do with the index and more to do with the other changes.</p>\n<pre><code>template &lt;class T&gt; bool Deck&lt;T&gt;::empty() const\n{\n return deck_top &gt;= playable.size();\n}\n\ntemplate &lt;class T&gt; T const &amp; Deck&lt;T&gt;::draw() // note we can now return a reference\n{\n return playable[deck_top++];\n}\n\ntemplate &lt;class T&gt; void Deck&lt;T&gt;::reset()\n{\n deck_top = 0;\n}\n\ntemplate &lt;class T&gt; void Deck&lt;T&gt;::shuffle()\n{\n std::random_shuffle(playable.begin() + deck_top, playable.end());\n}\n</code></pre>\n<p>This of course has multiple tradeoffs besides the ones I already mentioned. Perhaps the biggest is that there's still no way to remove cards (temporarily or permanently), so it's hard to model a game that shuffles a partial deck while people are still holding some cards in their hands. I think you will rapidly find that it's hard to make this data structure usable for all the scenarios you think you want it to support without making it almost as generic as vector itself. At which point you will have to consider whether it's worth reusing the data structure, or if it's really just for a single program's use.</p>\n<h3>Final notes</h3>\n<p>As a generic comment, I'm undecided on <code>card</code> vs. <code>item</code>. I think <code>card</code> conveys the intended use better, and doesn't really get in the way if someone wants, say, a &quot;Deck&quot; of tiles instead. But I do agree in general with the point about not boxing yourself in by your parameter names.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:32:11.647", "Id": "60281", "Score": "0", "body": "Fun fact to add to your `T Deck<T>::draw()` section: `T pop_back()` is impossible to implement correctly unless `T`'s copy constructor is not allowed to throw exceptions. This undoubtedly affected the decision to have `pop_back` return void too. Even if performance were not a concern, `pop_back` would return void. (Oh, and move operations can throw exceptions, so `T pop_back` is still impossible.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:38:21.087", "Id": "60282", "Score": "0", "body": "I especially like your point about the modelling of card removal. This was one of my biggest obstacles, and it appears that I may not be able to do this correct. @Corbin told me in an earlier review that this implementation would be no different than maintaining an STL data structure and putting cards into that. I do agree with him on that. That also leads me to agree with your point regarding reusability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:40:55.753", "Id": "60283", "Score": "0", "body": "When I mentioned this, I was referring to my own programs. I know that someone else can just use an STL container and put it into a sorting function or something, but I personally wanted to use something generic and... well, personalized for my own use. I still want it to be *good*, of course. But from what I see, I'm best off making it as proper as an STL container as possible, while not needing to account for everything (such as all the operator overloads and iterators). And yes, I do still want to make sure I'm not misusing templates early on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:45:08.160", "Id": "60285", "Score": "0", "body": "I also don't have full access to C++11 on my machine, so I don't think I could properly test move semantics, even if I wanted to here. So, to ease the confusion, I'll just consider this a C++03 program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T13:20:43.233", "Id": "60327", "Score": "0", "body": "@Jamal To lightly contradict myself, especially in the case you describe of personal use only, it's not at all required to match STL. (Like you say, save iterators for later.) [YAGNI](http://en.wikipedia.org/wiki/You_aren't_gonna_need_it) is an important mindset to remember. Just balance it with avoiding gratuitous differences with other classes you'll use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T14:37:55.707", "Id": "60336", "Score": "0", "body": "@MichaelUrman: Thanks for the reminder about YAGNI. :-) I will do just that, and leave out some unneeded functionality such as some operator overloads and iterators (I haven't written the latter for any program before anyway)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T09:15:15.007", "Id": "60465", "Score": "0", "body": "Don't agree with your arguments about copying in `T Deck<T>::draw()` I think this argument is very outdated . All modern compilers have exceedingly good RVO and NRVO build in. The copy will be elided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T10:23:00.080", "Id": "60470", "Score": "0", "body": "@LokiAstari: I didn't like returning by reference anyway, and I don't think my own `Card` class is too large to copy inexpensively (if it's even relevant here)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:07:13.763", "Id": "60522", "Score": "0", "body": "@Jamal: Return by value is usually not expensive (put prints in to check). The RVO and NRVO optimizations will kick in and the copy will be elided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-22T01:26:24.370", "Id": "73149", "Score": "0", "body": "My approach to removing a card from my Deck class: track n_remaining (originally 52 if a standard deck). Pick a number from 0-51. Decrement n_remaining. Swap that card with the (n_remaining)th. Reshuffle is just reset n_remaining to 52." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T01:54:34.793", "Id": "36677", "ParentId": "36657", "Score": "12" } }, { "body": "<p>The only additional point I have is the use of class:</p>\n\n<pre><code>template &lt;class T&gt; class Deck \n // ^^^^^^\n This one.\n</code></pre>\n\n<p>Its technically valid. But the implications that T should be some class type (or user defined type) make me dislike this form. I prefer the modern version:</p>\n\n<pre><code>template &lt;typename T&gt; // PS. I also prefer line break here.\nclass Deck // It makes the class look like a normal class\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T09:11:16.753", "Id": "36760", "ParentId": "36657", "Score": "4" } }, { "body": "<ul>\n<li><p>I did have access to C++11 when writing this code, but I never found a use for it at the time. I am now aware that there's a better replacement for <code>std::random_shuffle()</code> available in C++11 which doesn't utilize <code>rand</code> (<a href=\"http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"nofollow\">now considered harmful</a>): <a href=\"http://en.cppreference.com/w/cpp/algorithm/random_shuffle\" rel=\"nofollow\"><code>std::shuffle()</code></a>.</p>\n\n<p>This requires a third parameter, a random number engine, supplied as such:</p>\n\n<pre><code>static std::random_device rd;\nstatic std::mt19937 engine(rd());\n</code></pre>\n\n<p>(The new C++11 library <a href=\"http://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow\"><code>&lt;random&gt;</code></a> is required for this.)</p>\n\n<p>In <code>shuffle()</code>, I can now replace <code>std::random_shuffle()</code> with <code>std::shuffle()</code>:</p>\n\n<pre><code>std::shuffle(playable.begin(), playable.end(), engine);\n</code></pre>\n\n<p>With this, I can also now remove <code>std::srand()</code> from the driver.</p></li>\n<li><p>Since neither <code>size()</code> nor <code>empty()</code> throw exceptions, I can add <code>noexcept</code> for both of them to make this clear:</p>\n\n<pre><code>SizeType size() const noexcept { return playable.size(); }\nbool empty() const noexcept { return playable.empty(); }\n</code></pre></li>\n<li><p>I can now use type aliasing for the type <code>std::vector&lt;T&gt;</code>:</p>\n\n<pre><code>using Cards = std::vector&lt;T&gt;;\n</code></pre>\n\n<p>This would allow me to change the type in just one place:</p>\n\n<pre><code>Cards original;\nCards playable;\n</code></pre></li>\n<li><p>Due to templating issues and a possible lack of <code>size_type</code> for a different container class, I can remove <code>SizeType</code> and have <code>size()</code> return <code>auto</code> (in C++14):</p>\n\n<pre><code>auto size() const noexcept { return playable.size(); }\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-01T22:13:49.947", "Id": "58799", "ParentId": "36657", "Score": "3" } } ]
{ "AcceptedAnswerId": "36677", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T19:54:26.297", "Id": "36657", "Score": "13", "Tags": [ "c++", "template", "playing-cards" ], "Title": "Use of templates with templated Deck class" }
36657
<p>Seeking code correctness and best practices. </p> <p>I would like to re-allocate various amounts of memory (0 or more) such that on systems that may return <code>NULL</code> for an allocation of 0 does not falsely imply a memory allocation error.</p> <p>Given:</p> <ul> <li><code>void *</code> (with a valid value or NULL already) <br></li> <li><code>size_t</code> (new desired size)</li> </ul> <p>Receive:</p> <ul> <li><code>void *</code> (new pointer)</li> <li><code>int</code> (failure status)</li> </ul> <p></p> <pre><code>#include &lt;assert.h&gt; #include &lt;stdlib.h&gt; int ReallocAndTest(char **Buf, size_t NewSize) { assert(Buf); char *NewBuf = realloc(*Buf, NewSize); if ((NewBuf == NULL) &amp;&amp; (NewSize &gt; 0)) { return 1; // return failure } *Buf = NewBuf; return 0; } </code></pre> <p>I came across the below references, which imply a <code>realloc()</code> return of <code>NULL</code> is not <em>always</em> a failure. The lone special case occurs with <code>size</code> is 0. The return value may or may not be <code>NULL</code>.</p> <blockquote> <p>C11dr 7.22.3.5 The realloc function 4 The <code>realloc</code> function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.</p> <p>C11dr §J.1 Unspecified behavior. — The amount of storage allocated by a successful call to the calloc, malloc, or realloc function when 0 bytes was requested (7.22.3).</p> <p>C11dr §J.3.12 Implementation-defined behavior. Whether the calloc, malloc, and realloc functions return a null pointer or a pointer to an allocated object when the size requested is zero (7.22.3).</p> </blockquote> <ul> <li><p>Discusses how a memory allocation of 0 is useful.<br> Answer: when a routine has a <code>malloc(size)</code>, testing for <code>size != 0</code> is not needed.<br> <a href="https://stackoverflow.com/questions/2022335/whats-the-point-in-malloc0/2022402#2022402">what's the point in malloc(0)?</a></p></li> <li><p>Asks if <code>realloc(ptr), 0)</code> is the same as <code>free(ptr)</code>.<br> Answer: Not necessarily.<br> <a href="https://stackoverflow.com/questions/2546572/what-happens-if-i-re-alloc-and-the-new-size-is-0-is-this-equivalent-with-a-free">What happens if I re-alloc and the new size is 0. Is this equivalent with a free?</a></p></li> <li><p>Allocation wrapper set.<br> Answer: Does not address <code>realloc(ptr, 0)</code>.<br> <a href="https://codereview.stackexchange.com/questions/26656/are-these-memory-allocation-wrapper-functions-kosher-with-all-c-compilers">Are these memory-allocation wrapper functions kosher with all C compilers?</a></p></li> </ul> <hr> <p>[Answer]</p> <ol> <li><p>Use <code>void*</code> rather than <code>char *</code>.</p></li> <li><p>With a 0 size, avoid returning the implementation defined<br> ..a) <code>NULL</code> or<br> ..b) <code>ptr</code> that cannot be referenced.<br> and return a pointer to insure only 1 of the 2 is ever returned. </p></li> </ol> <p>On point #2, I only slightly favor returning <code>NULL</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:45:45.067", "Id": "60239", "Score": "0", "body": "I already see I should be using `void *` rather than `char *`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T10:00:04.857", "Id": "60711", "Score": "0", "body": "For semantic consistency, you might want to change 0 to FALSE, 1 to TRUE and int to bool(C++) or bool_t/BOOL/BOOLEAN (or whatever standard bool type you're using in your C program). That will make it more clear to callers what they should expect the function to do." } ]
[ { "body": "<p>With the variety of behaviors exhibited by different implementations, I think the only safe thing is to test for zero size before the <code>realloc</code> call and set a minimum allocation (eg 1 byte). </p>\n\n<p>Note that <code>realloc</code> will probably set <code>errno</code> to <code>ENOMEM</code> when it fails, but I don't think this is guaranteed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T00:15:26.263", "Id": "60264", "Score": "1", "body": "`ENOMEM` appears to be in Linux and not the C standard. It is surprising that a memory allocation error does not generate a error code per the C standard. Maybe a history thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T11:53:49.520", "Id": "60967", "Score": "3", "body": "+1 Checking for 0 before calling realloc is indeed the correct approach. Avoid writing code that relies on unspecified or impl.defined behavior. One of the point of writing a wrapper is to get rid of such things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-03T12:13:11.237", "Id": "143817", "Score": "1", "body": "I (also) suggest if someone calls your_malloc() or your_realloc() with size 0, you should call malloc() or realloc() with size 1. That way you always have a distinct pointer. Some code may benefit from the assumption that distict allocated objects have distinct addresses; and of course it's not good to be confused between success and failure! I did this in my malloc and realloc wrappers: http://sam.nipl.net/libb/alloc.b Additionally, this allows your_malloc and your_realloc to be signature compatible with the originals." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:32:00.440", "Id": "36666", "ParentId": "36662", "Score": "5" } }, { "body": "<ol>\n<li><p>Standard naming convention in C is usually <code>lower_case_with_underscore</code>.</p></li>\n<li><p>You should be using <code>void *</code> rather than <code>char *</code></p></li>\n<li><p>I would consider making the return value deterministic when the new size is 0 by always returning <code>NULL</code> rather than the implementation defined behaviour (which could technically be a pointer which is not <code>NULL</code> but still not allowed to be dereferenced). <code>free</code> guarantees by spec that <code>free(NULL)</code> is legal.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T00:09:21.030", "Id": "60263", "Score": "0", "body": "I am unfamiliar with the standard in 1. Where may I find it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T06:20:34.497", "Id": "60293", "Score": "0", "body": "@chux: http://en.wikipedia.org/wiki/Naming_convention_%28programming%29#C_and_C.2B.2B and http://stackoverflow.com/questions/1722112/what-are-the-most-common-naming-conventions-in-c" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:54:03.680", "Id": "60537", "Score": "0", "body": "The wiki says \"standard library identifiers are mostly lowercase\" and this is not a standard library identifier. Sorry if the \"wrapper\" description misled. The SO post reflect various conventions but not a standard. The C standard _does_ distinguish between upper and lower case letter in all identifiers, so this implies that upper case usage is not verboten. The SO post did stress _consistency_. I concur with your naming convention of trying to be standard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T00:12:13.530", "Id": "60587", "Score": "2", "body": "Yes, naming conventions are always subjective. However `PascalCase` for local variables and function parameters is rather unusual." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-03T12:20:28.950", "Id": "143822", "Score": "0", "body": "This is a good \"patch critique\" for the given wrapper. The other answer explains a better wrapper." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:59:04.020", "Id": "36669", "ParentId": "36662", "Score": "6" } } ]
{ "AcceptedAnswerId": "36669", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:39:18.560", "Id": "36662", "Score": "6", "Tags": [ "c", "memory-management", "wrapper" ], "Title": "Critique of realloc() wrapper" }
36662
<pre><code>var romanArray = []; var toRoman = { analyze: function(number){ romanArray = []; if (number &gt;= 1000) { return this.thousands(number); }else if (number &gt;= 100){ return this.hundreds(number); }else if (number &gt;= 10) { return this.tens(number); }else{ return this.last_number(number); } }, thousands: function(number){ var remainder = number % 1000; var thousands = Math.floor(number / 1000); for(var e = 0; e &lt; thousands; e++) { romanArray.push('M'); } return this.hundreds(remainder); }, hundreds: function(number){ var remainder = number % 100; var hundreds = Math.floor(number / 100); if (hundreds === 4){ romanArray.push('CD'); }else if(hundreds === 9){ romanArray.push('CM'); }else if(hundreds &gt;= 5 &amp;&amp; hundreds &lt; 9){ romanArray.push('D'); for(var i = 0; i &lt; (hundreds % 5); i++) { romanArray.push('C'); } }else if (hundreds &gt; 0 &amp;&amp; hundreds &lt; 4){ for(var e = 0; e &lt; hundreds; e++) { romanArray.push('C'); } }else{ } return this.tens(remainder); }, tens: function(number){ var remainder = number % 10; var tens = Math.floor(number / 10); if (tens === 4){ romanArray.push('XL'); }else if(tens === 9){ romanArray.push('XC'); }else if(tens &gt;= 5 &amp;&amp; tens &lt; 9){ romanArray.push('L'); for(var i = 0; i &lt; (tens % 5); i++) { romanArray.push('X'); } }else if (tens &gt; 0 &amp;&amp; tens &lt; 4){ for(var e = 0; e &lt; tens; e++) { romanArray.push('X'); } }else{ } return this.last_number(remainder); }, last_number: function (number){ if (number === 4){ romanArray.push('IV'); }else if(number === 9){ romanArray.push('IX'); }else if(number &gt;= 5 &amp;&amp; number &lt; 9){ romanArray.push('V'); var remainder = number % 5; for(var i = 0; i &lt; remainder; i++) { romanArray.push('I'); } }else if (number &gt; 0 &amp;&amp; number &lt; 4){ for(var e = 0; e &lt; number; e++) { romanArray.push('I'); } }else{ } return romanArray.join(''); } }; console.log(toRoman.analyze(1000)); console.log(toRoman.analyze(2999)); console.log(toRoman.analyze(2555)); </code></pre> <p>I'm wondering if this JavaScript can be refactored using some sort of base/template function.<br> For Example:</p> <pre><code>base_function: function (number, four, nine, five, one){ if (number === 4){ romanArray.push(four); }else if(number === 9){ romanArray.push(nine); }else if(number &gt;= 5 &amp;&amp; number &lt; 9){ romanArray.push(five); var remainder = number % 5; for(var i = 0; i &lt; remainder; i++) { romanArray.push(one); } }else if (number &gt; 0 &amp;&amp; number &lt; 4){ for(var e = 0; e &lt; number; e++) { romanArray.push(one); } }else{ } return romanArray; }, </code></pre> <p>How can I improve this code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:03:33.273", "Id": "60243", "Score": "0", "body": "Your example confuses me. What would the variables `four`, `nine`, `five`, and `one` be? The names aren't very descriptive..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:17:16.233", "Id": "60246", "Score": "0", "body": "You're really close to answering your own question with `base_function()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:33:18.190", "Id": "60248", "Score": "0", "body": "I've updated the question per @DanielCook suggestion. The parameters four, nine, five, and one represent the strings at each position of the number. For example at last_number position ('IV', 'IX', 'V', 'I'), but at tens position the variables would be ('XL', 'XC', 'L', 'X')." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:43:47.617", "Id": "60249", "Score": "0", "body": "@200_success I feel I'm close to solving this, but I don't know how to make the base function chain with the next function. Any and all help is greatly appreciated." } ]
[ { "body": "<p>You may be aware that there are simpler answers to this problem, such as:</p>\n\n<pre><code>function toRoman(n) {\n var r = '',\n decimals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],\n roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];\n for (var i = 0; i &lt; decimals.length; i++) {\n while (n &gt;= decimals[i]) {\n r += roman[i];\n n -= decimals[i];\n }\n }\n return r;\n}\n</code></pre>\n\n<p>Bearing this in mind it might be useful to explain what exactly you are trying to achieve with your refactoring? E.g. is it to practice using more complicated language patterns?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:06:03.473", "Id": "60256", "Score": "0", "body": "This is an elegant solution @Stuart. My goal was to refactor my code by eliminating repetition and using object oriented JavaScript(OOJS) for clarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:17:27.860", "Id": "60259", "Score": "0", "body": "@ltrainpr my opinion, but \"I want to do this using js prototype inheritence\" is the source of quite a few crappy, unnecessarily complex frameworks I've seen people build over and over again. OO in JS is an awkward shim. It's useful for optimization, or if you're building something with a plugin architecture, but contributes little else. It's usually much better to rely on the functional aspects of JS than on the object-oriented ones /opinion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:18:36.133", "Id": "60260", "Score": "2", "body": "My comment would also be that this problem does not call for OO design... There are no 'objects' here (except a number) and it does not in practice seem to improve clarity, and I can't see any way to improve the clarity and eliminate repetition while retaining the OO design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:20:18.950", "Id": "60261", "Score": "0", "body": "@GeorgeMauer You may be right but I don't think this problem would call for OO design in any language" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:21:43.197", "Id": "60262", "Score": "0", "body": "Except of course in Java where if you don't have an AbstractFactory that is driven by a xml configuration you're not doing it right :) All kidding aside, that's a good point." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:51:32.030", "Id": "36667", "ParentId": "36664", "Score": "8" } }, { "body": "<p>Normally, asking for code to be written is against the rules of this website. However, since you already have a working solution, an idea of where you want to go, and an independent solution from @Stuart, I suppose there's no harm in just finishing it for you:</p>\n\n<pre><code>hundreds: function(number) {\n base_function(Math.floor(number / 100), 'CD', 'CM', 'D', 'C');\n return this.tens(number % 100);\n},\n\n// etc.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T01:42:27.187", "Id": "60272", "Score": "0", "body": "I was returning the wrong thing. I kept attempting to return this.base_function instead of this.tens. Good to know I was close thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T01:46:29.597", "Id": "60273", "Score": "0", "body": "I think you need to include this before base_function for the solution to work." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T01:19:40.617", "Id": "36675", "ParentId": "36664", "Score": "3" } } ]
{ "AcceptedAnswerId": "36675", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:50:15.400", "Id": "36664", "Score": "2", "Tags": [ "javascript", "converting", "roman-numerals" ], "Title": "Number to Roman Numeral" }
36664
<p>I've been learning Haskell for a few weeks after coming from a C# background. I've written a function to return a number of unique <code>Int</code>s from a specified range:</p> <pre><code>module MrKWatkins.Random ( uniqueRandomInts ) where import System.Random import qualified Data.IntSet as I uniqueRandomInts :: RandomGen g =&gt; (Int, Int) -&gt; Int -&gt; g -&gt; ([Int], g) uniqueRandomInts range@(min, max) n rng | n &lt; 0 = error "n must be positive" | n &gt; max - min + 1 = error "n is too large for range" | otherwise = recursion n I.empty ([], rng) where recursion n used (xs, rng) | n == 0 = (xs, rng) | I.member x used = recursion n used (xs, rng') | otherwise = recursion (n-1) (I.insert x used) (x:xs, rng') where (x, rng') = randomR range rng </code></pre> <p>Then to produce 5 numbers in the (inclusive) range 1 -> 10 the call would be something like:</p> <pre><code>uniqueRandomInts (1, 10) 5 $ mkStdGen 42 </code></pre> <p>Firstly I have a few specific questions:</p> <ol> <li>I've prefixed my module name with <code>MrKWatkins</code> to distinguish it as my module (much as I would with a namespace in C#). Is this common practice, or would I be better with a single word for the module name that is more descriptive?</li> <li>I've done some pre-condition checking on the parameters, throwing exceptions if they're not satisfied. Is this common practice in Haskell, and is this the best way to do it?</li> <li>I've used a nested function for the recursion. Would I be better off separating this out into a top level function that I don't export from the module?</li> <li>I've reused some variable names in the recursion function, hiding the ones from the parent scope. Should I use different names instead?</li> </ol> <p>On top of those if there is any advice on style, better ways to implement the above or just general advice would be greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T07:49:14.067", "Id": "60294", "Score": "2", "body": "obligatory http://xkcd.com/221/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-20T19:12:17.420", "Id": "230011", "Score": "0", "body": "On point (2): Often, Haskell code (esp public APIs) will constrain the type of the parameter into an acceptable range; that way, it is impossible to construct an invalid argument. If it can't be done with the type system (so that erroneous input produces a static error), we turn to [smart constructors](https://wiki.haskell.org/Smart_constructors)." } ]
[ { "body": "<p>Haskell is very different than other languages.</p>\n\n<p>Here is how I would solve the problem:</p>\n\n<pre><code>import Control.Arrow\nimport System.Random\n\nuniqueRandomInts :: (RandomGen g, Random a)\n =&gt; (a, a) -&gt; Int -&gt; g -&gt; ([a], g)\nuniqueRandomInts range n = \n (map fst &amp;&amp;&amp; snd . last) . take n . iterate getNext . randomR range\n where getNext = randomR range . snd\n</code></pre>\n\n<p>What does this do? </p>\n\n<p>First note that the <code>g</code> (generator) parameter isn't shown in the example, but it is there.... <code>uniqueRandomInts range n</code> returns a function of type </p>\n\n<pre><code>RandomGen g =&gt; g -&gt; ([a], g)\n</code></pre>\n\n<p>so you will still need to apply this parameter in order to get the values.</p>\n\n<p>I've also refrained from specifying the type of the return value at this stage.... This function is a tool that could be used for any type, why artificially bind it at this point?</p>\n\n<p>The <code>iterate getNext $ randomR range g</code> part (where I've shown where the <code>g</code> will be applied) creates an infinite list of <code>(a, g)</code>, where the <code>a</code>'s are the random values, and the <code>g</code>'s are the generators returned at each step. (for reference, <code>iterate f x</code> is a function that returns <code>[x, f x, (f.f) x, (f.f.f) x, ....]</code>).</p>\n\n<p>Passing around infinite lists is one of those mind blowing things to people who are coming to Haskell from other languages, but remember that the language is lazy, so no actual value will be calculated until requested (this is sort of how the human mind works.... If I ask you to imagine an infinite sequence of <code>1</code>'s, you can reason about it without actually sitting there trying to enumerate all the <code>1</code>'s in your brain before you go on).</p>\n\n<p>We then apply <code>take n</code> to this, to take the first <code>n</code> values of the sequence (thus turning it into something finite before we actually need to calculate any of the values).</p>\n\n<p>Finally, we have the mysterious <code>(map fst &amp;&amp;&amp; snd . last)</code> part. This isn't actually needed for the calculations themselves, but just to format the values in the way that you wanted them. <code>(func1 &amp;&amp;&amp; func2) x</code> applies the functions on the value <code>x</code>, and returns <code>(func1 x, func2 x)</code>. We are pulling out the random values in the first slot, and getting the last random generator for the second spot.</p>\n\n<p>You can use this function as follows (because we kept things generic, you need to specify the type)</p>\n\n<pre><code>main = do\n g &lt;- getStdGen\n print $ randomValues (1, 10::Int) 10 g\n</code></pre>\n\n<p>As to your particular questions:</p>\n\n<ol>\n<li><p>As to the prefixing, Haskell has a vibrant community ecosystem where many people contribute code to the public, and some sort of prefixing is needed to keep things sane.... Of course this is only needed if you plan to contribute your code. I personally don't prefix at all when I am writing something small for myself (why complicate things?), and can always add it if I need later. If a personal project becomes larger, I can always add it. This is pretty much how I programmed in Java also....</p></li>\n<li><p>Pre-checking is very common and valuable in Haskell, however.... so is generality. There is no reason that this particular function shouldn't be used by an numerical type over any range (would you want to rewrite the exact same function for a set of random floats over the range <code>-1.0</code> to <code>+1.0</code>?). I would personally place the limit check and type fixing higher up in the code.... And when I did, I would use the <code>Data.Ix.inRange</code> function.</p></li>\n<li><p>I didn't use explicit recursion (it was used in a lower level function that I used), however I'll answer the general philosophy that I follow to determine if a subfunction should be top level or not.... I make a function top level if it describes a generic tool that others could use. I usually use a \"where\" clause generally only for function documentation (ie- when the name of the variable describes what it is doing). Sometimes you need to define a where clause variable for other reasons (ie- recursion or to avoid repetition), but strangely enough these are usually cases that you are better off writing around anyway (recursion and repetition are usually abstracted away in lower level calls like <code>iterate</code> and <code>(&amp;&amp;&amp;)</code>, which are cleaner to use anyway). This isn't a hard fast rule though! Not everything can be abstracted in some high level function yet.</p></li>\n<li><p>I don't know :), however if you ever turn on <code>-Wall</code> in the compiler, it will complain every time you shadow another variable, so to avoid the nagging I usually try to change the name. Sometimes choosing a different name becomes annoying, so I just turn off <code>-Wall</code> :)</p></li>\n</ol>\n\n<p>EDIT-----</p>\n\n<p>Oops, as you pointed out, I misread the problem.... You need <em>unique</em> values.</p>\n\n<p>Luckily we can still use all the code above, with a slight addition. Add this-</p>\n\n<pre><code>removeDuplicatesUsing::Ord b=&gt;(a-&gt;b)-&gt;[a]-&gt;[a]\nremoveDuplicatesUsing f theList = [x|(Just x, _, _) &lt;- iterate getNext (Nothing, theList, empty)]\n where \n getNext (_, x:xs, used) \n | f x `member` used = (Nothing, xs, used)\n | otherwise = (Just x, xs, insert (f x) used)\n</code></pre>\n\n<p>Then put one more filter in your <code>randomValue</code> pipeline-</p>\n\n<pre><code>(map fst &amp;&amp;&amp; snd . last) . take n . removeDuplicatesUsing fst . iterate getNext . randomR range\n</code></pre>\n\n<p>Let me explain what is going on here</p>\n\n<ol>\n<li><p>There are many algorithms to generate random <em>unique</em> values.... The unique part complicates things a bit, and depending on your circumstances, different algorithms work better. I will discuss those cases later in this answer, but for now I chose the same algorithm that you used in your answer.</p></li>\n<li><p>Because Haskell is lazy, adding another function <code>filter</code> in a bunch of composed functions barely takes a speed, memory or latancy performance hit. Data will flow through the functions from right to left as it is generated, you will start to see results even before all the data has started to flow into the pipeline. In this way, Haskell function composition is more like Unix pipe chaining than anything else.</p></li>\n<li><p>In fact breaking things apart like this is my preferred way to do things. By now I might have more code than if I wrote it all in one function, but each of these are simple, easy to debug tools that you could imagine reusing.</p></li>\n<li><p>A <code>removeDuplicates</code> function (which I didn't write) would read a stream of values in, and filter out anything that it has previously seen. This is almost what we need, but we want to base uniqueness on only the resulting random value (if we included the generator, it would always be unique!). It is common in Haskell to write generalized <code>-Using</code> or <code>-With</code> functions that allow you to pass a function in to give the \"key\" that you want to use for comparisons (....and note that you can easily define <code>removeDuplicates = removeDuplicatesUsing id</code>).</p></li>\n<li><p>I wrote the <code>removeDuplicates</code> in the same style as the <code>uniqueRandomInts</code> function (using a list of tuples generated by <code>iterate</code>).... Writing out using recursion here might be easier to read, I guess it is just a matter of taste. This feels more Haskell-y to me, and that was the point of this comparison.</p></li>\n<li><p>I still left out the range check, but after reading your comment I reverse what I said above, I think it is a good idea to put it in! (I looked too quickly and thought it was a value range, not a count range).</p></li>\n</ol>\n\n<hr>\n\n<p>Finally, a note about algorithms (independent on the language chosen to write this). If you are choosing <code>n</code> unique items from a range of <code>N</code> values....</p>\n\n<ol>\n<li><p>If <code>N</code> and <code>n</code> are small&nbsp;--- It doesn't matter what algorithm you choose, they will all be fast.</p></li>\n<li><p>If <code>N</code> is huge and <code>n</code> is small&nbsp;--- the given algorithm above works great. It breaks down however....</p></li>\n<li><p>as <code>n</code> approaches <code>N</code> in size&nbsp;--- Once a sizable percentage of <code>N</code> has been filled, you will start hitting many repeat hits (if 90% of the range has already been taken, only one in 10 tries will get something new). You can of course flip the chosen and not chosen values (ie- generate the 10% you don't want, then return all the others), or you can move on to a solution of this type- <a href=\"https://stackoverflow.com/questions/196017/unique-random-numbers-in-o1\">https://stackoverflow.com/questions/196017/unique-random-numbers-in-o1</a>. While this is doable in Haskell, the part where you start swapping values in an array is trickier than in any mutable language (you basically either have to use IO around a mutable array, or start making copies of the initial array, which Haskell can do much more efficiently by reusing parts of the initial array in the copied version, but still, less efficient than just doing mutating swaps.... Someone else might have a better suggestion than this....).</p></li>\n<li><p>If <code>N</code> is really large, holding all values in an array in memory might not be practical. In this case, you might want to use some sort of \"unsort\" command line tool (a few of these exist in Unix), do a one time pass over all the values, and then take the first <code>n</code> elements of the list.</p></li>\n<li><p>If <code>N</code> is huge, and you don't care that <code>n</code> come out precisely, you can always do something statistical (do one linear pass and accept each value with probability <code>n/N</code>). This should be much faster than method (4), but of course you won't get exactly <code>n</code> values, and you can't just truncate early, or else you will be favoring earlier values over latter ones.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T09:43:01.000", "Id": "60307", "Score": "0", "body": "Thanks for your reply. However there is nothing above to make the values unique - running with mkStdGen 42 I get [2,2,8,5,7]... My version above uses an IntSet to check for uniqueness. (I originally used an infinite sequence with nub to make them unique, but I believe that is O(n^2) so I used the IntSet to try and improve the bounds. Although it doesn't really matter much on the small values of n I'm using...) How would you go about making the returned list of values unique?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T10:27:51.980", "Id": "60311", "Score": "0", "body": "Also thanks for inRange, didn't know about that either. Although not sure it will help here. The pre-condition checks I have are basically to stop infinite loops. For example if the range is (1, 10) and n == 11 then I'd get an infinite loop as there are only 10 unique integers available in the range. Similarly I check n is 0 or greater otherwise the recursion will decrement it repeatedly rather than stopping. (Of course it might overflow I guess and eventually stop, but still not what you want...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T23:43:38.110", "Id": "60440", "Score": "0", "body": "Oops, you are correct, I missed the word \"unique\" (right in the title no less :) ). Of course that makes this a more \"interesting\" problem (in any language). I will add some modifications to the answer later to remedy this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T12:32:59.493", "Id": "60809", "Score": "0", "body": "Thanks for the reply. Haven't had a chance to go through it yet but will do so soon..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T09:55:05.040", "Id": "64537", "Score": "0", "body": "*Still* haven't had a chance to go through in detail unfortunately... I'll mark it as the answer though as I'm pretty sure it covers everything. I Might come back to you with more questions at some point though..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T02:09:28.863", "Id": "36678", "ParentId": "36671", "Score": "9" } } ]
{ "AcceptedAnswerId": "36678", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:36:37.923", "Id": "36671", "Score": "5", "Tags": [ "haskell", "recursion", "random" ], "Title": "Function to produce unique random numbers" }
36671
<p>I've been playing around with Clojure for a while now, and one of the tasks I occasionally find awkward is parsing input. For example, I took part in the facebook hacker cup recently, where part of the challenge was to read input like this:</p> <pre><code>5 4 ..## ..## .... .... 4 ..## ..## #... .... 4 #### #..# #..# #### 5 ##### ##### ##### ##### ..... 5 ##### ##### ##### ##### ##### </code></pre> <p>Where the first line is the number of "cases" to follow and the first line of each case is the number of lines in that case. It seems fairly obvious to me that the output of parsing this should be a list of "cases", but there's no obvious way to know when to split the data without reading part of the data first. (In this particular case I know I could look for lines with numbers vs. lines with #s, but I'm more interested in a general solution)</p> <p>I ended up implementing this like:</p> <pre><code>(defn read-stdin [] (line-seq (java.io.BufferedReader. *in*))) (defn my-iterate [f n input] "Calls iterate on input and returns the final result" (nth (iterate f input) n)) (defn parse-grid "Parses a text grid of .s and #s and returns a set of coord pairs for each # element" [lines] (set (filter identity (for [[row line] (map-indexed vector lines) [col c] (map-indexed vector line)] (if (= c \#) [row col] nil))))) (defn parse-case "Takes a case-array and some lines, parses out a single case, adds it to the case-array and returns along with the remainder of the lines. Meant to be used with iterate" [[cases [first-line &amp; lines]]] (let [problem-size (read-string first-line)] [(conj cases {:size problem-size :blacks (parse-grid (take problem-size lines))}), (drop problem-size lines)])) (defn parse-cases [[first-line &amp; rest-lines]] (let [num-cases (read-string first-line)] (first (my-iterate parse-case num-cases [[] rest-lines])))) (def read-cases-stdin (comp parse-cases read-stdin)) </code></pre> <p>The <code>parse-case</code> function is my main worry here - it feels really awkward to have to return a vector of the current case list and the rest of the input, and have to deal with unpacking it again on the next iteration of the function. Is there a more idiomatic way of going about doing this?</p> <p>Any other general feedback on my code would also be welcome.</p>
[]
[ { "body": "<p>I think your main problem is that you're using <code>iterate</code> where partitioning and <code>map</code>ping would work just fine.</p>\n\n<p>I would create a simple helper function that splits the input line-seq into cases. Normally you could use <code>partition</code> for this, but since the number of lines can vary from case to case, you would have to use <code>loop</code>/<code>recur</code>. (See my <code>split-cases</code> function below. Also, note that we don't really care about the number of cases on the first line; we completely ignore it via destructuring.)</p>\n\n<p>Now, believe it or not, all you have to do is <code>map</code> your <code>parse-grid</code> function over the result of <code>(split-cases ...)</code> and you'll end up with a list of sets of coordinates, one for each case. </p>\n\n<p>I think your <code>parse-grid</code> function is very nice. It's concise and it makes good use of <code>map-indexed</code> and destructuring. The only thing I would tweak is that I would leverage the built-in <code>:when</code> syntax of Clojure's <code>for</code> macro to filter out the coordinates of the non-# characters. Then you can take out the <code>filter identity</code> part because there are no longer any <code>nil</code> values to remove.</p>\n\n<p>So, here is how I would revise your code:</p>\n\n<pre><code>(defn split-cases [[_ &amp; lines]]\n \"Returns a seq of cases, each of which is a seq of #/. lines.\"\n (loop [result []\n [number-of-lines &amp; lines] lines]\n (if (seq lines)\n (recur (conj result (take number-of-lines lines))\n (drop number-of-lines lines))\n result)))\n\n(defn parse-grid [grid]\n \"Parses a text grid of .s and #s and returns a set of coord\n pairs for each # element\"\n (set (for [[row line] (map-indexed vector grid)\n [col c] (map-indexed vector line)]\n :when (= c \\#)]\n [row col])))\n\n(defn read-stdin [] \n (line-seq (java.io.BufferedReader. *in*)))\n\n(defn parse-cases-stdin []\n (map parse-grid (split-cases (read-stdin))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T18:19:00.947", "Id": "79214", "Score": "0", "body": "I'd almost given up on this question, but that's a great answer. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T21:03:36.283", "Id": "79243", "Score": "0", "body": "As CR's top clojure answerer, you should join us in [our chatroom](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime so you can get to know the site better. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:29:26.533", "Id": "79605", "Score": "0", "body": "@syb0rg Think I will sometime!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T17:11:51.123", "Id": "45425", "ParentId": "36672", "Score": "3" } } ]
{ "AcceptedAnswerId": "45425", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T00:09:03.627", "Id": "36672", "Score": "3", "Tags": [ "clojure" ], "Title": "Idiomatic input parsing in clojure" }
36672
<p>I'm not a dedicated cryptographer, so I'm looking for someone to look over these functions I wrote and let me know if there are any implementation errors leading to security vulnerabilities or just anything I should improve. Any other comments about improving performance, etc. would be great too.</p> <p>This is used in a PHP-based file server I'm writing, where users can optionally encrypt their files individually through their web browser. These are the filesystem functions that are called in the middle of Ajax request.</p> <p>I had to separate the decryption into 3 parts because it's used not only for statically decrypting files but also for doing it on the fly during a file download. So it's not always used the same way.</p> <p>It's designed to be very modular so that ciphers and other settings can be changed readily. I also took a cautious approach to security, using cascading ciphers, a 512-bit salt, 4000-iteration whirlpool-based key derivation and multiple keys and initialization vectors per file, which also saves on memory usage.</p> <pre><code>public static function EncryptFile($owner, $id, $password) { // This requires PHP 5.5.0 or higher! global $mysqli, $settings; if (empty($owner) || empty($id) || !isset($password)) { return false; } $crypto_settings = unserialize($settings['crypto']); $secure = false; openssl_random_pseudo_bytes(1, $secure); if (!$secure) { return false; } if (!($file = mysqli_fetch_assoc(mysqli_query($mysqli, 'SELECT * FROM content_files WHERE owner="' . $owner . '" AND id="' . $id . '"')))) { return false; } if ($file['crypto_binary'] || $file['crypto_settings']) { return false; } $chunks = ceil($file['size'] / $crypto_settings['chunk_size']); $keys = array(); $vectors = array(); $keys_string = ""; $vectors_string = ""; for ($i = 0; $i &lt; $chunks; $i++) { $keys[$i] = array(); for ($n = 0; $n &lt; count($crypto_settings['ciphers']); $n++) { $key = openssl_random_pseudo_bytes($crypto_settings['key_lengths'][$n] / 8); $keys[$i][$n] = $key; $keys_string. = $key; } $vectors[$i] = array(); for ($n = 0; $n &lt; count($crypto_settings['ciphers']); $n++) { $vector = openssl_random_pseudo_bytes($crypto_settings['vector_lengths'][$n] / 8); $vectors[$i][$n] = $vector; $vectors_string. = $vector; } } $salt = openssl_random_pseudo_bytes($crypto_settings['salt_length'] / 8); $master_key_length = 0; for ($i = 0; $i &lt; count($crypto_settings['ciphers']); $i++) { $master_key_length += ($crypto_settings['key_lengths'][$i] + $crypto_settings['vector_lengths'][$i]) / 8; } $master_key = openssl_pbkdf2($password, $salt, $master_key_length, $crypto_settings['pbkdf2_iterations'], $crypto_settings['pbkdf2_algorithm']); $master_key_used = 0; $crypto_binary = "TRUE".$keys_string.$vectors_string; for ($i = 0; $i &lt; count($crypto_settings['ciphers']); $i++) { $crypto_binary = openssl_encrypt($crypto_binary, $crypto_settings['ciphers'][$i], substr($master_key, $master_key_used, $crypto_settings['key_lengths'][$i] / 8), OPENSSL_RAW_DATA, substr($master_key, $master_key_used + $crypto_settings['key_lengths'][$i] / 8, $crypto_settings['vector_lengths'][$i] / 8)); $master_key_used += ($crypto_settings['key_lengths'][$i] + $crypto_settings['vector_lengths'][$i]) / 8; } $crypto_binary = $salt.$crypto_binary; if (!mysqli_query($mysqli, 'UPDATE content_files SET crypto_binary="'.mysqli_real_escape_string($mysqli, $crypto_binary). '", crypto_settings="'.mysqli_real_escape_string($mysqli, serialize($crypto_settings)). '" WHERE id="'.$id. '" AND owner="'.$owner. '"')) { return false; } for ($chunk = 0; $chunk &lt; $chunks; $chunk++) { $file = fopen("content/$id", 'rb+'); if (!$file) { return false; } fseek($file, $chunk * $crypto_settings['chunk_size']); $data = fread($file, $crypto_settings['chunk_size']); for ($i = 0; $i &lt; count($crypto_settings['ciphers']); $i++) { $data = openssl_encrypt($data, $crypto_settings['ciphers'][$i], $keys[$chunk][$i], OPENSSL_RAW_DATA, $vectors[$chunk][$i]); } fseek($file, $chunk * $crypto_settings['chunk_size']); fwrite($file, $data); fclose($file); } return true; } public static function DecryptHeader($crypto_settings, $crypto_binary, $filesize, $password) { $chunks = ceil($filesize / $crypto_settings['chunk_size']); $salt = substr($crypto_binary, 0, $crypto_settings['salt_length'] / 8); $header = substr($crypto_binary, $crypto_settings['salt_length'] / 8); $master_key_length = 0; for ($i = 0; $i &lt; count($crypto_settings['ciphers']); $i++) { $master_key_length += ($crypto_settings['key_lengths'][$i] + $crypto_settings['vector_lengths'][$i]) / 8; } $master_key = openssl_pbkdf2($password, $salt, $master_key_length, $crypto_settings['pbkdf2_iterations'], $crypto_settings['pbkdf2_algorithm']); $master_key_used = 0; for ($i = count($crypto_settings['ciphers']) - 1; $i &gt;= 0; $i--) { $header = openssl_decrypt($header, $crypto_settings['ciphers'][$i], substr($master_key, -1 * $master_key_used - ($crypto_settings['key_lengths'][$i] + $crypto_settings['vector_lengths'][$i]) / 8, $crypto_settings['key_lengths'][$i] / 8), OPENSSL_RAW_DATA, substr($master_key, -1 * $master_key_used - ($crypto_settings['vector_lengths'][$i] / 8), $crypto_settings['vector_lengths'][$i] / 8)); $master_key_used += ($crypto_settings['key_lengths'][$i] + $crypto_settings['vector_lengths'][$i]) / 8; } if (substr($header, 0, 4) != "TRUE") { return false; } else { $header = substr($header, 4); } $keys = array(); $vectors = array(); $header_position = 0; for ($c = 0; $c &lt; $chunks; $c++) { $keys[$c] = array(); for ($n = 0; $n &lt; count($crypto_settings['ciphers']); $n++) { $keys[$c][$n] = substr($header, $header_position, $crypto_settings['key_lengths'][$n] / 8); $header_position += $crypto_settings['key_lengths'][$n] / 8; } } for ($c = 0; $c &lt; $chunks; $c++) { $vectors[$c] = array(); for ($n = 0; $n &lt; count($crypto_settings['ciphers']); $n++) { $vectors[$c][$n] = substr($header, $header_position, $crypto_settings['vector_lengths'][$n] / 8); $header_position += $crypto_settings['vector_lengths'][$n] / 8; } } return array('keys' = &gt; $keys, 'vectors' = &gt; $vectors); } public static function DecryptChunk($file, $crypto_settings, $header, $chunk) { fseek($file, $chunk * $crypto_settings['chunk_size']); $data = fread($file, $crypto_settings['chunk_size']); for ($i = count($crypto_settings['ciphers']) - 1; $i &gt;= 0; $i--) { $data = openssl_decrypt($data, $crypto_settings['ciphers'][$i], $header['keys'][$chunk][$i], OPENSSL_RAW_DATA, $header['vectors'][$chunk][$i]); } fseek($file, $chunk * $crypto_settings['chunk_size']); return $data; } public static function DecryptFile($owner, $id, $password) { // This requires PHP 5.5.0 or higher! global $mysqli; if (empty($owner) || empty($id) || !isset($password)) { return false; } if (!($file = mysqli_fetch_assoc(mysqli_query($mysqli, 'SELECT size, crypto_settings, crypto_binary FROM content_files WHERE owner="'.$owner. '" AND id="'.$id. '"')))) { return false; } if (!$file['crypto_settings'] || !$file['crypto_binary']) { return false; } $crypto_settings = unserialize($file['crypto_settings']); $crypto_binary = $file['crypto_binary']; $header = Filesystem::DecryptHeader($crypto_settings, $crypto_binary, $file['size'], $password); if (!$header) { return false; } for ($chunk = 0; $chunk &lt; count($header['keys']); $chunk++) { $handle = fopen("content/$id", 'rb+'); if (!$handle) { return false; } $data = Filesystem::DecryptChunk($handle, $crypto_settings, $header, $chunk); fwrite($handle, $data); fclose($handle); } if (!mysqli_query($mysqli, 'UPDATE content_files SET crypto_binary="", crypto_settings="" WHERE id="'.$id. '" AND owner="'.$owner. '"')) { return false; } return true; } </code></pre> <p>Here's what I currently have in the DB as the starting cipher settings:</p> <pre><code>a:7:{s:7:"ciphers";a:2:{i:0;s:16:"CAMELLIA-256-CFB";i:1;s:11:"AES-256-CFB";}s:11:"key_lengths";a:2:{i:0;i:256;i:1;i:256;}s:14:"vector_lengths";a:2:{i:0;i:128;i:1;i:128;}s:11:"salt_length";i:512;s:16:"pbkdf2_algorithm";s:9:"whirlpool";s:17:"pbkdf2_iterations";i:3996;s:10:"chunk_size";i:20971520;} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T04:26:42.280", "Id": "60287", "Score": "1", "body": "`mysqli_query()` input must be properly escaped. Can you guarantee this happens outside the `EncryptFile()` function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T04:27:37.403", "Id": "60288", "Score": "0", "body": "Oh no, I haven't actually put any effort at all into that yet, should've mentioned that! Right now $password comes directly from the outside, but I will validate it (it just won't happen here, it'll go in the ajax wrapper around these!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T04:30:34.557", "Id": "60289", "Score": "0", "body": "Actually the $id and $owner both originally come from the client as well, but those will be easy to validate since they're both 32-character alphanumerics." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T04:48:26.627", "Id": "60291", "Score": "4", "body": "Definitely need to look into prepared statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php - or better yet, use PDO: http://php.net/manual/en/book.pdo.php." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T11:19:18.160", "Id": "60480", "Score": "0", "body": "Aside from the obvious swap to prepared statements (don't use PDO unless you plan on swapping from mysql in future using mysqli prepares is just fine and pdo is horrible) the rest of the code relating to the crypto side of things looks ok to me, formatting seems nice and I can't see any obvious security holes or reasons for failure. Just makesure you validate all your inputs properly if they come from anywhere a user can provide them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:53:39.047", "Id": "60556", "Score": "0", "body": "I've never used prepared statements before, what's the benefit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T09:40:20.147", "Id": "60707", "Score": "1", "body": "@user3068322: The benefit is that without it your code is riddled with SQL-injection vulnerabilities that will allow remote attackers to take control of your website." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T23:20:12.307", "Id": "60779", "Score": "0", "body": "And using prepared statements makes you immune or just slightly more safe?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T03:30:07.910", "Id": "60946", "Score": "0", "body": "Should I implement some sort of data integrity check like calculating the CRC32 of the file and storing that in the header? Would that improve security?" } ]
[ { "body": "<ol>\n<li><p><a href=\"http://hu1.php.net/fwrite\" rel=\"nofollow noreferrer\">fwrite</a> returns <code>FALSE</code> on error. You should handle that to avoid dangerous silent data corruption.</p></li>\n<li><p>If you're using PHP 5.5 I guess you could <a href=\"https://stackoverflow.com/q/3549344/843804\">use exceptions</a> with detailed error messages instead of <code>false</code> return values. Getting different error messages for different type of errors makes development easier since it requires less debugging, developers don't have to dig into the called function to figure out which <code>return false</code> they got and what was its cause.</p></li>\n<li><blockquote>\n<pre><code>public static function EncryptFile($owner, $id, $password) { // This requires PHP 5.5.0 or higher!\n</code></pre>\n</blockquote>\n\n<p>You could put the comment a line before the function to avoid horizontal scrolling:</p>\n\n<pre><code>// This requires PHP 5.5.0 or higher!\npublic static function EncryptFile($owner, $id, $password) { \n</code></pre>\n\n<p>On the other hand you could automatize that with <a href=\"http://php.net/version_compare\" rel=\"nofollow noreferrer\"><code>version_compare</code></a> to avoid debugging and support calls by users with older PHP versions.</p></li>\n<li><p>Lines are too long, horizontal scrolling makes the code hard to read:</p>\n\n<blockquote>\n<pre><code>for ($i = 0; $i &lt; count($crypto_settings['ciphers']); $i++) {\n $crypto_binary = openssl_encrypt($crypto_binary, $crypto_settings['ciphers'][$i], substr($master_key, $master_key_used, $crypto_settings['key_lengths'][$i] / 8), OPENSSL_RAW_DATA, substr($master_key, $master_key_used + $crypto_settings['key_lengths'][$i] / 8, $crypto_settings['vector_lengths'][$i] / 8));\n $master_key_used += ($crypto_settings['key_lengths'][$i] + $crypto_settings['vector_lengths'][$i]) / 8;\n}\n</code></pre>\n</blockquote>\n\n<p>You could create some explanatory variables here:</p>\n\n<pre><code>for ($i = 0; $i &lt; count($crypto_settings['ciphers']); $i++) {\n $method = $crypto_settings['ciphers'][$i];\n $password = substr($master_key, $master_key_used, $crypto_settings['key_lengths'][$i] / 8);\n $options = OPENSSL_RAW_DATA;\n $iv = substr($master_key, $master_key_used + $crypto_settings['key_lengths'][$i] / 8, $crypto_settings['vector_lengths'][$i] / 8);\n\n $crypto_binary = openssl_encrypt($crypto_binary, $method, $password, $options, $iv);\n $master_key_used += ($crypto_settings['key_lengths'][$i] + $crypto_settings['vector_lengths'][$i]) / 8;\n}\n</code></pre>\n\n<p>This does not force readers to check the documentation of <code>openssl_encrypt</code> to understand its parameters and expresses the intent of the original author. If he mixed up two parameters it is easy to spot. (<code>$crypto_settings['key_lengths'][$i] / 8</code> also deserves a local variable here, it's used twice.)</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n<li><p>The following loop is duplicated:</p>\n\n<blockquote>\n<pre><code>for ($i = 0; $i &lt; count($crypto_settings['ciphers']); $i++) {\n $master_key_length += ($crypto_settings['key_lengths'][$i] + $crypto_settings['vector_lengths'][$i]) / 8;\n}\n</code></pre>\n</blockquote>\n\n<p>You should create a separate function for that to reduce the duplicated maintenance costs.</p></li>\n<li><p><code>4</code> is a magic number here:</p>\n\n<blockquote>\n<pre><code>if (substr($header, 0, 4) != \"TRUE\") {\n return false;\n} else {\n $header = substr($header, 4);\n}\n</code></pre>\n</blockquote>\n\n<p>Usually you should crate a named constant for it which expresses the intent but here I'd create a <a href=\"https://stackoverflow.com/q/834303/843804\"><code>startsWith</code></a> function for better readability:</p>\n\n<pre><code>$HEADER_PREFIX = \"TRUE\";\nif (!startsWith($header, $HEADER_PREFIX)) {\n return false;\n}\n$header = substr($header, strlen($HEADER_PREFIX));\n</code></pre>\n\n<p>Note the <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clause</a>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T18:59:43.630", "Id": "44524", "ParentId": "36679", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T03:00:47.350", "Id": "36679", "Score": "6", "Tags": [ "php", "ajax", "cryptography" ], "Title": "Cryptography implementation for a web-based file server" }
36679
<p>I have a number of text files (they are reports from a financial system) stored in a directory. Each report has a particular piece of text to search for (eg Report Total) and then a range of characters to extract for the value (e.g. position 78 for 10 characters). There are a number of these reports - but no more than 200 so not a huge amount of processing or work required.</p> <p>The premise of my solution is to maintain a simple CSV file with the report name, text to search for, start value for extract, length of characters to extract. Then, it is a simple case of updating this text file to add or remove the reports as necessary.</p> <p>The script I have developed is below, and it works, but I would be interested in some critique as to how it may be made "better".</p> <p>What needs changing/improving and why?</p> <pre><code>#!/usr/bin/perl -w use strict; use strict; use Data::Dumper; use Cwd; use Text::CSV; my $SrcDir="/data03/adudata/live/work/"; my $RepDir="/data03/adudata/live/archive/"; my $ReportList='pl_rec.list'; my $csv = Text::CSV-&gt;new(); my @FileToRead; my @TextToFind; my @RowsOffset; my @DataStart; my @DataEnd; my %ReportData; chdir $SrcDir; open my $fh, '&lt;', $ReportList or die "Could not open file"; while (my $row = $csv-&gt;getline( $fh )) { push (@FileToRead, $row-&gt;[0]); push (@TextToFind, $row-&gt;[1]); push (@RowsOffset, $row-&gt;[2]); push (@DataStart, $row-&gt;[3]); push (@DataEnd, $row-&gt;[4]); } close ($fh); for my $i(0 .. $#FileToRead) { open $fh, "&lt;", $RepDir.$FileToRead[$i]. ".prn" or die "Could not open $FileToRead[$i]"; while (&lt;$fh&gt;) { if (grep /$TextToFind[$i]/, $_) { my $extractValue = substr($_,$DataStart[$i],$DataEnd[$i]); $extractValue =~s/(^\s+)|(s+$)//g; $extractValue =~ s/,//g; $ReportData{$TextToFind[$i]} = $extractValue+0; } } close $fh; } while(my($code,$value)=each(%ReportData)){ print "$code,$value\n"; } </code></pre>
[]
[ { "body": "<p>The point of filehandles is that it allows you to open more than one file simultaneously. So you could be reading the file list and the files you're searching through simultaneously.</p>\n\n<p>Also, this:</p>\n\n<pre><code>if (grep /$TextToFind[$i]/, $_)\n</code></pre>\n\n<p>Is a a really convoluted way to write:</p>\n\n<pre><code>if (/$TextToFind[$i]/)\n</code></pre>\n\n<p>Overall, I'd do something like this:</p>\n\n<pre><code>#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\nuse Text::CSV;\n\nmy $SrcDir = \"/data03/adudata/live/work/\";\nmy $RepDir = \"/data03/adudata/live/archive/\";\nmy $ReportList = 'pl_rec.list';\n\nopen my $list_fh, '&lt;', $SrcDir.$ReportList\n or die \"Could not open $ReportList: $!\";\n\nmy %ReportData;\nmy $csv = Text::CSV-&gt;new();\n\nwhile (my $row = $csv-&gt;getline( $list_fh ))\n{\n my ($filename, $text, $rows_offset, $data_start, $data_end) = @$row;\n\n open my $fh, '&lt;', $RepDir.$filename\n or die \"Could not open $filename: $!\";\n\n while (&lt;$fh&gt;)\n {\n next unless /\\Q$text_to_find/;\n\n my $extractValue = substr($_, $data_start, $data_end);\n $extractValue =~ s/(^\\s+)|(s+$)//g;\n $extractValue =~ s/,//g;\n\n $ReportData{$text} = $extractValue + 0;\n }\n}\n\nfor (sort keys %ReportData)\n{\n my $value = $ReportData{$_};\n print \"$_,$value\\n\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:35:37.863", "Id": "60373", "Score": "0", "body": "Many thanks for the time to respond :) and for the pointers! I'll add those to my learnings!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-13T09:26:52.457", "Id": "145555", "Score": "0", "body": "`$_` used in loops... See my comment on the other answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-26T23:54:42.323", "Id": "148775", "Score": "0", "body": "Except that `while (<$fh>)` is valid syntax, and your suggestion is not. You may have meant `while (defined(my $line = <$fh>))`. However, using `$_` in a tight loop through a file is perfectly good, idiomatic Perl." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:53:51.397", "Id": "36682", "ParentId": "36681", "Score": "5" } }, { "body": "<p>This is pretty good for beginner code.</p>\n\n<p>Stating <code>use strict</code> twice does not make Perl any more strict. ☺ You have some extraneous requirements for <code>Cwd</code> and <code>Data::Dumper</code>.</p>\n\n<p>A more proper way to append a filename to a directory is to use <code>File::Spec-&gt;catfile()</code>.</p>\n\n<p>Since you operate on each row of the CSV file independently, there's no need to build up arrays like <code>@FileToRead</code> — just do the processing as you progress through the CSV.</p>\n\n<p>Strings interpolated inside a regular expression are treated as regular expressions. That is, if <code>$TextToFind</code> contains any \"special regex characters\" (e.g. <code>.</code>), they are not treated literally (e.g. match any character). If you want to do a string match for <code>$TextToFind</code> rather than a regular expression match, you can quote it as <code>/\\Q$TextToFind\\E/</code>.</p>\n\n<p>You can strip whitespace and commas in one substitution. You missed a backslash when specifying the trailing whitespace.</p>\n\n<pre><code>#!/usr/bin/perl -w\n\nuse strict;\nuse File::Spec;\nuse Text::CSV;\n\nmy $ReportList = 'pl_rec.list';\nmy $SrcDir = \"/data03/adudata/live/work/\";\nmy $RepDir = \"/data03/adudata/live/archive/\";\n\nmy %ReportData;\n\nsub process_row {\n my ($FileToRead, $TextToFind, $RowsOffset, $DataStart, $DataEnd) = @_;\n open my $fh, \"&lt;\", File::Spec-&gt;catfile($RepDir, \"$FileToRead.prn\")\n or die \"Could not open $FileToRead\";\n\n while (&lt;$fh&gt;) {\n if (grep /\\Q$TextToFind\\E/, $_) {\n my $extractValue = substr($_, $DataStart, $DataEnd);\n $extractValue =~ s/(^\\s+)|,|(\\s+$)//g;\n $ReportData{$TextToFind} = $extractValue + 0;\n }\n }\n close $fh;\n}\n\nopen my $fh, '&lt;', File::Spec-&gt;catfile($SrcDir, $ReportList)\n or die \"Could not open file\";\nmy $csv = Text::CSV-&gt;new();\nwhile (my $row = $csv-&gt;getline($fh)) {\n process_row(@$row);\n}\nclose ($fh);\n\nwhile (my ($code,$value) = each(%ReportData)) {\n print \"$code,$value\\n\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:36:38.307", "Id": "60374", "Score": "0", "body": "I hadn't noticed the double 'strict' declaration - would be funny if it DID make it extra strict!! As above, many thanks for taking the time to respond and show me different ways of achieving the result!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-13T09:25:54.367", "Id": "145554", "Score": "0", "body": "Don't use `$_`, instead implicitly state what you're doing/dealing with, i.e. `while my $line (<$fh>) { ..`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T07:59:40.720", "Id": "36688", "ParentId": "36681", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:45:17.657", "Id": "36681", "Score": "5", "Tags": [ "beginner", "file", "csv", "perl", "finance" ], "Title": "Reading CSV files pertaining to financial recorts" }
36681
<p>Other people will be looking at this jquery code and i'm not an expert with jQuery so im asking. How can i make this jQuery code shorter, more efficient, and easier to read? </p> <pre><code>/* HEADER NAVIGATION */ /* navigation tabs click highlight */ $(".header-main-tabs").click(function() { $(".header-main-tabs").removeClass("header-tab-selected"); $(this).addClass("header-tab-selected"); }); /* drop menu hide and show for desktop */ $(".header-main-tabs").hover(function() { $(this).children(".header-drop-menu").toggleClass("show-drop-menu-hover"); }); /* search input hide and show when search icon is pressed */ $("#search-icon-container span").click(function() { $(this).toggleClass("fa-times"); $("#search-input-container").fadeToggle("fast"); }); /* mobile navigation */ /* show mobile tabs when toggle nav mobile button is clicked and when browser width is over 990px */ /* toggle mobile navigation when nav button is clicked */ $("#toggle-mobile-nav").click(function() { $("#nav-tabs-list").slideToggle(); $("#toggle-mobile-nav").toggleClass("toggle-mobile-nav-clicked"); }); var browserWidth = $(window).width(); $(window).resize(function() { browserWidth = $(window).width(); if (browserWidth &gt; 990) { $("#nav-tabs-list").show(); } }); $('#nav-tabs-list li').click(function() { if (browserWidth &lt;= 990) { $('#nav-tabs-list').slideUp(); } }); /* always show drop menu when on mobile version (when browser width is below 960px) */ $(document).ready(function() { fadeMobile(); }); $(window).resize(function() { fadeMobile(); }); function fadeMobile() { browserWidth = $(window).width(); if (browserWidth &lt; 990) { $("#nav-tabs-list").hide(); $('.header-drop-menu').show(); $("#toggle-mobile-nav").removeClass("toggle-mobile-nav-clicked"); } } </code></pre>
[]
[ { "body": "<h2>Easier to Read</h2>\n\n<p>Make sure you use the same standard everywhere, indent nicely and be consistent. Then the code already looks a lot better:</p>\n\n<pre><code>/* \nHEADER NAVIGATION \n*/\n\n/* navigation tabs click highlight */\n$(\".header-main-tabs\").click(function() {\n $(\".header-main-tabs\").removeClass(\"header-tab-selected\");\n $(this).addClass(\"header-tab-selected\");\n});\n\n/* drop menu hide and show for desktop */\n$(\".header-main-tabs\").hover(function() {\n $(this).children(\".header-drop-menu\").toggleClass(\"show-drop-menu-hover\");\n});\n\n/* search input hide and show when search icon is pressed */\n$(\"#search-icon-container span\").click(function() {\n $(this).toggleClass(\"fa-times\");\n $(\"#search-input-container\").fadeToggle(\"fast\");\n});\n\n/* mobile navigation */\n/* show mobile tabs when toggle nav mobile button is clicked and when browser width is over 990px */\n/* toggle mobile navigation when nav button is clicked */\n$(\"#toggle-mobile-nav\").click(function() {\n $(\"#nav-tabs-list\").slideToggle();\n $(\"#toggle-mobile-nav\").toggleClass(\"toggle-mobile-nav-clicked\");\n});\n\nvar browserWidth = $(window).width();\n\n$(window).resize(function() {\n browserWidth = $(window).width();\n if (browserWidth &gt; 990) {\n $(\"#nav-tabs-list\").show();\n }\n});\n\n$('#nav-tabs-list li').click(function() {\n if (browserWidth &lt;= 990) {\n $('#nav-tabs-list').slideUp();\n }\n});\n\n/* always show drop menu when on mobile version (when browser width is below 960px) */\n$(document).ready(function() { \n fadeMobile(); \n});\n\n$(window).resize(function() { \n fadeMobile(); \n});\n\nfunction fadeMobile() {\n browserWidth = $(window).width(); \n if (browserWidth &lt; 990) { \n $(\"#nav-tabs-list\").hide();\n $('.header-drop-menu').show(); \n $(\"#toggle-mobile-nav\").removeClass(\"toggle-mobile-nav-clicked\");\n }\n}\n</code></pre>\n\n<h2>Shorter</h2>\n\n<ul>\n<li>Don't use <code>$('...')</code> twice for the same selector and don't use it in an event. Instead, save the element in a variable and use that. It's both faster and easier to read</li>\n<li>Group events on the same element. The first 2 events are both placed on <code>$('.header-main-tabs')</code>, group them together</li>\n<li>Put all code in the <code>$(document).ready()</code> callback, this will avoid \"DOM not ready\" errors</li>\n<li>Use CSS to hide/show elements, don't use jQuery for that</li>\n<li>Combine the same events, you now have 2 <code>$(window).resize()</code> events</li>\n<li>Don't show on each resize, only show if it was hidden before</li>\n<li>Don't use global variables to store data</li>\n</ul>\n\n\n\n<pre><code>/* \nHEADER NAVIGATION \n*/\n\n$(document).ready(function () {\n\n var $mainTabs = $(\".header-main-tabs\");\n var $searchInputContainer = $(\"#search-input-container\");\n\n $mainTabs\n .click(function() { // navigation tabs click highlight\n $mainTabs.removeClass(\"header-tab-selected\");\n\n $(this).addClass(\"header-tab-selected\");\n }) \n .hover(function() { // drop menu hide and show for desktop\n $(this).children(\".header-drop-menu\").toggleClass(\"show-drop-menu-hover\");\n });\n\n /* search input hide and show when search icon is pressed */\n $(\"#search-icon-container span\").click(function() {\n $(this).toggleClass(\"fa-times\");\n\n $searchInputContainer.fadeToggle(\"fast\");\n });\n\n /* mobile navigation */\n /* show mobile tabs when toggle nav mobile button is clicked and when browser width is over 990px */\n /* toggle mobile navigation when nav button is clicked */\n var $navTabsList = $(\"#nav-tabs-list\");\n var $toggleMobileNav = $(\"#toggle-mobile-nav\");\n var $headerDropMenu = $('.header-drop-menu');\n\n $toggleMobileNav.click(function() {\n $navTabsList.slideToggle();\n\n $toggleMobileNav.toggleClass(\"toggle-mobile-nav-clicked\");\n });\n\n $(window).resize(function() {\n browserWidth = $(window).width();\n\n if (browserWidth &gt; 990 &amp;&amp; $navTabsList.is(':hidden')) {\n $navTabsList.show();\n }\n\n fadeMobile();\n });\n\n $('li', $navTabsList).click(function() {\n if ($(window).width() &lt;= 990) {\n $navTabsList.slideUp();\n }\n });\n\n /* always show drop menu when on mobile version (when browser width is below 960px) */\n fadeMobile(); \n\n function fadeMobile(browserWidth) {\n if (browserWidth &lt; 990) { \n if ($navTabsList.is(':visible')) {\n $navTabsList.hide();\n }\n\n if ($headerDropMenu.is(':hidden')) {\n $headerDropMenu.show(); \n }\n\n if ($toggleMobileNav.hasClass('toggle-mobile-nav-clicked')) {\n $toggleMobileNav.removeClass(\"toggle-mobile-nav-clicked\");\n }\n }\n }\n\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T20:53:31.197", "Id": "36729", "ParentId": "36686", "Score": "2" } }, { "body": "<p>All changes are documented below, however here is a quick-hit list:</p>\n\n<blockquote>\n <ul>\n <li>contain everything in $(document).ready() to ensure elements exist before assigning handlers</li>\n <li>make better use of caching, <code>.find()</code>, and event delegation</li>\n <li>combine width-specific functions into a single item, with width passed as parameter</li>\n <li>make use of <code>.on()</code> rather than shorthand (<code>.click()</code>, <code>.hover()</code>) to combine bindings into a single handler</li>\n <li>split <code>hover</code> into <code>mouseenter</code> and <code>mouseleave</code> to prevent possible double-toggling</li>\n </ul>\n</blockquote>\n\n<p>Many of these not only make the code more readable, but makes runtime much faster by preventing excessive DOM querying, having smaller object sets to source from, consolidating similarly-applied code, and removal of unneeded code / event handlers.</p>\n\n<p>Here's a draft of the new setup:</p>\n\n<pre><code>/* contain everything within a $(document).ready() function to ensure elements \n* exist before handlers assigned to them - shorthand of $(function used here */\n\n$(function() {\n /* \n * cache objects used more than once, as well as appropriate children\n * make use of $(this) rather than re-querying the DOM\n * make use of .find() selector when caching children rather than requerying for a new object\n */\n var $mainTabs = $(\".header-main-tabs\"),\n $headerDropMenu = $mainTabs.children('.header-drop-menu'),\n $navTabsList = $(\"#nav-tabs-list\"),\n $searchInputContainer = $(\"#search-input-container\"),\n $toggleMobileNav = $(\"#toggle-mobile-nav\");\n\n /* place function declarations prior to event handlers in case any of the handlers use it,\n * and consolidate your winWidth-based logic into one function */\n function setMobile(winWidth) { \n /* this was two separate functions, since you run this every time you can consolidate */\n if (winWidth &lt;= 990) { \n $navTabsList.hide();\n $headerDropMenu.show(); \n $toggleMobileNav.removeClass(\"toggle-mobile-nav-clicked\");\n\n /* only bind the click handler if winWidth calls for it, and use delegation of click \n * events where possible, rather than using CSS selector */\n $navTabsList.on('click','li',function() { \n $navTabsList.slideUp();\n });\n } else {\n $navTabsList.show();\n $headerDropMenu.hide(); \n $toggleMobileNav.addClass(\"toggle-mobile-nav-clicked\");\n\n /* else remove the binding */\n $navTabsList.off('click');\n }\n }\n\n /* combine multiple on declarations into a single .on() binding */\n $mainTabs.on({\n click:function(){\n $mainTabs.removeClass(\"header-tab-selected\");\n $(this).addClass(\"header-tab-selected\");\n },\n /* separate hover event into mouseenter / mouseleave to prevent possible double-toggling,\n * which can happen on rapid hover changes and .toggleClass() */\n mouseenter:function(){\n $headerDropMenu.addClass(\"show-drop-menu-hover\");\n },\n mouseleave:function(){\n $headerDropMenu.removeClass(\"show-drop-menu-hover\");\n }\n });\n\n $searchInputContainer.on('click','span',function() {\n $(this).toggleClass(\"fa-times\");\n $searchInputContainer.fadeToggle(\"fast\");\n });\n\n $toggleMobileNav.on('click',function() {\n $navTabsList.slideToggle();\n $(this).toggleClass(\"toggle-mobile-nav-clicked\");\n });\n\n /* call your consolidated function, passing the width as parameter rather then\n * assigning to a variable within the function */\n setMobile($(window).width()); \n\n /* change to non-shorthand in case you wanted to add a different window \n * handler later ('load' to wait for images, for example). also, contain it within the \n * document.ready so that it doesnt accidentally fire before document.ready (bug in early \n * webkit versions) */\n $(window).on('resize',function() {\n setMobile($(window).width());\n });\n});\n</code></pre>\n\n<p>Here it is without the clutter of the comments:</p>\n\n<pre><code>$(function() {\n var $mainTabs = $(\".header-main-tabs\"),\n $headerDropMenu = $mainTabs.children('.header-drop-menu'),\n $navTabsList = $(\"#nav-tabs-list\"),\n $searchInputContainer = $(\"#search-input-container\"),\n $toggleMobileNav = $(\"#toggle-mobile-nav\");\n\n function setMobile(winWidth) { \n if (winWidth &lt;= 990) { \n $navTabsList.hide();\n $headerDropMenu.show(); \n $toggleMobileNav.removeClass(\"toggle-mobile-nav-clicked\");\n\n $navTabsList.on('click','li',function() { \n $navTabsList.slideUp();\n });\n } else {\n $navTabsList.show();\n $headerDropMenu.hide(); \n $toggleMobileNav.addClass(\"toggle-mobile-nav-clicked\");\n\n $navTabsList.off('click');\n }\n }\n\n $mainTabs.on({\n click:function(){\n $mainTabs.removeClass(\"header-tab-selected\");\n $(this).addClass(\"header-tab-selected\");\n },\n mouseenter:function(){\n $headerDropMenu.addClass(\"show-drop-menu-hover\");\n },\n mouseleave:function(){\n $headerDropMenu.removeClass(\"show-drop-menu-hover\");\n }\n });\n\n $searchInputContainer.on('click','span',function() {\n $(this).toggleClass(\"fa-times\");\n $searchInputContainer.fadeToggle(\"fast\");\n });\n\n $toggleMobileNav.on('click',function() {\n $navTabsList.slideToggle();\n $(this).toggleClass(\"toggle-mobile-nav-clicked\");\n });\n\n setMobile($(window).width()); \n\n $(window).on('resize',function() {\n setMobile($(window).width());\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T23:57:17.713", "Id": "36740", "ParentId": "36686", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T07:50:19.267", "Id": "36686", "Score": "2", "Tags": [ "javascript", "jquery", "animation" ], "Title": "Window-size-dependent navigation menu with animation effects" }
36686
<p>What can be improved in my code:</p> <pre><code> using (var oracleConnection = new OracleConnection(ConnectionString)) { using (var oracleCommand = oracleConnection.CreateCommand()) { oracleConnection.Open(); oracleCommand.CommandText = "SELECT * FROM table_sample Table_Sample WHERE table_sample.id &gt; 1000"; using (var reader = oracleCommand.ExecuteReader()) { while (reader.Read()) { int id = reader.GetValue(0); } } } } </code></pre> <p>As the most "dangerous" thing I see the ugly string statement for database query.</p> <p>I dont want to use Entity Framework for Oracle - cause its not as actual as one for MS SQL Server. And also some Oracle features are not supported.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T08:45:46.463", "Id": "60300", "Score": "1", "body": "You mean like having parametrized queries? Check the docs: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.110%29.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T08:49:47.880", "Id": "60302", "Score": "0", "body": "@ChrisWue maybe something that looks like EF syntax. Or anything else but not such a long string" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T08:51:05.077", "Id": "60303", "Score": "0", "body": "@ChrisWue have look at your link - as I understand it is only the opportunity to use parameters, but string itself stay as ugly as before :) But thanks for this link!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T11:03:23.197", "Id": "60314", "Score": "1", "body": "AFAIK, you can use EF with other databases, including Oracle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T11:05:56.480", "Id": "60315", "Score": "0", "body": "@svick its true. But the support for Oracle is not the best one. It is possible that in case of DB First some Oracle features cannot be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T11:37:03.943", "Id": "60317", "Score": "0", "body": "@MikroDel I don't see any Oracle-specific features in your code, so it looks like you didn't explain well what you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-30T19:47:41.100", "Id": "194538", "Score": "0", "body": "FYI I've used EF in combination with Oracle using https://www.devart.com/dotconnect/oracle/ ." } ]
[ { "body": "<p>You're using <code>using</code> blocks to dispose your disposables, which is excellent. However these blocks increase the nesting of your code; since there's nothing between <code>using (var oracleConnection = new OracleConnection(ConnectionString))</code> and <code>using (var oracleCommand = oracleConnection.CreateCommand())</code> you could drop the curly braces and \"stack\" them, like this:</p>\n\n<pre><code> using (var oracleConnection = new OracleConnection(ConnectionString))\n using (var oracleCommand = oracleConnection.CreateCommand())\n {\n ...\n }\n</code></pre>\n\n<p>Within that scope, you're reassigning variable <code>Id</code> at each row that gets read; ultimately the value of <code>Id</code> will be that of the last row that was read. I doubt this is the intended behavior.</p>\n\n<p>As for the string query, I agree it's \"dangerous\" - I prefer (by far) to use an object-relational mapper such as <strong>Entity Framework</strong> (which as @svick has mentioned has an Oracle provider), but never used it for anything other than SQL Server. I believe you could look into <strong>NHibernate</strong> as well, or shop around - something like <em>\".net ORM for oracle\"</em> should find you some interesting links :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:06:10.447", "Id": "36711", "ParentId": "36687", "Score": "5" } }, { "body": "<p>You have one or two issues in your SQL query:</p>\n\n<ul>\n<li><strong>Pointless table aliasing:</strong> You aliased the table <code>table_sample</code> as <code>Table_Sample</code>, which is pointless since identifiers in Oracle are case-insensitive.</li>\n<li><strong>Reliance on case-insensitivity of identifiers:</strong> Once you alias the table name, you are supposed to use the alias, not the original. Therefore, if you keep the pointless alias, your WHERE-clause should be <code>WHERE Table_Sample &gt; 1000</code> to be consistent. Your query happens to work, but only because Oracle identifiers are case-insensitive.</li>\n</ul>\n\n<p>The most obvious solution is to get rid of the alias:</p>\n\n<pre><code>\"SELECT * FROM table_sample WHERE table_sample.id &gt; 1000\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:15:31.223", "Id": "36720", "ParentId": "36687", "Score": "5" } }, { "body": "<p>I would not use <code>select *</code> as this will retrieve all the columns, instead you should be explicit as to what columns you want to retrieve. </p>\n\n<p>Another potential issue with <code>select *</code> and then calling <code>reader.getValue([index])</code> is that you are relying on the index you are using for each column to be the same as the the order which they are in the table - this isn't maintainable and open to bugs, again explicitly stating the columns will ensure that the order you are expecting the column data to be in is correct.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-30T17:44:09.903", "Id": "106162", "ParentId": "36687", "Score": "2" } } ]
{ "AcceptedAnswerId": "36711", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T07:52:22.750", "Id": "36687", "Score": "4", "Tags": [ "c#", "sql", "oracle" ], "Title": "Connecting to Oracle using ODP.NET" }
36687
<p>I have a program I am writing that calculates Algebra 2 functions and equations. The interface is all CLI, and I even made commands that are similar to shell commands. That's not the part I want review on, so in the interest of space I'm going to consolidate as much as possible. If you want to check out the full program so far, you can see it <a href="http://samrapdev.com/projects.php" rel="nofollow">here</a>.</p> <p>Tonight, I added a class and a few methods that factors the quadratic formula. The methods are capable of factoring when the <code>a</code> term is 1, or greater than 1.</p> <p>Here is the code relevant to the function:</p> <pre><code>class Factor(Formulas): #---------- factor quadratic equation def FactorQuad(self, aval, bval, cval): # if the a value is equal to 1, we can factor the standard way if aval == 1: common_factor = self.MultSum(bval, cval) if common_factor: print "(x + %s)" % common_factor[0] print "(x + %s)" % common_factor[1] return True else: return False # if the a value is greater than 1, we must factor by grouping else: multval = aval * cval common_factor = self.MultSum(bval, multval) group_one = [aval, common_factor[0]] group_two = [common_factor[1], cval] # abs() insures the gcd is not negative due to negative values # on the second terms of each group group_one_gcd = fractions.gcd(group_one[0], abs(group_one[1])) group_two_gcd = fractions.gcd(group_two[0], abs(group_two[1])) # this conditional makes sure not to ignore negative values # on the first terms of each group if group_one[0] &lt; 0: group_one_gcd *= -1 if group_two[0] &lt; 0: group_two_gcd *= -1 set_one = (group_one_gcd, group_two_gcd) set_two = (int(group_one[0] / group_one_gcd), int(group_one[1] / group_one_gcd)) print "(%sx + %s)(%sx + %s)" % (set_one[0], set_one[1], set_two[0], set_two[1]) #---------- multsum method def MultSum(self, bval, cval): """Find the number that multiplies to c and adds to b This is used to factor terms in the quadratic equation """ tries = 0 common_factor = 0 factor = abs(int(cval / 2)) while not common_factor: # first part of condition makes sure factor doesn't cause zero division error if factor and cval % factor == 0 and (factor + (cval / factor)) == bval: common_factor = factor if tries &gt; abs(cval * 2): print "Error: The quadratic equation is not factorable" return False factor -= 1 tries += 1 return (int(common_factor), int(cval / common_factor)) </code></pre> <p><strong>Brief explanation:</strong></p> <ul> <li><p>The <code>Factor</code> class inherits from the <code>Formulas</code> class which contains various basic calculations that can be used universally across functions and methods (reduce fractions, count significant figures, etc). In these methods shown here, none of the inheritance is used so I figured it was pointless to show the parent class.</p></li> <li><p>The <code>Factor</code> class will soon contain factorization methods for other equations, but right now it is just the quadratic.</p></li> <li><p>It contains two methods, one that factors the quadratic equation (<code>FactorQuad</code>) and one that finds the factors that multiply to the <code>c</code> value and add to the <code>b</code> value (<code>MultSum</code> for lack of a better name).</p></li> <li><p><code>FactorQuad</code> is separated into two parts - one if the <code>a</code> value of the quadratic is 1, which is fairly simple to calculate, and a second part if the <code>a</code> value is greater than 1, which requires factoring by grouping. </p></li> </ul> <p>I am hoping to get two things out of this review post:</p> <ul> <li><p><strong>I'd love to hear feedback on my code formatting, clarity of comments, and overall "cleanness" of the code.</strong> I only recently started writing useful programs over 50 lines long and I know that "clean code" is essential to programming. I'm really interested to see how I could improve formatting, docstrings, and comments.</p></li> <li><p><strong>I would also like to know if there are simpler ways to calculate the factorization.</strong> My particular concern is in the <code>MultSum</code> method. I feel like there must be a quicker way than looping through and checking a condition in every loop, but I'm missing it. Also, although factoring by grouping is more complicated than the first type of factoring, it seems like it could be shorter.</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T09:10:14.410", "Id": "60304", "Score": "0", "body": "Do you assume that a, b, and c are all positive integers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:03:26.287", "Id": "60369", "Score": "0", "body": "No @200_success it worked with negative integers despite the many bugs pointed out below" } ]
[ { "body": "<h3>1. Bugs</h3>\n\n<ol>\n<li><p>The code fails to factorize \\$x^2 + 2x + 1\\$:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; Factor().FactorQuad(1, 2, 1)\nError: The quadratic equation is not factorable\nFalse\n</code></pre>\n\n<p>It should print the factorization <code>(x + 1)(x + 1)</code>.</p>\n\n<p>This is caused by a bug in <code>MultSum</code> when <code>cval</code> is 1:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; Factor().MultSum(2, 1)\nError: The quadratic equation is not factorable\nFalse\n</code></pre>\n\n<p>It should return the pair <code>(1, 1)</code>. The problem here is that the loop starts at <code>int(cval / 2)</code>, but when <code>cval</code> is 1 then this is 0 and so the factor 1 is never considered.</p></li>\n<li><p>The code fails to factorize \\$x^2 + 2x\\$:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; Factor().FactorQuad(1, 2, 0)\nError: The quadratic equation is not factorable\nFalse\n</code></pre>\n\n<p>It should print the factorization <code>x(x + 2)</code>.</p>\n\n<p>This is caused by a bug in <code>MultSum</code> when <code>cval</code> is 0:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; Factor().MultSum(2, 0)\nError: The quadratic equation is not factorable\nFalse\n</code></pre>\n\n<p>It should return the pair <code>(2, 0)</code>.</p></li>\n<li><p>The code raises <code>TypeError</code> if I ask it to factorize \\$2x^2 + 2x + 1\\$:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; Factor().FactorQuad(2, 2, 1)\nError: The quadratic equation is not factorable\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"cr36689.py\", line 21, in FactorQuad\n group_one = [aval, common_factor[0]]\nTypeError: 'bool' object has no attribute '__getitem__'\n</code></pre>\n\n<p>That's because the function <code>MultSum</code> returns the exceptional value <code>False</code> if it fails. But <code>FactorQuad</code> neglects to check for this exceptional value.</p>\n\n<p>It is generally best in Python to handle exceptional cases by <em>raising an exception</em>, so in <code>MultSum</code> I would write:</p>\n\n<pre><code>raise ValueError(\"Quadratic expression is not factorable.\")\n</code></pre>\n\n<p>This would avoid the need to handle the exceptional return value in <code>FactorQuad</code>.</p></li>\n</ol>\n\n<h3>2. Other comments</h3>\n\n<ol>\n<li><p>The <code>Factor</code> class is unnecessary. In object-oriented programming, an object represents some <em>thing</em> and a class represents a <em>group of things</em> with similar behaviour.</p>\n\n<p>But an instance of the <code>Factor</code> class doesn't seem to be any kind of <em>thing</em>. It doesn't have any instance data. And the methods <code>FactorQuad</code> and <code>MultSum</code> make no essential use of <code>self</code>. You can see in the examples above that they all start by creating a <code>Factor()</code> object that is thrown away as soon as its method has been called. All this suggests that there is no need for the <code>Factor</code> class, and <code>FactorQuad</code> and <code>MultSum</code> could just be ordinary functions, not methods. (Most likely there is no need for the <code>Formulas</code> class either.)</p>\n\n<p>In some programming languages classes are also used as containers for functions. But in Python that's not necessary: you can collect functions into a <a href=\"http://docs.python.org/3/tutorial/modules.html\" rel=\"nofollow noreferrer\"><em>module</em></a>.</p></li>\n<li><p>The <code>FactorQuad</code> methods lacks a docstring. What does it do and how am I supposed to call it?</p></li>\n<li><p>Variables could be named <code>a</code>, <code>b</code> and <code>c</code> instead of <code>aval</code>, <code>bval</code> and <code>cval</code>.</p></li>\n<li><p>Instead of writing:</p>\n\n<pre><code>int(cval / 2)\n</code></pre>\n\n<p>make use of Python's <a href=\"http://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations\" rel=\"nofollow noreferrer\"><em>floor division</em></a> operator and write:</p>\n\n<pre><code>cval // 2\n</code></pre></li>\n<li><p>The docstring for <code>MultSum</code> says:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Find the number that multiplies to c and adds to b\n</code></pre>\n\n<p>but actually the method returns <em>two</em> numbers. The docstring needs to be something like this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Return a pair of integers (x, y) such that x+y = b and x*y = c.\nIf there are no such integers, raise ValueError.\n</code></pre></li>\n<li><p>The <code>MultSum</code> method loops over the numbers from <code>abs(int(cval / 2))</code> downwards to <code>abs(int(cval / 2)) - abs(cval * 2)</code>. The usual way to loop over numbers in a range in Python is to use the <a href=\"http://docs.python.org/3/library/functions.html#func-range\" rel=\"nofollow noreferrer\"><code>range</code></a> function. Here you might write something like:</p>\n\n<pre><code>c = abs(cval) // 2 + 1\nfor factor in range(-c, c + 1):\n # ...\n</code></pre></li>\n<li><p>If <code>aval</code> is 1, then <code>FactorQuad</code> prints the two factors on separate lines and returns <code>True</code>, otherwise it prints the two factors on the same line and returns <code>None</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; Factor().FactorQuad(1, 3, 2)\n(x + 1)\n(x + 2)\nTrue\n&gt;&gt;&gt; Factor().FactorQuad(2, 3, 1)\n(1x + 1)(2x + 1)\n</code></pre>\n\n<p>It would be better if the output were consistent in the two cases. Also, it would be nice to print <code>(x + 1)</code> instead of <code>(1x + 1)</code>.</p></li>\n<li><p>If any of the roots is positive, the printed results look poor:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; Factor().FactorQuad(1, -2, 1)\n(x + -1)\n(x + -1)\nTrue\n&gt;&gt;&gt; Factor().FactorQuad(2, -3, 1)\n(2x + -1)(1x + -1)\n</code></pre>\n\n<p>It would be nicer to print <code>(x - 1)</code> instead of <code>(x + -1)</code>.</p></li>\n<li><p>If \\$a\\$, \\$b\\$ and \\$c\\$ have a common divisor, that divisor is not pulled out of the factorization. For example: </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; Factor().FactorQuad(2, 4, 2)\n(2x + 2)(1x + 1)\n</code></pre>\n\n<p>It would be nicer to print <code>2(x + 1)(x + 1)</code> here.</p></li>\n</ol>\n\n<h3>3. An alternative approach</h3>\n\n<p>I'm sure you're familiar with the <a href=\"http://en.wikipedia.org/wiki/Quadratic_formula\" rel=\"nofollow noreferrer\">quadratic formula</a>: $$x = {−b ± \\sqrt{b^2 − 4ac} \\over 2a}$$ </p>\n\n<p>The expression \\$b^2 − 4ac\\$ (inside the square root) is known as the <a href=\"http://en.wikipedia.org/wiki/Discriminant\" rel=\"nofollow noreferrer\"><em>discriminant</em></a>. If this is a perfect square, then the quadratic equation has rational root(s); if not, the equation cannot be solved over the rational numbers.</p>\n\n<p>That suggests the following approach:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from math import sqrt\nfrom fractions import Fraction, gcd\n\ndef factorize_quadratic(a, b, c):\n \"\"\"Factorize the quadratic expression ax^2 + bx + c over the\n rational numbers and print the factorization. If this is not\n possible, raise ValueError.\n\n &gt;&gt;&gt; factorize_quadratic(1, 3, 2)\n (x + 1)(x + 2)\n &gt;&gt;&gt; factorize_quadratic(1, 3, 0)\n x(x + 3)\n &gt;&gt;&gt; factorize_quadratic(2, -9, -5)\n (2x + 1)(x - 5)\n &gt;&gt;&gt; factorize_quadratic(4, -12, 8)\n 4(x - 1)(x - 2)\n &gt;&gt;&gt; factorize_quadratic(1, -2, 1)\n (x - 1)^2\n &gt;&gt;&gt; factorize_quadratic(5, 0, 0)\n 5x^2\n &gt;&gt;&gt; factorize_quadratic(1, 3, 1)\n Traceback (most recent call last):\n ...\n ValueError: No factorization over the rationals.\n\n \"\"\"\n # Extract common factor, if any.\n f = abs(gcd(gcd(a, b), c))\n a, b, c = a // f, b // f, c // f\n\n # Is the discriminant a perfect square?\n discriminant = b * b - 4 * a * c\n root = int(sqrt(discriminant))\n if root * root != discriminant:\n raise ValueError(\"No factorization over the rationals.\")\n\n # The two roots of the quadratic equation.\n r, s = Fraction(-b - root, 2 * a), Fraction(-b + root, 2 * a)\n\n # Sort the roots by absolute value. (This step is purely for\n # the readability of the printed output: the intention is that\n # we get \"x(x + 1)\" instead of \"(x + 1)x\", and \"(x + 1)(x + 2)\"\n # instead of \"(x + 2)(x + 1)\".)\n r, s = sorted((r, s), key=abs)\n\n # Self-test: check that the factorization is correct.\n assert(r.denominator * s.denominator == a)\n assert(r.denominator * s.numerator + r.numerator * s.denominator == -b)\n assert(r.numerator * s.numerator == c)\n\n def maybe(x):\n if x == -1: return '-'\n if x == 1: return ''\n return x\n\n def factor(r):\n if r == 0: return \"x\"\n n, d = r.numerator, r.denominator\n return \"({}x {} {})\".format(maybe(d), '-+'[n &lt; 0], abs(n))\n\n if r == s:\n print(\"{}{}^2\".format(maybe(f), factor(r)))\n else:\n print(\"{}{}{}\".format(maybe(f), factor(r), factor(s)))\n</code></pre>\n\n<p>Note that the docstring for the function includes some example code. These examples can be executed using the <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> module.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:09:37.810", "Id": "60344", "Score": "0", "body": "Thank you for pointing out the bugs and I completely forgot about the quadratic formula, it's been two years since I took Algebra 1 and we haven't got to it yet in Alg2. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T13:17:22.593", "Id": "36695", "ParentId": "36689", "Score": "15" } } ]
{ "AcceptedAnswerId": "36695", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T08:57:51.250", "Id": "36689", "Score": "11", "Tags": [ "python", "algorithm", "mathematics", "symbolic-math" ], "Title": "Factoring quadratic equation" }
36689
<p>Below is a code snippet of how I have been laying out my WPF control XAML. I do it mainly because I get intellisense in the editor and I can change the implementation of the viewmodel and push the layout into a resource file.</p> <p>However, I am not sure whether you gurus have a better insight into why I should not do this?</p> <p>I'm just after a critique really.</p> <pre><code>&lt;UserControl.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="../../Styles/BaseStyles.xaml"/&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;DataTemplate x:Key="LayoutRoot" DataType="{x:Type ns:IViewModel}"&gt; &lt;Grid Height="200" Width="300"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Label Content="Some Label" Style="{StaticResource BoldLabel}" Margin="5, 0" Target="{Binding ElementName=Lcb1}"/&gt; &lt;endorsements:LimitComboBox Grid.Row="0" Grid.Column="1" x:Name="Lcb1" Limit="{Binding SomeData}" /&gt; &lt;Label Grid.Row="1" Grid.Column="0" Content="Some Other Label" Style="{StaticResource BoldLabel}" Margin="5, 0" Target={Binding ElementName=Lcb2/&gt; &lt;endorsements:LimitComboBox Grid.Row="0" Grid.Column="1" x:Name="Lcb2" Limit="{Binding SomeOtherData}" /&gt; &lt;StackPanel Grid.Row="3" Grid.Column="0" Orientation="Horizontal" HorizontalAlignment="Right" Grid.ColumnSpan="2"&gt; &lt;Button Content="OK" Command="{Binding ApplyCommand}" IsDefault="True"/&gt; &lt;Button Content="Cancel" IsCancel="True"/&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/ResourceDictionary&gt; </code></pre> <p></p> <p> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:34:42.890", "Id": "60382", "Score": "0", "body": "Could you explain how is this user control meant to be used?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:20:20.850", "Id": "60820", "Score": "0", "body": "It not so much about what the control does, but more about how to layout the markup. Instead of putting the markup directly into the body, I am placing it in a data template which may or may not be in the resources tag, then using a content presenter to display." } ]
[ { "body": "<p>There are 2 things that I could critisize on your code with the information you gave us:</p>\n\n<ol>\n<li>Don't load style resources inside the usercontrol. Let the application hold control over how to style a usercontrol</li>\n<li>Try not to use a grid in this context, because it prevents the control from adopting itself to new sizes of the window. StackPanels and Dockpanel are much better for this </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:37:14.403", "Id": "60383", "Score": "0", "body": "How exactly would another kind of panel help here? I think that `Grid` is ideal for this kind of label-value UIs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T07:03:00.233", "Id": "60458", "Score": "0", "body": "Well it depends where you will integrate that user control. If you know that that part of the UI never will get resized then you are fine using grid yes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:11:53.127", "Id": "36702", "ParentId": "36691", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T09:46:07.543", "Id": "36691", "Score": "3", "Tags": [ "c#", "wpf", "xaml" ], "Title": "Is this a good user control layout for WPF?" }
36691
<p>I'm new to ASP.Net and up until now my code has worked but has been a mish mash all over the place with no real structure. I'm trying to teach myself how to keep the presentation/BLL/DAL separate so I have built a simple page to try and work with. </p> <p>Page has 3 text boxes: clock number, first name and last name. On inputting a clock number in the clock number text box, I want to go off to my database and fetch the first name and last name of the person that clock number belongs to.</p> <p>My DAL consists of 3 classes as below:</p> <pre><code>Public Class EmployeeName Private _FirstName As String Private _Lastname As String Public Property FirstName() As String Get Return _FirstName End Get Set(value As String) _FirstName = value End Set End Property Public Property LastName() As String Get Return _Lastname End Get Set(value As String) _Lastname = value End Set End Property End Class Public Class EmployeeNameDBAccess Public Function GetEmployeeName(clockNo As Integer) As EmployeeName Dim employeeName As EmployeeName = Nothing Dim params As SqlParameter() = New SqlParameter() {New SqlParameter("@clockNo", clockNo)} Using tbl As DataTable = SMARTDBHelper.ExecuteParameterisedSelectCommand("getEmployeeName", CommandType.StoredProcedure, params) If tbl.Rows.Count = 1 Then Dim row As DataRow = tbl.Rows(0) employeeName = New EmployeeName employeeName.FirstName = row("INITIALS").ToString() employeeName.LastName = row("SURNAME").ToString() End If End Using Return employeeName End Function End Class Public Class SMARTDBHelper Const constr As String = "connection string goes here" Friend Shared Function ExecuteParameterisedSelectCommand(cmdName As String, cmdType As CommandType, param As SqlParameter()) As DataTable Dim tbl As New DataTable() Using con As New SqlConnection(constr) Using cmd As SqlCommand = con.CreateCommand() cmd.CommandType = cmdType cmd.CommandText = cmdName cmd.Parameters.AddRange(param) Try If con.State &lt;&gt; ConnectionState.Open Then con.Open() End If Using da As New SqlDataAdapter(cmd) da.Fill(tbl) End Using Catch ex As Exception Throw End Try End Using End Using Return tbl End Function End Class </code></pre> <p>My BLL consists of the following class</p> <pre><code>Public Class EmployeeNameHandler Private employee As EmployeeNameDBAccess Public Sub New() employee = New EmployeeNameDBAccess() End Sub Public Function GetFirstname(clockNo As Integer) As String Dim emp = employee.GetEmployeeName(clockNo) Return emp.FirstName End Function Public Function GetLastname(clockNo As Integer) As String Dim emp = employee.GetEmployeeName(clockNo) Return emp.LastName End Function End Class </code></pre> <p>Then on my page I have the following code to populate the text boxes</p> <pre><code>Protected Sub txtCLock_TextChanged(sender As Object, e As EventArgs) Handles txtCLock.TextChanged Dim emp As New EmployeeNameHandler Dim cn As Integer = CInt(txtCLock.Text) Dim firstname = emp.GetFirstname(cn) Dim lastname = emp.GetLastname(cn) txtFirstName.Text = firstname txtLastName.Text = lastname End Sub </code></pre> <p>I appreciate this is basic however I would be interested to gather opinion of if I am going down the correct route here? Could this be done in a better way? Also, there is next to no error handling here, this is a topic I'm very weak on so would appreciate any advice etc. Thanks</p>
[]
[ { "body": "<p>Just a few suggestions:</p>\n\n<p>Probably advisable to use Int.TryParse instead of CInt(txtCLock.Text) for parsing user input so you don't get an invalid type exception.</p>\n\n<p>On general error handling you might at least put a try/catch around the logic in txtCLock_TextChanged to catch any errors at a lower layer and either log them or present to the user in a nice way if applicable.</p>\n\n<p>If you're not actually referencing the first/last name backing fields you can use <a href=\"http://msdn.microsoft.com/en-us/library/dd293589.aspx\" rel=\"nofollow\">automatic properties</a> so you don't have to write a get/set for every property.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:17:43.517", "Id": "36731", "ParentId": "36692", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T11:01:10.843", "Id": "36692", "Score": "1", "Tags": [ "asp.net", "vb.net" ], "Title": "Separating presentation/BLL/DAL" }
36692
<p>I have a folder called uploads in this folder is a folder for the year the file was uploaded(2013,2014,2015 etc...), inside the year folder are usernames(rick, dan, edward etc...), inside the usernames folder are folders 1-12 for the month that the file was uploaded.</p> <p>I want to search through the folders and if there is a file in the folder display the link, the problem I am having is figuring out how to do the check on all of the folders:</p> <p>Here is my code so far:</p> <pre><code>&lt;?php //array for years to check for $year = array('2013','2014','2015','2016','2017','2018','2019','2020'); $month = array('1','2','3','4','5','6','7','8','9','10','11','12'); //loop through years array and populate $existingYears[] array with years that exist on server foreach($year as $years){ if(is_dir($yearPath = ABSPATH."/"."uploads/".$years."/".$username)){ $existingYears[] = $years; } } //loop through existings years foreach($existingYears as $year){ //title print "&lt;h1&gt;".$year."&lt;/h1&gt;"; //loop for months for ($i=1; $i&lt;=12; $i++) { if($i == 1){ $title = "January"; } elseif($i == 2){ $title = "February"; }elseif($i == 3){ $title = "March"; }elseif($i == 4){ $title = "April"; }elseif($i == 5){ $title = "May"; }elseif($i == 6){ $title = "June"; }elseif($i == 7){ $title = "July"; }elseif($i == 8){ $title = "August"; }elseif($i == 9){ $title = "September"; }elseif($i == 10){ $title = "October"; }elseif($i == 11){ $title = "November"; }elseif($i == 12){ $title = "December"; } //path to months directories $url=$userPath.'/'.$i; $newUrl = $url.'/'.$files[2]; print $newUrl; //check if directory exists if(is_dir($url)){ //assign open state to $dir $dir = opendir($url); //add all files to $files[] array while (($file = readdir($dir)) !== false){ $files[] = $file; } closedir($dir); //display link to payslips print "&lt;div class='month-box' id='box$i'&gt;"; print "&lt;h2&gt;".$title."&lt;/h2&gt;"; print "&lt;a class='download-link' id='download-link-$i' href='".$host."/uploads/".$year.'/'.$username.'/'.$i.'/'.$files[2]."'&gt;Download&lt;/a&gt;"; print "&lt;/div&gt;"; } } } ?&gt; </code></pre> <p>Very messy I know, I am sure there is a better way to do this just not sure how.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:58:39.307", "Id": "60367", "Score": "0", "body": "Where do you initialize `$username` and `$userPath` ?" } ]
[ { "body": "<p>You might want to try using the <a href=\"http://php.net/manual/en/function.scandir.php\" rel=\"nofollow\">scandir</a> function to build your arrays of directories and files, makes it a bit more future proof.</p>\n\n<pre><code>$baseDir = ABSPATH.\"/uploads\";\n$calendarinfo = cal_info(0); //built-in function to generate calendar info, e.g. month names\n$years = scandir($baseDir);\n\n//You might want to ignore certain folders, e.g. on UNIX systems:\n$ignore = [\".\",\"..\",\".DS_Store\"];\n\nforeach ($years as $year) {\n\n if (!in_array($year, $ignore)) { //the folder is not in the ignore array\n\n //then scan the year directory for user folders\n $users = scandir($baseDir.\"/\".$year);\n foreach ($users as $user) {\n\n if ($user == $username) { //if the year contains a folder belonging to logged in user\n echo \"&lt;h1&gt;\".$year.\"&lt;/h1&gt;\"; //create a year heading\n $months = scandir($baseDir.\"/\".$year.\"/\".$user); //scan it for month folders\n foreach ($months as $month) { //scan for month folders\n\n if (!in_array($month, $ignore)) { //ignore specified folders\n\n echo \"&lt;div class='month-box' id='box$month'&gt;\";\n echo \"&lt;h2&gt;\".$calendarinfo[\"months\"][$month].\"&lt;/h2&gt;\";\n\n $contents = scandir($baseDir.\"/\".$year.\"/\".$user.\"/\".$month); //scan each month folder\n foreach ($contents as $key=&gt;$item) { //for every item found in the month folder\n\n if (!is_dir($baseDir.\"/\".$year.\"/\".$user.\"/\".$month.\"/\".$item)) { //ignore directories\n //and list out the files\n echo \"&lt;a class='download-link' id='download-link-$key' href='\".$host.\"/uploads/\".$year.'/'.$username.'/'.$month.'/'.$item.\"'&gt;Download&lt;/a&gt;\";\n }\n }\n\n echo \"&lt;/div&gt;\";\n\n }\n }\n }\n }\n}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:59:28.030", "Id": "60435", "Score": "0", "body": "+1 for `cal_info`. I'd never seen that before. Strange that it has a single `maxdaysinmonth` instead of the number of days in each month, but still handy for getting the month names." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T14:53:06.360", "Id": "36701", "ParentId": "36694", "Score": "2" } } ]
{ "AcceptedAnswerId": "36701", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T12:18:45.077", "Id": "36694", "Score": "2", "Tags": [ "php", "file-system" ], "Title": "Search through server folders and display files that exist" }
36694
<p>I am working on using monad transformers in C#. I would like to know if the following code I present, shows that I have understood this. I am fairly new to this so any feedback / comments are really welcome. This example is just for wrapping a maybe monad in a validation monad.</p> <pre><code>using System; using NUnit.Framework; namespace Monads { public static class MaybeExtensions { public static IMaybe&lt;T&gt; ToMaybe&lt;T&gt;(this T value) { if (value == null) return new None&lt;T&gt;(); return new Just&lt;T&gt;(value); } } public interface IMaybe&lt;T&gt; { IMaybe&lt;U&gt; Select&lt;U&gt;(Func&lt;T, U&gt; f); IMaybe&lt;U&gt; SelectMany&lt;U&gt;(Func&lt;T, IMaybe&lt;U&gt;&gt; f); U Fold&lt;U&gt;(Func&lt;U&gt; error, Func&lt;T,U&gt; success); } public class Just&lt;T&gt; : IMaybe&lt;T&gt; { public Just(T value) { this.value = value; } public IMaybe&lt;U&gt; Select&lt;U&gt;(Func&lt;T, U&gt; f) { return f(value).ToMaybe(); } public IMaybe&lt;U&gt; SelectMany&lt;U&gt;(Func&lt;T, IMaybe&lt;U&gt;&gt; f) { return f(value); } public U Fold&lt;U&gt;(Func&lt;U&gt; error, Func&lt;T,U&gt; success) { return success(value); } public IValidation&lt;U,T&gt; ToValidationT&lt;U&gt;() { return new ValidationMaybeT&lt;U,T&gt;(this, default(U)); } private readonly T value; } public class None&lt;T&gt; : IMaybe&lt;T&gt; { public IMaybe&lt;U&gt; Select&lt;U&gt;(Func&lt;T, U&gt; f) { return new None&lt;U&gt;(); } public IMaybe&lt;U&gt; SelectMany&lt;U&gt;(Func&lt;T, IMaybe&lt;U&gt;&gt; f) { return new None&lt;U&gt;(); } public U Fold&lt;U&gt;(Func&lt;U&gt; error, Func&lt;T,U&gt; success) { return error(); } public IValidation&lt;U,T&gt; ToValidationT&lt;U&gt;(U exceptionalValue) { return new ValidationMaybeT&lt;U,T&gt;(this, exceptionalValue); } } public class Customer { public Customer(string name) { Name = name; } public string Name{ get; set; } } public interface IValidation&lt;T,U&gt; { IValidation&lt;T,V&gt; Select&lt;V&gt;(Func&lt;U,V&gt; f); IValidation&lt;T,V&gt; SelectMany&lt;V&gt;(Func&lt;U,IValidation&lt;T,V&gt;&gt; f); } public class ValidationError&lt;T,U&gt; : IValidation&lt;T,U&gt; { public ValidationError(T error) { Error = error; } public IValidation&lt;T, V&gt; Select&lt;V&gt;(Func&lt;U, V&gt; f) { return new ValidationError&lt;T, V&gt;(Error); } public IValidation&lt;T, V&gt; SelectMany&lt;V&gt;(Func&lt;U, IValidation&lt;T, V&gt;&gt; f) { return new ValidationError&lt;T, V&gt;(Error); } public T Error{ get; private set; } } public class ValidationSuccess&lt;T,U&gt; : IValidation&lt;T,U&gt; { public ValidationSuccess(U value) { Result = value; } public IValidation&lt;T, V&gt; Select&lt;V&gt;(Func&lt;U, V&gt; f) { return new ValidationSuccess&lt;T, V&gt;(f(Result)); } public IValidation&lt;T, V&gt; SelectMany&lt;V&gt;(Func&lt;U, IValidation&lt;T, V&gt;&gt; f) { return f(Result); } public U Result{ get; private set; } } public class ValidationMaybeT&lt;T,U&gt; : IValidation&lt;T,U&gt; { public ValidationMaybeT(IMaybe&lt;U&gt; value, T error) { Value = value; Error = error; } public IValidation&lt;T, V&gt; Select&lt;V&gt;(Func&lt;U, V&gt; f) { return Value.Fold&lt;IValidation&lt;T, V&gt;&gt;(() =&gt; new ValidationError&lt;T,V&gt;(Error), s =&gt; new ValidationSuccess&lt;T,V&gt;(f(s))); } ValidationError&lt;T, V&gt; SelectManyError&lt;V&gt;() { return new ValidationError&lt;T, V&gt;(Error); } public IValidation&lt;T, V&gt; SelectMany&lt;V&gt;(Func&lt;U, IValidation&lt;T, V&gt;&gt; f) { return Value.Fold(() =&gt; SelectManyError &lt;V&gt;(), s =&gt; f(s)); } public IMaybe&lt;U&gt; Value{ get; private set; } public T Error{ get; private set; } } public interface ICustomerRepository { IValidation&lt;Exception,Customer&gt; GetById(int id); } public class CustomerRepository : ICustomerRepository { public IValidation&lt;Exception,Customer&gt; GetById(int id) { if (id &lt; 0) return new None&lt;Customer&gt;().ToValidationT&lt;Exception&gt;(new Exception("Customer Id less than zero")); return new Just&lt;Customer&gt;(new Customer("Structerre")).ToValidationT&lt;Exception&gt;(); } } public interface ICustomerService { void Delete(int id); } public class CustomerService : ICustomerService { public CustomerService(ICustomerRepository customerRepository) { this.customerRepository = customerRepository; } public void Delete(int id) { customerRepository.GetById(id) .SelectMany(x =&gt; SendEmail(x).SelectMany(y =&gt; LogResult(y))); } public IValidation&lt;Exception,Customer&gt; LogResult(Customer c) { Console.WriteLine("Deleting: " + c.Name); return new ValidationSuccess&lt;Exception,Customer&gt;(c); //return new ValidationError&lt;Exception, Customer&gt;(new Exception("Unable write log")); } private IValidation&lt;Exception,Customer&gt; SendEmail(Customer c) { Console.WriteLine("Emailing: " + c.Name); return new ValidationSuccess&lt;Exception,Customer&gt;(c); } ICustomerRepository customerRepository; } [TestFixture] public class MonadTests { [Test] public void Testing_With_Maybe_Monad() { new CustomerService(new CustomerRepository()).Delete(-1); } } } </code></pre> <p>Another smaller sub question is if C# had higher kinded types could I just implement this class once (ValidationT) and it work for all other wrapped monads or is this incorrect?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:52:21.497", "Id": "60339", "Score": "0", "body": "+1 for the effort, but I wonder if maybe the non-standard names will be confusing to people familiar with monads? For instance, it looks like your `Select` is often called `map` and `SelectMany` is often called `bind`. (Not a criticism, just an observation)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:00:44.347", "Id": "60340", "Score": "3", "body": "@MattFenwick: You are completely correct, however much of LINQ is inspired by monads and C# uses the terms Select and SelectMany instead of map and bind. It does this faithfully enough that anybody writing monadic code in C# should be quite comfortable using Select/SelectMany." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:06:34.177", "Id": "60341", "Score": "6", "body": "I question whether monad transformers are a good idea in C#. For one, they already are semi-unpleasant to use in Haskell (Many people want a better system for combining effects) and two, the reason why they don't suck is because of the typeclass-y prolog we do to make it so that operations like `get`, `put`, and `tell` automagically propogate up a monad stack, this isn't possible in C#. You'd end up with the dreaded `lift(lift(lift(foo)))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:29:13.913", "Id": "60342", "Score": "0", "body": "Just a note, your validation type can be generalized to the [Either type](http://www.scala-lang.org/api/2.9.2/scala/Either.html), or disjoint union." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T00:59:03.277", "Id": "60343", "Score": "0", "body": "@jozefg Are you saying that because you have type classes in Haskell / Scala you do not need to manually convert like how I do with .ToTValidationT()? Secondly I am unsure what you mean by the operations get / put and lift? Can you further explain?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T10:00:50.913", "Id": "60469", "Score": "0", "body": "Question of 'Is this a Monad?' aside, add a `remove(Customer)` method to repository and show us how you would *bind* `getById` and `remove` as you would in an actual `Delete`. write the same code with `if`&`try` statements an compare. What happens to the exceptions we get from repository etc when we `Delete`?" } ]
[ { "body": "<p>There isn't much to review here. However I did find this:</p>\n\n<blockquote>\n<pre><code>public class CustomerRepository : ICustomerRepository\n{\n public IValidation&lt;Exception,Customer&gt; GetById(int id)\n {\n if (id &lt; 0)\n return new None&lt;Customer&gt;().ToValidationT&lt;Exception&gt;(new Exception(\"Customer Id less than zero\"));\n\n return new Just&lt;Customer&gt;(new Customer(\"Structerre\")).ToValidationT&lt;Exception&gt;();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Here I find the condition would be best written like this:</p>\n\n<pre><code>if (id &lt; 0)\n{\n var exception = new Exception(\"Customer Id is less than zero\");\n return new None&lt;Customer&gt;().ToValidationT&lt;Exception&gt;(exception);\n}\nelse\n{\n return new Just&lt;Customer&gt;(new Customer(\"Structerre\")).ToValidationT&lt;Exception&gt;();\n}\n</code></pre>\n\n<p>And as I typed this I noticed you were instantiating <code>System.Exception</code>. You should be using a more specific exception here, <code>InvalidArgumentException</code> seems appropriate - throwing <code>System.Exception</code> is bad.</p>\n\n<p>Also the <code>CustomerService</code> is tied to the <code>Console</code>, you may prefer injecting some <code>IServiceOutputProvider</code> which could be implemented with console output, but just as well with a MessageBox output - basically <code>CustomerService</code> has too many responsibilities here, writing to the console has nothing to do with logging results or sending an email.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T23:38:36.400", "Id": "62759", "Score": "0", "body": "I don't agree with using if-else and bracers and stuff here, but throwing a more specific exception is good advice. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T23:43:57.557", "Id": "62761", "Score": "0", "body": "@SimonAndréForsberg instantiating the exception on the same line as instantiating the `None<T>` and calling the `.ToValidationT<T>` is a little too much to put on a single line. It deserves a scope. Thus a proper `else` block." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T23:24:28.923", "Id": "37786", "ParentId": "36699", "Score": "1" } }, { "body": "<h1>Maybe</h1>\n\n<p>If you're writing a maybe monad, it's very informative to think about <code>IEnumerable&lt;T&gt;</code>. Maybe can be thought of as a special type of enumerable, which instead of having 0, 1 or many items, can only have 0 or 1 items.</p>\n\n<p>Thought of that way, you can transform any <code>IEnumerable&lt;T&gt;</code> to a <code>IMaybe&lt;T&gt;</code> simply by calling <code>.Take(1)</code>. So to start off, we can create a wrapped enumerable:</p>\n\n<pre><code>public class Maybe&lt;T&gt;\n{\n internal IEnumerable&lt;T&gt; _inner;\n\n internal Maybe&lt;T&gt;(IEnumerable&lt;T&gt; inner)\n {\n _inner = inner.Take(1);\n }\n\n public T Value =&gt; _inner.First();\n public bool HasValue =&gt; _inner.Any(); \n}\n</code></pre>\n\n<p>Now we have a <code>Maybe</code>, but we can't really do anything with it. I already decided that the constructor shouldn't be exposed publicly, its behaviour seems too confusing to expose directly to consumers.</p>\n\n<p>LINQ-to-Objects can give us another hint here: static constructors and extension methods are likely to be very powerful. Let's start with:</p>\n\n<pre><code>public static class Maybe\n{\n public static Maybe&lt;T&gt; None&lt;T&gt;()\n {\n return new Maybe&lt;T&gt;(Enumerable.Empty&lt;T&gt;());\n }\n\n public static Maybe&lt;T&gt; Some&lt;T&gt;(T value)\n {\n return new Maybe&lt;T&gt;(Enumerable.Repeat(value,1));\n }\n\n public static Maybe&lt;U&gt; Select(Maybe&lt;T&gt; source, Func&lt;T,U&gt; selector)\n {\n return new Maybe&lt;T&gt;(source._inner.Select(selector));\n }\n}\n</code></pre>\n\n<p>Now we have a start, we can compare across to yours:</p>\n\n<ul>\n<li>I picked \"Some\" instead of \"Just\" because I think it's a more conventional name for this</li>\n<li>By making <code>Select</code> an extension method, we don't have to do a separate implementation for the cases of having and not having a value.</li>\n<li>We're able to easily make use of LINQ for trivial implementations of most of the methods we want.</li>\n<li>For free we get LINQ's lazy evaluation, which is idiomatic here</li>\n</ul>\n\n<p>Probably the best way to decide what extension methods to include is to look at LINQ and decide what methods are applicable, and whether they need to be renamed. For example, <code>Where</code> is useful, but might be better named <code>If</code>. <code>Concat</code> is also useful if we think of it as <code>Coalesce</code> (in the same sense as null coalescing).</p>\n\n<p>However, we're sort of cheating here. By making <code>_inner</code> internal, we can write the extension methods we need, but only in this project. By contrast, <code>IEnumerable&lt;T&gt;</code> lets anyone extend it by exposing the underlying properties needed to use it. </p>\n\n<p>We could fix this by just exposing <code>_inner</code>, but this again is potentially confusing to consumers, and could be thought of as an implementation detail. It's somewhat a judgement call, but an alternative would be:</p>\n\n<pre><code>public class Maybe&lt;T&gt;\n{\n // ...\n\n public Maybe&lt;U&gt; Map(Func&lt;IEnumerable&lt;T&gt;,IEnumerable&lt;U&gt;&gt; transform)\n {\n return new Maybe&lt;U&gt;(transform(_inner));\n }\n}\n</code></pre>\n\n<p>Now our <code>Select</code>, for example, becomes:</p>\n\n<pre><code>public static Maybe&lt;U&gt; Select&lt;T,U&gt;(this Maybe&lt;T&gt; source, Func&lt;T,U&gt; selector)\n{\n source.Map(_inner =&gt; _inner.Select(selector));\n}\n</code></pre>\n\n<p>This leaves us with a minimal interface for <code>Maybe&lt;T&gt;</code>, which shouldn't need to be modified or extended.</p>\n\n<hr>\n\n<h1>Either</h1>\n\n<p>As Matt H mentioned, it's probably more useful to think of your \"Validation\" class as an \"Either\". This is a useful decoupling of what functionality the class provides and what you happen to be using that functionality for. You should also keep that in mind with your <code>Maybe</code> implementation. For example, your <code>Fold</code> uses the names <code>success</code> and <code>error</code>, but in general there's no reason to think that having a value indicates success and not having a value indicates an error. Perhaps you have a <code>Maybe&lt;Exception&gt;</code>!</p>\n\n<p>In the same way that Maybe can be thought of as \"IEnumerable with the restriction that there is at most one value\", Either can be thought of as \"Tuple of Maybes with the restriction that exactly one has a value\". So we can do the same process of encoding this in the class via the constructors:</p>\n\n<pre><code>public class Either&lt;T,U&gt;\n{\n Tuple&lt;Maybe&lt;T&gt;,Maybe&lt;U&gt;&gt; _inner;\n\n internal Either(Tuple&lt;Maybe&lt;T&gt;,Maybe&lt;U&gt;&gt; inner)\n {\n _inner = inner;\n }\n\n public V Fold(Func&lt;T,V&gt; selectOne, Func&lt;U,V&gt; selectTwo)\n {\n var left = _inner.ItemOne.Select(selectOne);\n var right = _inner.ItemTwo.Select(selectTwo);\n\n return left.Coalesce(right).Value;\n }\n}\n</code></pre>\n\n<p>We can now go through the same process of static constructors (one for the \"left has value\" case, one for the \"right has value\" case), exposing a single method that lets us write any extension methods we need, and then writing relevant extension methods. By comparison to the version in the question, this leaves us with:</p>\n\n<ul>\n<li>Only one actual implementing class, with extension methods not caring about whether the left or right has the value</li>\n<li>A class which is general enough to be used for validation, but also other purposes</li>\n<li>Easy extensibility</li>\n<li>A nice general mechanism for getting values (note if we wanted something more tailored to validation, we could write an extension method like: <code>T GetOrThrow&lt;T&gt;(this Either&lt;T,Exception&gt; source);</code></li>\n</ul>\n\n<hr>\n\n<p>As a side note, this is a good demonstration of the power of <em>invariants</em>. By carefully protecting state, we've managed to transform <code>IEnumerable&lt;T&gt;</code> into <code>Maybe&lt;T&gt;</code>, and <code>Tuple&lt;Maybe&lt;T&gt;,Maybe&lt;U&gt;&gt;</code> into <code>Either&lt;T,U&gt;</code>, just by adding a straightforward restriction to each one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-22T16:35:25.890", "Id": "114766", "ParentId": "36699", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:22:50.407", "Id": "36699", "Score": "10", "Tags": [ "c#", "functional-programming", "validation", "null", "monads" ], "Title": "Monad transformers in C# for use in validation" }
36699
<p>I wrote this code in Java without using any methods, just by using simple <code>for</code> loop and <code>if</code> statements.</p> <p>When we input a number, it checks whether it's a prime or not. If it's a prime, then it prints "It's a prime". And if it's not a prime number, it says "It's not a prime" and prints the first number which divides it.</p> <p>For example, if we input 1457, it will output "1457 is not a prime 1457 Divide by 31".</p> <p>I want to know whether or not I can make this coding shorter.</p> <pre><code>import java.util.*; public class PrimeNum{ public static void main(String args[]){ Scanner x=new Scanner(System.in); System.out.println("Enter the number : "); long y=x.nextLong(); long i; for( i=2;i&lt;y;i++){ long z=y%i; if(z==0){ System.out.println(y+" is not a prime"); System.out.println(y+" Divide by "+i); i=y; } }if(i==y) System.out.println("Number is prime"); if(y==1) System.out.println("Number 1 is not a prime"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:15:34.890", "Id": "60351", "Score": "0", "body": "You wrote what code ?!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:18:01.860", "Id": "60352", "Score": "1", "body": "Could you please describe what you mean by 'short'? Length of code? How fast it runs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:23:12.700", "Id": "60353", "Score": "0", "body": "What i mean by short is , the length of the code ? :)" } ]
[ { "body": "<p>You don't have to iterate from 2 to y.</p>\n\n<p>It's enough to iterate from 2 to sqrt(y).</p>\n\n<p>This is not necessarily a Java optimization, it's an optimization of the algorithm applicable no matter the implementation.</p>\n\n<p><strong>LATER EDIT</strong></p>\n\n<p>And this is how you can shorten your method:</p>\n\n<pre><code>public static void main(String args[]){\n Scanner x=new Scanner(System.in);\n System.out.println(\"Enter the number:\");\n long y = x.nextLong();\n for(long i=2;i&lt;=Math.sqrt(y);i++){\n if(y % i == 0){\n System.out.println(y+\" is not a prime\");\n System.out.println(y+\" divides by \"+i);\n System.exit();\n }\n\n }\n System.out.println(y + \" is a prime number.\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:21:02.063", "Id": "60354", "Score": "0", "body": "Thanks mate.btw Is there a theorem which says that the max possible divider of a number is less than or equal to the square root of the number?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:25:25.137", "Id": "60355", "Score": "0", "body": "no, consider 10. Its sqrt is around 3.16, but you can divide it by 5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:26:14.027", "Id": "60356", "Score": "0", "body": "See my comment on user987339's answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:26:14.963", "Id": "60357", "Score": "3", "body": "@user3070800 It's very easy to see that for yourself. If a number has one or more divisors, then at least one of them must be less than or equal to the square root of the number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:30:23.857", "Id": "60358", "Score": "0", "body": "Okay i got it now .\"If a number has one or more divisors, then at least one of them must be less than or equal to the square root of the number. \" Thanks. Do you study maths? Is there a way to prove the above statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:33:51.863", "Id": "60359", "Score": "3", "body": "@EdgarBoda Yes, but you will find out it's divisible by 2 first, so you don't need to bother checking for divisibility by 5. Consider an integer N and a factor x. Since x is a factor of N, then N / x is also a factor of N. If x <= sqrt(N), then 1 <= sqrt(N) / x, then 1 / sqrt(N) <= 1 / x, then N / sqrt(N) <= N / x, then sqrt(N) <= N / x. Therefore any factor of N that's greater than or equal to sqrt(N) has a corresponding factor that's less than or equal to sqrt(N)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:35:07.597", "Id": "60360", "Score": "0", "body": "@user3070800: I added to my answer my idea of how you can also shorten your code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:38:55.723", "Id": "60361", "Score": "0", "body": "I tried to run this code using eclipse.But it shows some errors in the code Andrei." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:02:41.887", "Id": "60368", "Score": "2", "body": "Rather than `System.exit()`, you could just `return`. It's more polite, and shorter too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:06:25.033", "Id": "60371", "Score": "1", "body": "BTW using the `sqrt` in the condition check is very inefficient. Instead use `for (long i = 2, n = Math.sqrt(x.nextLong()); i < n; i++)` and it would be much better. Otherwise the square root will be evaluated every time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:41:24.287", "Id": "60385", "Score": "1", "body": "This won't work for squares of primes e.g. `9` will fail to detect it is not prime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:43:35.677", "Id": "60387", "Score": "0", "body": "FYI, this is known as the \"sieve\" method. It is mathematically sound." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T20:21:40.340", "Id": "60410", "Score": "0", "body": "@Peter: great observation. I edited my solution." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:16:36.850", "Id": "36704", "ParentId": "36703", "Score": "2" } }, { "body": "<blockquote>\n <p>The most efficient way to find all small primes was proposed by the\n Greek mathematician Eratosthenes. His idea was to make a list of\n positive integers not greater than n and sequentially strike out the\n multiples of primes less than or equal to the square root of n.</p>\n</blockquote>\n\n<p>You can make less checks since the max possible divider is square root of the number. So you can change your for loop to:</p>\n\n<pre><code>for( i=2;i&lt;=Math.sqrt(y);i++)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:20:11.107", "Id": "60362", "Score": "0", "body": "Is there a theorem which says that the max possible divider of a number is less than or equal to the square root of the number?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:23:21.870", "Id": "60363", "Score": "2", "body": "No, there's no such theorem. But if there is such a number (let's call it `x`), the other factor `y` (that would make for `x * y = the initial number`) would be less than the square root, so one would have already found it and inferred the number is not prime. E.g. The square root of 64 is 8. 16 is a divider of 64 and it is larger than sqrt(64), but you would have already found 4 as a divider of 64 before reaching sqrt(64). And 4 * 16 = 64." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:25:30.057", "Id": "60364", "Score": "0", "body": "The most efficient way to find all small primes was proposed by the Greek mathematician Eratosthenes. His idea was to make a list of positive integers not greater than n and sequentially strike out the multiples of primes less than or equal to the square root of n. After this procedure only primes are left in the list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:42:08.617", "Id": "60386", "Score": "1", "body": "Using `i<Math.sqrt(y)` will fail for squares of a prime number e.g. 9, 25, 49, ... will fail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:13:07.500", "Id": "60416", "Score": "0", "body": "Thanx for improving the answer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:17:28.960", "Id": "36705", "ParentId": "36703", "Score": "0" } }, { "body": "<p>Since this has been migrated to CodeReview, it makes sense to inspect it from a review perspective.</p>\n\n<p>Others have correctly pointed out that the limit of your iteration is the root of the the number. That will impact the performance.... but what about your actual question: can the code be shorter (rather than faster)?</p>\n\n<p>First, some comments....</p>\n\n<ol>\n<li>you really should not use <code>System.exit(...)</code>. A simple <code>return</code> would work better in this situation</li>\n<li>You are not closing the Scanner when you are done with it. I <strong>know</strong> that in this case, working on <code>System.in</code> you don't think it's necessary, but, you should get in the habit of doing it. I have seen too many occasions where unclosed-handles create problems.</li>\n<li>the variable names are horrible .... <code>x</code>, <code>y</code> and <code>i</code>? (Well, <code>i</code> is OK....).</li>\n<li>in the current version of the code, you are still doing <code>i++</code> and not <code>i+=2</code>. This is because you are starting at <code>2</code>. If you start at <code>3</code> you can do a clean <code>+=2</code>.</li>\n<li><code>Math.sqrt(...)</code> returns a <code>double</code>. Doing a comparison against double for each loop is something the JIT compiler may be able to optimize, but I would err on the side of caution, and manually cast it <strong>outside</strong> the loop.</li>\n</ol>\n\n<p>So, putting it together, I would suggest something like:</p>\n\n<pre><code>public static void main(String args[]){\n System.out.println(\"Enter the number:\");\n try (Scanner scanner=new Scanner(System.in)) {\n final long target = scanner.nextLong();\n final long limit = (long)Math.sqrt(target);\n for(long factor = 2; factor &lt;= limit; factor += factor == 2 ? 1 : 2){\n if(target % factor == 0) {\n System.out.printf(\"%d is not a prime\\n%d divides by %d\", target, target, factor);\n return;\n }\n\n }\n System.out.println(target + \" is a prime number.\");\n }\n}\n</code></pre>\n\n<p>The above code is reasonably well structured, etc.</p>\n\n<p>If I was aiming for raw performance though, and I threw out some of the validation rules, and allowed myself to hack it a bit, I would consider:</p>\n\n<pre><code>private static final long factor(final long target) {\n if (target &lt;= 2) {\n return 1; // 1 and 2 are 'prime' external call will have to special-case 1 and negative numbers..\n }\n if ((target &amp; 0x001) == 0) {\n return 2; // it's even.\n }\n final long limit = (long)Math.sqrt(target);\n for(long factor = 3; factor &lt;= limit; factor += 2){\n if(target % factor == 0) {\n return factor;\n }\n }\n return 1;\n}\n\npublic static void main(String args[]){\n System.out.println(\"Enter the number:\");\n try (Scanner scanner=new Scanner(System.in)) {\n final long target = scanner.nextLong();\n final long fac = factor(target);\n if(fac &gt; 1) {\n System.out.printf(\"%d is not a prime\\n%d divides by %d\", target, target, fac);\n return;\n }\n System.out.println(target + \" is a prime number.\");\n }\n}\n</code></pre>\n\n<p>The reason for this is:</p>\n\n<ol>\n<li>measuring performance with a single call is never going to do anything in Java - you need to call the code enough times to allow the JIT compiler to compile it.</li>\n<li>It is unlikely that the JIT compiler will ever compile the <code>main</code> method</li>\n<li>So I extract the 'hard' logic in to a seperate method that the JIT system can compile and isolate.</li>\n<li>I handle the special cases seperately....</li>\n<li>put the user-dialog outside the calculation....</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:20:58.327", "Id": "60379", "Score": "0", "body": "OP wanted to optimize for compactness, not efficiency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T10:23:06.730", "Id": "60471", "Score": "0", "body": "Actually, `long limit = (long)Math.sqrt(target)` can fail in this context. Consider a very large prime `p` so that `target = p*p`, and that `p` can't be represented exactly as a floating point number. If the prime `p` is chosen suitably, then `limit < p`, in which case we get a false positive, because no factor is ever found. The solution would be to do something like `limit = (long) nextHighestFloatingPointNumber(Math.sqrt(target))`, but I have no idea how to *implement* this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T11:00:16.617", "Id": "60477", "Score": "0", "body": "Hmm, I played around with a [list of primes](http://primes.utm.edu/lists/small/millions/) but they are to small to trigger inaccuracies in doubles, so my previous comment is just floating point paranoia." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T11:03:08.070", "Id": "60478", "Score": "0", "body": "@amon - since the input is a long (target is long) which is implicitly up-cast to double... how can the input to sqrt be to large?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T11:13:10.083", "Id": "60479", "Score": "0", "body": "Floating point numbers cannot represent all integers. Two “consecutive” floats can have a distance greater than `1`. The idea of my comment was to find inputs where this distance creates false positives, which can occur if (a) `target` is rounded down to the nearest double during the implicit conversion, and (b) the sqrt of the two neighbouring doubles is different. I have not yet done a complete analysis to prove the existence or absence of such a value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:58:59.553", "Id": "76986", "Score": "0", "body": "long limit = 1 + (long) Math.sqrt (target) will be fine. If target >= n^2, then target rounded to double can be a bit smaller than n^2, Math.sqrt can be a bit less than n which casting to long might convert to n - 1, but adding 1 makes it fine. My very first ever program to print prime numbers printed the number 121... Quite embarrassing! So identifying squares of primes as prime should really be avoided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:02:49.160", "Id": "76987", "Score": "0", "body": "And if anyone thinks that one additional test takes too long... Test for division by 2 and 3. Then set factor = 5, change = 2. After each test, factor += change and change = 6 - change. change alternates between 2 and 4. So we divide by 5, 7, 11 (not 9), 13, 17 (not 15), 19, 23 (not 21), 25, ... avoiding all the factors that are divisible by 3. That saves one third of all divisions." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:12:57.210", "Id": "36712", "ParentId": "36703", "Score": "3" } } ]
{ "AcceptedAnswerId": "36704", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:13:10.763", "Id": "36703", "Score": "2", "Tags": [ "java", "optimization", "primes" ], "Title": "Determining whether or not a number is prime" }
36703
<p>I have some code below that takes different detected users recognized by the Kinect and assigns them a specific random id range based on the player they are. I use this to grab the x,y coordinates of their left or right hand. I was trying to have the Kinect get at least 6 peoples coordinates with the code. Am I taking the approach right or should I perform it differently? I am using the Kinect SDK v1.8.</p> <pre><code> Using skeletonFrameData As SkeletonFrame = e.OpenSkeletonFrame If skeletonFrameData Is Nothing Then Exit Sub End If ' sensor.SkeletonStream.AppChoosesSkeletons = True Dim allSkeletons(skeletonFrameData.SkeletonArrayLength - 1) As Skeleton skeletonFrameData.CopySkeletonDataTo(allSkeletons) </code></pre> <p>Player Identification:</p> <pre><code> 'identify specific players by ID 'ResetValues() For j = 0 To playerid.Length - 1 'all players playerid(i) = CInt(Rnd() * 4 + (i * 5)) allSkeletons(i).TrackingId = playerid(0) Next j 'force each player to be moved to first blank spot Dim tempList As New List(Of Skeleton)(allSkeletons) tempList.RemoveAll(Function(sk) IsNothing(sk)) allSkeletons = tempList.ToArray Log("Tracking id for player#1: " + allSkeletons(0).TrackingId.ToString) Log("Tracking id for player#2: " + allSkeletons(1).TrackingId.ToString) Log("Tracking id for player#3: " + allSkeletons(2).TrackingId.ToString) </code></pre> <p>Make sure current player is getting tracked or not:</p> <pre><code> If IsNothing(s) Then Exit Sub End If If s.TrackingState = SkeletonTrackingState.Tracked Then activeCount = activeCount + 1 End If If s.TrackingState = SkeletonTrackingState.PositionOnly Then passiveCount = passiveCount + 1 End If If s.TrackingState = SkeletonTrackingState.NotTracked Then nottracked = nottracked + 1 End If totalplayers = activeCount + passiveCount + nottracked 'Log("passive count: " + passiveCount.ToString + " date: " + Now.ToString) </code></pre> <p>Player x,y display:</p> <pre><code> ' the first found/tracked skeleton moves the mouse cursor If s.TrackingState = SkeletonTrackingState.Tracked Then ' make sure both hands are tracked 'If Skeleton.Joints(JointType.HandLeft).TrackingState = JointTrackingState.Tracked AndAlso Skeleton.Joints(JointType.HandRight).TrackingState = JointTrackingState.Tracked Then Dim cursorX, cursorY As Integer ' get the left and right hand Joints Dim jointRight As Joint = s.Joints(JointType.HandRight) Dim jointLeft As Joint = s.Joints(JointType.HandLeft) ' scale those Joints to the primary screen width and height Dim scaledRight As Joint = jointRight.ScaleTo(CInt(Fix(SystemParameters.PrimaryScreenWidth)), CInt(Fix(SystemParameters.PrimaryScreenHeight)), SkeletonMaxX, SkeletonMaxY) Dim scaledLeft As Joint = jointLeft.ScaleTo(CInt(Fix(SystemParameters.PrimaryScreenWidth)), CInt(Fix(SystemParameters.PrimaryScreenHeight)), SkeletonMaxX, SkeletonMaxY) ' relativemouselocation.Content = jointRight.Position ' figure out the cursor position based on left/right handedness If LeftHand.IsChecked.GetValueOrDefault() Then cursorX = CInt(Fix(scaledLeft.Position.X)) cursorY = CInt(Fix(scaledLeft.Position.Y)) Else cursorX = CInt(Fix(scaledRight.Position.X)) cursorY = CInt(Fix(scaledRight.Position.Y)) End If Dim leftClick As Boolean ' figure out whether the mouse button is down based on where the opposite hand is If (LeftHand.IsChecked.GetValueOrDefault() AndAlso jointRight.Position.Y &gt; ClickThreshold) OrElse ((Not LeftHand.IsChecked.GetValueOrDefault()) AndAlso jointLeft.Position.Y &gt; ClickThreshold) Then leftClick = True ' MsgBox("clicked") Else leftClick = False End If 'if i is less then the total amount of players then send players coordinates for person that is active. If i &lt;= 5 Then Select Case True Case Is = s.TrackingId &gt;= 1 And s.TrackingId &lt;= 4 i = 0 playeractive(i) = True player1xy.Content = cursorX &amp; ", " &amp; cursorY &amp; ", " &amp; leftClick Status.Text = "player1 identified" &amp; cursorX.ToString &amp; ", " &amp; cursorY.ToString &amp; ", " &amp; leftClick.ToString ' sensor.SkeletonStream.ChooseSkeletons(1, 2) Case Is = s.TrackingId &gt;= 5 And s.TrackingId &lt;= 9 i = 1 playeractive(i) = True player2xy.Content = cursorX &amp; ", " &amp; cursorY &amp; ", " &amp; leftClick Status.Text = "player2 identified" &amp; cursorX.ToString &amp; ", " &amp; cursorY.ToString &amp; ", " &amp; leftClick.ToString Case Is = s.TrackingId &gt;= 10 And s.TrackingId &lt;= 14 i = 2 playeractive(i) = True player3xy.Content = cursorX &amp; ", " &amp; cursorY &amp; ", " &amp; leftClick Status.Text = "player3 identified" &amp; cursorX.ToString &amp; ", " &amp; cursorY.ToString &amp; ", " &amp; leftClick.ToString Case Is = s.TrackingId &gt;= 15 And s.TrackingId &lt;= 19 i = 3 playeractive(i) = True player4xy.Content = cursorX &amp; ", " &amp; cursorY &amp; ", " &amp; leftClick Status.Text = "player4 identified" &amp; cursorX.ToString &amp; ", " &amp; cursorY.ToString &amp; ", " &amp; leftClick.ToString Case Is = s.TrackingId &gt;= 20 And s.TrackingId &lt;= 24 i = 4 playeractive(i) = True player5xy.Content = cursorX &amp; ", " &amp; cursorY &amp; ", " &amp; leftClick Status.Text = "player5 identified" &amp; cursorX.ToString &amp; ", " &amp; cursorY.ToString &amp; ", " &amp; leftClick.ToString Case Is = s.TrackingId &gt;= 25 And s.TrackingId &lt;= 29 i = 5 playeractive(i) = True player6xy.Content = cursorX &amp; ", " &amp; cursorY &amp; ", " &amp; leftClick Status.Text = "player6 identified" &amp; cursorX.ToString &amp; ", " &amp; cursorY.ToString &amp; ", " &amp; leftClick.ToString End Select Log("person #: " + i.ToString + "Tracking ID: " + s.TrackingId.ToString) currentperson.Content = i.ToString + "Tracking ID: " + s.TrackingId.ToString End If 'If playeractive(i) = True And i &gt;= 0 And frame.SkeletonArrayLength &gt; 0 Then 'NativeMethods.SendMouseInput(cursorX, cursorY, CInt(Fix(SystemParameters.PrimaryScreenWidth)), CInt(Fix(SystemParameters.PrimaryScreenHeight)), leftClick, totalplayers, i) 'End If 'if total players is 1 or greater send coordinate data. If totalplayers &gt;= 1 Then DefineMouseData(cursorX, cursorY, leftClick) End If 'make the below code active when I get multiple player tracking working If playeractive(i) = True Then ' Environment.SetEnvironmentVariable("Player" + i.ToString + "xcoords", player(i).bytex.ToString, EnvironmentVariableTarget.Machine) ' Environment.SetEnvironmentVariable("Player" + i.ToString + "ycoords", player(i).bytey.ToString, EnvironmentVariableTarget.Machine) 'Environment.SetEnvironmentVariable("Player" + i.ToString + "leftclick", player(i).leftclick.ToString, EnvironmentVariableTarget.Machine) 'System.Threading.Thread.Sleep(300) End If If i &lt;= 5 Then If playeractive(5) = True Then 'if 6th player exit for loop and open next frame. playeractive(5) = False Exit For Else 'd = d + 1 End If End If End If NumPassive.Content = "passive count: " + passiveCount.ToString Numactive.Content = "active count: " + activeCount.ToString nottrackedplayers.Content = "not tracked players: " + nottracked.ToString playeractive(i) = False </code></pre> <p>Choose specific player:</p> <pre><code> For h = 0 To activeCount - 1 If h &gt;= 2 Then If activeCount - 1 &gt; 0 Then sensor.SkeletonStream.ChooseSkeletons(playerid(h), playerid(h + 1)) End If End If Next Next ResetValues() End Using </code></pre> <p>As you can see I go from 1-4 for player one (it might be 0-4), 5-9 for player 2, and so on for each player. If anyone can improve this code or know of any methods I am not using please post a solution below. Sorry for the long code post but if someone thinks that what I have commented out is irrelevant please edit this and remove the comments. I plan on using the multiple Kinect code too I commented out to do more then 6 players later but wish to get 4-6 players working for now. Edit: I removed the unimportant parts. The important part is the sensor.SkeletonStream.ChooseSkeletons(s.TrackingId) Line here.</p> <p>For more explanation: <a href="http://msdn.microsoft.com/en-us/library/microsoft.kinect.skeletonstream.chooseskeletons.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.kinect.skeletonstream.chooseskeletons.aspx</a></p> <p>I want a specific user to be looped through such as player 1's coordinates retrieved first, then second, and so on so it does not seem slow. But I need the best method to do so. The problem is: ChooseSkeletons only does 2 people. I can loop through each person passing their id to chooseskeleton and this gives me 4-6 people but this seems inefficient because chooseskeleton takes too long (maybe improper usage?).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:47:08.053", "Id": "60375", "Score": "0", "body": "Note: the full source is located here: http://kinectmultipoint.codeplex.com/releases/view/104786" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:52:42.520", "Id": "60376", "Score": "0", "body": "Code works for the most part but full source is too much to post here so I listed full source link. Also, here's more information on my programming environment: Xbox 360 Kinect (debug environment only), windows 7, and a laptop computer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T18:41:25.093", "Id": "60394", "Score": "0", "body": "Is this using XNA libraries? I'm hesitant to retag - if it's using XNA you should tag your question with the XNA tag :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T18:42:36.223", "Id": "60395", "Score": "0", "body": "Is the procedure much longer than that? It would be helpful if the code included at least `Sub ProcedureName` up to `End Sub`. You've posted an incomplete `Using` scope..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:27:56.120", "Id": "60401", "Score": "2", "body": "Rather than trying to make us review your entire project, which is apparently too large to post. I recommend breaking it into working parts and asking separate questions for those parts. The shorter and more focused your question is, the more likely you are to get a relatively quick and useful answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:02:31.890", "Id": "60412", "Score": "0", "body": "The code is what it is guys. I took out the comments so who even put -1 if it was for comments I remove them. If iam missing something please comment below but as far as posting the whole sub retail coder its too big." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:08:52.313", "Id": "60413", "Score": "0", "body": "I broke the code into sections as suggested and added information for each section." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:39:10.307", "Id": "60418", "Score": "0", "body": "I also edited and removed some repeated code and shorted the player id assign section with a for loop as suggested by Daniel cook. It looks much better now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:39:48.227", "Id": "70439", "Score": "0", "body": "Note: please check the Kinect multipoint codeplex page (http://kinectmultipoint.codeplex.com) for more code updates. I should have the latest code update with most of the changes listed above. However, If anyone knows how to use properly sendinput with multiple mouse devices I can make a new post on that (I attempted searching for the correct method to do that as an alterative to DSF(Device simulation framework from Microsoft)). I think the Kinect code is more of a design issue as it involves more how it is completed and looks to a user then a specific stackoverflow programming question." } ]
[ { "body": "<p>I'm just going to review what's here:</p>\n\n<ol>\n<li>Your comments are excessive. Commented out code helps no one. If you remove code and want it later, that's what version control is for.</li>\n<li>Your method is too long. You should break it into smaller pieces.</li>\n<li><p>Use loops instead of very similar repeated code for instance:</p>\n\n<pre><code>For i As Integer = 0 To playerid.Length - 1\n playerid(i) = CInt(Rnd() * 4 + (i * 5))\n allSkeletons(i).TrackingId = playerid(i)\nNext \n</code></pre></li>\n<li>Do not use multiple <code>if</code> statements to check the same variable. Either use an <code>if-else</code> block or <code>Select Case</code></li>\n<li>You do not have to post all of your project, but you should at least post pieces that are whole. If we must go to a separate site to even properly review what you posted, it probably isn't going to happen. </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:40:55.643", "Id": "60419", "Score": "0", "body": "Thanks Daniel. I thing the problem is that I need to have chooseskeletons track one- two skeletons at a time and return that person's x,y coordinates (both need to be done fast though - this is the problem)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:12:13.700", "Id": "36719", "ParentId": "36707", "Score": "4" } }, { "body": "<p>Anything that defines a scope or a code block, should make you hit that <kbd>Tab</kbd> key on the next line. <code>Using</code> defines a scope, so your indentation is off.</p>\n\n<p>This might be personal preference, but I find this:</p>\n\n<pre><code>If skeletonFrameData Is Nothing Then\n Exit Sub\nEnd If\n</code></pre>\n\n<p>Would look cleaner written like this:</p>\n\n<pre><code>If skeletonFrameData Is Nothing Then Exit Sub\n</code></pre>\n\n<p>Since your <code>allSkeletons</code> array is populated by copying another array, I think you could just do this - less verbose, and still clear; note that I'm coming from <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged &#39;c#&#39;\" rel=\"tag\">c#</a> so I'm not sure if this is legal <a href=\"/questions/tagged/vb.net\" class=\"post-tag\" title=\"show questions tagged &#39;vb.net&#39;\" rel=\"tag\">vb.net</a>:</p>\n\n<pre><code>Dim allSkeletons() As Skeleton = skeletonFrameData.CopySkeletonDataTo(allSkeletons)\n</code></pre>\n\n<p>What comes next really looks like something that should be refactored into its own function, and called in a loop (see point 3 of @DanielCook's answer):</p>\n\n<pre><code>Private Sub AssignSkeletonTrackingId(playerSkeleton As Skeleton, playerIndex As Integer)\n playerSkeleton.TrackingId = CInt(Rnd() * 4 + (playerIndex * 5))\n Log(\"Tracking id for player#\" playerIndex + 1 + \": \" + playerSkeleton.TrackingId.ToString()\nEnd Sub\n</code></pre>\n\n<p>It appears traversing your <code>allSkeletons</code> array after that would be redundant.</p>\n\n<p>The rest is pretty much unreviewable, please update your original post with enough code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:22:37.267", "Id": "60399", "Score": "0", "body": "That definitely is personal preference. Personally, I dislike VB.Net single line If statements. It almost feels like a syntax error cause of the missing `End If`. There is functionality to copy an array, but it definitely isn't a method called `CopySkeletonDataTo` using `CopyTo` would be appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:49:05.100", "Id": "60406", "Score": "0", "body": "@DanielCook I didn't make up the `CopySkeletonDataTo` method, it's from the OP's code ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T20:37:10.030", "Id": "60411", "Score": "0", "body": "Oh, well in that case you deserve the +1 I already gave you even more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:54:50.260", "Id": "60420", "Score": "0", "body": "Great solution! I am having problems with the code but it seems you guys were right I reeated a section twice. No, retailcoder that would cause an error in VB.NET with the allskeletons variable not being declared or cause memory leak issues. As far as I remember you need Redim to avoid this error. But If it works I will have to give you kudos." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:17:21.583", "Id": "36721", "ParentId": "36707", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:43:52.533", "Id": "36707", "Score": "2", "Tags": [ "vb.net" ], "Title": "Identifying specific players with the kinect?" }
36707
<p>I wrote the following Fizz Buzz program. How can I improve it or make it more efficient?</p> <pre><code>public class FizzBuzz { public static void main(String[] args) { System.out.println("--------Fizz Buzz program-------------"); for(int num=1;num&lt;=100;num++) { if(num%3==0) { if(num%5==0) System.out.println("FizzBuzz"); else System.out.println("Fizz"); } else if(num%5==0) { if(num%3==0) System.out.println("FizzBuzz"); else System.out.println("Buzz"); } else System.out.println(num); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T18:02:21.547", "Id": "60393", "Score": "10", "body": "Advice to reviewers: This being Code Review, answers of the form \"This is how I would do it: _code_\" are insufficient. Your answer must bear some relationship to the code in the original question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:35:13.537", "Id": "60428", "Score": "0", "body": "Efficiency is defined as work performed per resource consumed. What work are you performing, and what resource do you care about? Until we know those things it is impossible to answer the question \"how can we make it more efficient?\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T14:52:29.347", "Id": "60495", "Score": "0", "body": "The performance of FizzBuzz itself is almost certainly by `System.out.println`. It also has only 100 iterations, so JVM startup is more expensive than your code. Are you sue you want to increase efficiency? Unless you know (usually because your profiled it) that this code is too slow, I'd focus on readability over performance." } ]
[ { "body": "<p>You have some redundant code there .... there is no need for the code :</p>\n\n<pre><code> if(num%3==0) \n System.out.println(\"FizzBuzz\");\n else\n</code></pre>\n\n<p>in the <code>else if(num%5==0)</code> side of the program. This is because if the number was <code>% 3 ==0</code> it would have gone to the first block.</p>\n\n<p>Then in general, looking at the logic, I can't help but think there's a trick you are missing:</p>\n\n<pre><code>for(int num=1;num&lt;=100;num++) {\n if (num % 15 == 0) System.out.println(\"FizzBuzz\");\n else if (num % 3 == 0) System.out.println(\"Fizz\");\n else if (num % 5 == 0) System.out.println(\"Buzz\");\n else System.out.println(num);\n}\n</code></pre>\n\n<p>This won't be the fastest option, but it sure looks neat.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:22:49.317", "Id": "36713", "ParentId": "36708", "Score": "11" } }, { "body": "<p>You can use just one modulus, but given the writing to the console is far, far more expensive than anything else changing the code without changing the output is unlikely to matter. i.e. removing one character from the output could make more of a difference.</p>\n\n<pre><code>for(int num = 1; num &lt;= 100; num++) {\n switch(num % 15) {\n case 0: \n System.out.println(\"FizzBuzz\");\n break;\n case 3: case 6: case 9: case 12:\n System.out.println(\"Fizz\");\n break;\n case 5: case: 10:\n System.out.println(\"Buzz\");\n break;\n }\n}\n</code></pre>\n\n<p>Note: Java doesn't compile to native code until a loop or method has been called 10,000 times by default. If you warm up you code it can be 20x faster without even changing it. i.e. if you haven't warmed up your code, trying to make it more efficient doesn't really matter.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:40:00.047", "Id": "36714", "ParentId": "36708", "Score": "7" } }, { "body": "<p>The issues I see with your code are:</p>\n\n<ul>\n<li><strong>Indentation:</strong> Your indentation is inconsistent. One space per level is insufficient for readability.</li>\n<li><p><strong>Brace style:</strong> Leaving out the optional braces can lead to bugs when code is modified later. If you want to omit the braces, then also put the body on the same line to avoid any misconceptions.</p>\n\n<pre><code>if (num % 3 == 0)\n{\n if (num % 5 == 0) System.out.println(\"FizzBuzz\");\n else System.out.println(\"Fizz\");\n}\n</code></pre>\n\n<p>Personally, I would advise that you stick with the standard Java conventions to make everyone's life easier. It also relieves the temptation to skimp on braces in the first place.</p>\n\n<pre><code>if (num % 3 == 0) {\n if (num % 5 == 0) {\n System.out.println(\"FizzBuzz\");\n } else {\n System.out.println(\"Fizz\");\n }\n}\n</code></pre>\n\n<p>By the way, opening braces on a separate line can be brutal when it comes to try-catch-finally blocks.</p>\n\n<pre><code>try\n{\n …\n}\ncatch (Exception e)\n{\n …\n}\nfinally\n{\n …\n}\n</code></pre></li>\n<li><strong>Redundancy:</strong> The multiple-of-15 case is handled twice; it should need to be handled once.</li>\n<li><p><strong>Repetition of <code>System.out.println()</code>:</strong> I suggest using a ternary conditional expression instead.</p>\n\n<pre><code>for (int num = 1; num &lt;= 100; num++) {\n System.out.println((num % 15 == 0) ? \"FizzBuzz\" :\n (num % 3 == 0) ? \"Fizz\" :\n (num % 5 == 0) ? \"Buzz\" :\n num);\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T18:57:21.687", "Id": "60396", "Score": "1", "body": "I definitely agree about the indentation. I got confused reading the post, so I submitted an edit which I shouldn't have done. Hope nobody approves it. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:42:16.307", "Id": "36715", "ParentId": "36708", "Score": "15" } }, { "body": "<p>Here is an example of what probably ends up being a pointless optimization, but it\nis a completely different approach to the other posted solutions.</p>\n\n<p>Generally integer addition and subtraction take fewer\ncpu cycles than multiplication and division. With that in mind\nyou might try the following:</p>\n\n<pre><code>int fizzcnt = 0;\nint buzzcnt = 0;\nString msg;\nfor(int num = 1; num &lt;= 100; num++) {\n fizzcnt++;\n buzzcnt++;\n if (fizzcnt == 3) {\n msg = \"Fizz\";\n fizzcnt = 0;\n }//this bracket was missing\n else {\n msg = \"\";\n }\n if (buzzcnt == 5) {\n msg = msg.concat(\"Buzz\");\n buzzcnt = 0;\n }\n System.out.format(\"%s %d%n\", msg, num);\n}\n</code></pre>\n\n<p>Managed to write the whole thing with 1 loop, 2 if statements and no multiplication/division/modulus\ncalculations. This should be more efficient. Maybe not. Notice the output message is created using String and concat.\nthese little guys probably suck up a lot more cycles than were gained through elimination of the other statements. You\nwould have to profile the code to really know.</p>\n\n<p>The lesson here is it is probably better to work on readability and logical simplicity than it is\nto worry about efficiency - unless performance becomes a real concern. When efficiency does become a concern be prepared to spend a lot of time using a profiler and running\nbenchmarks to verify that what you are doing is truly an improvement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T20:30:15.353", "Id": "36727", "ParentId": "36708", "Score": "2" } }, { "body": "<p>Most style related issues have already been addressed so I'll focus on design:</p>\n\n<ol>\n<li><p>All your code is in the main method. This makes it not reusable. You should start refactoring it by creating something like a <code>FizzBuzzGame</code> class with a <code>play</code> method and move the code in there.</p></li>\n<li><p>Next your upper limit is hard coded to 100. If you have followed the above step then add a parameter to the constructor which lets the user define the upper limit.</p></li>\n<li><p>Your output is tied to standard out. What if you wanted to write it directly to a file, a network stream or just another programmer using the sequence?</p>\n\n<p>There are some options to remove this implicit dependency on standard out:</p>\n\n<ol>\n<li>The <code>play</code> method could accept an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html\" rel=\"nofollow\"><code>Appendable</code></a> or a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/Writer.html\" rel=\"nofollow\"><code>Writer</code></a> and use it to write the result to it.</li>\n<li>Return the results as a list from the <code>play</code> method.</li>\n</ol></li>\n</ol>\n\n<p>While this might possibly seem like a bit of overkill for this specific problem it's still a good idea to practice good design implementations.</p>\n\n<p>It's a bit like muscle memory: If you just want to quickly hack together some code to test something and you tend to do it in a crappy way then chances are that you are prone to write more crappy code in production as well. However if you practice and attempt to write reasonably well designed code (at least in terms of dependencies and encapsulation) then it becomes easy and natural over time and your production code is more likely to be of a higher quality without you actually having to put a lot of conscious effort into it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:38:05.923", "Id": "60432", "Score": "1", "body": "On the other hand, I've often heard that interviewers will penalize you for overengineering. Good interviewers would continue from the \"hacky\" code with \"Well, what if ____?\", and at that point you could refactor into what this answer suggests." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:08:39.480", "Id": "36730", "ParentId": "36708", "Score": "3" } } ]
{ "AcceptedAnswerId": "36715", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T16:59:25.870", "Id": "36708", "Score": "11", "Tags": [ "java", "beginner", "performance", "fizzbuzz" ], "Title": "Efficient FizzBuzz" }
36708
<p>The aim is to enumerate all possible sets of whole numbers whose sum is a given integer.</p> <pre><code>class partition { public static void main(String[] ar) { part(66); } public static void part(int n) { part(n,1,""); } public static void part(int n, int st, String prefix) { if(n == 0) { System.out.println(prefix.substring(1)); return; } for(int i = st; i &lt;= n; i++) part(n-i,i,prefix + " " + i); } } </code></pre> <p>Please help to improve my code and suggest a better solution.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:38:25.577", "Id": "60402", "Score": "2", "body": "Can you please describe what \"partition an integer\" means?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:41:40.690", "Id": "60555", "Score": "0", "body": "See follow-up question: [Integer Partition using an iterator](http://codereview.stackexchange.com/q/36815/9357)." } ]
[ { "body": "<p>My first observation is that your variable names mean nothing. <code>n</code> and <code>st</code> should describe what they are supposed to represent. </p>\n\n<p>I don't like having the <code>println</code> in the <code>part</code> function. In my opinion, the value should be returned back up the stack and printed in the user interface layer. Please see <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\">Separation of Concerns</a> for more information. This will allow your code to be followed a little easier.</p>\n\n<p>Other than that, not too many other things to note.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:37:55.370", "Id": "36724", "ParentId": "36722", "Score": "6" } }, { "body": "<p>This program finds all combinations of numbers that add up to a specified number (<code>66</code>). There are a number of things that I dislike about it.</p>\n\n<ol>\n<li>Using String concatenation in a tight loop is a poor choice when it comes to performance. This statement <code>prefix + \" \" + i</code> has to go.</li>\n<li>the variable names in your loop are almost meaningless.</li>\n<li>You are using a String <code>prefix</code> as if it is a Stack (adding a value to the String in the loop). Since most combinations are not going to add to the target it seems like a lot of String manipulation to get there.</li>\n<li>the recursive method should not be public.</li>\n<li>Java classes should be named with a capital letter, i.e. it should be <code>Partition</code>.</li>\n</ol>\n\n<p>Using a Stack (really, a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html\" rel=\"nofollow\">Deque</a> - or <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html\" rel=\"nofollow\">ArrayDeque</a> ) would ba a typical choice, but in this case, I feel that converting the primitive int values to an Integer would be unnecessary. Using an <code>int[]</code> array would be simple enough.... especially because there is an upper-bound on the stack size.</p>\n\n<p>So, taking that all in to account, I would suggest the following changes:</p>\n\n<ol>\n<li>the <code>part(int)</code> (renamed to partition) should construct an int[] array as a stack. It should then call the recursive method.</li>\n<li>the recursive method should only construct the String value for actual results, not intermediate results.</li>\n<li>rename the variables (and methods) to be more descriptive.</li>\n<li>used 'final' where I can to show what variables cannot change, and it can help with the JIT Optimization.</li>\n</ol>\n\n<p>The refactor would end up looking like:</p>\n\n<pre><code>public static void main(String[] ar)\n{\n partition(66);\n}\n\npublic static void partition(final int n)\n{\n recursivePartition(n, 1, new int[n], 0);\n}\n\nprivate static void recursivePartition(final int target, final int from, final int[] stack, final int stacksize)\n{\n if(target == 0) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; stacksize; i++) {\n sb.append(stack[i]).append(\" \");\n }\n System.out.println(sb.toString());\n return;\n }\n for(int i = from; i &lt;= target; i++) {\n stack[stacksize] = i;\n recursivePartition(target-i, i, stack, stacksize + 1);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T20:12:38.187", "Id": "60407", "Score": "0", "body": "The `StringBuilder` seems _less_ efficient than the original, which only did one string concatenation to the end of a mostly complete list. Here you're starting from scratch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T21:21:39.640", "Id": "60563", "Score": "1", "body": "@200_success - saw your other question... I tried to do the match whether sb.append() was called more with the above solution, or with string-concatenation on the stack.... I ended up just running the code with counters: `Concat 33288432 Append 76808852` ... 'my solution` does more than double the number of appends.... FYI" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T20:02:49.003", "Id": "36725", "ParentId": "36722", "Score": "3" } } ]
{ "AcceptedAnswerId": "36724", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T19:32:48.880", "Id": "36722", "Score": "6", "Tags": [ "java", "combinatorics" ], "Title": "Integer Partition" }
36722
<p>I would like the have a second opinion on my code I've written to calculate <code>e</code></p> <p><code>e</code> is an integer that you wherefore the following counts <code>gcd(φ(n),e) = 1 with 1 &lt; e &lt; φ(n)</code></p> <pre><code>public int calce() { do { e = priemgen.newKey(1, euler); } while (GCD(euler, e) != 1); return e; } private int GCD(int value1, int value2) { while (value1 != 0 &amp;&amp; value2 != 0) { if (value1 &gt; value2) { value1 %= value2; } else value2 %= value1; } return Math.Max(value1, value2); } private int NewPrime(int lowerbound, int upperbound) { return priemgen.newKey(lowerbound, upperbound); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:11:24.837", "Id": "60414", "Score": "0", "body": "Could you clarify this sentence please: `e is an integer that you wherefore the following counts`? I have trouble understanding what it should mean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T14:43:52.910", "Id": "60494", "Score": "0", "body": "1) I'd fix `e to a small prime (3 or 65537) and reject the primes if `e` dives `p-1`. 2) Why `int` instead of `BigInteger`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T09:54:30.433", "Id": "60710", "Score": "0", "body": "Just to be clear: if this is for anything other than learning/school, you should NOT be implementing RSA in C#. Instead use the prebuilt C# classes in System.Security.Cryptography which will do all of the encryption properly and securely." } ]
[ { "body": "<p>There is not a huge amount of code to review here, just a few things:</p>\n\n<ol>\n<li><p>You have a method <code>NewPrime</code> which I assume provides a prime number between the two bounds provided. Yet you do not use it and call <code>priemgen.newKey</code> directly in <code>calce</code>. You should either get rid of the wrapper method or use it consistently.</p></li>\n<li><p>Braces are used inconsistently:</p>\n\n<pre><code>else\n value2 %= value1;\n</code></pre>\n\n<p>Should be same as the if block:</p>\n\n<pre><code>else\n{\n value2 %= value1;\n}\n</code></pre></li>\n<li><p>The naming conventions are inconsistent. Standard naming convention for C# for methods and fields is <code>PascalCase</code> and local variables and parameters are <code>camelCase</code>:</p>\n\n<ul>\n<li><code>calce</code> -> <code>CalculateE</code></li>\n<li><code>newKey</code> on <code>priemgen</code> should be <code>NewKey</code></li>\n<li><code>priemgen</code> - I assume it's a field so should be <code>PrimGenerator</code></li>\n<li><code>lowerbound</code> -> <code>lowerBound</code></li>\n<li><code>upperbound</code> -> <code>upperBound</code></li>\n<li><code>GCD</code> -> <code>Gcd</code></li>\n</ul></li>\n<li><p>If <code>priemgen</code> is what it sounds like then the name for <code>nextKey</code> should be <code>NextPrime</code>.</p></li>\n<li><p>What does <code>priemgen.newKey</code> return if there is no prime within the given bounds?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:26:18.393", "Id": "36733", "ParentId": "36726", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T20:27:55.560", "Id": "36726", "Score": "3", "Tags": [ "c#" ], "Title": "RSA calculating e in C#" }
36726
<p>The game will be combination of text adventure (navigate through buttons), RPG, sandbox, strategy and turn-based game where the main task of player is to explore the game's world and survive (since I cannot classify my game with one genre just yet, I'm still experimenting).</p> <p>The interaction between player and game, as I said, will be based on button clicks. The player will be able to go to different locations using tabs, check some statistics ("Attributes") and perform actions in each location to advance in the game.</p> <p>I've got a code that compiles, and it works the way I want. However, I wondered if I can do anything to make process of programming-in more Actions easier and 'cheaper' in terms of time&amp;effort I have to put into each button, since I want to have a LOT of actions available for player.</p> <p>Currently I am using this method below to display Actions to player and I'm calling it on the start of each turn to refresh the whole layout and display Actions that are available to player (based on his Resources and his Achievements so far).</p> <p>The code is much longer but it is pretty similar with each next action in the 'database' of sorts.</p> <p>Do I have any options to reduce the size of the code needed to make another button (considering I have a few <code>if</code> statements here and there), and/or reduce time I have to put into adding more actions into the game?</p> <p>Because as I add more actions (and I plan to have way over 100 actions at some point, of course not all will be displayed to player) the code is getting really long and really littered due to the space being taken JUST by this single method (<code>displayactivity()</code>) in my MainActivity.java.</p> <pre><code>public void displayactions(){ setContentView(R.layout.main_game); displaytabs(); displayturns(); textView = (TextView) findViewById(R.id.workers); switch(people){ case 1: textView.setText(workers+"/"+people+" worker available."); break; default: textView.setText(workers+"/"+people+" workers available."); } textView = (TextView) findViewById(R.id.gamelogs); textView.setText(sb); LinearLayout layoutmain1 = (LinearLayout) findViewById(R.id.actions); switch (tabs){ case 2: if(true){ Button button = new Button(this); button.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); button.setText("Collect wood | Cost: 1 ["+workers+"] Worker &amp; 1 ["+food+"] Food | Effect: +2-5 Materials"); button.setId(201); button.setTextSize(15); if(food &gt;= 1 &amp;&amp; workers &gt;= 1){ button.setTextColor(getResources().getColor(R.color.black)); } else { button.setEnabled(false); button.setTextColor(getResources().getColor(R.color.grey)); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { food -= 1; workers -= 1; int found = getrandom(2, 5); materials += found; displayactions(); sb.insert(0,"There are lots of branches to collect in the forest. You find "+found+" materials.\n"); textView = (TextView) findViewById(R.id.gamelogs); textView.setText(sb); } }); layoutmain1.addView(button); } if(true){ Button button = new Button(this); button.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); button.setText("Go hunting | Cost: 1 ["+workers+"] Worker | Effect: +1-2 Food"); button.setId(202); button.setTextSize(15); if(workers &gt;= 1){ button.setTextColor(getResources().getColor(R.color.black)); }else{ button.setEnabled(false); button.setTextColor(getResources().getColor(R.color.grey)); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { workers -= 1; int found = getrandom(1, 2); food += found; displayactions(); //Button button = (Button) findViewById(202); //button.setEnabled(false); //button.setTextColor(getResources().getColor(R.color.grey)); switch(found){ case 1: sb.insert(0,"Wilderness feeds you. Your hunting efforts bring "+found+" portion of food.\n"); break; default: sb.insert(0,"Wilderness feeds you. Your hunting efforts bring "+found+" portions of food.\n"); } textView = (TextView) findViewById(R.id.gamelogs); textView.setText(sb); } }); layoutmain1.addView(button); } if(constructor == 0 &amp;&amp; campfire == 1 &amp;&amp; tent == 1){ Button button = new Button(this); button.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); button.setText("Hire a Constructor | Cost: 1 ["+workers+"] Worker &amp; 10 ["+food+"] Food | Effect: A good man, who only desires food and a shelter."); button.setId(203); button.setTextSize(15); if(workers &gt;= 1 &amp;&amp; food &gt;= 10){ button.setTextColor(getResources().getColor(R.color.black)); }else{ button.setEnabled(false); button.setTextColor(getResources().getColor(R.color.grey)); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { workers -= 1; food -= 10; constructor += 1; people += 1; displayactions(); sb.insert(0,"You welcome the Constructor.\n"); textView = (TextView) findViewById(R.id.gamelogs); textView.setText(sb); } }); layoutmain1.addView(button); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:11:49.900", "Id": "60422", "Score": "0", "body": "One problem jumps out `if(true)` is a useless `if` statement that causes clutter. Remove it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T15:33:18.377", "Id": "60502", "Score": "0", "body": "Yea i know that if(true) is unnecessary, I simply put it there so I don't forget to revise the requirements of these 'Actions'. I could use brackets {} for now to separate the code.\n\nThanks for your suggestion, I'll try to keep it in mind." } ]
[ { "body": "<p>When reading your code, the <a href=\"http://altreus.github.io/qi-klaxon/?Strategy+Pattern\" rel=\"nofollow noreferrer\">Strategy Pattern alarm</a> goes off in my head. Before that however, I have some other remarks.</p>\n<ul>\n<li><p>Indentation. If you are using Eclipse, please select your code and press <strong>Ctrl + I</strong> to indent your code properly. Please read up on <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#262\" rel=\"nofollow noreferrer\">indentation in the Java Coding Conventions</a></p>\n</li>\n<li><p>Spacing. This can be seen as a very minor thing, but when you think about it it makes sense that you should be consistent in the usage of spacing around braces; in Java, it is convention to always use a space before a <code>{</code>.</p>\n</li>\n<li><p>As stated by Jeff Vanzella in a comment to your question, <code>if(true) {</code> is an unnecessary condition. If you use a different block to separate variable scoping to avoid variable naming collisions, you can simply use <code>{ }</code>-bracers without an <code>if</code>-condition. Or you might want to extract a method that is doing that part. Or, you might want to remove the extra block entirely. (without removing the code, of course)</p>\n</li>\n<li><p>Duplicate as small strings as possible. Instead of using two separate long strings, use one string for <code>portion</code> and one for <code>portions</code>. One string for <code>worker</code> and one for <code>workers</code>. Use <a href=\"http://developer.android.com/guide/topics/resources/string-resource.html\" rel=\"nofollow noreferrer\">Android String Resources</a>, which even supports <a href=\"http://developer.android.com/guide/topics/resources/string-resource.html#Plurals\" rel=\"nofollow noreferrer\">plurals</a>, instead of hard-coding strings. It is quite neat to gather all strings in one place, and it makes internationalization so much easier.</p>\n</li>\n</ul>\n<h3>Now, about that strategy pattern...</h3>\n<p><em>(This is only an example on how to do it, there are many other ways. Use the things that fits you. The important thing is that you understand the overall structure of what I am doing below)</em></p>\n<p>Something that can improve the cleanliness of your code is to put the game variables in one object of a <code>Game</code> class; this could contain variables such as <code>food</code>, <code>workers</code>, <code>materials</code> and so on.</p>\n<p>Then create a <code>GameAction</code> interface.</p>\n<pre><code>public interface GameAction {\n // You might not want all these methods, perhaps you only want one method for returning a Button\n // and one for updating the Button status or something similar. Use what fits you.\n boolean isAllowed(Game game);\n String getText(Game game);\n void execute(Game game);\n}\n</code></pre>\n<p>Then create a <code>List&lt;GameAction&gt; actionList;</code></p>\n<p>Create some implementations of <code>GameAction</code> (possibly one for each action, or some actions might be possible to group together).</p>\n<pre><code>public class CollectBranchesAction implements GameAction {\n @Override\n public boolean isAllowed(Game game) {\n // This action is allowed if we have at least 1 food and at least 1 worker.\n return game.getFood() &gt; 0 &amp;&amp; game.getWorkers() &gt; 0;\n }\n\n @Override\n public String getText(Game game) {\n return &quot;Collect wood | Cost: 1 [&quot; + game.getWorkers() + &quot;] Worker &amp; 1 [&quot; + game.getFood() + &quot;] Food | Effect: +2-5 Materials&quot;;\n }\n\n @Override\n public void execute(Game game) {\n game.changeFood(-1);\n game.changeWorkers(-1);\n int found = getrandom(2, 5);\n game.changeMaterials(found);\n game.addText(&quot;There are lots of branches to collect in the forest. You find &quot;+found+&quot; materials.\\n&quot;);\n }\n}\n</code></pre>\n<p>Initialize the list, and add an instance of <code>CollectBranchesAction</code> to the list:</p>\n<pre><code>List&lt;GameAction&gt; actionList = new ArrayList&lt;GameAction&gt;();\nactionList.add(new CollectBranchesAction());\n</code></pre>\n<p>Loop through the list, and create buttons for the list - and call the <code>GameAction</code> methods to determine the state of the button.</p>\n<pre><code>for (final GameAction action : actionList) {\n Button button = new Button(this);\n button.setText(action.getText(game));\n button.setEnabled(action.isAllowed(game));\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n action.execute(game);\n }\n });\n layoutmain1.addView(button);\n}\n</code></pre>\n<p>I hope this will get you started in the right direction!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T15:31:58.917", "Id": "60501", "Score": "0", "body": "Thank you a lot for help! =)\n\nI appreciate the time you've spent making this post for me.\n\nI'll now re-read it few times and try to make sense of it. Then I will try to implement it in my code and i'll get back here as fast as possible with any further questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T15:36:55.627", "Id": "60503", "Score": "0", "body": "I'm fairly new to programming so I still make such silly mistakes.\n\nI do not have the knowledge you guys have, and am still learning. I really appreciate all the suggestions you've put into your post and I will attempt to stick to them.\n\nI seriously didn't even think of making separate class for each Action even though now that you've said it, it makes perfect sense.\n\nSimon, would I be pushing it if I made sense of your post, then applied it to my code and then reposted ALL of my code (likely 500 lines or so) somewhere so you can revise all of it and perhaps suggest anything else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:18:27.267", "Id": "60506", "Score": "0", "body": "@Dravic Sure, I think I can be able to go through 500 lines. I would like that when you post it, you can explain your code a bit (similar to what you have been doing now). That makes it easier for us reviewers :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:18:54.333", "Id": "60507", "Score": "0", "body": "@Dravic By the way, the reason for why I am suggesting this approach is that I have done the exact same mistakes that you have :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:48:21.353", "Id": "60518", "Score": "0", "body": ":)\n\nPlease check out @OP, i edited it and added another block of code, this time with my save and load methods.\n\nIn answer to this:\n\"Something that can improve the cleanliness of your code is to put the game variables in one object of a Game class; this could contain variables such as food, workers, materials and so on.\" - see, I have a problem because i need a new way to save my stuff. currently i used SharedPreferences for saving primitive fields but now, with objects, i am not sure how do i save this 'object with variables inside'. :/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:02:20.473", "Id": "60521", "Score": "0", "body": "@Dravic StackExchange sites are not a forum. It is not a good idea to edit your entire question like that. I do have a few pointers for you though: Consider using a `Map<ResourceType, Integer>` (`ResourceType` can be replaced with `String`, or it could be an `enum`) to hold your resources. Then you can iterate through that map and put the contents of the map into your `SharedPreferences`, or vice versa." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:20:26.677", "Id": "60525", "Score": "0", "body": "Thanks for help, sorry for editing my question. I'll try to make something out of your suggestions and meanwhile I mark your question as answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:30:12.997", "Id": "60528", "Score": "0", "body": "@Dravic Your edit wasn't actually that bad since you didn't remove anything from the question, just added new things. But anyway, welcome back with a new question when your code is ready to be reviewed :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T00:05:30.007", "Id": "36742", "ParentId": "36732", "Score": "4" } } ]
{ "AcceptedAnswerId": "36742", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:24:34.460", "Id": "36732", "Score": "4", "Tags": [ "java", "performance", "android" ], "Title": "Adding buttons for a text adventure game" }
36732
<p>I've never done a FizzBuzz before, so I decided I would. Please let me know what I could have done better. This is ran via a .bat file in Windows.</p> <pre><code> @echo off set loopStart=1 set loopEnd=100 set /a i=%loopStart% - 1 :LoopStart if %i% == %loopEnd% goto :LoopEnd set /a i=%i% + 1 set /a fizzbuzz=%i%%%15 set /a buzz=%i%%%5 set /a fizz=%i%%%3 if %fizzbuzz% == 0 ( echo FizzBuzz ) else if %buzz% == 0 ( echo Buzz ) else if %fizz% == 0 ( echo Fizz ) else ( echo %i% ) goto :LoopStart :LoopEnd set loopStart= set loopEnd= set i= set fizzbuzz= set buzz= set fizz= </code></pre>
[]
[ { "body": "<p>Use FOR /L to iterate a range of numbers - much faster than SET /A with GOTO loop.</p>\n\n<p>Use SETLOCAL to localize variables so no need to undefine them. The EnableDelayedExpansion option does just that so that you can use <code>!var!</code> within a FOR loop.</p>\n\n<p>A minor optimization - it is faster to combine multiple math computations into one SET /A.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>@echo off\nsetlocal enableDelayedExpansion\nfor /l %%N in (1 1 100) do (\n set /a \"fizzbuzz=%%N%%15, buzz=%%N%%5, fizz=%%N%%3\"\n if !fizzbuzz! == 0 (\n echo FizzBuzz\n ) else if !buzz! == 0 (\n echo Buzz\n ) else if !fizz! == 0 (\n echo Fizz\n ) else echo %%N\n)\n</code></pre>\n\n<p>You might consider parameterizing the start and end conditions of the loop.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>@echo off\nREM %1=start %2=end\nsetlocal enableDelayedExpansion\nfor /l %%N in (%1 1 %2) do (\n set /a \"fizzbuzz=%%N%%15, buzz=%%N%%5, fizz=%%N%%3\"\n if !fizzbuzz! == 0 (\n echo FizzBuzz\n ) else if !buzz! == 0 (\n echo Buzz\n ) else if !fizz! == 0 (\n echo Fizz\n ) else echo %%N\n)\n</code></pre>\n\n<p>You could even parameterize the two divisors, but then a different algorithm is needed. Here is a fully parameterized solution that is efficient, though perhaps a bit obfuscated. I still use a modulo operation to test if divisible, but instead of an IF statement, I intentionally divide by zero to raise an error and trigger the conditional execution of the SET statement. Of course I redirect error messages to NUL to avoid unwanted error messages..</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>@echo off\nREM %1=start %2=end %3=divisor1 %4=divisor2\nsetlocal enableDelayedExpansion\nfor /l %%N in (%1 1 %2) do (\n set \"val=\"\n set /a \"1/(%%N %% %3)\" 2&gt;nul || set \"val=Fizz\"\n set /a \"1/(%%N %% %4)\" 2&gt;nul || set \"val=!val!Buzz\"\n if defined val (echo !val!) else echo %%N\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T03:33:55.423", "Id": "60454", "Score": "0", "body": "This is great. I tried to find the proper way to loop via searching and the only method I could find was using GOTOs. I'm glad there's a better way." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T02:05:09.203", "Id": "36745", "ParentId": "36735", "Score": "10" } }, { "body": "<p>When there is a large set of input data for processing, but the different output results are just a small set (that is, several input data produce the same output result), the process is much faster if the set of different results is calculated just once in advance and then the appropriate result is just choosen in accordance with the input data:</p>\n\n<pre><code>@echo off\nsetlocal enableDelayedExpansion\n\nrem Prepare in advance the 15 different results:\nfor /l %%N in (0,1,14) do (\n set /a \"fizzbuzz=%%N%%15, buzz=%%N%%5, fizz=%%N%%3\"\n if !fizzbuzz! == 0 (\n set result[%%N]=FizzBuzz\n ) else if !buzz! == 0 (\n set result[%%N]=Buzz\n ) else if !fizz! == 0 (\n set result[%%N]=Fizz\n )\n)\n\nrem Process input and get output at the fastest possible speed:\nfor /l %%N in (%1 1 %2) do (\n set /a \"fizzbuzz=%%N%%15\"\n if defined result[!fizzbuzz!] (\n for %%I in (!fizzbuzz!) do echo !result[%%I]!\n ) else (\n echo %%N\n )\n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-04T04:08:11.547", "Id": "48901", "ParentId": "36735", "Score": "2" } } ]
{ "AcceptedAnswerId": "36745", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:00:48.243", "Id": "36735", "Score": "9", "Tags": [ "fizzbuzz", "batch" ], "Title": "Batch-File FizzBuzz" }
36735
<p>I created a quiz using the module pattern. My code is as follows:</p> <pre><code>; (function ($) { "use strict"; var s, QuizDefaults = { modalOverlay: $(".modal-overlay"), modalWrap: $(".js-modal-container"), timer: null, // setInterval var for timer totalSeconds: 10, // Amount of seconds for timer count: null, // Current location of timer answerCorrect: null, // Set to true on correct answer, false incorrect score: 0, // Score counter questionCounter: 1, // store which question user is currently on questionText: "quickly click on the correct answer above!", // text below multiple answers frameCur: null // store the current position in quiz }, QuizApp = { settings: $.extend({}, QuizDefaults), // copy default settings // Kick it off // Kick it off init: function () { s = $.extend({}, QuizDefaults); this.questionsGet(); this.bindUIActions(); }, // User interaction events bindUIActions: function () { // Open modal trigger $(".js-quiz-modal-trigger").on("click", function () { QuizApp.toggleModal(s.modalWrap, s.modalOverlay); QuizApp.stateInactive(); }); // Close modal trigger $(".js-quiz-modal-close, .js-quiz-button-finish").on("click", function () { QuizApp.timerReset(); QuizApp.toggleModal(s.modalWrap, s.modalOverlay); QuizApp.restartQuiz(); }); // Begin quiz and timer trigger $(".js-quiz-button-begin").on("click", function () { QuizApp.frameNext($(".js-quiz-body-question1")); QuizApp.stateActive(); QuizApp.timerReset(); QuizApp.timerStart(); }); // Help trigger $(".js-quiz-help").on("click", function () { QuizApp.helpToggle(); }); // Selected answer check trigger $(".quiz-body").on("click", ".js-quiz-answer a", function () { QuizApp.answerCheck($(this)); }); // Move to next question trigger $(".js-quiz-button-continue").on("click", function () { QuizApp.questionNext(); }); // Restart quiz trigger $(".js-quiz-button-again").on("click", function () { QuizApp.restartQuiz(); QuizApp.stateInactive(); }); }, // Pop up or hide Modal toggleModal: function (modal, overlay) { modal.toggleClass("is-open"); this.centerModal(); if (modal.hasClass("is-open")) { $(window).bind("resize", this.centerModal); modal.add(overlay).fadeIn(100); } else { modal.add(overlay).fadeOut(100); $(window).unbind("resize"); } }, // center modal centerModal: function () { var top, left; top = Math.max($(window).height() - s.modalWrap.outerHeight(), 0) / 2; left = Math.max($(window).width() - s.modalWrap.outerWidth(), 0) / 2; s.modalWrap.css({ top: top + $(window).scrollTop(), left: left + $(window).scrollLeft() }); }, // Start timer timerStart: function () { this.timerDisplay(); var ic = $(".js-quiz-body-incorrect"); if (s.count === 0) { ic.addClass("is-expired"); this.frameNext(ic); } else { s.count -= 1; s.timer = setTimeout(function () { QuizApp.timerStart(); }, 1000); } }, // Stop timer timerPause: function () { clearInterval(s.timer); }, // resets countdown timerReset: function () { this.timerPause(); s.count = s.totalSeconds; this.timerDisplay(); }, // prints timer to page timerDisplay: function () { $(".js-numeric-timer-ticker").text(s.count); $(".js-pie-timer div").attr("class", "pie-timer-" + s.count); }, // shows tooltips helpToggle: function () { var helpTip = $(".tip"); if ($('.js-quiz-header').hasClass("is-overlay")) { $('.js-quiz-header').removeClass("is-overlay"); this.frameNext(s.frameCur); helpTip.fadeOut(100); if ($(s.frameCur).is($("[class*=' js-quiz-body-question']")) &amp;&amp; s.count &gt; 0) { this.timerStart(); } else if ($(s.frameCur).is($("[class*=' js-quiz-body-question']"))){ var ic = $(".js-quiz-body-incorrect"); ic.addClass("is-expired"); this.frameNext(ic); this.timerDisplay(); } } else { $('.js-quiz-header').delay(100).queue(function (next) { $(this).addClass("is-overlay"); next(); }); this.frameNext($(".js-quiz-body-default-question")); helpTip.delay(100).fadeIn(100); this.timerPause(); this.frameGet(); } }, // Faded out elements state stateInactive : function () { $(".js-quiz-header").addClass("is-inactive"); }, stateActive : function () { $(".js-quiz-header").removeClass("is-inactive"); }, // Store the current frame so we can access it from another function frameGet: function () { s.frameCur = $(".quiz-body &gt; div:visible"); }, // get Questions TODO Clean up questionsGet: function () { $.get('questions.xml', function (d) { $('item', d).each(function (index) { var $quiz = $(this), question = $quiz.find('question').text(), answers = '', correctAnswer = $.trim($quiz.find('answer[correct]').text()), html; $quiz.find('answer').each(function (i) { var answer = $.trim($(this).text()); answers += '&lt;div class="quiz-answer answer-' + (i + 1) + ' js-quiz-answer"&gt;&lt;a href="#"&gt;' + answer + '&lt;/a&gt;&lt;/div&gt;'; }); html = '&lt;div class="quiz-body-question js-quiz-body-question' + (index + 1) + '"&gt;'; html += '&lt;p&gt; ' + question + '&lt;/p&gt;'; html += answers; html += '&lt;div class="fine"&gt;' + s.questionText + '&lt;/div&gt;'; html += '&lt;div class="correct-answer hidden"&gt;' + correctAnswer + '&lt;/div&gt;'; html += '&lt;/div&gt;'; $('.js-quiz-body-correct').before($(html)); }); }); }, //compare Answers answerCheck: function (userAnswer) { var u = userAnswer.text(), c = userAnswer.parents(".quiz-body-question").find(".correct-answer").text(); this.timerPause(); s.answerCorrect = u === c ? true : false; this.answerScreen(c); }, // Choose corect or incorrect answer screen answerScreen: function (c) { if (s.answerCorrect === false) { var ic = $(".js-quiz-body-incorrect"); this.frameNext(ic); ic.removeClass("is-expired"); } else { this.frameNext($(".js-quiz-body-correct")); this.scoreTally(); } this.answerDisplay(c); }, // Show next question questionNext: function () { s.questionCounter += 1; if ($(".js-quiz-body-question" + s.questionCounter).length &gt; 0) { this.frameNext($(".js-quiz-body-question" + s.questionCounter)); this.stateActive(); this.timerReset(); this.timerStart(); } else { this.stateInactive(); this.scoreFinalUpdate(); this.frameNext($(".js-quiz-body-final")); } }, answerDisplay: function (c) { $(".js-display-correct-answer span").text(c); }, // Hide current slide frameHide: function () { $(".quiz-body &gt; div").stop(true,true).fadeOut(100); }, // Move to next step frameNext: function (next) { this.frameHide(); next.delay(100).fadeIn(100); }, // Tally score scoreTally: function () { s.score += 100 + ((s.count + 1) * 10); this.scoreUpdate(); }, // Update score display scoreUpdate: function () { $(".js-quiz-score-numeric").text(s.score); }, scoreFinalUpdate: function () { $(".js-final-score-numeric").text(s.score); }, // reset app restartQuiz: function () { s = $.extend({}, QuizDefaults); this.scoreUpdate(); this.timerReset(); this.frameNext($(".js-quiz-body-start")); } }; $(function () { QuizApp.init(); }); }(jQuery)); </code></pre> <p>My main question is how do I know how deep to abstract functionality into individual functions? Two that I struggled with abstracting further but that really needed it were the functions <code>helpToggle</code> and <code>questionsGet</code>. Also wondering how much abstraction is too much? Lastly, any pointers on ways to optimize this style of coding are appreciated, I'm new to the module pattern and have been writing mediocre code for a while, <em>really</em> trying to get better, so anything helps. Thank you!</p> <p>EDIT: Per request, I've added the relevant html below, in case it makes my question clearer. I attempted to create a jsfiddle, but failed when I tried to use the XML import.</p> <pre><code> &lt;div class="modal-overlay js-modal-overlay"&gt; &lt;/div&gt; &lt;div class="modal-container js-modal-container"&gt; &lt;div class="modal-wrapper"&gt; &lt;div class="modal"&gt; &lt;div class="close"&gt; &lt;a href="#" class="js-quiz-modal-close"&gt;&lt;span&gt;X&lt;/span&gt; Close&lt;/a&gt; &lt;/div&gt; &lt;div class="quiz"&gt; &lt;div class="quiz-header js-quiz-header"&gt; &lt;div class="quiz-logo"&gt; &lt;img src="img/quiz-logo.png" /&gt; &lt;/div&gt; &lt;div class="quiz-options"&gt; &lt;div class="quiz-score"&gt; &lt;span class="quiz-score-text"&gt;Score:&lt;/span&gt; &lt;span class="quiz-score-numeric js-quiz-score-numeric"&gt;0&lt;/span&gt; &lt;/div&gt; &lt;div class="quiz-help"&gt; &lt;a href="#" class="js-quiz-help"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="quiz-tooltips"&gt; &lt;div class="tip tip-resume"&gt; &lt;p&gt;Click to resume game&lt;/p&gt; &lt;/div&gt; &lt;div class="tip tip-score"&gt; &lt;p&gt;The quicker you answer correctly the more points you receive&lt;/p&gt; &lt;/div&gt; &lt;div class="tip tip-timer"&gt; &lt;p&gt;10 seconds to answer&lt;/p&gt; &lt;/div&gt; &lt;div class="tip tip-answer"&gt; &lt;p&gt;Click on the answer to make your selection&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="quiz-timer"&gt; &lt;div class="numeric-timer js-numeric-timer"&gt; &lt;span class="numeric-timer-ticker js-numeric-timer-ticker"&gt;10&lt;/span&gt;&lt;span class="numeric-timer-default"&gt;10&lt;/span&gt; &lt;/div&gt; &lt;div class="pie-timer js-pie-timer"&gt;&lt;div&gt;&lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="quiz-body"&gt; &lt;div class="quiz-body-start js-quiz-body-start"&gt; &lt;p&gt;Think you are &lt;br /&gt;the ULTIMATE FAN?&lt;/p&gt; &lt;a href="#" class="quiz-button js-quiz-button-begin"&gt;Test Your Wits &lt;span&gt;&amp;#x25b6;&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="quiz-body-correct quiz-result js-quiz-body-correct"&gt; &lt;p&gt;Nicely Done!&lt;/p&gt; &lt;div class="quiz-answer is-selected js-display-correct-answer"&gt; &lt;span&gt;Professional Wrestler&lt;/span&gt; &lt;/div&gt; &lt;a href="#" class="quiz-button quiz-button-continue js-quiz-button-continue"&gt;Continue &lt;span&gt;&amp;#x25b6;&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="quiz-body-incorrect quiz-result js-quiz-body-incorrect"&gt; &lt;p&gt;Oops, &lt;span class="missed-it"&gt;missed it&lt;/span&gt;&lt;span class="times-up"&gt;Time's up&lt;/span&gt;.&lt;/p&gt; &lt;span class="missed-answer fine"&gt;Correct Answer:&lt;/span&gt; &lt;div class="quiz-answer is-selected js-display-correct-answer"&gt; &lt;span&gt;Professional Wrestler&lt;/span&gt; &lt;/div&gt; &lt;a href="#" class="quiz-button quiz-button-continue js-quiz-button-continue"&gt;Continue &lt;span&gt;&amp;#x25b6;&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="quiz-body-final js-quiz-body-final"&gt; &lt;p&gt;You Rock!&lt;/p&gt; &lt;div class="final-score"&gt; &lt;span class="final-score-text"&gt;Final Score:&lt;/span&gt; &lt;span class="final-score-numeric js-final-score-numeric"&gt;123&lt;/span&gt; &lt;/div&gt; &lt;a href="#" class="quiz-button quiz-button-finish js-quiz-button-finish"&gt;Finish &lt;span&gt;&amp;#x25b6;&lt;/span&gt;&lt;/a&gt; &lt;a href="#" class="quiz-button quiz-button-again js-quiz-button-again"&gt;Play Again &lt;span&gt;&amp;#x25b6;&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="quiz-body-default-question js-quiz-body-default-question"&gt; &lt;p&gt;Sample quiz question goes here multiple lines?&lt;/p&gt; &lt;div class="quiz-answer quiz-answer1"&gt; &lt;span class="answer-demo"&gt;Answer&lt;/span&gt; &lt;/div&gt; &lt;div class="quiz-answer quiz-answer2"&gt; &lt;span class="answer-demo"&gt;Answer&lt;/span&gt; &lt;/div&gt; &lt;div class="quiz-answer quiz-answer3"&gt; &lt;span class="answer-demo"&gt;Answer&lt;/span&gt; &lt;/div&gt; &lt;div class="quiz-answer quiz-answer4"&gt; &lt;span class="answer-demo"&gt;Answer&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- .quiz --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- .modal-container --&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T12:03:22.453", "Id": "60482", "Score": "0", "body": "Can you add the html to go with this? Even better a [fiddle](http://jsfiddle.net/) also." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T19:05:22.833", "Id": "60541", "Score": "0", "body": "@abuzittingillifirca : added HTML." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T12:28:31.860", "Id": "60621", "Score": "0", "body": "Two things I need to know. First, are you at all interested in security, e.g. is there any consequence or motivation for someone to cheat on your quiz? Second, when you ask about abstraction, what sort of changes are you interested in protecting against, e.g. do you need this JS to survive a total HTML transplant?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T01:43:27.240", "Id": "60943", "Score": "0", "body": "@sqykly, no security necessary, it's a children's quiz with no reward besides a score :) it does not need to survive a transplant, I was just looking for general guidance and best practices." } ]
[ { "body": "<ol>\n<li><p>Slight issue in your JavaScript. I can't find <code>s</code> declared. I assume it should have been <code>settings</code>.</p></li>\n<li><p>String concatenation inside a loop is not a good idea for performance. I'd also try to keep the addition to the DOM till after the loop.</p></li>\n<li><p>you can treat some values as truthy/falsey instead of <code>===</code> if you know you have set them.</p>\n\n<pre><code>if(s.answerCorrect === false)\n</code></pre>\n\n<p>is more confusing than writing</p>\n\n<pre><code>if(!s.answerCorrect)\n</code></pre>\n\n<p>Similarly I'd change</p>\n\n<pre><code>s.answerCorrect = u === c ? true : false;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>s.answerCorrect = u === c;\n</code></pre></li>\n<li><p>I'd say your level of abstraction is bordering on too much. for example:</p>\n\n<pre><code>this.centerModal();\n</code></pre>\n\n<p>is used in only one place and is only a couple of lines of code. This wouldn't be enough to make me create another function for it.</p>\n\n<p>On the otherhand I would move constants into variables/settings like: </p>\n\n<pre><code>var CLASS_PREFIX = \".js-quiz\";\nvar INCORRECT_BODY_CSS_CLASS = CLASS_PREFIX + \"-body-incorrect\";\n</code></pre>\n\n<p><strong>only</strong> for classes and text you might want to change or repeat.</p></li>\n</ol>\n\n<hr>\n\n<p>In general I would say this is a clean and readable attempt.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T23:46:00.240", "Id": "60441", "Score": "0", "body": "Thank you for the in-depth analysis sir! Great info here. S is declared at the very top: \n`; (function ($) {\n\"use strict\";\n\nvar s,\n QuizDefaults`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T23:50:13.113", "Id": "60442", "Score": "0", "body": "So in general, it's better to not abstract functionality into a separate function if it's only going to be used in one other function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T00:46:48.497", "Id": "60449", "Score": "0", "body": "@IvanDurst - it may be language dependant, but sometimes (like in Java), having a function call inside a loop even if that function is only called from in the loop, can sometimes in fact help performance. For non-looped, called-from-one-place, small functions, I would say, manually 'inline' the function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T01:04:12.890", "Id": "60450", "Score": "0", "body": "@rolfl, great info, thank you. James, I will likely be accepting this answer soon." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T23:32:46.733", "Id": "36739", "ParentId": "36736", "Score": "5" } }, { "body": "<p>Your application does not regard <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">Separation of Concerns</a>.\nWhich makes it unmaintainable and untestable.</p>\n\n<p>For example:</p>\n\n<p>You store your application state in DOM. If you are not experienced enough to know that <em>it's just bad</em>, consider this: string <code>js-quiz-body-question</code> found <strong>6</strong> times throughout the code. Every piece of code should be as <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> as possible.</p>\n\n<p>Look for example at function <code>questionsGet</code>. </p>\n\n<ol>\n<li>It does retrieves an XML document. </li>\n<li>Walks its DOM.</li>\n<li>Builds up HTML snippet.</li>\n<li>Inserts the HTML snippet to current document.</li>\n</ol>\n\n<p>A function's name should tell what it does. Just extracting the last 3 of the above into a named function, say <code>renderQuestionsFromXmlDocument</code> you could easily add XML inline for testing.</p>\n\n<pre><code>renderQuestionsFromString : function() {\n var doc = $.parseXML(\"&lt;quiz&gt;&lt;item&gt;&lt;question&gt;question?&lt;/question&gt;&lt;answer&gt;ans1&lt;/answer&gt;&lt;answer correct='correct'&gt;ans2&lt;/answer&gt;&lt;/item&gt;&lt;/quiz&gt;\");\n renderQuestionsFromXmlDocument(doc);\n}\n</code></pre>\n\n<p>You should not do much in <code>init</code> at all. <a href=\"http://www.youtube.com/watch?v=RlfLCWKxHJ0\" rel=\"nofollow\">Don't look for things</a> for example. <code>init</code> should only set fields that differ from their *sensible default*s.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T11:51:08.437", "Id": "36845", "ParentId": "36736", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:21:44.840", "Id": "36736", "Score": "2", "Tags": [ "javascript", "jquery", "html", "closure" ], "Title": "Deeper abstracting of code into functions" }
36736
<pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt; &lt;title&gt;Car Rental Calculator&lt;/title&gt; &lt;style type="text/css" media="screen"&gt; .number { font-weight: bold; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;?php // Script 4.2 - handle_calc.php /* This script takes values from calculator.html and performs total cost and monthly payment calculations. */ // Address error handling, if you want. if(isset($_POST['f_name'])){ // Get the values from the $_POST array: $Name = $_POST['f_name']; $depositAmount = $_POST['deposit']; $days = $_POST['days']; $B_miles = $_POST['b_mileage']; $E_miles = $_POST['e_mileage']; $insurance = $_POST['insurance']; $drivers = $_POST['drivers']; $car = $_POST['rental']; $age = $_POST['age']; $gas = $_POST['gas']; // Calculate the total: switch ($car) { case "subcompact": $car_per_day = 20; $max_gas_gallons = 10; break; case "compact": $car_per_day = 30; $max_gas_gallons = 20; break; case "luxury": $car_per_day = 40; $max_gas_gallons = 30; break; case "mid-size": $car_per_day = 25; $max_gas_gallons = 35; break; case "minivan": $car_per_day = 80; $max_gas_gallons = 20; break; case "suv": $car_per_day = 60; $max_gas_gallons = 15; break; } if (isset($_POST['drivers_under_25'])) { $drivers_under_25 = $_POST['drivers_under_25']; } else { $drivers_under_25 = 0; } if ($_POST['gas'] == 'empty' { price = xx} else { price =zz } $daycharge = 30.00 * $days; $initial_amount = $daycharge + .35 *($E_miles - $B_miles - ($days * 100) ); $initial_amount = $initial_amount - $depositAmount; $gas_charge = ($max_gas_gallons - $gallons_user) *$price_per_gallon; $drivercharge = 5 *($drivers - 1); $initial_amount = $initial_amount + $drivercharge; $inscharge = $initial_amount * $insurance; $total = $initial_amount + $inscharge; // Print out the results: echo 'Hello '; echo $Name; echo "&lt;br&gt;"; echo 'Deposit Amount : ' ; echo $depositAmount; echo "&lt;br&gt;"; echo 'Your daily charge will be: '; echo $daycharge; echo "&lt;br&gt;"; echo 'Total Days : '; echo $days; echo "&lt;br&gt;"; echo 'Insurance Charge : '; echo $inscharge; echo "&lt;br&gt;"; echo 'Driver Charge : '; echo $drivercharge; echo "&lt;br&gt;"; echo 'Your Total Price : '; echo $total; } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:29:41.357", "Id": "60423", "Score": "5", "body": "Explain what your code is doing, please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:31:56.433", "Id": "60425", "Score": "0", "body": "this is a code for a car rental form, would like me to share my html part too @SimonAndréForsberg" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:32:43.433", "Id": "60426", "Score": "0", "body": "I think @SimonAndréForsberg means for you to edit the title of your question so it is more relevant to what your code does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:33:04.360", "Id": "60427", "Score": "1", "body": "What exactly are you unsure about that requires review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:36:08.253", "Id": "60429", "Score": "1", "body": "And some more text in the question to summarize the code would be a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:37:27.183", "Id": "60430", "Score": "0", "body": "i just want to know what everyone thinks of my code, and if it needs work" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:37:57.640", "Id": "60431", "Score": "2", "body": "@Garry General code reviews [are accepted](http://meta.codereview.stackexchange.com/questions/790/should-a-post-with-no-specific-questions-imply-a-general-review) on Code Review. Doesn't need to be anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T09:47:47.003", "Id": "60708", "Score": "0", "body": "You will want to sanitize all of those strings before you write them out; otherwise there's an XSS risk to your application." } ]
[ { "body": "<p>Just a few things (not including the obvious suggestion to try an object-oriented implementation - though I prefer it, a script of this size won't hurt anyone this way):</p>\n\n<ol>\n<li>Your <code>switch()</code> statement doesn't have a <code>default:</code> case. What\nhappens if there's a problem with the input and it doesn't match any\ncase? This <em>can</em> be a security risk.</li>\n<li>Have you considered simply setting the values of your calculations\nin this script and then <code>return</code>ing them? This will allow your end user to do whatever they like with the HTML and place your variables where they're necessary rather than tying your front-end design to your function.</li>\n<li>You really need to name your variables more consistently and meaningfully. It seems like a small thing, but will make all the difference in the long run. Start this practice now with small applications and you'll continue it when you work on the big stuff - and it'll pay off.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T03:03:27.773", "Id": "36748", "ParentId": "36737", "Score": "3" } }, { "body": "<p>First of all, it's always a good practise to put all your PHP logic above the template (or in another file) and only put some simple if statements and echo in the HTML itself. This avoids \"headers already send\" errors and it's better for seperation of the code.</p>\n\n<p><strong>Line 19-28.</strong> Here you simply save the POST variables in variables. This is just useless spilling of memory, why don't you use the POST variables instead?<br>\n<strong>Line 17.</strong> You can better check if the <code>$_SERVER['REQUEST_METHOD']</code> is POST<br>\n<strong>Line 71.</strong> Syntax error, you are missing <code>)</code> and <code>price</code> is not a variable (missing <code>$</code>) and <code>xx</code> and <code>zz</code> are not strings: <code>if ($_POST['gas'] == 'empty' { price = xx} else { price =zz }</code><br></p>\n\n<p>Some overall tips:</p>\n\n<ul>\n<li>Please be consistent, choose a coding standard and use it everywhere in your script. Make sure you indents are the same everywhere, your variables all use the same capitialization rules, etc.</li>\n<li>Including an input, e.g. <code>f_name</code>, only to be able to show his name seems a bit weird to me. I'd like to only input things the application needs, instead of some stuff to personalize the final message...</li>\n<li>Break you code into functions. This way you can easily call <code>calculateCarRental(...)</code> and it'll give you the information.</li>\n<li>Use validation. You don't check if the user filled in the fields.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T09:50:51.757", "Id": "60709", "Score": "0", "body": "Saving the POST variables to other variables is *ugly* - I'll give you that. But arguing that it's \"spilling of memory\" is kinda pointless. Variables are cheap, and you have no idea if PHP will alias those variables together (which it will if you Zend optimise it). Even if they don't get aliased, variables are cheap and will cost a trivial quantity of memory compared with, say, doing a single concatenation operation anywhere in the program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T18:00:07.013", "Id": "60745", "Score": "0", "body": "Comments are even cheaper than variables. More `$_POST` variables like, `$gas` and `$age`, are saved into other variables than are later used in the code. A comment telling the next programmer which form fields are available would be cheaper than just rote copying of all `$_POST` variables." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T13:03:27.193", "Id": "36850", "ParentId": "36737", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:25:36.880", "Id": "36737", "Score": "0", "Tags": [ "php", "html" ], "Title": "Car Rental Form" }
36737
<p>I have project where I need to use C# and Entity Framework.</p> <p>After my question <a href="https://stackoverflow.com/questions/20277478/entity-framework-create-and-update-related-objects-in-wpf">here</a>, I have decided to use Unit of Work and Repository patterns. </p> <p>This is the first time when I'm using this. Can anyone tell me if I'm doing this right or I have to redesign something?</p> <p>BTW: why do I have to set <code>student.Group = null</code> in <code>Service.StudentService.Update()</code>? Without this I'm getting exception. I don't understand when should I use <code>student.Group</code>, and when <code>student.GroupId</code>.</p> <p>Entities:</p> <pre><code>namespace Model { public abstract class BaseEntity { [Timestamp] public Byte[] TimeStamp{get; set;} } } namespace Model { public class Group : BaseEntity { [Key] public int GroupId {get; set;} public string Name {get; set;} public virtual ICollection&lt;Student&gt; Students {get; set;} } } namespace Model { public class Student : BaseEntity { [Key] public int StudentId {get; set;} public string FirstName {get; set;} public string LastName {get; set;} public string IndexNo {get; set;} public int GroupId {get; set;} [ForeignKey("GroupId")] public virtual Group Group {get; set;} public virtual ICollection&lt;Registration&gt; Registrations {get; set;} } } </code></pre> <p>Context:</p> <pre><code>namespace Model { public class StorageContext : DbContext { public DbSet&lt;Group&gt; Groups {get; set;} public DbSet&lt;Student&gt; Students {get; set;} ... } } </code></pre> <p>Repository:</p> <pre><code>namespace Repository { public class GenericRepository&lt;TEntity&gt; where TEntity : BaseEntity { internal StorageContext context; internal DbSet&lt;TEntity&gt; dbSet; public GenericRepository(StorageContext context) { this.context = context; this.dbSet = context.Set&lt;TEntity&gt;(); } public virtual IEnumerable&lt;TEntity&gt; Get( Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null, Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, string includeProperties = "") { IQueryable&lt;TEntity&gt; query = dbSet; if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } if (orderBy != null) { return orderBy(query).ToList(); } else { return query.ToList(); } } public virtual TEntity GetById(object id) { return dbSet.Find(id); } public virtual void Insert(TEntity entity) { dbSet.Add(entity); } public virtual void Delete(object id) { TEntity entityToDelete = dbSet.Find(id); Delete(entityToDelete); } public virtual void Delete(TEntity entity) { if (context.Entry(entity).State == EntityState.Detached) { dbSet.Attach(entity); } dbSet.Remove(entity); } public virtual void Update (TEntity entity) { dbSet.Attach(entity); context.Entry(entity).State = EntityState.Modified; } } } </code></pre> <p>UnitOfWorks:</p> <pre><code>namespace Repository { public class GenericUnitOfWork&lt;TEntity&gt; : IDisposable where TEntity : BaseEntity{ public readonly StorageContext Context; private bool _disposed; private GenericRepository&lt;TEntity&gt; repository; public GenericRepository&lt;TEntity&gt; GetRepository() { return repository; } public GenericUnitOfWork(StorageContext context) { this.Context = context; repository = new GenericRepository&lt;TEntity&gt;(Context); } public IEnumerable&lt;TEntity&gt; Get() { return repository.Get(null, null, ""); } public virtual void Insert(TEntity entity) { repository.Insert(entity); Save(); } public virtual void Update(TEntity entity) { repository.Update(entity); Save(); } public void Delete(object id) { repository.Delete(id); Save(); } public void Save() { Context.SaveChanges(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { Context.Dispose(); } this._disposed = true; } } } } namespace Repository { public class GroupUnitOfWork : GenericUnitOfWork&lt;Group&gt;{ private GenericRepository&lt;Group&gt; repository; public GroupUnitOfWork(StorageContext context) : base(context){ repository = new GenericRepository&lt;Group&gt;(Context); } public IEnumerable&lt;Group&gt; GetIncludeStudents() { return repository.Get(null,null,"Students"); } } } namespace Repository { public class StudentUnitOfWork : GenericUnitOfWork&lt;Student&gt; { private GenericRepository&lt;Student&gt; repository; public StudentUnitOfWork(StorageContext context) : base(context){ repository = new GenericRepository&lt;Student&gt;(Context); } public IEnumerable&lt;Student&gt; GetByGroupId(object groupId) { return repository.Get(s =&gt; s.GroupId == (int)groupId, null, "Group"); } public override void Insert(Student student) { repository.Insert(student); Save(); } public override void Update(Student student) { repository.Update(student); Save(); } } } </code></pre> <p>Services:</p> <pre><code>namespace Service { public class GenericService&lt;TEntity&gt; where TEntity : BaseEntity{ protected StorageContext context; public IEnumerable&lt;TEntity&gt; Get() { using(var context = new StorageContext()) { return new GenericUnitOfWork&lt;TEntity&gt;(context).Get(); } } public virtual void Insert(TEntity entity) { using(var context = new StorageContext()) { new GenericUnitOfWork&lt;TEntity&gt;(context).Insert(entity); } } public virtual void Update(TEntity entity) { using(var context = new StorageContext()) { new GenericUnitOfWork&lt;TEntity&gt;(context).Update(entity); } } public void Delete(object id) { using(var context = new StorageContext()) { new GenericUnitOfWork&lt;TEntity&gt;(context).Delete(id); } } } } namespace Service { public class GroupService : GenericService&lt;Group&gt;{ public IEnumerable&lt;Group&gt; GetIncludeStudents() { using(var context = new StorageContext()) { return new GroupUnitOfWork(context).GetIncludeStudents(); } } } } namespace Service { public class StudentService : GenericService&lt;Student&gt; { public IEnumerable&lt;Student&gt; GetByGroupId(object id) { using(var context = new StorageContext()) { return new StudentUnitOfWork(context).GetByGroupId(id); } } public override void Update(Student student) { using(var context = new StorageContext()) { //without set student.Group to null I'm getting exception. student.Group = null; new StudentUnitOfWork(context).Update(student); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T23:32:07.923", "Id": "60439", "Score": "0", "body": "Group entity vs GroupId: choose one, stick to it. You can specify either, or both. I think you're getting an exception because your navigation property isn't `virtual`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T00:23:44.083", "Id": "60445", "Score": "0", "body": "True, I've overlooked this. But still, I'm getting: `A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.` exception" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:58:02.730", "Id": "60559", "Score": "1", "body": "Can you post your controller... that's really where it matters the most." } ]
[ { "body": "<p>That looks pretty good but it depends on what your controller looks like. </p>\n\n<p>There is a valid argument that the Entity Framework implements the Repository Pattern for you and all you need to implement is the service layer. </p>\n\n<p>So you could put the service layer directly on top of the dbSet. Since I started using just the service layer without the repo pattern directly (so the service layer accesses DbSet) I have not had any problems. </p>\n\n<hr>\n\n<p>DbSet == Repository<br>\nDbContext == Unit of Work</p>\n\n<hr>\n\n<p>Here is what a controller with the repo looks like. If yours is similar I would say that your code is correct. </p>\n\n<p><strong>Cheeseburger Controller</strong></p>\n\n<pre><code>namespace WickedAwesomeWebApp\n{ \n public class CheeseburgerController : Controller\n {\n public UnitOfWork unitOfWork = new UnitOfWork();\n public CheeseburgerRepository cheeseburgerRepository = new CheeseburgerRepository(new MyDbContext());\n\n public ViewResult Index()\n {\n var viewModel = new CheeseburgerViewModel();\n viewModel.Cheeseburger = unitOfWork.CheeseburgerRepository.Get();\n\n return View(viewModel);\n }\n // GET: /Cheeseburger/Details/5\n public ViewResult Details(int id)\n {\n return View(unitOfWork.CheeseburgerRepository.GetById(id));\n }\n\n // GET: /Cheeseburger/Create\n public ActionResult Create()\n {\n return View();\n } \n\n // POST: /Cheeseburger/Create\n [HttpPost]\n public ActionResult Create ([Bind(Include = {CheeseburgerId,/*Include Object Properties to Bind*/{)]Cheeseburger cheeseburger)\n {\n if (ModelState.IsValid) {\n unitOfWork.CheeseburgerRepository.Insert(cheeseburger);\n unitOfWork.CheeseburgerRepository.Update(cheeseburger);\n return RedirectToAction({Index{);\n } else {\n return View();\n }\n }\n\n // GET: /Cheeseburger/Edit/5\n\n public ActionResult Edit(int id)\n {\n return View(unitOfWork.CheeseburgerRepository.GetById(id));\n }\n\n // POST: /Cheeseburger/Edit/5\n\n [HttpPost]\n public ActionResult Edit(Cheeseburger cheeseburger)\n {\n if (ModelState.IsValid) {\n unitOfWork.CheeseburgerRepository.Update(cheeseburger);\n unitOfWork.Save();\n return RedirectToAction({Index{);\n } else {\n return View();\n }\n }\n\n // GET: /Cheeseburger/Delete/5\n\n public ActionResult Delete(int id)\n {\n return View(unitOfWork.CheeseburgerRepository.GetById(id));\n }\n\n // POST: /Cheeseburger/Delete/5\n\n [HttpPost, ActionName({Delete{)]\n public ActionResult DeleteConfirmed(int id)\n {\n unitOfWork.MealRepository.Delete(id);\n unitOfWork.Save();\n\n return RedirectToAction({Index{);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing) {\n unitOfWork.Dispose();\n }\n base.Dispose(disposing);\n }\n }\n}\n</code></pre>\n\n<p><strong>ICheeseburgerRepository</strong></p>\n\n<pre><code>namespace WickedAwesomeWebApp\n{\n public interface ICheeseburgerRepository : IDisposable\n {\n IQueryable Cheeseburgers { get; }\n IEnumerable GetCheeseburgers();\n Cheeseburger GetCheeseburgerById(int? id);\n void InsertCheeseburger(Cheeseburger id);\n void DeleteCheeseburger(int cheeseburgerId);\n void UpdateCheeseburger(Cheeseburger cheeseburger);\n void Save();\n new void Dispose();\n }\n</code></pre>\n\n<p><strong>CheeseburgerRepository With CRUD</strong></p>\n\n<pre><code> public class CheeseburgerRepository : ICheeseburgerRepository\n {\n private SkimosContext context = new SkimosContext();\n\n public CheeseburgerRepository(SkimosContext context)\n {\n this.context = context;\n }\n\n public IQueryable Cheeseburgers\n {\n get { return context.Cheeseburgers; }\n }\n\n public IEnumerable GetCheeseburgers()\n {\n return context.Cheeseburgers.ToList();\n }\n\n public Cheeseburger GetCheeseburgerById(int? id)\n {\n return context.Cheeseburgers.Find(id);\n }\n\n public void InsertCheeseburger(Cheeseburger cheeseburger)\n {\n context.Cheeseburgers.Add(cheeseburger);\n }\n\n public void DeleteCheeseburger(int cheeseburgerId)\n {\n Cheeseburger cheeseburger = context.Cheeseburgers.Find(cheeseburgerId);\n context.Cheeseburgers.Remove(cheeseburger);\n }\n\n public void UpdateCheeseburger(Cheeseburger cheeseburger)\n {\n context.Entry(cheeseburger).State = System.Data.Entity.EntityState.Modified;\n }\n\n public void Save()\n {\n context.SaveChanges();\n }\n\n private bool disposed;\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposed)\n {\n if (disposing)\n {\n context.Dispose();\n }\n }\n disposed = true;\n }\n\n public void Dispose()\n {\n if (context != null) context.Dispose();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-27T21:19:59.747", "Id": "248871", "Score": "2", "body": "Isn't the UnitOfWork supposed to contain the repositories and the DB context? Isn't that sort of the point of the UnitOfWork?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-30T11:08:02.357", "Id": "249411", "Score": "0", "body": "No your coupling the unit of work and repositories together. They are different patterns commonly used together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-24T15:16:42.660", "Id": "329911", "Score": "0", "body": "Not coupling implementations - but unit of work should have repository interfaces exposed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T21:09:59.670", "Id": "36818", "ParentId": "36738", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T23:15:37.317", "Id": "36738", "Score": "4", "Tags": [ "c#", "design-patterns", "entity-framework" ], "Title": "Is this correct usage of Repository + Unit of Work + Service Pattern" }
36738
<p>I'm creating a simple <a href="http://en.wikipedia.org/wiki/Syslog" rel="nofollow">syslog server</a> in Delphi XE2 using Indy's <code>TIdSyslogServer</code>. I've decided to make it dump into a <code>TClientDataSet</code> and display in a <code>TDBGrid</code>, but I'm skeptical about how well it would handle if the log got quite big, and what I should expect when it grows to millions of records. This application is for internal use and I don't intend to make any software from it, and just keep the code real simple.</p> <p>The purpose of the application is for numerous IP surveillance cameras along with various other network based equipment to report their log to one place.</p> <p>This is a simple application with just 1 form, all the code is directly in the form's unit. The actual application is a separate project (call this my SSCCE).</p> <p><strong>uMain.pas</strong></p> <pre><code>unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdSocketHandle, IdBaseComponent, IdComponent, IdSysLogServer, IdSysLog, IdSysLogMessage, IdUDPBase, IdUDPServer, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Data.DB, Datasnap.DBClient, MidasLib {to avoid requiring MIDAS.DLL}; type TForm1 = class(TForm) Server: TIdSyslogServer; DS: TClientDataSet; DSC: TDataSource; DBGrid1: TDBGrid; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ServerSyslog(Sender: TObject; ASysLogMessage: TIdSysLogMessage; ABinding: TIdSocketHandle); private procedure PrepareDS; public end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var H: TIdSocketHandle; begin PrepareDS; Server.Bindings.Clear; H:= Server.Bindings.Add; H.IP:= '0.0.0.0'; //All IP's H.Port:= 514; //syslog standard port 514 Server.Active:= True; //Activate server end; procedure TForm1.PrepareDS; begin DS.DisableControls; try DS.Close; DS.FieldDefs.Clear; DS.FieldDefs.Add('timestamp', ftDateTime); DS.FieldDefs.Add('pri', ftInteger); //Need to convert the next 2 to string DS.FieldDefs.Add('facility', ftString, 15); DS.FieldDefs.Add('severity', ftString, 15); DS.FieldDefs.Add('hostname', ftString, 15); DS.FieldDefs.Add('message', ftString, 200); DS.CreateDataSet; DS.Open; finally DS.EnableControls; end; end; procedure TForm1.FormDestroy(Sender: TObject); begin Server.Active:= False; end; procedure TForm1.ServerSyslog(Sender: TObject; ASysLogMessage: TIdSysLogMessage; ABinding: TIdSocketHandle); begin DS.Append; DS['timestamp']:= ASysLogMessage.TimeStamp; DS['pri']:= ASysLogMessage.Pri; DS['facility']:= ASysLogMessage.Facility; DS['severity']:= ASysLogMessage.Severity; DS['hostname']:= ASysLogMessage.Hostname; DS['message']:= ASysLogMessage.Msg.Content; DS.Post; end; end. </code></pre> <p><strong>uMain.dfm</strong></p> <pre><code>object Form1: TForm1 Left = 354 Top = 124 Caption = 'Form1' ClientHeight = 400 ClientWidth = 597 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate OnDestroy = FormDestroy PixelsPerInch = 96 TextHeight = 13 object DBGrid1: TDBGrid Left = 0 Top = 48 Width = 597 Height = 352 Align = alBottom Anchors = [akLeft, akTop, akRight, akBottom] DataSource = DSC TabOrder = 0 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clWindowText TitleFont.Height = -11 TitleFont.Name = 'Tahoma' TitleFont.Style = [] end object Server: TIdSyslogServer Bindings = &lt;&gt; OnSyslog = ServerSyslog Left = 120 Top = 168 end object DS: TClientDataSet Aggregates = &lt;&gt; Params = &lt;&gt; Left = 168 Top = 168 end object DSC: TDataSource DataSet = DS Left = 200 Top = 168 end end </code></pre> <p>I'm assuming that at some point I should at least make it dump to a file, then start fresh. That's an obvious feature I will need to add. Along with that of course a way to recall the saved logs. That all comes later, but I'm only worried how the client dataset will handle it when it gets very large, and really how I should determine the maximum before I dump it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T01:18:33.853", "Id": "60451", "Score": "0", "body": "I'm kinda wondering if this type of question is better off on programmers SE?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T01:22:46.197", "Id": "60452", "Score": "0", "body": "For the record, I started building my own syslog using an Indy UDP server, and got it working, but then realized Indy already has a syslog server :-)" } ]
[ { "body": "<p><code>TClientDataset</code> will work fine for this purpose, except for the \"million of records\". I don´t believe that any dataset will have a good response for such an amount of data, so I think you will have to work some kind of paging system and keep in the dataset only some hundreds or thoudsands of records, after all, it´s unhuman to handle millions of anything (;-)).</p>\n\n<p>If you really need to keep millions of records, so it´s my opinion that you really need some kind of database system to stored it, not an in-memory structure. </p>\n\n<p>I took a look on your code and noticed that you call <code>Open</code> just after calling <code>CreateDataset</code>. That´s unnecessary given <code>CreateDataset</code> already gets the dataset open.</p>\n\n<p>By the way, you had and excelent idea on including <code>MidasLib</code> in you uses clause.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T13:36:57.020", "Id": "36777", "ParentId": "36743", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T01:00:07.670", "Id": "36743", "Score": "1", "Tags": [ "performance", "logging", "delphi", "server" ], "Title": "Is it feasible to create a syslog server which writes to a client dataset?" }
36743
<p>I have code that checks the range of a value and sets a variable accordingly. </p> <pre><code>if ( 169 &lt;= angle &amp;&amp; angle &lt; 191 ) {currentOrientation = "1";} if ( 191 &lt;= angle &amp;&amp; angle &lt; 214 ) {currentOrientation = "2";} if ( 214 &lt;= angle &amp;&amp; angle &lt; 236 ) {currentOrientation = "3";} if ( 236 &lt;= angle &amp;&amp; angle &lt; 259 ) {currentOrientation = "4";} if ( 259 &lt;= angle &amp;&amp; angle &lt; 281 ) {currentOrientation = "5";} if ( 281 &lt;= angle &amp;&amp; angle &lt; 304 ) {currentOrientation = "6";} if ( 304 &lt;= angle &amp;&amp; angle &lt; 326 ) {currentOrientation = "7";} if ( 326 &lt;= angle &amp;&amp; angle &lt; 349 ) {currentOrientation = "8";} if ( 349 &lt;= angle) {currentOrientation = "9";} if ( angle &lt; 11 ) {currentOrientation = "9";} if ( 11 &lt;= angle &amp;&amp; angle &lt; 34 ) {currentOrientation = "10";} if ( 34 &lt;= angle &amp;&amp; angle &lt; 56 ) {currentOrientation = "11";} if ( 56 &lt;= angle &amp;&amp; angle &lt; 79 ) {currentOrientation = "12";} if ( 79 &lt;= angle &amp;&amp; angle &lt; 101 ) {currentOrientation = "13";} if ( 101 &lt;= angle &amp;&amp; angle &lt; 124 ) {currentOrientation = "14";} if ( 124 &lt;= angle &amp;&amp; angle &lt; 146 ) {currentOrientation = "15";} if ( 146 &lt;= angle &amp;&amp; angle &lt; 169 ) {currentOrientation = "16";} </code></pre> <p>Each range is 1/16 of 360°. There is a shift so that cardinal values (90,180..) are in the center of the range. </p> <p>I am curious about how this code can be optimized. Maybe a jQuery function? So far a loop isn't interesting enough if I can't get the values automatically. </p>
[]
[ { "body": "<p>Use <code>else if</code> statements after the first <code>if</code> so that it breaks out of the comparisons when a match is found:</p>\n\n<pre><code>if ( 169 &lt;= angle &amp;&amp; angle &lt; 191 ) {currentOrientation = \"1\";}\nelse if ( 191 &lt;= angle &amp;&amp; angle &lt; 214 ) {currentOrientation = \"2\";}\n...\nelse ( 146 &lt;= angle &amp;&amp; angle &lt; 169 ) {currentOrientation = \"16\";}\n</code></pre>\n\n<p>Also the condition for the \"9\" orientation can be combined into a single \"or\" condition:</p>\n\n<pre><code>if ( 349 &lt;= angle || angle &lt; 11) {currentOrientation = \"9\";}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T02:48:18.963", "Id": "36746", "ParentId": "36744", "Score": "2" } }, { "body": "<p>This function has very slightly different boundaries, but you may find it does better than what you have right now:</p>\n\n<pre><code>function degreesToOrientation(degrees){\n return 1 + Math.floor(((Number(degrees) + 180 + 11.25) % 360.0) / 22.5);\n}\n</code></pre>\n\n<p>one sixteenth of a circle is 22.5 degrees. centering that is at 11.25 degrees.</p>\n\n<p>So, you add 11.25 degrees to your angle, rotate it a further 180 degrees, Use the Modulo to bring the value back in to range, then divide it by the size of each segment.</p>\n\n<p>This returns a value from 0 through 15 (for the 16 segments). So, add 1 to get your 'orientation'.</p>\n\n<p>It does not care about the degree amount as long as it is greater than -191.25 ... to start with... (the modulo operation is funny with negative numbers...)</p>\n\n<p><a href=\"http://jsfiddle.net/DmZsc/3/\" rel=\"nofollow\">Here is a jfiddle</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T03:45:37.873", "Id": "60455", "Score": "0", "body": "Fantastic. I wish I could write clever things like this in seconds. Thanks a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T03:08:16.607", "Id": "36749", "ParentId": "36744", "Score": "4" } } ]
{ "AcceptedAnswerId": "36749", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T01:47:12.460", "Id": "36744", "Score": "3", "Tags": [ "javascript", "jquery", "optimization", "mathematics" ], "Title": "Find number matching range" }
36744
<p>Some recent discussions on this site involved the <strong>Fizz-Buzz</strong> game - I have never actually implemented this, but for the record this is what I put together:</p> <pre><code>public class FizzBuzzConverter { private readonly int _fizz; private readonly int _buzz; public FizzBuzzConverter(int fizz, int buzz) { _fizz = fizz; _buzz = buzz; } public string Convert(int value) { if (value % (_fizz*_buzz) == 0) return "FizzBuzz"; if (value % _buzz == 0) return "Buzz"; if (value % _fizz == 0) return "Fizz"; return value.ToString(); } } </code></pre> <p>When people implement <a href="/questions/tagged/fizzbuzz" class="post-tag" title="show questions tagged &#39;fizzbuzz&#39;" rel="tag">fizzbuzz</a>, they tend to run a loop going from 1 to 100 and outputting the results to some console. According to Wikipedia, that's not how the game plays:</p> <blockquote> <p>Players generally sit in a circle. The player designated to go first says the number "1", and each player thenceforth counts one number in turn. However, any number divisible by three is replaced by the word fizz and any divisible by five by the word buzz. Numbers divisible by both become fizz buzz. A player who hesitates or makes a mistake is eliminated from the game.</p> </blockquote> <p>So I'm thinking of going that way - and since I've never actually coded anything remotely resembling AI since I tweaked some <a href="http://en.wikipedia.org/wiki/Duke_Nukem_3D" rel="nofollow noreferrer">Duke Nukem 3D</a> configuration files in 1997, I'd like to get some feedback and refactoring thoughts about this:</p> <pre><code>public class PseudoBrain { private readonly FizzBuzzConverter _converter; public PseudoBrain(FizzBuzzConverter converter) { _converter = converter; } public virtual string Think(string lastResult, int value) { var random = new Random(); var ai = random.Next(0, 99); var result = _converter.Convert(value); if (ai &lt; 85) { // thinks straight most of the time. return result; } else { Hesitate(); if (ai &lt; 95) return result; // could be right, could be wrong. hesitant anyway. return lastResult == "fizz" ? value.ToString() : "buzz"; } } private void Hesitate() { Thread.Sleep(500); } } </code></pre> <p>This brain works, ..it's just a little too hesitant:</p> <p><img src="https://i.stack.imgur.com/Cfgos.png" alt="enter image description here"></p> <p>Still, it's not <em>too</em> dumb:</p> <p><img src="https://i.stack.imgur.com/sYJkC.png" alt="enter image description here"></p> <p>I'm sure I could tweak the percentages to come up to something decently smart enough to implement a game with 5-6 of those "brains" playing against a human player, who would win if all the brains fried before his.</p> <p>How's this <code>PseudoBrain</code> class doing? Don't <code>Hesitate()</code>, just say what you <code>Think()</code>!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T10:45:34.603", "Id": "60474", "Score": "1", "body": "[According to Jeff, it is how you write FizzBuzz.](http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T10:48:57.370", "Id": "60475", "Score": "0", "body": "Also, if you wanted to have a human-like AI, you would need to factor in how difficult computing the modulo is for a human." } ]
[ { "body": "<p>I'd first create an <code>interface</code> that your <code>FizzBuzzConverter</code> class can implement:</p>\n\n<pre><code>public interface IConverter\n{\n string Convert(int value);\n}\n\npublic class FizzBuzzConverter : IConverter\n{\n // ...\n}\n</code></pre>\n\n<p>Then the <code>PseudoBrain</code> can have any implementation of the interface injected into it:</p>\n\n<pre><code>public class PseudoBrain\n{\n private readonly IConverter _converter;\n\n public PseudoBrain(IConverter converter)\n {\n _converter = converter;\n }\n\n // ...\n}\n</code></pre>\n\n<p>This will allow for easier unit testing via mocking or writing and using new Converters.</p>\n\n<p>Lastly, I have a bit of a squicky feeling when I see random number generators created over and over (as <code>Think()</code> will be called repeatedly). So I put that at the class level:</p>\n\n<pre><code>public class PseudoBrain\n{\n private readonly Random _random = new Random();\n private readonly IConverter _converter;\n\n public PseudoBrain(IConverter converter)\n {\n _converter = converter;\n }\n\n public virtual string Think(string lastResult, int value)\n {\n var ai = _random.Next(0, 99);\n\n // ...\n }\n\n // ...\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T04:36:17.740", "Id": "36753", "ParentId": "36750", "Score": "4" } } ]
{ "AcceptedAnswerId": "36753", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T03:34:20.190", "Id": "36750", "Score": "5", "Tags": [ "c#", "fizzbuzz", "ai" ], "Title": "PseudoBrain FizzBuzz Thoughts" }
36750
<p>I've been reading about <code>WeakPointer</code> and <code>WeakPointer&lt;T&gt;</code> today, and it looks very useful. Rather than just using it as-is though, I decided to write a wrapper around it that covers a common usage case for me.</p> <p>Code as follows:</p> <pre><code>public class Temporary&lt;T&gt; where T : class { Func&lt;T&gt; generator = null; WeakReference&lt;T&gt; reference = null; public T Value { get { return GetValue(); } } public Temporary(T value) : this(value, null) { } public Temporary(Func&lt;T&gt; generator) : this(null, generator) { } public Temporary(T value, Func&lt;T&gt; generator) { reference = new WeakReference&lt;T&gt;(value); this.generator = generator; } public T GetValue() { if (reference == null) return null; T res; if (!reference.TryGetTarget(out res) &amp;&amp; generator != null) { res = generator(); reference.SetTarget(res); } return res; } } </code></pre> <p>I've tested this against my use-case and it works as I expect - the garbage collector cleans out items with no active references, and they are re-instantiated at need.</p> <p>I'm looking for critiques of the implementation and suggestions for improvements/additions.</p>
[]
[ { "body": "<p>It's pretty good, clean and simple code. Not a lot to critique really. A few minor things:</p>\n\n<ol>\n<li><p>Some people (myself included) prefer to prefix private fields with <code>_</code>. This way it's easy to see that it's a field rather than a local variable (and gets rid of the <code>this.</code> in most cases).</p></li>\n<li><p>You shouldn't have a public property and a public method which do the same thing. How is a programer supposed to know whether to use <code>Value</code> or <code>GetValue</code>? It's not obvious what the difference is or if there is one at all.</p></li>\n<li><p>Not 100% sure about the <code>null</code> check in <code>GetValue()</code>. There is no code path where <code>reference</code> should ever be <code>null</code>. So it would actually indicate a bug if it were the case which you are hiding with this check. Consider removing the check or actually throwing an <code>InvalidOperationException</code> or similar instead. Detecting bugs early is important. Another option would be to look at <a href=\"http://research.microsoft.com/en-us/projects/contracts/\">Code Contracts</a> to state the invariants of that method.</p></li>\n<li><p>I have started to try and avoid <code>null</code> checks where possible by making sure that there is always an object. In your case this could be something like this:</p>\n\n<pre><code>public class Temporary&lt;T&gt; where T : class\n{\n private static Func&lt;T&gt; NullGenerator = () =&gt; null;\n\n Func&lt;T&gt; generator = NullGenerator;\n WeakReference reference = null;\n\n public T Value\n {\n get\n {\n return GetValue();\n }\n }\n\n public Temporary(T value)\n : this(value, NullGenerator)\n { }\n\n public Temporary(Func&lt;T&gt; generator)\n : this(null, generator)\n { }\n\n public Temporary(T value, Func&lt;T&gt; generator)\n {\n if (generator == null)\n throw new ArgumentNullException(\"generator\");\n reference = new WeakReference(value);\n this.generator = generator;\n }\n\n private T GetValue()\n {\n T res;\n if (!reference.TryGetTarget(out res))\n {\n res = generator();\n reference.SetTarget(res);\n }\n return res;\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T10:59:31.980", "Id": "60476", "Score": "1", "body": "I'm not sure about `NullGenerator`, it makes the code simpler, but I also think it makes it less clear. The explicit check against `null` in the original version is very clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T13:21:41.477", "Id": "60486", "Score": "0", "body": "+1 for the null generator and rewriting GetValue() around nulls. Exactly what I would have said. That null check on reference was certainly a bug. Also, could not agree more with item 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T09:06:13.927", "Id": "60613", "Score": "0", "body": "Good answer Chris. The `reference == null` check was a leftover from when I was thinking about implementing `IDisposable`, but it should `throw` if there's a problem with the reference. I agree with @svick about the NullGenerator, but the rest of your points are excellent." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T07:47:52.997", "Id": "36757", "ParentId": "36754", "Score": "6" } } ]
{ "AcceptedAnswerId": "36757", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T04:55:30.787", "Id": "36754", "Score": "4", "Tags": [ "c#", "generics", "weak-references" ], "Title": "Generic 'temporary instance' class" }
36754
<p><strong>Disclaimer: The code already was graded - so I don't ask for a homework here -just for a code review. :)</strong></p> <p>For a university course my colleagues and I had to implement a list without using any Arrays or any utilities from java collections. Only interfaces were allowed.</p> <p>We received a small feedback complaining that the our class Tuple is publicly visible. As I do this course just for learning I felt the need for more details and a comprehensive feedback. I add our task that you can better understand why we coded it in this way.</p> <p><strong>Our Task</strong></p> <p>We had to implement a list with two inheritance generations with the following properties. </p> <ul> <li><p><strong>SList</strong>: <code>SList</code> implements <code>java.lang.Iterable</code> and provides a method <code>add</code> with two parameters: </p> <ul> <li>the <code>position</code> where it should be inserted and </li> <li>the element which should be added.</li> </ul></li> <li><p><strong>AList</strong>: <code>AList</code> inherits from <code>SList</code> - with the necessary types set through generics it is a subtype of <code>SList</code>. Each AList list element is affiliated with a possible empty list. The type of the affiliated list items is set through an other type parameter. AList provides another <code>add</code> method with three parameters:</p> <ul> <li><code>position</code> and</li> <li><code>element</code> like in <code>SList</code> </li> <li><code>affiliated_list</code> which is affiliated to the added <code>element</code>.</li> </ul></li> <li><p><strong>DList</strong>: With the necessary types set through generics it is a subtype of <code>AList</code>. All elements added to <code>DList</code> should support a <code>dependsOn</code> method. Moreover <code>DList</code> provides a method <code>consistent</code> which returns <code>true</code> if all list elements from <code>DList</code> do not depend on each other. This is evaluated thanks to the <code>dependsOn</code> method.</p></li> </ul> <p><a href="http://www.complang.tuwien.ac.at/franz/oop13w5" rel="nofollow">If you speak German, you can take a look on the task directly</a>.</p> <p><strong>SList</strong></p> <pre><code>package Aufgabe5; import java.util.Iterator; public class SList&lt;T&gt; implements Iterable&lt;T&gt;{ // A Double Linked List with Iterator and ListElements. protected class ListIterator&lt;T&gt; implements Iterator&lt;T&gt;{ private ListElement&lt;T&gt; currentElement; /** * PRECONDITION * head != null */ protected ListIterator(ListElement&lt;T&gt; head) { this.currentElement = head; } /** * POSTCONDITIONS * return the current element */ public ListElement&lt;T&gt; getCurrentElement(){ return this.currentElement; } /** * POSTCONDITIONS * return the next current element */ public boolean hasNext() { return this.currentElement != null; } /** * PRECONDITION * currentElement != null * POSTCONDITIONS * return all elements consecutively in the given order */ public T next(){ ListElement&lt;T&gt; next = this.currentElement.getNext(); ListElement&lt;T&gt; returnElement = this.currentElement; this.currentElement = next; return returnElement.getValue(); } /** * PRECONDITION * currentElement != null * POSTCONDITION: The element is removed from the linked list. */ public void remove() { ListElement&lt;T&gt; nextElement = this.currentElement.getNext(); ListElement&lt;T&gt; previousElement = this.currentElement.getPrevious(); previousElement.setNext(nextElement); nextElement.setPrevious(previousElement); this.currentElement = nextElement; } /** * PRECONDITION * builder != null * POSTCONDITIONS * return elements as a String */ public String toString(){ ListIterator&lt;T&gt; iterator = new ListIterator&lt;T&gt;(this.currentElement); StringBuilder builder = new StringBuilder(); builder.append("["); while(iterator.hasNext()){ builder.append(iterator.next()); builder.append(", "); } builder.append("]"); return builder.toString(); } } protected class ListElement&lt;T&gt;{ private T value; private ListElement&lt;T&gt; previous; private ListElement&lt;T&gt; next; private ListElement(){ this(null, null, null); } /** * PRECONDITION * value != null, previous != null, next != null */ protected ListElement(T value, ListElement&lt;T&gt; previous, ListElement&lt;T&gt; next){ this.value = value; this.previous = previous; this.next = next; } /** * POSTCONDITIONS * return next element in the list */ protected ListElement&lt;T&gt; getNext(){ return this.next; } /** * PRECONDITION * next != null */ public void setNext(ListElement&lt;T&gt; elem){ this.next = elem; } /** * POSTCONDITIONS * return previous element */ public ListElement&lt;T&gt; getPrevious(){ return this.previous; } /** * PRECONDITION * previous != null */ public void setPrevious(ListElement&lt;T&gt; elem){ this.previous = elem; } /** * POSTCONDITIONS * return value */ public T getValue(){ return this.value; } /** * POSTCONDITIONS * return the value as a String */ public String toString(){ return this.value.toString(); } } private ListElement&lt;T&gt; head; private ListElement&lt;T&gt; tail; private int listSize; public SList(){ this.listSize = 0; this.head = null; this.tail = null; } public void add(int position, T value){ if (Math.abs(position) &gt; (this.listSize + 1)){ throw new IndexOutOfBoundsException("The provided position is out of bounds: "+position); } // hier noch ein paar Exceptions her zum Schutz! if (shouldBeAppend(position)) { append(value, position); } else if (shouldBeLeftAppended(position)) { leftAppend(value, position); }else if (shouldBeInsertedLeft(position)){ leftInsert(value, position); }else if (shouldBeInsertedRight(position)){ rightInsert(value, position); } listSize ++; } private void append(T value, int position){ // first entry in new list if (listSize == 0 &amp;&amp; head == null &amp;&amp; tail == null){ ListElement&lt;T&gt; element = new ListElement&lt;&gt;(value, null, null); this.head = element; this.tail = element; }else{ ListElement&lt;T&gt; element = new ListElement&lt;&gt;(value, this.tail, null); tail.setNext(element); this.tail = element; } } /** * PRECONDITION * head != null, tail != null, value != null */ private void leftAppend(T value, int position){ ListElement&lt;T&gt; element = new ListElement&lt;&gt;(value, null, this.head); this.head.setPrevious(element); this.head = element; } /** * PRECONDITION * foundElement != null, value != null * POSTCONDITION * An additional element is added to the list. */ private void insert(T value, ListElement&lt;T&gt; foundElement){ ListElement&lt;T&gt; nextElement = foundElement.getNext(); ListElement&lt;T&gt; element = new ListElement&lt;&gt;(value, foundElement, nextElement); foundElement.setNext(element); nextElement.setPrevious(element); } /** * PRECONDITION * head != null, value != null, position &gt; 0 * POSTCONDITION * An additional element is added to the list. */ private void leftInsert(T value, int position){ ListElement&lt;T&gt; foundElement = head; for (int i=1; i &lt; position; i++){ foundElement = foundElement.getNext(); } insert(value, foundElement); } /** * PRECONDITION * tail != null, value != null, position &lt; 0 * POSTCONDITION * An additional element is added to the list. */ private void rightInsert(T value, int position){ ListElement&lt;T&gt; foundElement = tail; for (int i=-1; i &gt; position; i--){ foundElement = foundElement.getPrevious(); } insert(value, foundElement); } private boolean shouldBeAppend(int position){ return (listSize == 0) || (position == -1) || (listSize == position); } private boolean shouldBeLeftAppended(int position){ return (listSize != 0) &amp;&amp; (position == 0); } private boolean shouldBeInsertedLeft(int position){ return (position != 0) &amp;&amp; (position &gt; 0) &amp;&amp; (position != listSize); } private boolean shouldBeInsertedRight(int position){ return (position &lt; 0) &amp;&amp; (position != -1) &amp;&amp; (Math.abs(position) != listSize); } public int size(){ return this.listSize; } public Iterator&lt;T&gt; iterator(){ ListIterator&lt;T&gt; iterator = new ListIterator&lt;&gt;(this.head); return iterator; } /** * POSTCONDITIONS * return the iterator as a String */ public String toString(){ return this.iterator().toString(); } } </code></pre> <p><strong>AList</strong></p> <pre><code>package Aufgabe5; import java.util.Iterator; public class AList&lt;K, V&gt; extends SList&lt;Tuple&lt;K, V&gt;&gt;{ public AList() { super(); } /** * POSTCONDITION * inserts an element with 3 parameters */ public void add(int position, K key, SList&lt;V&gt; elements){ Tuple&lt;K, V&gt; tuple = new Tuple&lt;&gt;(key, elements); super.add(position, tuple); } /** * POSTCONDITION * return another iterator in Iterator */ public Iterator&lt;Tuple&lt;K, V&gt;&gt; iterator(){ return super.iterator(); } } </code></pre> <p><strong>DList</strong></p> <pre><code>import java.util.Iterator; public class DList&lt;K extends Dependent&lt;? super K&gt;,V &gt; extends AList&lt;K, V&gt; { /** * CLIENT HISTORY CONSTRAINT: list was filled with elements. * POSTCONDITIONS * return true if all elements don't depend on one another (false) */ public boolean consistent() { Iterator&lt;Tuple&lt;K,V&gt;&gt; it= super.iterator(); boolean pos_found = false; boolean independent = true; while (it.hasNext() ) { Tuple&lt;K,V&gt; elem = it.next(); Iterator&lt;Tuple&lt;K,V&gt;&gt; it2 = super.iterator(); pos_found = false; while(it2.hasNext()) { Tuple&lt;K,V&gt; elem2 = it2.next(); if(pos_found) { if(elem.getXCoordinate().dependsOn(elem2.getXCoordinate())) { independent = false; } } if(elem2.equals(elem)) { pos_found = true; } } } return independent; } } </code></pre> <p><strong>Tuple</strong></p> <pre><code>package Aufgabe5; import java.util.Iterator; class Tuple&lt;X, Y&gt; implements Iterable&lt;Y&gt;{ private final X xCoordinate; private final SList&lt;Y&gt; yCoordinate; /** * PRECONDITION * xCoordinate != null, yCoordinate != null, */ public Tuple(X xCoordinate, Y yCoordinate){ this.xCoordinate = xCoordinate; this.yCoordinate = new SList&lt;&gt;(); } /** * PRECONDITION * xCoordinate != null, yCoordinate != null, */ public Tuple(X xCoordinate, SList&lt;Y&gt; list){ this.xCoordinate = xCoordinate; this.yCoordinate = list; } /** * POSTCONDITIONS * return xCoordinate */ public X getXCoordinate() { return this.xCoordinate; } public Iterator&lt;Y&gt; iterator(){ return yCoordinate.iterator(); } /** * PRECONDITION * builder != null * POSTCONDITIONS * return key and value as a String */ public String toString(){ StringBuilder builder = new StringBuilder(); builder.append("("); builder.append(this.xCoordinate); builder.append(" ,"); // (key, builder.append(this.yCoordinate); builder.append(")"); // value) return builder.toString(); } } </code></pre> <p><strong>Interface Dependent necessary for dependsOn</strong></p> <pre><code>public interface Dependent &lt;T&gt; { // Compares two items on a certain property // Such a property can be e.g. if elements are integers // or if the elements are characters. // PRECONDITION: x != null public boolean dependsOn(T x); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T13:34:49.243", "Id": "60487", "Score": "0", "body": "A comment about `Tuple.toString`, in this case you can concat Strings without StringBuilder: `\"(\" + this.xCoordinate+ \" ,\" + this.yCoordinate + \")\"`. The only situation where it can be a problem is when you are concatenating strings inside a loop. More here: http://bit.ly/1gcj08u" } ]
[ { "body": "<p>Just some comments on your code:</p>\n\n<ul>\n<li>Don't call your Iterator <code>ListIterator&lt;T&gt;</code> - that is the name of an interface in <code>java.util</code> and it confused me for a moment.</li>\n<li>It is 'unconventional' to use positive/negative positions to insert values relative to the beginning/end of the list. One effect of this, is that you cannot use <code>-0</code> to insert at the end of the list.... right? (some form of <code>rightAppend()</code>) method</li>\n<li>you have split up the logic about how you append/insert the data relatively well, but pwehaps you can take it further... Since you know the length of the list, and since you are doubly-linked... when you are inserting data you should go the 'short' way around the loop to find the insert point ... i.e. if the list is size 10, and the position is 9, then you should step 1 back from the end instead of 9 forward from the front.</li>\n</ul>\n\n<p>As for the actual criticism from your course... your Tuple class is not publically visible.... what are they talking about? It is 'package private' ... only classes in your package can see it. If you wanted to, you could nest the Tuple class in your AList class as a protected-static class, but I am not sure that is any better... well, actually, it <strong>is</strong> better. So, let me change my mind... Tuple should be a protected-static nested class in AClass.</p>\n\n<p>I have not inspected the logic of the Depends processing, but at face value it looks right. I think the interfaces is fine. One possible extension is to use another (a second) interface so that you can support classes that do not implement <code>Dependent</code>, just like there is <code>Comparable</code> and <code>Comparator</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T12:46:48.617", "Id": "36770", "ParentId": "36759", "Score": "3" } }, { "body": "<p>This is great code, and I trust that you can implement the required data structure correctly. Therefore, I won't review it with respect to the assignment.</p>\n\n<p>Most things I found are nitpicks (e.g. about proper formatting). There are a couple of suggestions you can consider. And then there is even one little bug.</p>\n\n<h2><code>SList</code></h2>\n\n<ul>\n<li><p>A <code>package</code> declaration should create a globally unique name space, e.g. <code>at.ac.tuwien.nutzerkennung.oop13.aufgabe5</code>. All parts should be lowercase.</p></li>\n<li><p>Inconsistent spacing irks me: <code>…head) {</code> vs <code>…Element(){</code>. Pick <em>one</em> style and enforce it consistently (e.g. by using automated formatters). The <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\">Java Coding Conventions</a> seem to suggest a single space between closing paren and opening curly brace.</p>\n\n<p>In a similar vein, always keep an empty line before a method declaration. A documentation comment belongs to the following declaration.</p>\n\n<p>It is almost never necessary for good readability to have the first line of a method empty.</p></li>\n<li><p><code>PRECONDITION head != null</code> doesn't help much as a comment. Enforce this precondition, e.g. via <code>assert head != null</code>. But it's good that you have carefully thought about such conditions.</p></li>\n<li><p>Having a comment describe the functionality of a class/method/field is a good idea. However, such a comment usually precedes the declaration, and should use a documentation comment (<code>/**</code>). This criticism applies to the comment <code>// A Double Linked List with Iterator and ListElements.</code>.</p></li>\n<li><p>You consequently mention <code>this</code> when referring to instance fields: <code>this.currentElement</code>. I personally like this a lot (coming from languages like Perl), but it isn't exactly common. Such usage is of course OK if it is part of your groups coding convention.</p></li>\n<li><p>The way you have designed your classes, <code>ListElement</code> is actually <code>Iterable</code> as well. At least you use it as such. Encoding this relationship by formally implementing that interface would clean your code up in some parts:</p>\n\n<p><code>SList#iterator()</code> would become</p>\n\n<pre><code>public Iterator&lt;T&gt; iterator(){\n return this.head.iterator();\n}\n</code></pre>\n\n<p>and <code>ListIterator#toString()</code> would become</p>\n\n<pre><code>public String toString(){\n StringBuilder builder = new StringBuilder();\n\n builder.append(\"[\");\n for (T item : this.currentElement) {\n builder.append(item);\n builder.append(\", \"); // FIXME remove trailing comma\n\n }\n builder.append(\"]\");\n\n return builder.toString();\n}\n</code></pre></li>\n<li><p>If we don't do that, there is an easy way to remove the trailing comma in <code>ListIterator#toString()</code>:</p>\n\n<pre><code>public String toString(){\n ListIterator&lt;T&gt; iterator = new ListIterator&lt;T&gt;(this.currentElement);\n StringBuilder builder = new StringBuilder();\n\n builder.append(\"[\");\n while(iterator.hasNext()){\n builder.append(iterator.next());\n if (iterator.hasNext()) {\n builder.append(\", \");\n }\n }\n builder.append(\"]\");\n\n return builder.toString();\n}\n</code></pre>\n\n<p>Notice also how I used empty lines to separate the three distinct tasks initialization – enclosing the items in brackets – returning.</p></li>\n<li><p>As far as I can see, <code>new ListElement()</code> == <code>new ListElement(null, null, null)</code> has no useful interpretation, and isn't used anywhere. Remove that useless constructor.</p></li>\n<li><p><code>shouldBeAppend</code> should be <code>shouldBeAppended</code> ;-)</p></li>\n<li><p>It is dubious that all those <code>shouldBeXAppended</code> methods make sense on their own; it would not impact the code negatively if you would put the conditions directly into the <code>SList#add</code> conditional. Having them in their own methods only makes the code more self-documenting, and a bit easier to test (also, it hides cyclomatic complexity). I personally would not have put them into separate methods, so that it is easier to get an overview of the possible paths.</p>\n\n<pre><code>if ((listSize == 0) || (position == -1) || (listSize == position)) {\n append(value, position);\n}\nelse if ((listSize != 0) &amp;&amp; (position == 0)) {\n leftAppend(value, position);\n}else if ((position != 0) &amp;&amp; (position &gt; 0) &amp;&amp; (position != listSize)){\n leftInsert(value, position);\n}else if ((position &lt; 0) &amp;&amp; (position != -1) &amp;&amp; (Math.abs(position) != listSize)){\n rightInsert(value, position);\n}\n</code></pre>\n\n<p>Can we be sure from this mess that all paths are actually covered, and that we are allowed to omit the <code>else</code>?</p>\n\n<p>Some of the tests are unneccessary: if the first branch is <em>not</em> taken, we already know that <code>(listSize != 0) &amp;&amp; (position != -1) &amp;&amp; (listSize != position)</code>. We can remove those tests from the other branches. The test <code>(position != 0) &amp;&amp; (position &gt; 0)</code> looks a bit silly, we can simplify that as well. In the final branch, we already know that <code>(position &lt; 0)</code> because the two other cases were handled earlier. The test <code>Math.abs(position) != listSize</code> simplifies to <code>-position != lisSize</code> because of that.</p>\n\n<pre><code>// assert Math.abs(position) &lt;= (this.listSize + 1)\nif ((listSize == 0) || (position == -1) || (listSize == position)) {\n append(value, position);\n}\nelse if (position == 0) {\n leftAppend(value, position);\n}\nelse if (position &gt; 0) {\n leftInsert(value, position);\n}\nelse if (-position != listSize) {\n rightInsert(value, position);\n}\n</code></pre>\n\n<p>So, what input doesn't get handled? <code>position == -listSize</code>. Oops!</p>\n\n<p>A note on style: Settle for one style to format <code>if</code>/<code>else</code>. In Java it is common to “cuddle” them onto one line, but in that case put a space in between: <code>} else if (...) {</code>. I prefer to put the <code>else</code> on a new line, because it allows me to put a comment line before each condition.</p></li>\n<li><p><code>if (listSize == 0 &amp;&amp; head == null &amp;&amp; tail == null)</code> – the class is small enough to keep all invariants in mind, but <code>listSize == 0</code> and <code>head == null &amp;&amp; tail == null</code> imply each other. In general, an assertion to make sure that these two are in sync would be better than to take another branch as if nothing happened.</p>\n\n<p>In this special case, you could remove those two large branches as they share most code, and write instead:</p>\n\n<pre><code>private void append(T value, int position){\n ListElement&lt;T&gt; element = new ListElement&lt;T&gt;(value, this.tail, null);\n\n // handle case of empty list: insert at beginning too\n if (tail == null) {\n assert listSize == 0;\n assert head == null;\n\n this.head = element;\n }\n // append at the end of an existing list\n else {\n assert tail.getNext() == null;\n\n tail.setNext(element);\n }\n\n this.tail = element;\n}\n</code></pre>\n\n<p>Is there any specific reason you use both <code>this.tail</code> and a bare <code>tail</code> here?</p></li>\n</ul>\n\n<h2><code>AList</code></h2>\n\n<ul>\n<li>I don't quite see why this class needs its own <code>iterator()</code> implementation, considering that it just calls the parent class' method.</li>\n</ul>\n\n<h2><code>DList</code></h2>\n\n<ul>\n<li><p>You have switched to another brace style, putting each brace on its own line for control flow constructs. Settle for a single style, etc.</p></li>\n<li><p>There is no way for <code>independent</code> to become <code>true</code> again once it is set to false. It might be better to remove that variable and return immediately once the value can be determined.</p></li>\n<li><p><code>pos_found</code> should be named <code>posFound</code>, because this is the naming convention is Java. Actually, booleans should usually have an <code>is…</code> prefix. As the variable is only used inside the loop (and reset there to its original value each time), it should be declared inside the loop.</p></li>\n<li><p>Conditionals of the form <code>if (cond1) { if (cond2) { ... } }</code> should be written as <code>if (cond1 &amp;&amp; cond2)</code> to avoid unnecessary indentation.</p></li>\n<li><p>When looping over the elements in an <code>Iterable</code> object, it is often better to use a <code>for (Tuple&lt;K, V&gt; elem : this) { ... }</code> loop rather than manually accessing the iterator methods with a <code>while</code>.</p></li>\n<li><p>It is usually better to use a 4-space indent instead of 8-space indent (or even tabs). Most editors can be configured to use a certain indentation style.</p></li>\n</ul>\n\n<p>This class looks like it was written by a C programmer.</p>\n\n<h2><code>Tuple</code></h2>\n\n<ul>\n<li><p>Using <code>X</code> and <code>Y</code> for type parameters is confusing. Use something that makes sense in the problem domain, like <code>K, V</code>.</p></li>\n<li><p>What is all this talk about coordinates, considering that <code>yCoordinate</code> isn't even a number, but a list? Such terminology generally needs a comment explaining what it means.</p></li>\n<li><p><code>return xCoordinate</code> – most useless comment ever.</p></li>\n<li><p>Don't put multiple statements onto the same line. You gain nothing, and loose readability.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T15:22:02.937", "Id": "60500", "Score": "0", "body": "Wow - this was really comprehensive. If you are next time around Vienna - drop me a line - I will invite you to a glass of beer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T14:30:51.897", "Id": "36781", "ParentId": "36759", "Score": "5" } } ]
{ "AcceptedAnswerId": "36781", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T08:41:25.103", "Id": "36759", "Score": "5", "Tags": [ "java", "linked-list", "generics" ], "Title": "Implementation of a double linked list with generics and inheritance" }
36759
<p>I wrote the following Caml light code to find prime factors of a number (part of an early <a href="http://projecteuler.net/problem=3" rel="nofollow">Project Euler question</a>).</p> <blockquote> <p><strong>Largest prime factor</strong></p> <p>The prime factors of 13195 are 5, 7, 13 and 29.</p> <p>What is the largest prime factor of the number 600851475143?</p> </blockquote> <pre><code>let rec find_factors target check = if (check &gt; (int_of_float (sqrt (float_of_int target)))) then [] else (find_factors target (check+1))@if target mod check == 0 then [ check; (target/check)] else[] ;; let display n = print_int n;print_newline();; do_list display (find_factors 10 1); print_newline();; </code></pre> <p>I'm very new to functional programming and I suspect I'm all over the place - if anyone would like to give me some tips that would be ideal. :)</p>
[]
[ { "body": "<p>I guess that I should not be giving you an answer, but guide you. So, one general remark that I have: stylistically, it would be preferable to see you start with</p>\n\n<pre><code>let largest_factor n =\n let rec aux_factor d n =\n ...\n in \n # some expression involving to aux_factor \n</code></pre>\n\n<p>The idea is that your solution function should be an expression of your problem and nothing else, so <code>largest_factor number</code>, not <code>largest_factor number what_is_that</code>.</p>\n\n<p>Note that I am talking OCaml here, not sure if the pseudosample I wrote is cromulent Caml Light.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:09:51.747", "Id": "36801", "ParentId": "36762", "Score": "4" } }, { "body": "<p>A couple of points regarding efficiency:</p>\n\n<ul>\n<li><p>You recompute the square root of <code>target</code> at every recursive call of <code>find_factors</code>. You can do better than that.</p></li>\n<li><p>You use list concatenation in a \\$O(n)\\$ algorithm: you can avoid it by prepending the values instead, and post process your result with a list reverse (<code>List.rev</code>).</p></li>\n</ul>\n\n<p>@agravier's answer offers a good hint as to how you may optimize the above points while still supporting a decent interface for your function.</p>\n\n<p>Consider the following functions, which calculate the sum of a list of integers:</p>\n\n<pre><code>let rec lsum l =\n match l with\n | [] -&gt; 0\n | x::xs -&gt; x + lsum xs\n\nlet rec lsum' acc l =\n match l with\n | [] -&gt; acc\n | x::xs -&gt; lsum (acc+x) xs\n</code></pre>\n\n<p>The first one provides a simple interface which corresponds exactly to the purpose of the function: it's easy to understand and use by just reading its signature. The second one is not as easy to understand (what's that <code>acc</code> parameter there?), but it is more efficient: it's a tail recursive definition, which may be optimized to a simple loop. You will want to write function in the second style, but with the interface of the first style.</p>\n\n<pre><code>(* simple interface *)\nlet lsum'' l =\n (* efficient implementation *)\n let rec lsum' acc l = ...\n in lsum' 0 l\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-19T10:57:34.530", "Id": "57451", "ParentId": "36762", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T09:51:23.350", "Id": "36762", "Score": "2", "Tags": [ "primes", "project-euler", "ocaml" ], "Title": "Caml light and finding the prime factors" }
36762
<p>I have written this code for cookie parsing. Can anyone tell me what optimizations we can do in this or what can we do to make it more concise? </p> <pre><code>function parseCookies(cookies) { var cookie, cookieParts, parsedCookies = []; if (!cookies || !cookies.length) { return null; } // Remove domain from each cookie to decrease the size of cookie (Not needed) for (var i = 0; i &lt; cookies.length; i++) { cookie = cookies[i]; cookieParts = cookie.split(';'); for (var index2 = cookieParts.length - 1; index2 &gt;= 0; index2--) { var pair = cookieParts[index2], key = pair.split('=')[0]; if (key &amp;&amp; key.trim().toLowerCase() == 'domain') { cookieParts.splice(index2, 1); } } cookie = cookieParts.join(';'); parsedCookies.push(cookie); } return parsedCookies; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:24:31.993", "Id": "60533", "Score": "0", "body": "Could you add examples of input and output? As far as I can tell, this isn't so much a parser but rather a sanitizer, since it returns the same format, just with some stuff removed" } ]
[ { "body": "<p>This question is a great candidate for using Array.map and Array.filter. That is, if you are willing to return [] instead null if cookies is not provided.</p>\n\n<p>Basically you map cookies to a new array which has modified cookies, and you filter out the value from the cookie that you don't want.</p>\n\n<p>I did not test this, but something like this ought to do the trick:</p>\n\n<pre><code>function parseCookies(cookies) {\n\n cookies = cookies || [];\n\n return cookies.map( function(cookie)\n {\n return cookie.split(\";\").filter( function( value )\n {\n return !( value &amp;&amp; value.trim().toLowerCase().substring(0,7) == \"domain=\" )\n }).join(\";\");\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T19:23:52.677", "Id": "36808", "ParentId": "36765", "Score": "1" } }, { "body": "<p>Like I wrote in my comment, the function you've got isn't really a parser. Yes, it parses the strings you pass it, but that's not its purpose, as far as I can tell. Parsing is a byproduct of the actual purpose, which seems to be to sanitize the strings by removing the <code>domain</code> key/value pair.</p>\n\n<p>Now, if you're just looking to remove that key/value pair, you could simply do</p>\n\n<pre><code>function sanitizeCookies(strings) {\n return strings.map(function (cookieString) {\n return cookieString.replace(/\\bdomain\\s*=[^;]*;?/ig, \"\");\n });\n}\n</code></pre>\n\n<p>Like @tomdemuyt, I'm using <code>Array.map()</code> so you won't get <code>null</code> back if you pass it an empty array; you'll just get another empty array (and, frankly, that makes more sense, I think).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:58:40.007", "Id": "36817", "ParentId": "36765", "Score": "2" } } ]
{ "AcceptedAnswerId": "36817", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T11:35:56.543", "Id": "36765", "Score": "1", "Tags": [ "javascript", "optimization", "parsing" ], "Title": "How to optimize Cookie Parsing?" }
36765
<p>Which of these two alternatives is more readable?</p> <pre><code>token = map.get(token_str) if not token: token = Course(token_str) return token </code></pre> <p>or</p> <pre><code>token = map.get(token_str) token if token else Course(token_str) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T12:07:27.687", "Id": "60483", "Score": "3", "body": "How about `token = map.get(token_str) or Course(token_str)`? Or `token = map.get(token_str, Course(token_str))` if map is a dict?" } ]
[ { "body": "<p>In python, a common style is \"easier to ask for forgiveness than permission\" (<a href=\"http://docs.python.org/2/glossary.html#term-eafp\" rel=\"nofollow\">http://docs.python.org/2/glossary.html#term-eafp</a>). I.e.</p>\n\n<pre><code>try:\n return map[token_str]\nexcept KeyError:\n return Course(token_str)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:31:49.663", "Id": "60511", "Score": "1", "body": "While this approach is certainly good to know, remember that exceptions aren't cheap. If `token_str` is almost always in `map`, this is fine; if it's middle or low odds of being present, this is likely a worse choice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T12:44:39.480", "Id": "36769", "ParentId": "36766", "Score": "1" } }, { "body": "<p>get() takes an optional second parameter, for a value to use if the key isn't present:</p>\n\n<pre><code>token = map.get(token_str, Course(token_str))\n</code></pre>\n\n<p>I think that one is clearly the best solution, <em>unless</em> you don't want to create and immediately throw away a Course object. In that case, I would use 'or':</p>\n\n<pre><code>token = map.get(token_str) or Course(token_str)\n</code></pre>\n\n<p>Both of these are only one line, that one line is quite readable, and there is no unnecessary repetition.</p>\n\n<p>There is one third possible situation, in which you don't want to unnecessarily construct a Course instance, and you also can't rely on the values that are present to evaluate as True. Then 'or' wouldn't work correctly.</p>\n\n<p>Then I would use an 'if' statement:</p>\n\n<pre><code>token = map.get(token_str)\nif token is None:\n token = Course(token_str)\n</code></pre>\n\n<p>but that's personal preference. Something using 'in' is also fine:</p>\n\n<pre><code>token = map[token_str] if token_str in map else Course(token_str)\n</code></pre>\n\n<p>although of course that looks up token_str in map twice, so if you need to be really time efficient then don't do that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T13:53:54.610", "Id": "60490", "Score": "0", "body": "The first suggestion with the default value isn't quite the behaviour asked for. Eg: `{0: False}.get(0, Course(0))` returns `False` because the truth value of the dict value is never determined. The second suggestion does work though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T14:09:09.057", "Id": "60492", "Score": "0", "body": "It's not exactly the same as his if statement, but I assumed that his values would be truthy Course instances. But good point." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T12:59:52.587", "Id": "36771", "ParentId": "36766", "Score": "5" } }, { "body": "<p>If this behavior is implemented at a specific consuming location of your <code>map</code>, I favor <code>token = map.get(token_str) or Course(token_str)</code> over both of your alternatives. This, like your original, assumes that no expected entries will have a <code>False</code> value.</p>\n\n<p>If this is a general need, such that for all <code>token_str</code> the <code>map</code> should contain a <code>Course</code> object, you could make this part of the dict instance itself:</p>\n\n<pre><code>class Courses(dict):\n def __missing__(self, key):\n return Course(key)\n\nmap = Courses()\n\n# ...\ntoken = map[token_str]\n</code></pre>\n\n<p>Note that this handles False values differently from your original code; it only instantiates new Course objects when there wasn't an entry in <code>map</code>.</p>\n\n<p>Side note: try to avoid using builtins such as <code>map</code> as local or global variables. It works fine, but throws readers off. In this case I would suggest a name such as <code>courses</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:44:55.700", "Id": "36792", "ParentId": "36766", "Score": "2" } } ]
{ "AcceptedAnswerId": "36771", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T12:00:09.080", "Id": "36766", "Score": "1", "Tags": [ "python" ], "Title": "Python - ternary operator or if statement?" }
36766
<p>I made a small text adventure. I'm not trying to make it appealing to anyone, but rather just to practice my Python skills. I am fairly new to Python and this was my next step after making a console calculator and BMI calculator. I would like someone to tell me how this code could be better optimised, less work, etc.</p> <pre><code>import time import random # game function def game(): print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print ("Welcome to the cavern of secrets!") print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") time.sleep(3) print ("You enter a dark cavern out of curiosity. It is dark and you can only make out a small stick on the floor.") ch1 = str(input("Do you take it? [y/n]: ")) # STICK TAKEN if ch1 in ['y', 'Y', 'Yes', 'YES', 'yes']: print("You have taken the stick!") time.sleep(2) stick = 1 # STICK NOT TAKEN else: print("You did not take the stick") stick = 0 print ("As you proceed further into the cave, you see a small glowing object") ch2 = str(input("Do you approach the object? [y/n]")) # APPROACH SPIDER if ch2 in ['y', 'Y', 'Yes', 'YES', 'yes']: print ("You approach the object...") time.sleep(2) print ("As you draw closer, you begin to make out the object as an eye!") time.sleep(1) print ("The eye belongs to a giant spider!") ch3 = str(input("Do you try to fight it? [Y/N]")) # FIGHT SPIDER if ch3 in ['y', 'Y', 'Yes', 'YES', 'yes']: # WITH STICK if stick == 1: print ("You only have a stick to fight with!") print ("You quickly jab the spider in it's eye and gain an advantage") time.sleep(2) print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print (" Fighting... ") print (" YOU MUST HIT ABOVE A 5 TO KILL THE SPIDER ") print ("IF THE SPIDER HITS HIGHER THAN YOU, YOU WILL DIE") print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") time.sleep(2) fdmg1 = int(random.randint(3, 10)) edmg1 = int(random.randint(1, 5)) print ("you hit a", fdmg1) print ("the spider hits a", edmg1) time.sleep(2) if edmg1 &gt; fdmg1: print ("The spider has dealt more damage than you!") complete = 0 return complete elif fdmg1 &lt; 5: print ("You didn't do enough damage to kill the spider, but you manage to escape") complete = 1 return complete else: print ("You killed the spider!") complete = 1 return complete # WITHOUT STICK else: print ("You don't have anything to fight with!") time.sleep(2) print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print (" Fighting... ") print (" YOU MUST HIT ABOVE A 5 TO KILL THE SPIDER ") print ("IF THE SPIDER HITS HIGHER THAN YOU, YOU WILL DIE") print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") time.sleep(2) fdmg1 = int(random.randint(1, 8)) edmg1 = int(random.randint(1, 5)) print ("you hit a", fdmg1) print ("the spider hits a", edmg1) time.sleep(2) if edmg1 &gt; fdmg1: print ("The spider has dealt more damage than you!") complete = 0 return complete elif fdmg1 &lt; 5: print ("You didn't do enough damage to kill the spider, but you manage to escape") complete = 1 return complete else: print ("You killed the spider!") complete = 1 return complete #DON'T FIGHT SPIDER print ("You choose not to fight the spider.") time.sleep(1) print ("As you turn away, it ambushes you and impales you with it's fangs!!!") complete = 0 return complete # DON'T APPROACH SPIDER else: print ("You turn away from the glowing object, and attempt to leave the cave...") time.sleep(1) print ("But something won't let you....") time.sleep(2) complete = 0 return complete # game loop alive = True while alive: complete = game() if complete == 1: alive = input('You managed to escape the cavern alive! Would you like to play again? [y/n]: ') if alive in ['y', 'Y', 'YES', 'yes', 'Yes',]: alive else: break else: alive = input('You have died! Would you like to play again? [y/n]: ') if alive in ['y', 'Y', 'YES', 'yes', 'Yes',]: alive else: break </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T12:49:11.960", "Id": "60484", "Score": "1", "body": "See [this question and its answers](http://codereview.stackexchange.com/q/16126/11728)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T13:44:27.607", "Id": "60489", "Score": "1", "body": "The list search is quite ugly. You can make use of string functions to take all cases into account: `if ch1.upper() in ['Y', 'YES']` or even `if ch1[0].upper() == 'Y'`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T14:05:31.053", "Id": "60491", "Score": "1", "body": "Also, \"not trying to make it appealing to anyone\" is a mistake. Make the game as appealing as you possibly can, and this will motivate you to learn more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T16:29:13.443", "Id": "484290", "Score": "0", "body": "I suggest adding variable names other than `ch1`. IMHO variable names should summarize what the variable is for, otherwise later in the program you'd have to look back to see. Try `takeStick` instead of `ch1`." } ]
[ { "body": "<p>You have a lot of repetition in your code, which is something you should focus on reducing.\nFor example, this recurring pattern: </p>\n\n<pre><code>ch2 = str(input(\"Do you approach the object? [y/n]\"))\n\n# APPROACH SPIDER\nif ch2 in ['y', 'Y', 'Yes', 'YES', 'yes']:\n</code></pre>\n\n<p>... can be encapsulated into a function and reused:</p>\n\n<pre><code>def ask(question):\n answer = input(question + \" [y/n]\")\n return answer in ['y', 'Y', 'Yes', 'YES', 'yes']\n\nif ask(\"Do you approach the object?\"):\n # ...\n</code></pre>\n\n<p>Another pattern is <code>print</code>ing followed by <code>time.sleep</code>:</p>\n\n<pre><code> print (\"You approach the object...\")\n time.sleep(2)\n print (\"As you draw closer, you begin to make out the object as an eye!\")\n time.sleep(1)\n print (\"The eye belongs to a giant spider!\")\n</code></pre>\n\n<p>which could be reduced to this:</p>\n\n<pre><code>def print_pause(lines):\n for line, pause in lines:\n print line\n time.sleep(pause)\n\nprint_pause([\n (\"You approach the object...\", 2),\n (\"As you draw closer, you begin to make out the object as an eye!\", 1),\n (\"The eye belongs to a giant spider!\", 0)\n ])\n</code></pre>\n\n<p>The spider fight part also contains a lot of repetition, but I will leave it as an exercise for you to turn it into a function and reuse. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T13:07:47.517", "Id": "36772", "ParentId": "36768", "Score": "16" } }, { "body": "<p>Once you have reduced the complexity by moving the repetitive code into functions and you start to grow your application it may end up being lengthy and difficult to follow. </p>\n\n<p>You could consider applying an object-oriented style by introducing classes. Classes for chapters, the player, locations, items in the story. Your program will make objects with these classes. Your user will interact with these objects and these objects interact with each other. </p>\n\n<p>For the current state of your game, that may be over-engineering but not if you continue it to, say a short story or a novel. Nevertheless, it seems a good opportunity to study OOP.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T14:13:41.500", "Id": "36779", "ParentId": "36768", "Score": "6" } }, { "body": "<p>This is very similar in spirit to other text adventure questions on the site, notably <a href=\"https://codereview.stackexchange.com/questions/36101/better-way-to-code-this-game/36112#36112\">Better way to code this game?</a> </p>\n\n<p>The basic goal you should pursue here is to reduce the amount of completely repetitive code: Since the basic game loop is so simple, the 'code' part should be equally simple. In a game like this that's actually very easy: almost everything breaks down to presenting the user with a list of choices, getting their input, and using it to move to a new list of choices.</p>\n\n<p>The 'right' way to do it, long term, is to follow @mrMishhall's advice and learn object-oriented techniques. However if you're still new to Ptthon and terms like OOP are intimidating, you can also do it using basic python data types - particularly dictionaries. That's what the example linked above does: every node in the game is a dictionary containing a description, a list of options, and a link to the nodes -- that is, other dictionaries -- you reach by folllowing a given option. </p>\n\n<p>Rather than duplicate the example in the link above, i'll give you an example of how the same idea can simplify the combat portion. Here's an attempt to do the same kind of combat system with less reliance on if/then.</p>\n\n<pre><code># instead of using an if/then tree, first we store the damage range \n# of all the weapons in the game\nWEAPONS = {'stick': (3, 10)), None:(1,8), 'knife':(4,16)}\n\n#and instead of tracking inventory with one variable, have a 'player' who\n# has stuff in a dictionary:\n\nplayer = {'weapon':None, 'health': None}\n\n#to give the player stuff, you add it to his dictionary:\n\nplayer['weapon'] = 'stick'\n\n# while we're at it, we can treat the monsters the same way:\n\nSPIDER = {name:'spider', 'health':5, 'attack':(1, 5) } \n\n# so for any given fight there's a player and an enemy:\n# and two possible outcomes for each combatant. You'll want to report \n# the damage (which varies) and the result:\n\ndef combat (player, enemy):\n player_damage = random.range(*WEAPONS[player['weapon'])\n enemy_damage = random.range(*enemy['attack'])\n\n player_win = player_damage &gt; enemy['health']\n enemy_win= enemy_damage &gt; player['health']\n\n return player_damage, player_win , enemy_damage, enemy_win\n\n# of course, you also want flavor text. So you can set that up as another dictionary.\n# you might want to make different dictionaries for different parts of the game\n# to give a different flavor to the fights as you did above:\n\nSIMPLE_FIGHT = {\nplayer_damage: 'You hit the %s for %i damage',\nenemy_damage: '%s hits you for %i damage',\nplayer_win: 'The %s dies!',\nenemy_win: 'You die!'\n}\n\ndef describe_combat(player, enemy, fight_description):\n player_damage, player_win , enemy_damage, enemy_win = combat(player, enemy)\n\n print fight_description['player_damage'] % (enemy['name'], player_damage)\n print fight_description['enemy_damage'] % (enemy['name'], enemy_damage)\n\n if player_win:\n print fight_description['player_win'] % enemy['name'])\n return True\n\n if enemy_win:\n print fight_description['player_win'] % enemy['name'])\n return False\n\n return None # this means a draw :)\n\n\n # with that in place, you can play out a fight like so:\n\n\n fight_result = describe_combat(player, SPIDER, SIMPLE_FIGHT)\n if fight_result is None:\n # what do you do for draws?\n elif fight_result: \n # you've won.\n else:\n # game over\n</code></pre>\n\n<p>This may seem like a lot of indirection at first, but you can create a whole different fight with just two new bits of data:</p>\n\n<pre><code>ELEPHANT = {'name':'Huge bull elephant', 'attack': (10,30)}\n\nELEPHANT_FIGHT = {\nplayer_damage: 'You desperately try to stop the %s for %i damage',\nenemy_damage: '%s gores you for %i damage',\nplayer_win: 'The %s collapses with a thunderous boom',\nenemy_win: 'You are squished'\n}\n</code></pre>\n\n<p>and so on. I'm sure you can see how the same strategy will help with things like different weapons and armor, different rooms and so on. The key principle is to keep the LOGIC as simple and streamlined as possible and make the DATA do the descriptive work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T00:57:46.707", "Id": "36829", "ParentId": "36768", "Score": "13" } }, { "body": "<p>For inputs, instead of saying ['y','Y','Yes','YES','yes'] etc, you could just do</p>\n\n<pre><code> if ch2.lower() in ['y','yes']:\n</code></pre>\n\n<p>The <code>lower()</code> makes it so that the string you type in is converted to all lower case. Also, this would work but would be pointless:</p>\n\n<pre><code> if ch2.upper() in ['Y','YES']:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-12T22:02:48.923", "Id": "80387", "ParentId": "36768", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T12:37:24.807", "Id": "36768", "Score": "14", "Tags": [ "python", "optimization", "beginner", "adventure-game" ], "Title": "Tiny text adventure" }
36768
<p>I must read and extract some values from string. These values are coded like this:</p> <pre><code>k="11,3,1" v="140.3" </code></pre> <p>I have defined the codes and created struct with all field as well as a temp one where I store k and v. In fillFields proc I transfer values from temp struct to the right one (with the valid types). It works but I have many fields and fillFields would need to have many if-conditions. Maybe someone could give me any hint how to write it smarter.</p> <p>The simplified code now:</p> <pre><code> #define ASK "11,3,1" #define BID "11,2,1" #define CLOSE "3,1,1" typedef struct tic { float ask; float bid; float close; }tic, *ticP; typedef struct pElem { char * k; char * v; }pElem, *pElemP; void fillFields(ticP t, pElemP p) { if (strcmp( ASK, p-&gt;k)==0) { printf ("ASK %s\n", p-&gt;v); t-&gt;ask = atof(p-&gt;v); } if (strcmp( BID, p-&gt;k)==0) { printf ("BID %s\n", p-&gt;v); t-&gt;bid = atof(p-&gt;v); } if (strcmp( CLOSE, p-&gt;k)==0) { printf("CLOSE &gt;&gt;&gt;%s&lt;&lt;&lt;\n", p-&gt;v) ; t-&gt;close = atof (p-&gt;v); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T19:26:12.787", "Id": "60544", "Score": "0", "body": "This is a more applicable forum for http://stackoverflow.com/questions/20423447/how-can-i-do-it-smarter/20424944#20424944" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T10:50:18.793", "Id": "60802", "Score": "0", "body": "@chux: I have posted it there first, but the users sent me here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:59:55.643", "Id": "60847", "Score": "0", "body": "Yes sometimes that happens. Good that you found a useful answer _somewhere_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T17:11:10.147", "Id": "60871", "Score": "0", "body": "If `ask`, `bid` and `close` represent currency values you [should not use float](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) for them." } ]
[ { "body": "<p>I am not sure, what you mean by 'smarter', but here is a possible speed improvement:</p>\n\n<p>If k is always ASK, BID or CLOSE, and nothing else, you can avoid calling <code>strcmp(..)</code> because looking at the 4th character shows which case it is</p>\n\n<pre><code>#define ASK '3' \n#define BID '2'\n#define CLOSE ','\n\ntypedef struct tic {\n float ask;\n float bid;\n float close;\n}tic, *ticP;\n\ntypedef struct pElem {\n char * k;\n char * v;\n}pElem, *pElemP;\n\nvoid fillFields(ticP t, pElemP p)\n{\n switch((p-&gt;k)[3]))\n {\n case ASK:\n printf (\"ASK %s\\n\", p-&gt;v);\n t-&gt;ask = atof(p-&gt;v);\n break;\n case BID:\n printf (\"BID %s\\n\", p-&gt;v);\n t-&gt;bid = atof(p-&gt;v);\n break;\n case CLOSE:\n printf(\"CLOSE &gt;&gt;&gt;%s&lt;&lt;&lt;\\n\", p-&gt;v) ;\n t-&gt;close = atof (p-&gt;v);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T13:35:50.457", "Id": "36776", "ParentId": "36774", "Score": "1" } }, { "body": "<p>I like to go data driven, so I can write a single loop for processing. First, let's factor out the three if blocks that are so similar into a helper function:</p>\n\n<pre><code>void fillField(pElemP p, char* match, char* message, float* pf)\n{\n if (strcmp(match, p-&gt;k)==0)\n {\n printf(message, p-&gt;v);\n *pf = atof(p-&gt;v);\n }\n}\nvoid fillFields(ticP t, pElemP p)\n{\n fillField(p, ASK, \"ASK %s\\n\", &amp;t-&gt;ask);\n fillField(p, BID, \"BID %s\\n\", &amp;t-&gt;bid);\n fillField(p, CLOSE, \"CLOSE &gt;&gt;&gt;%s&lt;&lt;&lt;\\n\", &amp;t-&gt;close);\n}\n</code></pre>\n\n<p>Now that we have this split out, we're repeating a lot less code, and have identified what information we'd need in order to make this data driven. I'm not sure going pure data driven is much better in this case, but let's look at one way it might be done:</p>\n\n<pre><code>struct FieldSpec {\n char *match;\n char *message;\n int offset;\n};\n\nstruct FieldSpec field_specs[] = {\n { ASK, \"ASK %s\\n\", offsetof(tic, ask) },\n { BID, \"BID %s\\n\", offsetof(tic, bid) },\n { CLOSE, \"CLOSE &gt;&gt;&gt;%s&lt;&lt;&lt;\\n\", offsetof(tic, close) },\n};\n\nvoid fillFields(ticP t, pElemP p)\n{\n for (int i = 0; i &lt; sizeof(field_specs) / sizeof(*field_specs); ++i)\n {\n fillFieldBySpec(field_specs[i], p, t);\n }\n}\n</code></pre>\n\n<p>I'll leave the implementation of <code>fillFieldBySpec</code> up to you if you want to go this route (feel free to put it inside the for loop instead of its own function). I don't think it helps significantly over the first refactoring, and the gynmastics to use the value from <code>offsetof</code> aren't pretty.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T10:52:10.393", "Id": "60803", "Score": "0", "body": "Yes, I guess I will use the first refactoring. The code is _m_u_c_h_ more readable now even though I still repeat a lot of code. Thank you!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:07:34.687", "Id": "36795", "ParentId": "36774", "Score": "6" } }, { "body": "<p>It seems to me that you are fine tuning the wrong bit. You have already done some parsing to get your <code>pElem</code> structure. If your input string really is as constrained as you say, then maybe you should look at improving the string parsing level. You could do, for example:</p>\n\n<pre><code>#define ASK \"k=\\\"11,3,1\\\" v=\\\"\"\n#define BID \"k=\\\"11,2,1\\\" v=\\\"\"\n#define CLOSE \"k=\\\"3,1,1\\\" v=\\\"\"\n\nif (!strcmp(s, ASK)) {\n ask = atof(s[sizeof(ASK) - 1]);\n}\nelse if (!strcmp(s, BID)) {\n bid = atof(s[sizeof(BID) - 1]);\n}\nelse if (!strcmp(s, CLOSE)) {\n close = atof(s[sizeof(CLOSE) - 1]);\n}\nelse {\n // error handling\n}\n</code></pre>\n\n<p>On your naming, it is usually much clearer if your types are <strong>not</strong> pointers.\nFor example, your types would be better as:</p>\n\n<pre><code>typedef struct tic {\n float ask;\n float bid;\n float close;\n} Tic;\n\ntypedef struct elem {\n char *k;\n char *v;\n} Elem;\n</code></pre>\n\n<p>Or miss out the typedef altogether and just use <code>struct tic</code> etc.\nBut as I said above, your element type seems redundant.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T19:22:42.030", "Id": "36807", "ParentId": "36774", "Score": "1" } }, { "body": "<p>How about creating a look-up table for your string literals like such:</p>\n\n<pre><code>#define NUM_COMMANDS (3)\n#define ASK (\"11,3,1\")\n#define BID (\"11,2,1\")\n#define CLOSE (\"3,1,1\")\n\nchar *lookUpTable[NUM_COMMANDS] = {ASK, BID, CLOSE};\n\ntypedef enum\n{\n ASK_CMD = 0,\n BID_CMD,\n CLOSE_CMD,\n END_CMD\n} enumCommands;\n</code></pre>\n\n<p>With this you can use a loop in your <code>fillFields</code> function like such:</p>\n\n<pre><code>void fillFields(ticP t, pElemP p)\n{\n for(enumCommands cmd = ASK_CMD; cmd &lt; END_CMD; cmd++)\n {\n if(strcmp(lookUpTable[cmd], p-&gt;v) == 0)\n {\n switch(cmd)\n {\n case ASK_CMD:\n t-&gt;ask = atof(p-&gt;v);\n break;\n case BID_CMD:\n t-&gt;bid = atof(p-&gt;v);\n break;\n case CLOSE_CMD:\n t-&gt;close = atof(p-&gt;v);\n break;\n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T16:18:02.193", "Id": "36911", "ParentId": "36774", "Score": "3" } } ]
{ "AcceptedAnswerId": "36795", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T13:21:40.430", "Id": "36774", "Score": "5", "Tags": [ "c", "parsing" ], "Title": "Parsing key-value pairs to fill a struct" }
36774
<p>Here are a couple of examples of one-liners that go way beyond 80 characters:</p> <pre><code>scope = DepartmentRepository.includes(:location).by_account(@request.account_id).find(approved_department_ids) departments = ActiveModel::ArraySerializer.new(scope, each_serializer: DepartmentWithLocationSerializer).as_json </code></pre> <p>I usually simply break these kinds of chained method calls before the <code>.</code> and indent the next line. My IDE (Emacs) runs <a href="https://github.com/bbatsov/rubocop" rel="noreferrer">rubocop</a> on my source files as I edit them and doesn't complain about this practice. It does complain about lines longer than 80 characters so I feel somewhat compelled to fix them. How would I refactor these? The first line is calling <code>ActiveRecord</code> finders and scopes. Scopes can be compbined but then they have ackward names that seldom see reuse (e.g. <code>by_account_with_locations</code>).</p>
[]
[ { "body": "<p>I don't really see any real trouble with those lines. But I know the feeling that a line just seems \"too long\" (especially if everything else in the file is nice and neat). It's often a good thing to notice, but in some cases it just doesn't make sense to worry.</p>\n\n<p>Are the lines readable? Absolutely. They are very descriptive in fact. If you were talking about a very long conditional filled with <code>&amp;&amp;</code> and <code>||</code> and negations, then yeah, it should probably be changed. But in this case, I don't see reason to fret.</p>\n\n<p>But if you're intent on refactoring, you could (as an example) move the <code>ArraySerializer</code> instantiation into a factory on <code>DepartmentWithLocationSerializer</code> and get something like</p>\n\n<pre><code>DepartmentWithLocationSerializer.serialize(scope).as_json\n</code></pre>\n\n<p>That sort of thing helps a bit. But if I knew a good zen quote about a little imperfection being OK too, I'd drop it here :)</p>\n\n<p>Anyway, don't worry about adding methods for things you'll only use once. You don't always need a very \"practical\" reason like DRY, to add some more methods. If adding some methods it can make the code a little neater to look at, that's a reason in itself. Everything in moderation, YMMV, etc., so just try it out and see if the code seems nicer afterwards. If it doesn't, well, then try to live with the long lines.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T21:13:22.707", "Id": "60562", "Score": "0", "body": "That serialize method idea works great! I created a base Serializer class that adds that method. I addded as_json to that method which cleans things up even more. This also happens to be reusable throughout our app." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T22:44:37.823", "Id": "60575", "Score": "1", "body": "@ReedG.Law Cool, glad it was helpful. Be sure to mention the inclusion of the `as_json` call in your serializer (or maybe leave it out). Compared to the original code, your new implementation makes the assumption that you'll always want to call `as_json` rather than get the `ArraySerializer` instance back. Probably a fair assumption (your app, so you'd know best), but still an assumption." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:16:05.480", "Id": "36802", "ParentId": "36782", "Score": "7" } }, { "body": "<p>My 2 cents: </p>\n\n<p>The 80 char limit is relatively silly at first glance, after all when was the last time you used a vt100 where lines > 80 chars were difficult to read? </p>\n\n<p>The real reason behind the 80 char limit is roughly the same reason to limit the\nnumber of arguments to any method. See </p>\n\n<p><a href=\"http://robots.thoughtbot.com/sandi-metz-rules-for-developers\" rel=\"nofollow\">http://robots.thoughtbot.com/sandi-metz-rules-for-developers</a></p>\n\n<p>When you chain long method calls like that you are effectively creating a one-off method with a long argument list. Every . in the chain corresponds to an argument of a method call. </p>\n\n<p>Maybe that's appropriate and frankly, I love these long method chains. I get a big grin on my face every time I come up with one. They are what makes ruby fun.\nBut they aren't what makes ruby maintainable. Maybe you should think about what class you would make that took fewer arguments and abstracted finding the \"scope\" of a Department. </p>\n\n<p>Long method chains like that create dependencies in your current object on every object in the method chain. That's probably okay if they are all \"standard\" objects, but if they aren't then any change in any of those objects will require changes everywhere those objects are used. </p>\n\n<p>As an aside: If you haven't read Sandi Metz's book, read it now. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T17:22:20.130", "Id": "61779", "Score": "1", "body": "\"you are effectively creating a one-off method with a long argument list. \" -- no. The main problem with long argument lists is that they're non-descriptive. This isn't the case with long chains, where each method defines the semantics of its arguments by its name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T17:24:02.653", "Id": "61781", "Score": "0", "body": "\"They are what makes ruby fun. But they aren't what makes ruby maintainable. Maybe you should think about what class you would ma\" -- I love Ruby for dense but very readable lines, not for very long method chains. Only sometimes does dense = chaining. If you love extreme chaining, jQuery is pretty good at letting you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T17:28:46.850", "Id": "61784", "Score": "0", "body": "\"Long method chains like that create dependencies in your current object on every object in the method chain.\" - I assume you're talking about the \"one period only rule\" which pretty much forbids the (very useful) builder pattern?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T17:09:17.367", "Id": "37363", "ParentId": "36782", "Score": "2" } } ]
{ "AcceptedAnswerId": "36802", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T14:41:39.897", "Id": "36782", "Score": "5", "Tags": [ "ruby" ], "Title": "How do I refactor lines of Ruby code that run too long due to method chaining or object instantiation?" }
36782
<p>I have a Google Maps Geocoder and I am looking to refactor it. The user enters address details into a form where at the bottom there is the option to show on map. </p> <ul> <li>First the map is hidden</li> <li>The user clicks <code>show_map</code> checkbox</li> <li>Map-area is shown</li> <li>Map is initialized</li> </ul> <p>The <code>codeAddress()</code> function is used if the user edits the address and wants to find it again. The <code>showCoords()</code> function passes the longitude and latitude through to the form for processing. I am looking for a best practice to refactor this code.</p> <pre><code>function initialize() { geocoder = new google.maps.Geocoder(); codeAddress(); map = new google.maps.Map(document.getElementById('map-canvas')); marker = new google.maps.Marker({ map: map, position: map.getCenter(), draggable: true }); google.maps.event.addListener(marker, 'dragend', function() { point = marker.getPosition(); map.panTo(point); showCoords(point); }); google.maps.event.addListener(map, 'dragend', function() { point = marker.getPosition(); marker.setPosition(map.getCenter()); showCoords(point); }); } /* END initialize */ function codeAddress(){ var address = document.getElementById('address').value; geocoder.geocode({'address': address}, function(results, status){ if(status == google.maps.GeocoderStatus.OK){ map.setCenter(results[0].geometry.location); map.setZoom(15); marker.setPosition(map.getCenter()); showCoords(); }else{ alert('Geocode was not successful for the following reason: ' + status) } }); } function showCoords(point){ point = marker.getPosition(); document.getElementById("lat").value = point.lat().toFixed(5); document.getElementById("lng").value = point.lng().toFixed(5); } </code></pre>
[]
[ { "body": "<p>The main change I would make is to reduce the responsibility of <code>codeAddress()</code> to do just the geocoding. If it successfully looks up the address, then it can pass the location to a callback.</p>\n\n<p>I don't have enough context to tell whether <code>geocoder</code>, <code>map</code>, and <code>marker</code> are global variables, or whether all of this code lies inside some other scope. Out of habit, I've converted them into local variables. You decide whether that's right for you. The <code>point</code> variables in your drag handlers should definitely be made local, though!</p>\n\n<pre><code>function initialize() {\n var geocoder = new google.maps.Geocoder();\n var map = new google.maps.Map(document.getElementById('map-canvas'));\n\n var marker = new google.maps.Marker({\n map: map,\n position: map.getCenter(),\n draggable: true\n });\n\n google.maps.event.addListener(marker, 'dragend', function() {\n var point = marker.getPosition();\n map.panTo(point);\n showCoords(point);\n });\n\n google.maps.event.addListener(map, 'dragend', function() {\n var point = marker.getPosition();\n marker.setPosition(map.getCenter());\n showCoords(point);\n });\n\n var address = document.getElementById('address').value;\n\n codeAddress(geocoder, address, function(location) {\n map.setCenter(results[0].geometry.location);\n map.setZoom(15);\n marker.setPosition(map.getCenter());\n showCoords();\n });\n}\n\nfunction codeAddress(geocoder, address, callback) {\n geocoder.geocode({'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n callback(results[0].geometry.location);\n } else {\n alert('Geocode was not successful for the following reason: ' + status)\n }\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T21:47:28.997", "Id": "36819", "ParentId": "36785", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T15:54:07.787", "Id": "36785", "Score": "3", "Tags": [ "geospatial", "google-apps-script", "google-maps" ], "Title": "Entering address details into Google Maps geocoder" }
36785
<p>I was asked to write a permutation algorithm to find the permutations of {a,b,c}. Since this is a famous question to which an answer is readily available online, I wanted to do it a little differently, so that it won't look like I copied off the Internet. It was evaluated as OK for the algorithm being correct, but said that the algorithm is inefficient and also there are 'major concerns' in the code.</p> <p>I would really appreciate if the experts here would advice me on what is wrong about this code, so that I can learn and fix my mistakes. I understand that the use of templates is an overkill, but other than that, what is so wrong about this code? The question was, find the permutations of {a,b,c}.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; using namespace std; template&lt;typename T&gt; vector&lt;T&gt; TruncateVector(vector&lt;T&gt;, int); template&lt;typename T&gt; vector&lt;vector&lt;T&gt; &gt; GetPerms(vector&lt;T&gt;); unsigned GetNumPerms(unsigned); template&lt;typename T&gt; bool ValidatePermutations(vector&lt;T&gt;, vector&lt;vector&lt;T&gt; &gt;); int main() { // Create a vector with the elements required to permute vector&lt;char&gt; permSet; permSet.push_back('a'); permSet.push_back('b'); permSet.push_back('c'); // Get the permutations vector&lt;vector&lt;char&gt; &gt; vectorOfPerms = GetPerms(permSet); /* Printing the permutations */ for(unsigned x=0, counter=1;x&lt;vectorOfPerms.size(); x++) { cout &lt;&lt; "(" &lt;&lt; counter &lt;&lt; ") "; for(unsigned y=0;y&lt;vectorOfPerms[x].size(); y++) { cout &lt;&lt; vectorOfPerms[x].at(y) &lt;&lt; ' '; } counter++; cout &lt;&lt; endl; } // Validate the calculated permutations // This validation only valid for sets with lexicographic order. See notes in the function. bool validation = ValidatePermutations(permSet,vectorOfPerms); return 0; } template&lt;typename T&gt; vector&lt;vector&lt;T&gt; &gt; GetPerms(vector&lt;T&gt; permSet) { /* --------------- Permutation algorithm ----------------- * In this algorithm permutations are calculated by sequentially taking each element in the vector, * and then combining it with 'all' the permutations of the rest of the vector elements. * Example: * GetPerms('a,b,c') --&gt; ( {a, GetPerms('b,c')}, {b, GetPerms('a,c')}, {c, GetPerms('a,b')} } * The resultant permutations are returned as a vector of vectors, with each vector consisting of one permutation. * * Vectors were chosen to store the elements because of its ease of handling (inserting, deleting) and also for its ability * to handle different types of data. */ vector&lt;vector&lt;T&gt; &gt; vectorOfPerms(GetNumPerms(permSet.size())); unsigned PermCount=0; if(permSet.size() == 1) // Base case. Only one element. Return it back. { vectorOfPerms[0].push_back(permSet.at(0)); } else { for(unsigned idx=0; idx&lt;permSet.size(); idx++) { vector&lt;T&gt; vectorToPermutate = RemoveElement(permSet, idx); // Remove the current element being combined to permutations. vector&lt;vector&lt;T&gt; &gt; PermVector = GetPerms(vectorToPermutate); // Get the permutations for the rest of the elements. // Combine with the received permutations for(unsigned count=0 ; count&lt;PermVector.size(); count++, PermCount++) { vectorOfPerms[PermCount].push_back(permSet.at(idx)); // Insert the first element vectorOfPerms[PermCount].insert(vectorOfPerms[PermCount].begin()+1, PermVector[count].begin(), PermVector[count].end()); // Insert the permutations } } } return vectorOfPerms; } /* * This function removes the element at index from the vector permSet */ template&lt;typename T&gt; vector&lt;T&gt; RemoveElement(vector&lt;T&gt; permSet, int index) { permSet.erase(permSet.begin()+index); return permSet; } /* * This function returns the number of possible permutations for a given * number of elements */ unsigned GetNumPerms(unsigned numElems) { return (numElems == 1 ? numElems : numElems*GetNumPerms(numElems - 1)); } /* * This function validates the calculated permutations with the std::next_permutation * IMPORTANT: This validation will only work if the elements are different and inserted in lexicographic order. * I.e. {a,b,c} will be correctly validated, but not {a,c,b}. * The permutations generated are CORRECT. Only the validation with std::next_permutation will not be correct. * This validation was chosen to validate the program for the given question of finding permutations of {a,b,c}. */ template&lt;typename T&gt; bool ValidatePermutations(vector&lt;T&gt; permSet, vector&lt;vector&lt;T&gt; &gt; result) { bool validationResult = true; /* Validating the calculated permutations with the std::next_permutation * Since std::next_permutation gives the next lexicographically greater permutation with each call, * it must match with the permutations generated in GetPerms() function. */ if(result.size() != GetNumPerms(permSet.size())) { cout &lt;&lt; "Number of permutations is incorrect." &lt;&lt; endl; } else { // Compare element by element for(unsigned permCount=0; permCount&lt;result.size(); permCount++) { for(unsigned elemCount=0; elemCount&lt;permSet.size(); elemCount++) { if(result[permCount].at(elemCount) != permSet.at(elemCount)) { validationResult = false; break; } } if(!validationResult) { break; } else { next_permutation(permSet.begin(),permSet.end()); } } } cout &lt;&lt; "Number of elements: " &lt;&lt; permSet.size() &lt;&lt; endl; cout &lt;&lt; "Number of permutations: " &lt;&lt; result.size() &lt;&lt; endl; if(validationResult) { cout &lt;&lt; "Validation: " &lt;&lt; "PASS" &lt;&lt; endl; } else { cout &lt;&lt; "Validation: " &lt;&lt; "FAIL" &lt;&lt; endl; } return validationResult; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:39:42.423", "Id": "60659", "Score": "1", "body": "You know there is a standard function `std::next_permutation()` http://www.cplusplus.com/reference/algorithm/next_permutation/" } ]
[ { "body": "<p>you pre generate all permutations, this means that when you have 20 elements you have <code>20! = 2.432902e+18</code> possible permutations all needing to reside in memory when the algorithm finishes</p>\n\n<p>then you copy all vectors over and over, also not a good idea as that requires a lot of memory allocations and deletes</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T03:03:08.083", "Id": "60602", "Score": "0", "body": "Thank you. That is a good point. This approach takes a lot of memory. Anything else you see wrong? Programming style?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:26:26.117", "Id": "36789", "ParentId": "36786", "Score": "3" } }, { "body": "<ul>\n<li><p>Prefer the preincrement operator (++variable) in place of the postincrement operator (variable++).</p></li>\n<li><p>Prefer range based for loops or <code>std::for_each</code> so that you can allow the compiler to handle container bounds checking for you. The compiler will be more efficient at this than you can, and can potentially perform loop unrolling especially in the case of <code>std::for_each</code>.</p></li>\n<li><p>Prefer to use std algorithms over writing your own for loops. <code>std::find_if</code> or <code>std::any_of</code> are good for finding elements in a container that match a condition. <code>std::generate</code> and <code>std::transform</code> are good for filling a container with values from a function or another container.</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>// Create a vector with the elements required to permute\nvector&lt;char&gt; permSet;\npermSet.push_back('a');\npermSet.push_back('b');\npermSet.push_back('c');\n</code></pre></li>\n<li><p>Prefer to initialize directly using uniform initialization such as:</p>\n\n<pre><code>vector&lt;char&gt; permSet{'a', 'b', 'c'};\n</code></pre>\n\n<p>Or better yet (if you know that you won't modify <code>permSet</code>):</p>\n\n<pre><code>const vector&lt;char&gt; permSet{'a', 'b', 'c'};\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T20:58:10.323", "Id": "61502", "Score": "1", "body": "Preincrement and postincrement are fundamentally different operators. Preincrement is intended to simply increment the value. Postincrement will typically make a copy of the value, increment the value, then return the unincremented copy. Don't pay for that extra copy if you don't plan to use it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T21:24:19.927", "Id": "61511", "Score": "1", "body": "Also keep in mind that the initialization here is only available in C++11. Other than that, +1 from me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T20:56:11.780", "Id": "37255", "ParentId": "36786", "Score": "5" } }, { "body": "<p>You asked about programming style. I am big fan of reducing things to as simple as possible, with clear names and strong types, and getting things down to the one definition rule as much as possible. There are multiple reasons to prefer simplicity: if you can read it, you can see that it's correct. And it can help make future maintenance activities easier and safer, especially if they're not done by you.</p>\n\n<p>So let's see what happens when I play with your main as an example. I'll go way over the top and define and strongly type everything.</p>\n\n<pre><code>typedef char PERMUTATION_TYPE;\ntypedef vector&lt;PERMUTATION_TYPE&gt; PERMUTATION_SET;\ntypedef vector&lt;PERMUTATION_SET&gt; PERMUTATION_SETS;\ntypedef PERMUTATION_SETS::const_iterator PERMUTATION_SETS_IT;\n\nvoid printElement(const PERMUTATION_TYPE &amp;element)\n{\n cout &lt;&lt; element &lt;&lt; ' ';\n}\n\nvoid printPermutation (const PERMUTATION_SET &amp;perm)\n{\n for_each(perm.begin(), perm.end(), printElement);\n cout &lt;&lt; endl;\n\n}\n\nvoid printIndexedPermutation (const unsigned int permIndex, const PERMUTATION_SET &amp;perm)\n{\n cout &lt;&lt; \"(\" &lt;&lt; permIndex &lt;&lt; \") \" ;\n printPermutation(perm);\n}\n\n\nvoid printPermutationCollection(const PERMUTATION_SETS &amp;permSet)\n{\n for (PERMUTATION_SETS_IT perm=permSet.begin(); perm!= permSet.end(); ++perm)\n {\n printIndexedPermutation(distance(permSet.begin(), perm), *perm);\n }\n}\n\nvoid fillPermutationSetWithTestData(PERMUTATION_SET &amp;permSet)\n{\n permSet.push_back('a');\n permSet.push_back('b');\n permSet.push_back('c');\n}\n\nint main()\n{\n PERMUTATION_SET permSet;\n fillPermutationSetWithTestData(permSet);\n\n PERMUTATION_SETS vectorOfPerms = GetPerms(permSet); \n\n printPermutationCollection(vectorOfPerms);\n\n ValidatePermutations(permSet,vectorOfPerms);\n\n return 0;\n}\n</code></pre>\n\n<p>So every routine is tiny. <code>main()</code> is now readable without comments. Since you were using std::collections, I got rid of the for loops that used indices, and used iterators instead. Every routine is as simple as possible. Yes, there are a lot of them, but they don't cost you anything. And they're all dead simple.</p>\n\n<p>Of course that led to an issue of printing the index number. If I didn't need the index number, I'd get rid of <code>printIndexedPermutation</code> completely, and have only this one line inside <code>printPermutationCollection()</code>:</p>\n\n<pre><code> for_each(permSet.begin(), permSet.end(), printPermutation);\n</code></pre>\n\n<p>Would I recommend you go this far with your code? It all depends on what you're trying to do, if you're trying to maintain the routine into the distant future, or if it's just throwaway code. But I also have a lot of experience that suggesgts that throwaway code has a nasty habit of sticking around for a lot longer than I ever intended.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T03:04:22.133", "Id": "61742", "Score": "0", "body": "Thank you John. Yes. This is much more readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-09T01:57:42.477", "Id": "227868", "Score": "0", "body": "I disagree. A function like `printElement` is just another thing to remember; it doesn't introduce any kind of abstractive benefit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-11T20:51:24.443", "Id": "228418", "Score": "0", "body": "@Veedrac, I agree. If I were writing this today, I'd probably use a lambda instead of creating a separate function." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T23:49:41.330", "Id": "37268", "ParentId": "36786", "Score": "2" } }, { "body": "<h2>Surely, this is what arrays are for</h2>\n\n<p>Read the input into an array of strings, permute a tuple of integer indices, and print out the same string array in the order of the permuted integer tuple. </p>\n\n<p>Apart from input and output no string operations whatsoever ! Also works for any Object type - so for the greatest generality code for an abstract base class, and late bind to String or whatever is required, less coding and more uses. One of the reasons for Object Oriented Programming: <strong>Polymorphism</strong> in this case a polymorphic algorithm.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-08T22:17:22.837", "Id": "122307", "ParentId": "36786", "Score": "2" } }, { "body": "<p>The permutations of <code>{a, b, c}</code> are <code>{a, b, c}</code>, <code>{a, c, b}</code>, <code>{b, a, c}</code>, <code>{b, c, a}</code>, <code>{c, a, b}</code> and <code>{c, b, a}</code>.</p>\n\n<p>That's the best solution to the question as stated, though I suppose it's likely a more general method is also wanted.</p>\n\n<hr>\n\n<p>Your solution is recursive and does a lot of allocation. A much more effective way would be <a href=\"https://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations\" rel=\"nofollow\">to make a <code>next_permutation</code> function using this Wikipedia section</a>, either generating them lexicographically or by some more efficient method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-09T02:11:08.837", "Id": "122324", "ParentId": "36786", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:03:01.787", "Id": "36786", "Score": "5", "Tags": [ "c++", "performance", "algorithm", "combinatorics" ], "Title": "Permutation algorithm" }
36786
<p>I just wrote this simple code, but I have a problem. I get the factorial for small numbers, but if I enter number like 45 or above, I get 0 as the factorial. Why is that? Check and let me know what you think:</p> <pre><code>import java.util.*; public class Testing1 { public static void main (String args[]){ Scanner sc=new Scanner(System.in); long fact=1,sum=0,numIn; System.out.print("Enter the number : "); numIn=sc.nextLong(); for(int i=1;i&lt;=numIn;fact*=i++); for(int i=1;i&lt;=numIn;sum+=i++); System.out.println("factorial of "+numIn+" = "+fact); System.out.println("Summation of numbers till "+numIn+" = "+sum); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:18:48.927", "Id": "60532", "Score": "0", "body": "You don't need a loop to calculate the sum of the first `n` numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:30:39.497", "Id": "60534", "Score": "0", "body": "This Code works.I just wanted someone to clarify why it doesnt give the proper answer for big integers.So i dont see a point for you to hold it here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T00:10:15.723", "Id": "60585", "Score": "0", "body": "I know that it work within given bounds. I was just pointing out that you don't need a loop to calculate the sum of the first `n` numbers. You can calculate that in `O(1)` while the loop is `O(n)`" } ]
[ { "body": "<p><code>45!</code> is a very large number. Your <code>fact</code> is a <code>long</code>, but <code>long</code> is not large enough to hold the value...</p>\n\n<pre><code>44! = 2673996885588443136\nLong.MAX_VALUE = 9223372036854775807\n</code></pre>\n\n<p>Multiplying <code>44!</code> by 45 will overflow the <code>long</code>.... which is exactly what you see:</p>\n\n<pre><code>45! = -8797348664486920192\n</code></pre>\n\n<p>So, you do not get '0' as you suggest, but -8797348664486920192</p>\n\n<p><strong>NOTE:</strong> You should be aware that <code>20!</code> is actually the last valid number before overflow happens on a <code>long</code>. It is just co-incidence that 44! is positive .... and 45! is not.</p>\n\n<hr>\n\n<h1>EDIT</h1>\n\n<p>You ask why <code>100! == 0</code>?</p>\n\n<p>It is a 'co-incidence' --- (NOTE: A really, really mysterious one, needs more investigation):</p>\n\n<pre><code>factorial of 64 = -9223372036854775808\nSummation of numbers till 64 = 2080\nfactorial of 65 = -9223372036854775808\n (9223372036854775807)\nSummation of numbers till 65 = 2145\nfactorial of 66 = 0\nSummation of numbers till 66 = 2211\n</code></pre>\n\n<p>64! is exactly Long.MIN_VALUE.... (coincidence?????)\n65! is <strong>also</strong> Long.MIN_VALUE\n66! is 0.</p>\n\n<p>After that, anything times 0 is 0,.</p>\n\n<h1>EDIT2:</h1>\n\n<p>OK, the reason for this, is that any time you multiple a value by 2, it is the same as a bitwise left-shift.... for example, <code>0b00000001</code> (1) multiplied by 2 is <code>0b00000010</code>.</p>\n\n<p>With this factorial, any time you multiple by an even number it is a bit-shift (because all even numbers are a multiple of 2). Also, because any time you multiply one value by an even number the result will always be even. (3*2 is 6, etc!). So, after you have 2! (1 * 2) the factorial result will always be even... (only 1! is odd) and thus every successive loop in the factorial is a bit-shift to the left.</p>\n\n<p>After 64! only the highest-bit is set in your long value..... and then, multiplying by 65 (because it is an odd number) is the same result.... finally, multiplying by 66 (an even number), is another shift, which shifts <strong>all</strong> the bits out of the long value and you are left with just zero <code>0</code>.</p>\n\n<p>You can see this using the following adaption of your code:</p>\n\n<pre><code>public static void main (String args[]){\n for (int numIn = 0; numIn &lt; 101; numIn++) {\n long fact=1;\n for(int i=1;i&lt;=numIn;fact*=i++);\n System.out.println(\"factorial of \"+numIn+\" = \"+ Long.toHexString(fact));\n }\n}\n</code></pre>\n\n\n\n<pre><code>factorial of 53 = b6da000000000000\nfactorial of 54 = 91fc000000000000\nfactorial of 55 = 5d24000000000000\nfactorial of 56 = 5fe0000000000000\nfactorial of 57 = 58e0000000000000\nfactorial of 58 = 22c0000000000000\nfactorial of 59 = 240000000000000\nfactorial of 60 = 8700000000000000\nfactorial of 61 = 2b00000000000000\nfactorial of 62 = 6a00000000000000\nfactorial of 63 = 1600000000000000\nfactorial of 64 = 8000000000000000\nfactorial of 65 = 8000000000000000\nfactorial of 66 = 0\nfactorial of 67 = 0\nfactorial of 68 = 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:33:39.573", "Id": "60512", "Score": "0", "body": "Okay.I understand it.But can you tell me why do i get 0 as the factorial if i put a number like 100?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:41:16.523", "Id": "60516", "Score": "0", "body": "@Razor1692 - updated my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:58:34.593", "Id": "60519", "Score": "0", "body": "@Razor1692 - updated again, with the reaso. Thanks for the diversion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:07:59.963", "Id": "60523", "Score": "0", "body": "I will go through this and try to understand it properly.if i come across any confusion i will ask you again.Thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:27:25.527", "Id": "60527", "Score": "0", "body": "@Razor1692 To solve your problem, you should use either `double` or `BigInteger`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:32:08.237", "Id": "36790", "ParentId": "36788", "Score": "4" } } ]
{ "AcceptedAnswerId": "36790", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:21:50.363", "Id": "36788", "Score": "-1", "Tags": [ "java" ], "Title": "Determining the factorial and the summation of numbers until that number" }
36788
<p>I'm curious about <code>Object.defineProperty</code>. It seems awfully verbose for not doing much more than what you can already do in the constructor. What's the point of it? Would it be 'bad code' to not use it? I know you have more control over read/write and enumerability with defineProperty, is that enough to use this verbose syntax?</p> <pre><code>function Person(age, name) { this.name = name; this.age = age; }; Object.defineProperty(Person.prototype, "age", { get: function() { return this._age; }, // Added a few things to demonstrate additional logic on the setter set: function(num) { num = parseInt(num, 10); if(num &gt; 0) { this._age = num; } } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:34:41.833", "Id": "60513", "Score": "0", "body": "You usually only use defineProperty in very specific cases. (let's say you wanted validation on age?) - in your case - I would not use it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:36:16.977", "Id": "60514", "Score": "0", "body": "@BenjaminGruenbaum simple enough answer, I like it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:37:57.750", "Id": "60515", "Score": "0", "body": "@BenjaminGruenbaum offhand can you think of anything outside of validation were it might be useful to use defineProperty?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:41:16.113", "Id": "60517", "Score": "1", "body": "Plenty of reasons - non-enumerable properties, frozen properties, computed properties, proxies (Create an object based on another object and mirror calls + observe). There are a lot of good use cases - they're just not very common in the web because of IE8 yet. In your case (age) I would not use Object.defineProperty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:21:52.923", "Id": "60526", "Score": "0", "body": "@BenjaminGruenbaum Can you create an answer with your comment, it will make CR look better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:04:26.380", "Id": "60530", "Score": "1", "body": "@tomdemuyt sure, done." } ]
[ { "body": "<p>As requested by tomdemuyt. I'm posting my comments as an answeR:</p>\n\n<p>You usually only use <code>defineProperty</code> in very specific cases. (let's say you wanted validation on age?) - in your case - I would not use it.</p>\n\n<p>Op then asked:</p>\n\n<blockquote>\n <p>offhand can you think of anything outside of validation were it might be useful to use defineProperty?</p>\n</blockquote>\n\n<p>Plenty of reasons:</p>\n\n<ul>\n<li>non-enumerable properties, </li>\n<li>frozen properties, </li>\n<li>computed properties, </li>\n<li>proxies (Create an object based on another object and mirror calls + observe). </li>\n</ul>\n\n<p>There are a lot of good use cases - they're just not very common in the web because of IE8 yet. In your case (age) I would not use <code>Object.defineProperty</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T17:25:08.200", "Id": "36797", "ParentId": "36791", "Score": "4" } } ]
{ "AcceptedAnswerId": "36797", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:32:32.367", "Id": "36791", "Score": "0", "Tags": [ "javascript" ], "Title": "JavaScript Object.defineProperty" }
36791
<p>I am building an web application that is going to work in a similar way like photoshop or illustrator regarding layers. Here are my code that is searching the ".case" div for images, and then put these images id's to an array. When that is done we are looping the array to find out if the received image is the same as the one we loop through from the array.</p> <p>When finding this image we wan't to move it one step up or down in the hierarchy. But this image have a div with controllers associated, so we have to move this in the same way.</p> <p>So do you think this is the best possible code we can create to get this work? It does work, I only want to find out if there are any better solutions for it.</p> <pre><code>var arrangeLayers = function(e,direction) { var timestampId = e.attr('id'); timestampId = timestampId.replace('name', ''); var elem = []; $('.case img').each(function(){ elem.push($(this).attr('id')); }); for (i=0;i&lt;elem.length;i++) { if (timestampId == elem[i] &amp;&amp; direction == 'down') { if (i != 0) { $('#' + timestampId).insertBefore($('#' + elem[(i-1)])); $('#name' + timestampId).insertBefore($('#' + timestampId)); } } else if (timestampId == elem[i] &amp;&amp; direction == 'up') { if (i != (elem.length) -1) { $('#' + timestampId).insertAfter($('#' + elem[(i+1)])); $('#name' + timestampId).insertBefore($('#' + timestampId)); } } } } </code></pre>
[]
[ { "body": "<p>I'm not sure if I understand what you're doing correctly.</p>\n<p>So essentially each image has itself, and then some other element that should be before it as a buddy? Assuming they are all siblings, you should utilize some of jQuery's functions that support working with siblings.</p>\n<p>Here's an example, though I'm sure it could still be better:</p>\n<pre><code>var arrangeLayers = function (e, direction) {\n var $target = $(e);\n var $targetBuddy = $target.prev();\n if (direction === 'down') { \n if($targetBuddy.index() &gt; 1) {\n $target.insertBefore($targetBuddy.prev().prev());\n }\n } else {\n if ($target.index() !=$target.siblings().length) {\n $target.insertAfter($target.next().next());\n }\n }\n $targetBuddy.insertBefore($target);\n}\n</code></pre>\n<p>Or if you don't care about index error checking (which in actual practice appears to not matter):</p>\n<pre><code>var arrangeLayers = function (e, direction) {\n var $target = $(e);\n var $targetBuddy = $target.prev();\n if (direction === 'down') { \n $target.insertBefore($targetBuddy.prev().prev());\n } else {\n $target.insertAfter($target.next().next());\n }\n $targetBuddy.insertBefore($target);\n}\n</code></pre>\n<p>Here's a <a href=\"http://jsfiddle.net/V9RH6/\" rel=\"nofollow noreferrer\">jsfiddle</a> without the checking:</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T11:12:02.347", "Id": "60619", "Score": "0", "body": "Great advice! That is correct, there are not really any reason to be checking for indexes when there are no siblings before or after. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-12-06T18:07:01.447", "Id": "36800", "ParentId": "36793", "Score": "2" } } ]
{ "AcceptedAnswerId": "36800", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T16:47:20.493", "Id": "36793", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Optimize “layering” in jQuery" }
36793
<p>We have a binary tree, suppose like this:</p> <pre><code> 8 / \ 6 10 / \ / \ 4 7 9 12 / \ 3 5 </code></pre> <p>We have to print this binary tree in top-down manner - column wise. Note that, <code>8, 7 &amp; 9</code> would be considered in same column. So the required output should be:</p> <pre><code>3 4 6 5 8 7 9 10 12 </code></pre> <p>Currently I've implemented this problem using two maps, and one queue. Here's the method <code>traversal(Node&lt;T&gt; node)</code>, which is invoked first time, passing the root node:</p> <pre><code>public void traverse(Node&lt;T&gt; node) { Queue&lt;Node&lt;T&gt;&gt; queue = new LinkedList&lt;&gt;(); Map&lt;Integer, List&lt;Node&lt;T&gt;&gt;&gt; columnMap = new TreeMap&lt;&gt;(); Map&lt;Node&lt;T&gt;, Integer&gt; map = new HashMap&lt;&gt;(); queue.add(node); while (!queue.isEmpty()) { Node&lt;T&gt; temp = queue.poll(); if (map.isEmpty()) { map.put(temp, 0); columnMap.put(0, new ArrayList&lt;Node&lt;T&gt;&gt;(Arrays.asList(temp))); } int column = map.get(temp); if (temp.left() != null) { queue.add(temp.left()); if (columnMap.containsKey(column - 1)) { columnMap.get(column - 1).add(temp.left()); } else { columnMap.put(column - 1, new ArrayList&lt;Node&lt;T&gt;&gt;(Arrays.asList(temp.left()))); } map.put(temp.left(), column - 1); } if (temp.right() != null) { queue.add(temp.right()); if (columnMap.containsKey(column + 1)) { columnMap.get(column + 1).add(temp.right()); } else { columnMap.put(column + 1, new ArrayList&lt;Node&lt;T&gt;&gt;(Arrays.asList(temp.right()))); } map.put(temp.right(), column + 1); } } for (Entry&lt;Integer, List&lt;Node&lt;T&gt;&gt;&gt; entry: columnMap.entrySet()) { System.out.println("Column - " + entry.getKey() + " : " + entry.getValue()); } } </code></pre> <p>The idea is, starting from root node as column number <code>0</code>, the left node will have column number <code>-1</code>, and the right node will have column number <code>1</code>. Then the right node of the left node will again have column number <code>0</code>. And similarly I proceed till I've exhausted all the nodes. I've used level order traversal for traversing.</p> <p>The first map - <code>Map&lt;Node&lt;T&gt;, Integer&gt;</code> is used to get the column number for a particular node. I've used this map, so that I can get the column number of a node in <code>O(1)</code> time. For example, starting with root, I put a mapping - <code>&lt;root, 0&gt;</code>, in the map. And then, put an entry in <code>columnMap</code> - <code>&lt;0, root&gt;</code>, specifying there is currently <code>root</code> at column <code>0</code>. I've used <code>Queue</code> for the purpose of <em>level-order traversal</em> (Well, it can be avoided by using <em>pre-order</em>, <em>post-order</em> or <em>in-order</em>). </p> <p>Now, I remove the <code>root</code> from <code>queue</code>, and push it's two children. For <code>left</code> child, I've to find the column number based on it's parent (in this case, <code>root</code>). So, I get the column number for <code>root</code> from <code>map</code>. And subtract <code>1</code> from it to get column of <code>left</code>. If the column number is already in the <code>columnMap</code>, I just update the existing list of node for that column, else I add a new entry.</p> <p>I thought of getting it done with just a single map, but I found it more clear.</p> <p>Is there some better option? Currently, the code looks a bit complex to me. May be it can be improvised? I'm open to a completely different implementation too, provided it is more clear, and space and time efficient.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T21:03:52.157", "Id": "60560", "Score": "0", "body": "The challenge seems ill formed. What if \"7\" has two complete levels under it? I think you would probably consider the left child of \"7\" to share the same column as \"5\". What about the leftmost grandchild of \"7\"? Would it be to the left of \"5\"? That doesn't make sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T07:34:22.443", "Id": "60611", "Score": "0", "body": "@200_success I know that doesn't make sense. Don't think it like printing the left childs first, and then the right child. Think of it a vertical traversal of tree. I've given the example that was asked in an interview (I didn't attend that interview though)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-14T09:31:38.470", "Id": "197168", "Score": "0", "body": "nicely explained with program:http://javabypatel.blogspot.in/2015/10/print-binary-tree-in-vertical-order.html" } ]
[ { "body": "<p>Using recursion in this instance helps a lot to reduce code duplication. Particularly, in this case, you have different code blocks depending on whether <code>left()</code> or <code>right()</code> are null.</p>\n\n<p>Using recursion you only need one null check, and this removes a big chunk of code.</p>\n\n<p>The queue is only needed for recursion as well, and, it's purpose was hard to figure out... you should have documented it more carefully...</p>\n\n<p>The <code>map</code> variable is also a variable which has a poorly documented purpose... it's hard to tell what variables are on that, and why.</p>\n\n<p>All in all, your suspicions are right that there's a better way to do this.....</p>\n\n<p>Algorithmically it strikes me that a single <code>Map&lt;List&lt;Integer&gt;&gt;</code> is probably the right structure, and that recursion is a better solution.... consider a recursive function:</p>\n\n<pre><code>recurseTraverse(final Node&lt;Integer&gt; node, final Map&lt;Integer, List&lt;Node&lt;Integer&gt;&gt;&gt; columnmap, final int column) {\n if (node == null) {\n return;\n }\n List&lt;Node&lt;Integer&gt;&gt; list = columnmap.get(column);\n if (list == null) {\n list = new ArrayList&lt;Node&lt;Integer&gt;&gt;();\n columnmap.put(column, list);\n }\n list.add(node);\n recurse(node.left(), columnmap, column - 1);\n recurse(node.right(), columnmap, column + 1);\n\n}\n</code></pre>\n\n<p>Then calling that with a <code>TreeMap&lt;Integer, List&lt;Node&lt;Integer&gt;&gt;&gt;</code> you should be able to get an improved version of your result.</p>\n\n<pre><code>public void traverse(Node&lt;Integer&gt; root) {\n TreeMap&lt;Integer, List&lt;Node&lt;Integer&gt;&gt;&gt; columnMap = new TreeMap&lt;&gt;();\n\n recurseTraverse(root, columnMap, 0);\n\n for (Entry&lt;Integer, List&lt;Node&lt;Integer&gt;&gt;&gt; entry: columnMap.entrySet()) {\n System.out.println(\"Column - \" + entry.getKey() + \" : \" + entry.getValue());\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Update:</strong> It has been pointed out by <a href=\"https://codereview.stackexchange.com/users/18347/fihop\">Fihop</a> that this answer produces the incorrect results. While it correctly puts each node in to the correct column, it adds them in a depth-first order:</p>\n\n<blockquote>\n <p>The accepted solution actually does not work. For example:</p>\n\n<pre><code> 1\n / \\\n 2 3\n \\\n 4\n \\\n 5\n</code></pre>\n \n <p>it gives:</p>\n\n<pre><code>2\n1 4\n5 3 =&gt; should be 3 5???\n</code></pre>\n</blockquote>\n\n<p>The right solution to this problem is to perform a breadth first traversal (traversing each row of the tree at a time), which requires a queue, and recursion is no longer the best, or even a viable, solution.</p>\n\n<p>In re-working this answer, I have also actually run the code (rather than just typing it in to an answer), and I have almost 2 more years of experience on this. So, there are some other things to point out.</p>\n\n<p>First up, this code can now use Java 8, and <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-\" rel=\"nofollow noreferrer\">the <code>computeIfAbsent()</code> Map method</a>.</p>\n\n<p>Next, using static methods that are also generic methods makes the dependence on <code>Node&lt;Integer&gt;</code> become the generic <code>Node&lt;N&gt;</code>. I have still worked the example using Integers, and I have invented what I believe the <code>Node</code> class should be. It's not exactly the way I would write it because the method names <code>left()</code> and <code>right()</code> would probably be named differently. I have also created a rudimentary <code>toString</code>.</p>\n\n<p>Finally, to work the traversal a helper container-class <code>ColumnFind</code> was created to link a node to a column, and allow the temporary storage of the column for when the next level of the tree is traversed.</p>\n\n<p>It pains me that the traversal and the println calls are in the same method, I feel they should be separate, but to keep the code consistent with my earlier answer, I will leave it like that. A Java 8 function passed in to the traversal would be a better solution....</p>\n\n<p>So, here's the traversal code (and it is working in ideone here: <a href=\"http://ideone.com/p8RWmE\" rel=\"nofollow noreferrer\">http://ideone.com/p8RWmE</a> ).</p>\n\n<pre><code>public static final &lt;N&gt; void traverse(Node&lt;N&gt; root) {\n\n final TreeMap&lt;Integer, List&lt;Node&lt;N&gt;&gt;&gt; columnMap = new TreeMap&lt;&gt;();\n final Queue&lt;ColumnFind&lt;N&gt;&gt; queue = new LinkedList&lt;&gt;();\n\n queueChild(0, root, queue);\n\n while (!queue.isEmpty()) {\n ColumnFind&lt;N&gt; cf = queue.remove();\n int column = cf.column;\n Node&lt;N&gt; node = cf.node;\n columnMap.computeIfAbsent(column, c -&gt; new ArrayList&lt;&gt;()).add(node);\n queueChild(column - 1, node.left(), queue);\n queueChild(column + 1, node.right(), queue);\n }\n\n for (Entry&lt;Integer, List&lt;Node&lt;N&gt;&gt;&gt; entry: columnMap.entrySet()) {\n System.out.println(\"Column - \" + entry.getKey() + \" : \" + entry.getValue());\n }\n}\n\nprivate static final &lt;N&gt; void queueChild(int column, Node&lt;N&gt; node, \n Queue&lt;ColumnFind&lt;N&gt;&gt; queue) {\n if (node == null) {\n return;\n }\n queue.add(new ColumnFind&lt;&gt;(column, node));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:57:45.190", "Id": "60538", "Score": "0", "body": "Updated the question. I hope that it is more clear now. For `queue` part, I guess I've overlooked the fact that I could have used preorder, postorder or inorder traversal. That wouldn't have made any difference. So, yes `queue` can be avoided here. BTW, thanks for your solution. I was completely ignoring the possible recursive solution. It looks so simple with that. Nice :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:59:30.700", "Id": "60539", "Score": "0", "body": "I was trying the iterative approach, because most of the time, interviewer ask for that explicitly, in cases where they know recursive approach is too easy to ask for, like in this case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:46:59.737", "Id": "36804", "ParentId": "36799", "Score": "6" } } ]
{ "AcceptedAnswerId": "36804", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:06:33.427", "Id": "36799", "Score": "14", "Tags": [ "java", "algorithm", "interview-questions", "tree" ], "Title": "Printing a Binary Tree top-down (column wise)" }
36799
<p>I'm just starting to get along with threads in Java and I need some code review, about interfaces, classes, managing threads, correct writing, secure threads, exposed objects etc.</p> <p>Horse-Race Implementation:</p> <pre><code>package HorseRace; public interface FinishingLine { public void arrive(Horse h); } </code></pre> <hr> <pre><code>package HorseRace; import java.util.Vector; public class FinishingLineImpl implements FinishingLine { Vector&lt;String&gt; Ranking = new Vector&lt;String&gt;(10); public FinishingLineImpl(){} @Override public void arrive(Horse h) { // TODO Auto-generated method stub Ranking.add(h.getId()); } public void print() { for (int i = 0; i &lt; 10 ; i++) { System.out.println("Place " + (i + 1)+ " is : " + Ranking.get(i)); } } } </code></pre> <hr> <pre><code>package HorseRace; public interface Horse { public void run(); public String getId(); } package HorseRace; import java.util.Random; public class HorseImpl implements Horse,Runnable { int _distance; String _id; FinishingLine _f; public HorseImpl(String id, FinishingLine f) { _id = id; _distance = 0; _f = f; } @Override public void run() { // TODO Auto-generated method stub Random rand = new Random(); int n = rand.nextInt(10) + 1; while (_distance &lt; 100) { try { Thread.sleep(n); } catch (Exception e) { e.printStackTrace(); } _distance += 1; } _f.arrive(this); } @Override public String getId() { // TODO Auto-generated method stud return _id; } } </code></pre> <hr> <pre><code>package HorseRace; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub ExecutorService e = Executors.newFixedThreadPool(10); FinishingLineImpl f = new FinishingLineImpl(); for (int i = 0; i&lt;10 ; i++) { System.out.println("Creating a horse with id = " + (i+1)); String strI = Integer.toString(i+1); HorseImpl h = new HorseImpl(strI,f); e.execute(h); } e.shutdown(); e.awaitTermination(60000, TimeUnit.SECONDS); f.print(); } } </code></pre>
[]
[ { "body": "<pre class=\"lang-java prettyprint-override\"><code>// package name should be lower case\npackage HorseRace;\n\npublic interface FinishingLine {\n\n public void arrive(Horse h);\n}\n\npackage HorseRace;\n\nimport java.util.Vector;\n\npublic class FinishingLineImpl implements FinishingLine {\n\n // Vector is discouraged, unless you are using an ancient version of java\n // use Collections.synchronizedList(new ArrayList()) instead\n // variable should start with a lowercase letter, i.e. camelCase\n Vector&lt;String&gt; Ranking = new Vector&lt;String&gt;(10);\n\n public FinishingLineImpl(){}\n @Override\n public void arrive(Horse h) {\n // TODO Auto-generated method stub\n Ranking.add(h.getId());\n }\n\n // override toString instead\n public void print()\n {\n // magic numbers are evil; use ranking.size() instead\n for (int i = 0; i &lt; 10 ; i++)\n {\n System.out.println(\"Place \" + (i + 1)+ \" is : \" + Ranking.get(i));\n }\n }\n}\n\npackage HorseRace;\n\npublic interface Horse {\n\n public void run();\n // change String to Object so you can use anything for the ID\n public String getId();\n}\n\npackage HorseRace;\nimport java.util.Random;\n\npublic class HorseImpl implements Horse,Runnable {\n\n // see previous comment regarding camelCase\n int _distance;\n String _id;\n FinishingLine _f;\n\n public HorseImpl(String id, FinishingLine f)\n {\n _id = id;\n _distance = 0;\n _f = f;\n }\n @Override\n public void run() {\n // TODO Auto-generated method stub\n Random rand = new Random();\n\n int n = rand.nextInt(10) + 1;\n\n while (_distance &lt; 100)\n {\n try\n {\n // why sleep? \n // why not create and increment a timeElapsed instance variable?\n // preferrably an AtomicInteger\n // then calculate ranking after the race, e.g. sort by elapsed time\n Thread.sleep(n);\n }\n catch (Exception e)\n {\n e.printStackTrace();\n // break out?\n }\n _distance += 1;\n }\n\n _f.arrive(this);\n }\n\n @Override\n public String getId() {\n return _id;\n }\n}\n\npackage HorseRace;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class Main {\n\n public static void main(String[] args) throws InterruptedException {\n // I suggest calculating nThreads as cpu count * 2\n // @see Runtime.getRuntime().availableProcessors();\n // please use descriptive variable names\n ExecutorService e = Executors.newFixedThreadPool(10);\n FinishingLineImpl f = new FinishingLineImpl();\n\n // another magic number\n for (int i = 0; i&lt;10 ; i++)\n {\n System.out.println(\"Creating a horse with id = \" + (i+1));\n // see comment regarding id type\n String strI = Integer.toString(i+1);\n HorseImpl h = new HorseImpl(strI,f);\n e.execute(h);\n }\n\n e.shutdown();\n // 16 hours? really?\n e.awaitTermination(60000, TimeUnit.SECONDS); \n\n // change to System.out.println(f);\n f.print();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:11:47.157", "Id": "60546", "Score": "0", "body": "First of all, thank you for your answer. What do you mean by \"change String to Object so you can use anything for the ID\"? and why \"calculating nThreads as cpu count *2\"? thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:30:19.963", "Id": "60554", "Score": "0", "body": "I suggested changing the return type of getId to Object so that you can use any object as the ID (so you don't have to convert an int to a String).\nThe benefit of calculating nThreads is the application will scale automatically. A computer might have 1 cpu or it might have 8. It should work optimally either way." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T19:56:06.480", "Id": "36809", "ParentId": "36806", "Score": "2" } } ]
{ "AcceptedAnswerId": "36809", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T18:55:10.970", "Id": "36806", "Score": "4", "Tags": [ "java", "thread-safety", "simulation", "multithreading" ], "Title": "Multithreaded horse race simulation" }
36806
<p>Please review my code based off of a responsive Initializr template. It's functional and visually correct, but I know there's better ways to write the code. Let me know if I can layout the HTML5 better and/or best practices I'm not using for CSS selectors because I feel my stylesheet is all over the place.</p> <p><strong>HTML</strong></p> <pre class="lang-html prettyprint-override"><code> &lt;!DOCTYPE html&gt; &lt;!--[if lt IE 7]&gt;&lt;html class="no-js lt-ie9 lt-ie8 lt-ie7"&gt;&lt;![endif]--&gt; &lt;!--[if IE 7]&gt;&lt;html class="no-js lt-ie9 lt-ie8"&gt;&lt;![endif]--&gt; &lt;!--[if lt IE 9]&gt;&lt;![endif]--&gt; &lt;!--[if gt IE 8]&gt;&lt;!--&gt;&lt;html class="no-js"&gt;&lt;!--&lt;![endif]--&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"&gt; &lt;title&gt;Site - example.org&lt;/title&gt; &lt;meta name="description" content=""&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,600,700' rel='stylesheet' type='text/css'&gt; &lt;link rel="stylesheet" href="css/normalize.css"&gt; &lt;link rel="stylesheet" href="css/main.css"&gt; &lt;script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!--[if lt IE 7]&gt; &lt;p class="chromeframe"&gt;You are using an &lt;strong&gt;outdated&lt;/strong&gt; browser. Please &lt;a href="http://browsehappy.com/"&gt;upgrade your browser&lt;/a&gt; or &lt;a href="http://www.google.com/chromeframe/?redirect=true"&gt;activate Google Chrome Frame&lt;/a&gt; to improve your experience.&lt;/p&gt; &lt;![endif]--&gt; &lt;div class="header-container"&gt; &lt;header class="clearfix"&gt; &lt;nav&gt; &lt;h1&gt;&lt;a href="/"&gt;&lt;img src="img/logo.png" class="logo" alt=""&gt;&lt;/a&gt;&lt;/h1&gt; &lt;div class="toggle"&gt; &lt;span class="bars-btn"&gt;&lt;/span&gt; &lt;span class="bars-btn"&gt;&lt;/span&gt; &lt;span class="bars-btn"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="social"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://www.facebook.com" class="facebook" target="_blank"&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://www.twitter.com" class="twitter" target="_blank"&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;ul class="accordion"&gt; &lt;li&gt;&lt;a href="#"&gt;About Us&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Programs&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;News and Events&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Apply&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Donate&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contact&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sub&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; &lt;/div&gt; &lt;div class="slider-container"&gt; &lt;div class="slider"&gt; &lt;article&gt; &lt;section&gt; &lt;h1&gt;Lorem ipsum dolor sit amet, te idque corpora sit.&lt;/h1&gt; &lt;p&gt;&lt;a href="#"&gt;Learn More About What We Do &amp;raquo;&lt;/a&gt;&lt;/p&gt; &lt;/section&gt; &lt;/article&gt; &lt;/div&gt; &lt;!-- #main --&gt; &lt;/div&gt; &lt;!-- #slider-container --&gt; &lt;div class="highlighter-container"&gt; &lt;div class="highlighter wrapper clearfix"&gt; &lt;ul&gt; &lt;li class="apply-btn"&gt;&lt;a href="#"&gt;Apply&lt;/a&gt;&lt;/li&gt; &lt;li class="donate-btn"&gt;&lt;a href="#"&gt;Donate&lt;/a&gt;&lt;/li&gt; &lt;li class="events-btn"&gt;&lt;a href="#"&gt;Events&lt;/a&gt;&lt;/li&gt; &lt;li class="volunteer-btn"&gt;&lt;a href="#"&gt;Volunteer&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- #main --&gt; &lt;/div&gt; &lt;!-- #hig-container --&gt; &lt;div class="main-container"&gt; &lt;div class="main wrapper clearfix"&gt; &lt;aside&gt; &lt;iframe width="499" height="281" src="//www.youtube.com/embed/mbfbzKquYYI" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;/aside&gt; &lt;article&gt; &lt;section&gt; &lt;p&gt;Lorem ipsum dolor sit amet, te idque corpora sit. Duo eu quas omittam, ex vis invidunt prodesset, est quem oblique at. Accusata consequat interesset ad eos, id prima vocent audire his, senserit indoctum at sit. Pro graeco reprehendunt in, vel equidem dolorum consequat id, no sea paulo platonem explicari.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, te idque corpora sit. Duo eu quas omittam, ex vis invidunt prodesset, est quem oblique at. Accusata consequat interesset ad eos, id prima vocent audire his, senserit indoctum at sit.&lt;/p&gt; &lt;h3&gt;&lt;a href="#"&gt;Learn More About What We Do &amp;raquo;&lt;/a&gt;&lt;/h3&gt; &lt;/section&gt; &lt;/article&gt; &lt;/div&gt; &lt;!-- #main --&gt; &lt;/div&gt; &lt;!-- #main-container --&gt; &lt;div class="footer-container"&gt; &lt;footer class="wrapper"&gt; &lt;div class="legal"&gt; &lt;p&gt;&lt;a href="#"&gt;Privacy Policy&lt;/a&gt; | &lt;a href="#"&gt;Legal Provisions&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="copyright"&gt; &lt;p&gt;12345 Fake St., Springfield IL&lt;br&gt;&lt;a href="tel:800-555-5555" class="telephone"&gt;(800) 555-5555&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;small&gt;Copyright &amp;copy; 2013 Site&lt;/small&gt;&lt;/p&gt; &lt;/div&gt; &lt;/footer&gt; &lt;/div&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt;window.jQuery || document.write('&lt;script src="js/vendor/jquery-1.10.1.min.js"&gt;&lt;\/script&gt;')&lt;/script&gt; &lt;script src="js/plugins.js"&gt;&lt;/script&gt; &lt;script src="js/main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>CSS</strong></p> <pre class="lang-css prettyprint-override"><code>body { font-family: 'Open Sans', sans-serif; color: #4C4C4E; } a { text-decoration: none; } .wrapper { width: 93.445%; margin: 0 auto; } /* =================== ALL: Orange Theme =================== */ .header-container { /* background-color: transparent;*/ } .light-gray { background-color: #F5F5F6; } .slider-container { background-color: #E6E7E8; } .finder-container { display: none; } .footer-container { background-color: transparent; } /* ============== MOBILE: Menu ============== */ header nav { width: 100%; margin: 0 auto; } header nav h1 { margin: 10px 0 15px 15px; /* 3% 0 5% 4% */ } .logo { width: 91px; height: 50px; } .toggle { position: absolute; float: right; right: 15px; top: 18px; width: 30px; color: #FFFFFF; cursor: pointer; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box } .bars-btn { background-color: #4D4D4F; box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); display: block; height: 4px; width: 30px; margin: 7.5px 0; border-radius: 50px 50px 50px 50px; } .social, .social ul, .social li { display: none; } .accordion { margin: 0 0 15px 0; padding: 0; list-style: none; *zoom: 1; } .accordion:before, .accordion:after { content: " "; display: table; } .accordion:after { clear: both; } .accordion ul { width: 100%; margin: 0; padding: 0; list-style: none; } .accordion &gt; li { position: relative; margin: 0; text-indent: 15px; list-style: none; font-family: "Open Sans", sans-serif; font-size: 13px; line-height: 45px; font-weight: 600; background-color: #404041; border-top: 1px solid #B1B3B5; } .accordion &gt; li &gt; .parent { margin-right: 15px; background: url(../img/bullet-down.png) no-repeat right; } .accordion &gt; li &gt; a { display: block; color: #E6E7E8; text-transform: uppercase; } .accordion li ul { position: absolute; left: -9999px; } .accordion &gt; li.hover &gt; ul { left: 0; background-color: #fff; } .accordion li li.hover ul { top: 0; left: 0; } .accordion li li a { display: block; color: #E6E7E8; font-size: 12px; font-weight: 600; background: #4D4D4F; position: relative; z-index: 100; border-top: 1px solid #B1B3B5; text-transform: none; } /* ============== MOBILE: Finder ============== */ /* ============== MOBILE: Slider ============== */ .slider { width: 93.445%; margin: 0 auto; padding: 24px 0; } .slider article section h1 { color: #626366; margin: 0; font-size: 18px; line-height: 27px; font-weight: 700; text-align: center; } .slider article section p { margin: 0; font-size: 14px; line-height: 39px; font-weight: 600; text-align: center; } .slider article p a { color: #7A7C7E } /* ============== MOBILE: Highlighter ============== */ .highlighter { background: #fff repeat 0 0; padding: 0; } .highlighter ul { width: 100%; overflow: hidden; margin: 0; padding: 0; text-align: center; clear: both; } .highlighter li { float: left; margin: 0; padding: 0; list-style: none; width: 100%; text-align: center; } .highlighter a { margin: 0; display: block; text-align: center; font-family: "Open Sans", sans-serif; font-size: 14px; line-height: 52px; font-weight: 600; color: #ffffff; } .highlighter li.apply-btn a, .highlighter li.donate-btn a, .highlighter li.events-btn a, .highlighter li.volunteer-btn a { margin-top: 16px; background: #7C7E80 repeat 0 0 } .highlighter li.volunteer-btn a { margin: 16px 0 ; background: #7C7E80 repeat 0 0 } .highlighter li.apply-btn a:hover, .highlighter li.donate-btn a:hover, .highlighter li.events-btn a:hover, .highlighter li.volunteer-btn a:hover { background: #ccc repeat 0 0 } /* ============== MOBILE: Main ============== */ .main { padding: 0; } .main aside { position: relative; padding-bottom: 56.25%; padding-top: 30px; height: 0; overflow: hidden; } .main p { margin: 0 0 28px 0; } .main iframe, .main object, .main embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .main article { width: 100%; padding: 15px 0; } .main article section p { font-size: 14px; line-height: 23px; font-weight: 400; } .main article section h3 { margin: 0; padding: 0 0 15px 0; font-size: 14px; line-height: 20px; font-weight: 600; } .main article section h3 a { color: #6F7073; } .footer-container footer { padding-top: 10px; border-top: 1px solid #B1B3B5; } .footer-container footer .legal p { font-size: 12px; line-height: 20px; font-weight: 400; text-transform: uppercase; } .footer-container footer .legal p a, .footer-container footer .copyright p a { color: #6F7073 } .footer-container footer .copyright p { font-size: 12px; line-height: 20px; font-weight: 400; } .footer-container footer .copyright small { color: #B1B3B5; font-size: 11px; line-height: 23px; } .page { margin-top: 20px; margin-bottom: 20px; } .page article { font-size: 14px; line-height: 23px; font-weight: 400; margin: 0; vertical-align: top; } .page article header h1 { margin: 0; font-size: 18px; line-height: 27px; font-weight: 700; } .page article p { margin: 0 0 20px 0; } .page aside { display: none; } .youtube { position: relative; margin-bottom: 30px; padding-bottom: 56.25%; /* 16:9 */ padding-top: 25px; height: 0; } .youtube iframe, .youtube object, .youtube embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .focus-box { padding: 10px; background-color: #F5F5F6; } .focus-box h3 { margin: 0; padding: 0; font-size: 16px; line-height: 45px; font-weight: 600; } .image img { display: none; } .focus-box ul { list-style-type: none; margin: 0; padding: 0; text-indent: 0; } .focus-box li { margin-bottom: 10px } .focus-box li:before { content: "- "; } /* =============== ALL: IE Fixes =============== */ .ie7 .logo { padding-top: 20px; } /* ========================================================================== Media Queries ========================================================================== */ @media only screen and (min-width: 600px) { /* ==================== INTERMEDIATE: All ==================== */ .wrapper { width: 93.165%; } header nav h1 { margin: 10px 0 15px 18px; /* 3% 0 5% 4% */ } .toggle { right: 25px; } .slider { width: 93.165%; margin: 0 auto; padding: 52px 0; } .slider article section h1 { font-size: 30px; line-height: 40px; width: 65%; text-align: left; } .slider article section h3 { font-size: 15px; line-height: 39px; font-weight: 600; } .slider article section p { font-size: 15px; text-align: left; } .highlighter li { width: 50%; } .highlighter li.apply-btn a { margin: 16px 10px 8px 0; } .highlighter li.donate-btn a { margin: 16px 0px 8px 10px; } .highlighter li.events-btn a { margin: 8px 10px 16px 0px; } .highlighter li.volunteer-btn a { margin: 8px 0px 16px 10px; } .footer-container footer .legal { float: left; } .footer-container footer .copyright { float: right; text-align: right; } .page article { font-size: 16px; } .page article header h1 { font-size: 30px; line-height: 40px; } .page article p { margin: 0 0 30px 0; } .focus-box { padding: 20px; } .focus-box h3 { font-size: 26px; } /* ======================== INTERMEDIATE: IE Fixes ======================== */ .oldie nav a { margin: 0 0.7%; } } @media only screen and (min-width: 768px) { /* ============ WIDE: Menu ============ */ header nav { width: 93%; margin: 0 auto; } header nav h1 { margin: 16px 0 14px 0px; width: 100%; } .finder-container { display: block; background-color: #E6E7E8; } .finder { font-size: 13px; line-height: 23px; font-weight: 600; } .finder a { color: #787A7C; } .logo { width: 105px; height: 58px; } .social { position: absolute; float: right; display: block; width: 100px; top: 24px; right: 8px; font-size: 12px; } .social ul { display: inline; padding: 0; margin: 0; } .social ul li { display: inline-block; vertical-align: middle; zoom: 1; *display: inline; } .facebook, .twitter { width: 39px; height: 39px; display: block; margin-right: 1px; vertical-align: middle; background: url(../img/icons-social.png) no-repeat; } .facebook { background-position: 0 0; } .twitter { background-position: 0 -47px ; } .accordion { float: right; margin: 0; padding: 0; list-style: none; *zoom: 1; background: none; } .accordion:before, .accordion:after { content: " "; display: table; } .accordion:after { clear: both; } .accordion ul { list-style: none; } .accordion a { font-size: 13px; line-height: 23px; font-weight: 700; color:#626366; text-transform: uppercase; } .accordion li { position: relative; } .accordion &gt; li { float: left; margin-right: 42px; padding-bottom: 8px; line-height: 23px; text-indent: 0px; background-color: transparent; border-top: 0; } .accordion &gt; li:last-child { margin-right: 0px; } .accordion &gt; li &gt; .parent { margin-right: 0; background-image: none; } .accordion &gt; li &gt; a { display: block; color: #626366; } .accordion li ul { position: absolute; left: -9999px; } .accordion &gt; li.hover &gt; ul { left: 0; margin-top: 6px; } .accordion li li.hover ul { left: 100%; } .accordion li li a { display: block; padding: 4px 0; min-width: 175px; text-indent: 10px; font-weight: 400; color: #fff; background: #BBBDC0; position: relative; z-index: 100; text-transform: none; border-top: 1px solid rgba(141, 144, 146, 0.3); } .accordion li li a:hover { background-color: #BBBDC0; } .accordion li li li a { z-index: 200; } .accordion ul li:first-child a { border-top: 3px solid #7b7c80; } .accordion ul li:first-child a:after { content: ''; position: absolute; left: 24px; top: -10px; width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 8px solid #7b7c80; } .accordion li:last-child ul li:first-child a:after { left: 140px; } .accordion &gt; li:last-child.hover &gt; ul { left: -112px; } .slider { margin: 0 auto; padding: 40px 0; } .slider article section h1 { font-size: 30px; width: 70%; } .page { margin-top: 30px; margin-bottom: 30px; } .page aside { display: block; float: left; padding-right: 20px; width: 26.5%; } .sub-menu { position: relative; padding: 0px; border: solid 1px #D1D2D4; } .sub-menu ul { margin: 0; padding: 0; list-style-type: none; } .sub-menu ul li { margin: 0; padding: 20px 0 0px 20px; font-size: 13px; font-weight: 700 } .sub-menu ul li:last-child { padding: 20px 0 20px 20px; } .sub-menu ul li a { color: #808284; } .page article { display: block; float: right; width: 70.5%; } .image img { display: block; float: left; width: 226px; height: 220px; padding: 0px 20px 10px 0; } } /* ============ WIDE: Main ============ */ @media only screen and (min-width: 1140px) { /* =============== Maximal Width =============== */ .wrapper { width: 86%; } header nav { width: 86%; } header nav h1 { float: left; width: 160px; } .logo { width: 160px; height: 88px; } .social { top: 10px; right: 68px; } .accordion { float: right; padding-top: 87px; } .accordion a { font-size: 15px; } .accordion &gt; li { margin-right: 42px; } .slider { width: 86%; margin: 0 auto; padding: 62px 0; } .slider article section h1 { font-size: 35px; width: 65%; } .slider article section h3 { font-size: 18px; } .highlighter li { float: left; width: 25%; } .highlighter li.apply-btn a { margin: 16px 10px 16px 0; } .highlighter li.donate-btn a, .highlighter li.events-btn a { margin: 16px 10px 16px 10px; } .highlighter li.volunteer-btn a { margin: 16px 0 16px 10px; } .main { padding: 0 0 30px 0; } .main aside { position: relative; float: left; width: 47.75%; height: 281px; padding: 0 10px 0 0; overflow: hidden; } .main article { float: right; padding: 0 0 0 10px; width: 48.75%; height: 281px; } .page aside { padding-right: 24px; width: 23.35%; } .sub-menu ul li { font-size: 14px; } .page article { display: block; float: right; width: 74.25%; } .image img { display: block; float: left; width: 252px; height: 246px; padding: 0px 20px 10px 0; } } /* ========================================================================== Helper classes ========================================================================== */ .ir { background-color: transparent; border: 0; overflow: hidden; *text-indent: -9999px; } .ir:before { content: ""; display: block; width: 0; height: 150%; } .hidden { display: none !important; visibility: hidden; } .visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .visuallyhidden.focusable:active, .visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; } .invisible { visibility: hidden; } .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:15:02.737", "Id": "60547", "Score": "2", "body": "I'd recommend trying to split the CSS section into separate parts since it's quite a large code block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:17:18.937", "Id": "60548", "Score": "0", "body": "Thanks Jamal. I've thought about using @import but I heard a mono-lithic format is better for speed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:18:51.540", "Id": "60549", "Score": "0", "body": "I'm not familiar with this myself, but I received a flag concerning the code length. You could still wait for someone more experienced to weigh in on this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T15:49:56.607", "Id": "61659", "Score": "3", "body": "The CSS code is gigantic! Does it all really matter for the question? Focusing on a small important part may attract more answers." } ]
[ { "body": "<p>Since I don't have high enough rep to comment, I'll post this instead...</p>\n\n<p>fyi: @import vs <a href=\"https://stackoverflow.com/questions/7199364/import-vs-link\">https://stackoverflow.com/questions/7199364/import-vs-link</a>\nI'd keep the same master stylesheet if it were me.</p>\n\n<hr>\n\n<p>EDIT:\n<code>&lt;h1&gt;</code> or <code>&lt;img&gt;</code> as a logo? Debate on... short answer, It depends on the context of the website&mdash;is it a single page layout? a personal blog? the next Amazon? Here's a few articles on the subject that will shed some light: <a href=\"http://csswizardry.com/2010/10/your-logo-is-an-image-not-a-h1/\" rel=\"nofollow noreferrer\">http://csswizardry.com/2010/10/your-logo-is-an-image-not-a-h1/</a> &amp; <a href=\"https://webmasters.stackexchange.com/questions/4515/h1-vs-h2-vs-other-for-website-title-logo-and-seo\">https://webmasters.stackexchange.com/questions/4515/h1-vs-h2-vs-other-for-website-title-logo-and-seo</a> &amp; <a href=\"http://www.amberweinberg.com/the-logo-to-h1-or-not-to-h1/\" rel=\"nofollow noreferrer\">http://www.amberweinberg.com/the-logo-to-h1-or-not-to-h1/</a> make your own asumptions. I've gone both ways on different projects. </p>\n\n<hr>\n\n<p>Here's a few links to look up and read into. On a smaller application such as this I doubt it would matter much, however, when you get into larger projects specificity and maintainability will cause you issues. <a href=\"http://css-tricks.com/efficiently-rendering-css/\" rel=\"nofollow noreferrer\">http://css-tricks.com/efficiently-rendering-css/</a> &amp; <a href=\"http://csswizardry.com/2011/09/writing-efficient-css-selectors/\" rel=\"nofollow noreferrer\">http://csswizardry.com/2011/09/writing-efficient-css-selectors/</a></p>\n\n<p><a href=\"http://smacss.com/\" rel=\"nofollow noreferrer\">http://smacss.com/</a> - if you don't like it, it's at least a great starting point for thinking about maintainability and organization. OOCSS and BEM are the alternative.</p>\n\n<p>Also, there are many ways to approach a menu icon, here's some methods of approach: <a href=\"http://css-tricks.com/three-line-menu-navicon/\" rel=\"nofollow noreferrer\">http://css-tricks.com/three-line-menu-navicon/</a> I prefer font icons in place of using three elements to make the bars but that's just my opinion.</p>\n\n<p>normalize.css is great! However, <a href=\"http://nicolasgallagher.com/about-normalize-css/\" rel=\"nofollow noreferrer\">http://nicolasgallagher.com/about-normalize-css/</a> read approach 1: </p>\n\n<blockquote>\n <p>Approach 1: use normalize.css as a starting point for your own project’s base CSS, customising the values to match the design’s requirements.</p>\n</blockquote>\n\n<p>Also, if you're going to use Conditional commenting for IE at least style the <code>.browsehappy</code> class so it isn't... you know... bare bones... ;) </p>\n\n<p>I'd steer clear of using heading tags for items such as this <code>&lt;h3&gt;&lt;a href=\"#\"&gt;Learn More About What We Do &amp;raquo;&lt;/a&gt;&lt;/h3&gt;</code> this isn't a heading, but the browser will read it as such, instead create a separate class for it and style it in a heading style if you want it to be bold and larger.</p>\n\n<p>Also, bear in mind, <code>&lt;section&gt;</code>'s, <code>&lt;article&gt;</code>'s, <code>&lt;main&gt;</code>'s, <code>&lt;footer&gt;</code>'s, and <code>&lt;header&gt;</code>'s will always label a heading as null if you don't have one (e.g. untitled) in the semantic outline. I'd drop your code into this: <a href=\"http://gsnedders.html5.org/outliner/\" rel=\"nofollow noreferrer\">http://gsnedders.html5.org/outliner/</a> and see if some of those tags shouldn't be replaced with <code>&lt;div&gt;</code>'s which hold no semantic value.</p>\n\n<p>as for the html5 portion. It really depends on the support levels you require for browser compatibility. I tend to forego wrapping html5 tags e.g. <code>&lt;div class=\"header-container\"&gt;</code> as it's a bit repetitive at this point and bulky (but I also tend to only target IE9+ too, anything under I feed a single column, but I'm lazy like that).</p>\n\n<p>I use a very simple starting point for most projects. It's laid out like this: </p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;!--[if IEMobile 7 ]&gt;&lt;html class=\"no-js iem7\"&gt;&lt;![endif]--&gt;\n&lt;!--[if lt IE 9]&gt;&lt;html class=\"no-js lte-ie8\"&gt;&lt;![endif]--&gt;\n&lt;!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]&gt;&lt;!--&gt;&lt;html class=\"no-js\" lang=\"en\"&gt;&lt;!--&lt;![endif]--&gt;\n\n&lt;head&gt;\n\n&lt;meta charset=\"utf-8\"&gt;\n&lt;link rel=\"dns-prefetch\" href=\"www.google-analytics.com\"&gt; \n&lt;meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"&gt;\n\n&lt;title&gt;&lt;/title&gt;\n&lt;meta name=\"description\" content=\"\"&gt;\n&lt;meta name=\"HandheldFriendly\" content=\"True\"&gt;\n&lt;meta name=\"MobileOptimized\" content=\"320\"&gt;\n&lt;meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimal-ui\"&gt;\n&lt;meta http-equiv=\"cleartype\" content=\"on\"&gt;\n\n&lt;link rel=\"stylesheet\" href=\"/libs/css/main.css\"&gt;\n&lt;script src=\"/libs/js/vendor/modernizr-custom.min.js\"&gt;&lt;/script&gt;\n\n&lt;body&gt;\n\n&lt;header role=\"banner\"&gt;\n &lt;a href=\"#\"&gt;&lt;/a&gt;\n &lt;h1 role=\"heading\"&gt;title&lt;/h1&gt;\n&lt;/header&gt;\n\n&lt;nav role=\"navigation\"&gt;\n &lt;a role=\"link\" href=\"#\" accesskey=\"1\"&gt;Who&lt;/a&gt;\n &lt;a role=\"link\" href=\"#\" accesskey=\"2\"&gt;What&lt;/a&gt;\n &lt;a role=\"link\" href=\"#\" accesskey=\"3\"&gt;When&lt;/a&gt;\n &lt;a role=\"link\" href=\"#\" accesskey=\"4\"&gt;Why&lt;/a&gt;\n&lt;/nav&gt;\n&lt;section&gt;\n &lt;form role=\"form\" id=\"email-form\" action=\"#\" method=\"post\" novalidate&gt;\n &lt;label for=\"email\" id=\"email-label\"&gt;Email&lt;/label&gt;\n &lt;input id=\"email\" aria-labelledby=\"email-label email-form\" type=\"email\" placeholder=\"e.g. john@doe.co\" name=\"email\"&gt;\n &lt;button role=\"button\" aria-labelledby=\"email-form\" type=\"submit\"&gt;Submit&lt;/button&gt;\n &lt;/form&gt;\n&lt;/section&gt;\n\n&lt;main role=\"main\"&gt;\n &lt;h2 role=\"heading\"&gt;&lt;/h2&gt;\n &lt;article role=\"article\"&gt;\n &lt;h3 role=\"heading\"&gt;&lt;/h3&gt;\n &lt;section&gt;\n &lt;h4 role=\"heading\"&gt;&lt;/h4&gt;\n &lt;p&gt;&lt;/p&gt;\n &lt;strong&gt;&lt;/strong&gt;\n &lt;/section&gt;\n &lt;aside role=\"complimentary\"&gt;\n &lt;figure&gt;\n &lt;img role=\"img\" src=\"\" width=\"\" height=\"\" alt&gt;\n &lt;figcaption&gt;&lt;/figcaption&gt;\n &lt;/figure&gt;\n &lt;/aside&gt;\n &lt;/article&gt;\n &lt;hr role=\"separator\"&gt;\n &lt;aside role=\"note\"&gt;\n &lt;/aside&gt;\n &lt;hr role=\"separator\"&gt;\n&lt;/main&gt;\n\n&lt;footer role=\"contentinfo\"&gt;\n &lt;h2 role=\"heading\"&gt;&lt;/h2&gt;\n&lt;/footer&gt;\n\n&lt;script src=\"/libs/js/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;script&gt;\n (function (a, h, d, c, g, f) {\n a.GoogleAnalyticsObject = c;\n a[c] || (a[c] = function () {\n (a[c].q = a[c].q || []).push(arguments)\n });\n a[c].l = +new Date;\n g = h.createElement(d);\n f = h.getElementsByTagName(d)[0];\n g.src = \"//www.google-analytics.com/analytics.js\";\n f.parentNode.insertBefore(g, f)\n }(window, document, \"script\", \"ga\"));\n ga(\"create\", \"UA-XXXXX-X\");\n ga(\"send\", \"pageview\");\n&lt;/script&gt;\n</code></pre>\n\n<p>P.S. If you're not going to use modernizr or jquery, make sure you don't include the libraries as they're unnecessary at that point. Additionally, you wouldn't need the conditional comments wrapping the <code>&lt;html&gt;</code> tag either, nor the <code>class=\"no-js\"</code> class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:06:51.707", "Id": "60905", "Score": "0", "body": "The difference hit from using selectors other than class/id is *greatly* exaggerated. Yes, they're faster, but not fast enough to make a difference: http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:16:19.567", "Id": "60908", "Score": "1", "body": "Using negative indentation for hiding text is rather antiquated and has poor performance in some browsers (see: http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T18:06:43.943", "Id": "61029", "Score": "0", "body": "@cimmanon The objective of that particular recommendation was more aimed at semantics, but thank you for that article, I'll definitely look into the differences from both approaches. As for the performance, it matters less now with the improvements in devices and web, but still something worth mentioning. But the real issue with selectors is organization and maintainability on a larger scale." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-25T08:41:01.907", "Id": "63340", "Score": "2", "body": "Whether the image should be an `<img>` tag or a CSS `background-image` depends on whether it is significant or decorative. When printing a hard copy, for example, many browsers will omit CSS backgrounds (some optionally, some forcibly). A logo might be significant enough to be an `<img>`. If so, be sure to provide an `alt` attribute." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-26T17:19:29.073", "Id": "63431", "Score": "0", "body": "Great point, I ran into that issue in the past and in that instance applied a work around using `@media print{ .logo:before { content: url(images/logo.png); } }` to make it work in the past, although I'm unsure whether or not it is actually good practice as you can't apply an `alt` attribute so it lacks any meaning. I've never looked into it enough tbh. Great comment!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T23:20:41.507", "Id": "36825", "ParentId": "36812", "Score": "10" } }, { "body": "<p><strong>HTML:</strong></p>\n\n<ol>\n<li><p>You should adjust your Conditional Comments based on the browsers you need to support. For example having support for IE7 is rare these days. Some projects don't even need IE8 support.</p>\n\n<p>As an example if you need support for IE8, you can use this:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;!--[if lt IE 9]&gt;&lt;html class=\"no-js lt-ie9\"&gt;&lt;![endif]--&gt;\n&lt;!--[if gt IE 8]&gt;&lt;!--&gt;&lt;html class=\"no-js\" lang=\"en\"&gt;&lt;!--&lt;![endif]--&gt;\n</code></pre></li>\n<li><p>Your viewport meta tag should look like this:</p>\n\n<pre><code>&lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n</code></pre></li>\n<li><p>You copied and pasted the Google Webfonts snippet. Just a little facelift, to match your coding style:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,600,700\"&gt;\n</code></pre>\n\n<p>I dropped the <code>type</code> attribute and used <code>\"</code> instead of <code>'</code></p></li>\n<li><p>Using headings for logos is wrong. A logo is branding, not a textual element. Headings should be used for site or page titles. Other than this, using a <code>h1</code> there doesn't boost your <em>SEO</em>.</p>\n\n<pre><code>&lt;a href=\"/\"&gt;&lt;img src=\"img/logo.png\" class=\"logo\" alt=\"logo\"&gt;&lt;/a&gt;\n</code></pre></li>\n<li><p>Your logo sits inside your navigation, but it's not a part of it. Move it outside the <code>nav</code> into your <code>header</code>:</p>\n\n<pre><code>&lt;a href=\"/\"&gt;&lt;img src=\"img/logo.png\" class=\"logo\" alt=\"logo\"&gt;&lt;/a&gt;\n&lt;nav&gt;\n &lt;!--your navigation--&gt;\n&lt;/nav&gt;\n</code></pre></li>\n<li><p><a href=\"http://css-tricks.com/use-target_blank/\">When to use <code>target=\"_blank\"</code></a></p>\n\n<blockquote>\n <p>A Bad Reason: \"Internal\" links and \"External\" links are different.</p>\n</blockquote></li>\n<li><p>Using a <code>section</code> inside an article which only has one <em>section</em> is unnecessary. The <code>article</code> itself creates a new document outline. Since there is a <code>section</code> inside, you have an <em>untitled</em> article and a section with a <em>Lorem ipsum</em> heading.</p></li>\n<li><p>You may want to use the <code>main</code> element to wrap your main content area. Remember to set <code>main { display: block; }</code> for it as well, because not all browswers have a User Agent Style for this already.</p></li>\n</ol>\n\n<p><strong>CSS:</strong></p>\n\n<ol>\n<li><p>Use classes (e.g. <code>site-title</code>) instead of selecting things like <code>header nav h1</code> (or in your case it's rather <code>site-logo</code> without a <code>h1</code>). Maybe you'll end up with another <code>header</code> element containing a navigation? What do you do then? Remember that the <code>header</code> element isn't limited for the use as a site wide header. You may have one in every article or even in your site footer.</p></li>\n<li><p>Use shorthand in cases like <code>border-radius: 50px 50px 50px 50px;</code> to reduce unnecessary repetition: <code>border-radius: 50px;</code></p></li>\n<li><p>If you drop IE7 support, you can use this clearfix:</p>\n\n<pre><code>.clearfix:after {\n content: \"\";\n display: table;\n clear: both;\n}\n</code></pre></li>\n<li><p>If you set <code>list-style: none;</code> on an unordered list, you don't need to repeat it on its list-items.</p></li>\n<li><p>Don't omit closing semi-colons on the last property declarations inside of rule declarations. That will run yourself into troubles for sure. The <em>performance gains</em> of saving the few bytes will almost be non-existent.</p></li>\n</ol>\n\n<p>I stop here for now, because your CSS you included is huge and there is probably a big room for further improvements. As a general advice: Think about these rules and reconsider if you really need such a deep structure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-16T09:11:24.687", "Id": "41785", "ParentId": "36812", "Score": "10" } } ]
{ "AcceptedAnswerId": "41785", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:12:40.273", "Id": "36812", "Score": "7", "Tags": [ "html", "css" ], "Title": "Web page code based off of a responsive Initializer template" }
36812
<p>I haven't had much experience with postgresql (none) and I am wondering/hoping that there is a better way for me to do this query.</p> <pre><code>SELECT * FROM member_copy WHERE id = 17579 OR id = 17580 OR id = 17582 ect. </code></pre> <p>There are about 800 where clauses in total so this will take a while and I need to run it on a fairly regular basis.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T22:56:12.023", "Id": "60577", "Score": "0", "body": "If there are really 800 where clauses I think you should work on your application" } ]
[ { "body": "<p>The way to write that query is:</p>\n\n<pre><code>SELECT * FROM member_copy WHERE id IN (17579, 17580, 17582);\n</code></pre>\n\n<p>However, the real question is, where did that list of <code>id</code>s come from? If the list of <code>id</code>s is the result of another database query, then you should be doing either a subselect or a join instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:57:23.587", "Id": "60558", "Score": "0", "body": "Worked perfectly. It was not from a database query, somebody actually went through and picked out every number. I do not envy them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:46:57.490", "Id": "36816", "ParentId": "36814", "Score": "18" } }, { "body": "<p>A test with <code>EXPLAIN ANALYZE VERBOSE</code> will show you that the form with <code>id IN (...)</code> in the <a href=\"https://codereview.stackexchange.com/a/36816/9501\">answer of @200_success</a> is transformed internally into:</p>\n\n<pre><code>SELECT * FROM member_copy WHERE id = ANY ('{17579, 17580, 17582}');\n</code></pre>\n\n<p>.. which therefore performs slightly faster to begin with (no conversion needed).</p>\n\n<p>Also, the form in your question will effectively perform very similar. </p>\n\n<p>With big lists, <a href=\"http://www.postgresql.org/docs/current/interactive/functions-array.html#ARRAY-FUNCTIONS-TABLE\" rel=\"nofollow noreferrer\">unnesting an array</a>, followed by a <code>JOIN</code> will generally be faster:</p>\n\n<pre><code>SELECT m.*\nFROM unnest('{17579, 17580, 17582}'::int[]) id\nJOIN member_copy m USING (id);\n</code></pre>\n\n<p>Since the list is <code>is the result of another database query</code>, it will be fastest to combine both in <em>one</em> query with a <code>JOIN</code>.</p>\n\n<p>More detailed explanation:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/31192557/939860\">How to use ANY instead of IN in a WHERE clause with Rails?</a></li>\n<li><a href=\"https://dba.stackexchange.com/q/91247/3684\">Optimizing a Postgres query with a large IN</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T17:14:50.570", "Id": "41236", "ParentId": "36814", "Score": "8" } }, { "body": "<p>For a single id the following query worked for me:</p>\n\n<pre><code>SELECT * FROM member_copy WHERE id IN ('17579');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:34:54.180", "Id": "430113", "Score": "1", "body": "Could you explain how this answers the OP?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:30:13.010", "Id": "222271", "ParentId": "36814", "Score": "0" } } ]
{ "AcceptedAnswerId": "36816", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:29:57.027", "Id": "36814", "Score": "8", "Tags": [ "sql", "postgresql" ], "Title": "SQL query where id=… or id=… or id=… etc" }
36814
<p>I tried implementing <a href="/q/36722">Integer Partition</a> (enumerating all possible sets of whole numbers whose sum is a given integer).</p> <p>Looking at <a href="/a/36725/9357">@rolfl's answer</a>, I reasoned that with a stack data structure, we shouldn't need to use recursion, since recursion implicitly stores state in the call stack. I also tried to address <a href="/a/36724/9357">@JeffVanzella's criticism</a> about separation of concerns by converting the class into an iterator.</p> <p>My solution ended up being a bit more monstrous than I had anticipated. It looks nothing like the elegant original, and runs more slowly too. Therefore, I suspect that a better iterative solution is possible.</p> <pre><code>import java.util.Iterator; public class Partition implements Iterator&lt;String&gt; { /** * Fixed-capacity stack of ints. As used in Partition.next(), the * invariant is that elements towards the top of the stack are never * larger than elements underneath. (In other words, the array * elements are nonincreasing. */ private static class IntStack { private int[] data; private int size; IntStack(int capacity) { this.data = new int[capacity]; this.size = 0; } public void push(int datum) { this.data[this.size++] = datum; } public int pop() { return this.data[--this.size]; } public boolean isEmpty() { return this.size == 0; } /** * Returns the elements as a space-delimited string. */ public String toString() { // toString() of an empty stack is never used in practice... if (this.isEmpty()) return ""; StringBuilder sb = new StringBuilder(String.valueOf(this.data[0])); for (int i = 1; i &lt; this.size; i++) { sb.append(' ').append(String.valueOf(this.data[i])); } return sb.toString(); } } ////////////////////////////////////////////////////////////////////// private IntStack stack; public Partition(int n) { if (n &lt;= 0) throw new IllegalArgumentException(); stack = new IntStack(n); stack.push(n); } @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public String next() { String retval = stack.toString(); int top; int ones = 0; // Count the ones at the top of the stack. Stop at "top", which is the // next element other than a 1. while (1 == (top = stack.pop())) { if (stack.isEmpty()) { // n has been completely partitioned into n ones. All done! return retval; } ones++; } // Transfer 1 from top to ones, then write out the remainder in as few // numbers as possible, observing the stack invariant that entries // must be nonincreasing. stack.push(--top); for (ones++; ones &gt; 0; ones -= top) { stack.push(top &lt; ones ? top : ones); } return retval; } @Override public void remove() { throw new UnsupportedOperationException(); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); Partition p = new Partition(n); while (p.hasNext()) { System.out.println(p.next()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T22:05:44.247", "Id": "60570", "Score": "1", "body": "Interesting to set it as an Iterator..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T22:13:33.023", "Id": "60572", "Score": "0", "body": "@rolfl Unfortunately Java doesn't have a [`yield`](https://code.google.com/p/java-yield/) keyword." } ]
[ { "body": "<p>I am not sure how to 'review' your code in this case.... I have a sense of 'competition' here, and the moment performance enters the equation, there are things I just know are going to be slower, but I cannot always explain why.....</p>\n\n<p>I think often times it simply comes down to primitives vs. Object creation.... whenever that happens things slow down.</p>\n\n<p>I have put together a 'competing' solution, and it uses tricks I have learned over the years... tricks I feel, for the most part, lead to 'fast' code. I have been accused of 'premature optimization' when I do these things, but, it tends to work for me.... ;-)</p>\n\n<p>printing Strings is never going to be a good measure of performance, so I have taken three solutions: the recursive solution I suggested in the earlier post. Your solution using the iterator, and then a 'competing' iterator performance.</p>\n\n<p>So, in my benchmarks, this iterative process is about 5 times faster than yours.... (excluding the System.out.println()):</p>\n\n<p>here are my results (times in milliseconds on my machine):</p>\n\n<pre><code>200_Success=2045.091 rolflIter=446.846=rolflRecur 2046.462011\n200_Success=1737.469 rolflIter=573.900=rolflRecur 1521.951070\n200_Success=1814.468 rolflIter=385.520=rolflRecur 1499.896568\n200_Success=1714.592 rolflIter=333.105=rolflRecur 1372.042103\n200_Success=1799.969 rolflIter=383.033=rolflRecur 1520.779467\n200_Success=1676.415 rolflIter=336.651=rolflRecur 1474.669545\n200_Success=1978.581 rolflIter=407.804=rolflRecur 1417.124248\n200_Success=1665.783 rolflIter=343.939=rolflRecur 1375.178203\n200_Success=1654.083 rolflIter=331.607=rolflRecur 1369.912767\n200_Success=1654.958 rolflIter=339.234=rolflRecur 1369.170302\n</code></pre>\n\n<p><strong>Edit:</strong>\nNew results ... note, 200_success is also running faster here.... \nHate performance variances ... probably a Windows/Intel CPU frequency thing.</p>\n\n<pre><code>200_Success=1463.484 rolflIter=624.754 rolflRecur=1777.548864\n200_Success=1304.401 rolflIter=302.086 rolflRecur=1492.951479\n200_Success=1577.132 rolflIter=367.537 rolflRecur=1485.176134\n200_Success=1230.959 rolflIter=266.068 rolflRecur=1389.742206\n200_Success=1230.445 rolflIter=269.587 rolflRecur=1382.473980\n200_Success=1220.637 rolflIter=269.352 rolflRecur=1376.292369\n200_Success=1204.206 rolflIter=266.920 rolflRecur=1369.920239\n200_Success=1201.280 rolflIter=264.481 rolflRecur=1365.711999\n200_Success=1204.419 rolflIter=262.047 rolflRecur=1368.854637\n200_Success=1251.656 rolflIter=264.030 rolflRecur=1416.935596\n</code></pre>\n\n<p>Main class:</p>\n\n<pre><code>package comp;\n\nimport java.util.Iterator;\n\npublic class RunParts {\n\n private static int charsIn(Iterator&lt;String&gt; iter) {\n int chars = 0;\n while (iter.hasNext()) {\n chars += iter.next().length();\n }\n return chars;\n }\n\n public static void main(String[] args) {\n final int target = Integer.parseInt(args[0]);\n long[] nanos = new long[3];\n int[] charlen = new int[3];\n for (int i = 0; i &lt; 10; i++) {\n System.gc();\n nanos[0] = System.nanoTime();\n charlen[0] = charsIn(new Partition(target));\n nanos[0] = System.nanoTime() - nanos[0];\n\n System.gc();\n nanos[1] = System.nanoTime();\n charlen[1] = charsIn(new PartitionRLIter(target));\n nanos[1] = System.nanoTime() - nanos[1];\n\n System.gc();\n nanos[2] = System.nanoTime();\n charlen[2] = PartitionRLRecur.partitionRL(target);\n nanos[2] = System.nanoTime() - nanos[2];\n\n System.out.printf(\"200_Success=%.3f rolflIter=%.3f rolflRecur=%3f\\n\",\n nanos[0] / 1000000.0, nanos[1] / 1000000.0, nanos[2] / 1000000.0);\n }\n\n }\n\n}\n</code></pre>\n\n<p>Your solution is above (I have left it called 'Partition').</p>\n\n<p>Then my iterative solution is...</p>\n\n<p><strong>EDIT:</strong>\nI have edited my solution to add comments. As I was adding the comments I realized that a lot of the logic in the advance() method was related to setup of the system.\nI have moved the setup to the constructor, and by verifying a couple of things, I am now able to guarantee a couple of behavioral advantages that mean I don't need a few of the loops in the system. I have updated my results now as well.</p>\n\n<pre><code>package comp;\n\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class PartitionRLIter implements Iterator&lt;String&gt; {\n\n private final int[] stack;\n private final int[] outpos;\n private final StringBuilder outstring;\n private final int limit;\n private boolean hasnext = true;\n private int spos = 0;\n\n public PartitionRLIter(int n) {\n if (n &lt;= 0) throw new IllegalArgumentException();\n limit = n;\n stack = new int[limit];\n outpos = new int[limit];\n // NOTE THAT THE CONSTRUCTOR NOW MANUALLY INITIALIZES THE SYSTEM\n outstring = new StringBuilder(limit * 2); // worst case is \"1 1 1 1 1 ...\";\n Arrays.fill(stack, 1);\n for (int i = 0; i &lt; limit; i++) {\n outpos[i] = outstring.length();\n outstring.append(\"1 \");\n }\n hasnext = true;\n spos = limit - 1;\n }\n\n @Override\n public boolean hasNext() {\n return hasnext;\n }\n\n @Override\n public String next() {\n if (!hasnext)\n throw new NoSuchElementException();\n\n try {\n return outstring.substring(0, outstring.length() - 1);\n } finally {\n hasnext = advance();\n }\n }\n\n private final boolean advance() {\n // advance() keeps four 'stack-like' variables in sync\n // advance() will only ever be called when the current system has a valid answer\n //\n // **stack** contains the digits that get summed... It is the 'real stack'. The constructor initializes it to all 1's.\n //\n // **spos** is our depth in the stack.\n //\n // the **outstring** is a StringBuilder that is kept in sync with the actual stack...\n // reusing the StringBuilder makes it much faster... but we need to manage it like a stack.\n // when you go deeper in the stack, the outstring has values added to it,\n // when you come back up, the outstring is truncated to remove unneeded characters.\n // very much like push and pop operations (except at the end of the string, not the front)\n //\n // the **outpos** is the array of integer positions in the outstring StringBuffer that\n // keeps track of where the outstring should be truncated at each level.\n // this is what allows working push/pop on the outstring.\n //\n\n // back up..... the stack, we always know we are already at the limit.\n // pop the value off (keep sum in sync).\n int sum = limit - stack[spos];\n if (--spos &lt; 0) {\n // we ran out of things to do, there's no more possibilities.\n return false;\n }\n\n // on the previous level, we increment....\n // we can never overflow the previous level because\n // of the way the math works (we would not have a next level if we can't increment this one).\n stack[spos] ++;\n sum++;\n\n // pop the previous value(s) off the stack representation.\n // outpos[spos] contains the character position in the output representing\n // our current depth.\n outstring.setLength(outpos[spos]);\n\n // check to see whether adding a new level of depth will work.....\n // the new level will have the same value as the stack's current value...\n while (sum + stack[spos] &lt;= limit) {\n // yes, the new level will work.\n // update our string stack, sum, and record the character position of the outstring.\n outstring.append(stack[spos]).append(\" \");\n sum+= stack[spos];\n stack[spos + 1] = stack[spos];\n spos++;\n outpos[spos]=outstring.length();\n }\n\n // take the new depth and increment it (if needed) to the limit.\n stack[spos] += limit - sum;\n outstring.append(stack[spos]).append(\" \");\n return true;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n}\n</code></pre>\n\n<p>Finally, my Recursive solution is (note, it has been modified to return the string length, not the string itself):</p>\n\n<pre><code>package comp;\n\n\npublic class PartitionRLRecur {\n\n public static int partitionRL(final int n)\n {\n return recursivePartition(n, 1, new int[n], 0);\n }\n\n private static int recursivePartition(final int target, final int from, final int[] stack, final int stacksize)\n {\n if(target == 0) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; stacksize; i++) {\n sb.append(stack[i]).append(\" \");\n }\n// System.out.println(sb.toString());\n// );\n return sb.toString().length();\n }\n int sz = 0;\n for(int i = from; i &lt;= target; i++) {\n stack[stacksize] = i;\n sz += recursivePartition(target-i, i, stack, stacksize + 1);\n }\n return sz;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T00:08:35.140", "Id": "60583", "Score": "0", "body": "It works, and it is definitely fast, but it's going to take me a while to understand `advance()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T00:12:06.153", "Id": "60586", "Score": "0", "body": "@200_success I will go through and comment it... I was hoping to squeak in by 00:00, but missed it ... give me 5 minutes and I'll edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T01:08:57.553", "Id": "60593", "Score": "0", "body": "Edited and change the constructor and advance method a little bit.... and then realized I can squeeze a tiny bit more ..... no need to add a space to the outputstring... and that was a long 5 minutes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T15:43:09.923", "Id": "60637", "Score": "0", "body": "Witty comment: If it was hard to write, it **should** be hard to read!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T23:49:44.123", "Id": "36827", "ParentId": "36815", "Score": "6" } }, { "body": "<p>Thanks to @rolfl for showing the way. Besides the performance gains, he also improved <code>next()</code> by throwing <code>NoSuchElementException</code> and by moving most of the code into <code>advance()</code>. </p>\n\n<p>I've concluded that his solution is faster due to three factors:</p>\n\n<ol>\n<li>Caching the <code>StringBuilder</code>.</li>\n<li>Enumerating the values in ascending rather than descending order. It turns out that putting the smaller numbers at the end results in greater churn of the stack. When the size of the stack keeps changing, the cached <code>StringBuilder</code> is less effective.</li>\n<li>Raw array access instead of using <code>IntStack</code>.</li>\n</ol>\n\n<p>Of those three factors, (3) has only a minor effect. However, if you delegate all the tedious bookkeeping to <code>IntStack</code>, the algorithm in <code>advance()</code> becomes quite understandable. Here is an implementation that reintroduces a smarter <code>IntStack</code> to <code>PartitionRLIter</code>.</p>\n\n<pre><code>import java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class PartitionRLIter2 implements Iterator&lt;String&gt; {\n\n private static class IntStack {\n private int[] data;\n private int size;\n\n private static final String DELIM = \" \";\n\n // sum, str, and strlen store redundant state for performance.\n\n // Sum of all data\n private int sum;\n\n // Each element of data followed by DELIM\n private StringBuilder str;\n\n // For each i, the length of the relevant portion of str when size = i\n private int[] strlen;\n\n IntStack(int capacity) {\n this.data = new int[capacity];\n\n // Likely worst case is \"1 1 ... 1 \"\n this.str = new StringBuilder(capacity * (1 + DELIM.length()));\n this.strlen = new int[capacity];\n }\n\n public void fill(int datum) {\n for (this.size = 0; this.size &lt; this.data.length; this.size++) {\n this.data[this.size] = datum;\n this.strlen[this.size] = this.str.length();\n this.str.append(String.valueOf(datum)).append(DELIM);\n }\n this.sum = datum * this.size;\n }\n\n public void push(int datum) {\n this.strlen[this.size] = this.str.length();\n this.data[this.size++] = datum;\n this.sum += datum;\n this.str.append(String.valueOf(datum)).append(DELIM);\n }\n\n public int pop() {\n int datum = this.data[--this.size];\n this.sum -= datum;\n this.str.setLength(this.strlen[this.size]);\n return datum;\n }\n\n /**\n * Shortcut for push(i + pop()), peek()\n */\n public int incr(int i) {\n if (i != 0) {\n int datum = this.data[this.size - 1] += i;\n this.sum += i;\n this.str.setLength(this.strlen[this.size - 1]);\n this.str.append(String.valueOf(datum)).append(DELIM);\n }\n return this.data[this.size - 1];\n }\n\n public boolean isEmpty() {\n return this.size == 0;\n }\n\n public int sum() {\n return this.sum;\n }\n\n public String toString() {\n return this.str.substring(0, this.str.length() - DELIM.length());\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n private final IntStack stack;\n private final int limit;\n\n public PartitionRLIter2(int n) {\n if (n &lt;= 0) throw new IllegalArgumentException();\n this.limit = n;\n this.stack = new IntStack(limit);\n this.stack.fill(1);\n }\n\n @Override\n public boolean hasNext() {\n return !this.stack.isEmpty();\n }\n\n @Override\n public String next() {\n if (this.stack.isEmpty()) {\n throw new NoSuchElementException();\n }\n try {\n return this.stack.toString();\n } finally {\n advance();\n }\n }\n\n private final void advance() {\n if (this.stack.pop() == this.limit) {\n // All the numbers have been gathered into the original\n // number. That's all, folks!\n return;\n }\n\n // Increment the previous level. We can never overflow because the\n // previous pop decremented the sum by at least one.\n int top = this.stack.incr(1);\n\n // Duplicate the top of the stack as many times as possible.\n while (this.stack.sum() + top &lt;= this.limit) {\n this.stack.push(top);\n }\n\n // Increment the top to the limit (if needed).\n this.stack.incr(this.limit - this.stack.sum());\n\n // Note stack invariant: values are always nondecreasing going from the\n // base to the top.\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T12:10:01.470", "Id": "60620", "Score": "0", "body": "If you upvote this answer, please upvote @rolfl's answer as well, as he deserves most of the credit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T12:31:30.437", "Id": "60622", "Score": "0", "body": "Excellent. Although I started by trying to read/understand the stack code, it actually makes it a lot easier to start with advance() and then see how the stack 'does it'. ... P.S. Upvote your's not upvoting mine ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T12:08:00.603", "Id": "36846", "ParentId": "36815", "Score": "4" } } ]
{ "AcceptedAnswerId": "36827", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:40:12.560", "Id": "36815", "Score": "6", "Tags": [ "java", "combinatorics", "iteration" ], "Title": "Integer Partition using an iterator" }
36815
<p>I would like to execute a certain method at a given interval. The reason why I can't use a timer + its event handler right away is because I want to add an offset to each tick (100ms in my example below).</p> <p>It seems to be working just as intented. The reason why I'm starting it manually is because if the <code>_action();</code> takes more than the given tick time, I want to let it finish before starting a new "tick".</p> <p>Perhaps this could be done in a much simpler way. I would like your thoughts on the code:</p> <pre><code>class RandomIntervalTask : IDisposable { private readonly Timer _timer; private readonly int _initialInterval; private readonly int _range; private readonly Action _action; public RandomIntervalTask(int initialInterval, int range, Action action) { this._range = range; this._initialInterval = initialInterval; this._action = action; _timer = new Timer { AutoReset = false, Interval = initialInterval }; _timer.Elapsed += TimerElapsed; _timer.Start(); } private void TimerElapsed(object sender, ElapsedEventArgs e) { var rnd = new Random(); _timer.Interval = rnd.Next(_initialInterval, _initialInterval + _range); _action(); _timer.Start(); } public void Dispose() { _timer.Stop(); _timer.Dispose(); } } </code></pre> <p>Executed like this:</p> <pre><code>var rit = new RandomIntervalTask(400, 100, DoStuff); private void DoStuff() { Debug.WriteLine("stuff"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T02:01:02.157", "Id": "60599", "Score": "0", "body": "My `IDisposable` (really my C#) is a little weaker than I like, but isn't that Dispose implementation open to a problem with a second call calling `_timer.Stop()` after `_timer.Dispose()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T18:49:53.507", "Id": "60654", "Score": "0", "body": "@MichaelUrman I actually changed it to `_timer.Dispose(); _timer = null;` yesterday, and checked if the timer is not null before starting it in the event handler. Otherwise the last tick could run on a disposed timer. This should also take care of your issue. Thanks for the feedback." } ]
[ { "body": "<p>Do <strong>not</strong> put the random number generator creation in the <code>TimerElapsed</code> method. This could wind up generating the same value if called in succession rapidly. Instead put it at the class level:</p>\n\n<pre><code>private readonly Random _rnd = new Random();\n</code></pre>\n\n<p>and change appropriately in the method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T23:51:08.613", "Id": "60582", "Score": "1", "body": "I would add a [Seed](http://stackoverflow.com/questions/1785744/how-do-i-seed-a-random-class-to-avoid-getting-duplicate-random-values) value to it too" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T00:43:37.340", "Id": "60591", "Score": "0", "body": "@JeffVanzella You mean a constant seed? That would mean the sequence of “random” numbers would be always the same. Or do you mean something more complicated?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T07:25:06.413", "Id": "60697", "Score": "0", "body": "Not a constant seed. There are a few examples in the link based off guids, datetime, and some others." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T23:21:02.883", "Id": "36826", "ParentId": "36824", "Score": "4" } } ]
{ "AcceptedAnswerId": "36826", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T23:01:10.363", "Id": "36824", "Score": "2", "Tags": [ "c#", "winforms", "timer" ], "Title": "Executing method on a certain interval + offset" }
36824
<p>I have not tried decorators yet or functions within functions, but this current un-pythonic method seems a little convoluted. I don't like how I need to repeat myself when I check the <code>return_type</code> 3 times.</p> <p>Any suggestions are welcome, especially if the repetion can be dealt with in an elegant way. Please note that I am not that interested in the numerous reference to test if an object is a number as I believe this part is incorporated within my solution. I am interested in addressing the 3x duplication to deal with the return type. Moreover, while I appreciate the locale method is the more rigorous way of dealing with internationalisation, I prefer the simplicity of allowing the caller more flexibility in choosing the characters. </p> <p>Also, some people on Stack Overflow just posted trivial solutions to the smaller boolean <code>is_number</code> function that has been asked many times.</p> <pre><code>def is_number(obj, thousand_sep=',', decimal_sep=None, return_type='b'): """ determines if obj is numeric. if return_type = b, returns a boolean True/False otherwise, it returns the numeric value Examples -------- &gt;&gt;&gt; is_number(3) True &gt;&gt;&gt; is_number('-4.1728') True &gt;&gt;&gt; is_number('-4.1728', return_type='n') -4.1728 &gt;&gt;&gt; is_number(-5.43) True &gt;&gt;&gt; is_number("20,000.43") True &gt;&gt;&gt; is_number("20.000,43", decimal_sep=",", thousand_sep=",") True &gt;&gt;&gt; is_number("20.000,43", decimal_sep=",", thousand_sep=".", return_type="n") 20000.43 &gt;&gt;&gt; is_number('Four') False &gt;&gt;&gt; is_number('Four', return_type='n') """ try: if is_string(obj): if decimal_sep is None: value = float(obj.replace(thousand_sep, "")) else: value = float(obj.replace(thousand_sep, "").replace(decimal_sep, ".")) if return_type.lower() == 'b': return True else: return value else: value = float(obj) if return_type.lower() == 'b': return True else: return value except ValueError: return False if return_type.lower() == 'b': return False else: return None </code></pre>
[]
[ { "body": "<p>I am disregarding some questionable code (such as the fact that <code>'3,,,4'</code> would be handled identically to <code>'34'</code>, and so forth), and as you mention, the fact that <a href=\"http://docs.python.org/dev/library/locale.html\" rel=\"nofollow\">locale</a>'s <code>atof</code> is probably more fitting than write-your-own. I am doing so because, worse than those, I really don't like the <code>return_type</code> parameter and its usage.</p>\n\n<p>I would strongly suggest separating this into two functions. For example a <code>to_number</code> which acts like <code>return_type='n'</code>, or even throws an exception instead of returning <code>None</code>, and an <code>is_number</code> which calls <code>to_number</code> and converts the exception or <code>None</code> to <code>False</code>, and other values to <code>True</code>. Each function would have very simple usage thanks to very simple definitions, and their code would become simpler accordingly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:23:16.217", "Id": "60656", "Score": "0", "body": "and is_number would just be `def is_number(...): return to_number(...) is not None`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T01:54:36.367", "Id": "36833", "ParentId": "36828", "Score": "3" } }, { "body": "<p><strong>Default arguments and returning</strong></p>\n\n<p>I have a few issues with your default arguments. Firstly, you're expecting the function to work with commas and periods so use those as the defaults! Also, the default behaviour is to return a bool so don't use a special letter to indicate this, use a boolean to explicitly choose non-default behaviour. Your definition should be something like:</p>\n\n<pre><code>def is_number(obj, thousand_sep=',', decimal_sep='.', return_the_value=False):\n</code></pre>\n\n<p>You should use <code>return_the_value</code> to choose what to return on the return line itself. Assuming that <code>value</code> is either valid or <code>None</code>, your <code>return</code> statements could look like this:</p>\n\n<pre><code>return value if return_the_value else not value is None\n</code></pre>\n\n<p>This removes the need for your many <code>if else return</code> structures.</p>\n\n<p><strong>Dealing with non-strings</strong></p>\n\n<p>Your function can handle two cases: either the obj is string-like and might have separators or it can cast into a float immediately. Otherwise it's invalid. You only need to do any real work in the string case. The python idiom for determining string-ness is <code>isinstance(obj, basestring)</code>, use this instead of your own <code>is_string</code> function.</p>\n\n<pre><code>def is_number(...):\n if not isinstance(obj, basestring):\n try:\n value = float(obj)\n except ValueError:\n value = None\n return value if return_the_value else not value is None\n else:\n # Deal with the string\n</code></pre>\n\n<p><strong>Dealing with strings</strong></p>\n\n<p>Assume the string is a valid number. What is the minimum manipulation you can do to it to turn it into a valid input for <code>float</code>? If you come up with a scheme that works for any valid number, then if float still fails - you can be happy that the number wasn't valid to start with!</p>\n\n<p>You're sort of thinking along these lines already but you're removing the thousands separator blindly, leaving your function vulnerable to inputs like <code>',,,,,,,,,,,,0,,,,,,,,,,,,,,'</code>.</p>\n\n<p>Valid numbers use decimal and thousands separators in very specific ways and you need to test for this behaviour. Here's some rules:</p>\n\n<ul>\n<li>There can only be zero or one decimal character</li>\n<li>Thousands separators can only be in the integer part of a decimal number</li>\n<li>From the decimal, working left, the thousands separator appears after every block of 3 digits</li>\n</ul>\n\n<p>The decimal is easiest to deal with. A valid number string can be split into an integer part and a decimal part. The decimal part should be pure numbers - no separators. The string <code>split</code> method can be used to split the number into these two parts, just be sure to handle the empty string <code>decimal_sep</code></p>\n\n<pre><code>parts = obj.split(decimal_sep) if decimal_sep else [obj]\n</code></pre>\n\n<p>A valid number will require no further manipulation of the decimal part so we just need to focus on the integer, and its thousands separators. All you need to check is that, if separators are being used, they are in all the right places. </p>\n\n<pre><code>integer_part = parts[0]\nif thousand_sep and thousand_sep in integer_part:\n # The number is using thousand separators\n chunks = integer_part.split(thousand_sep)\n if len(chunks[0].lstrip('-')) &gt; 3 or any(len(chunk) != 3 for chunk in chunks[1:]):\n return None if return_a_value else False\n parts[0] = ''.join(chunks) # Rejoin the number without separators\n</code></pre>\n\n<p>Finally, rejoin the integer and decimal parts with a period separator and try to <code>float</code> them:</p>\n\n<pre><code>try:\n value = float('.'.join([integer_part] + parts[1:])\nexcept ValueError:\n # not a number!\n</code></pre>\n\n<p><strong>Final result</strong></p>\n\n<pre><code>def is_number(obj, thousand_sep=',', decimal_sep='.', return_the_value=False):\n if isinstance(obj, basestring):\n parts = obj.split(decimal_sep) if decimal_sep else [obj]\n integer_part = parts[0]\n if thousand_sep and thousand_sep in integer_part:\n chunks = integer_part.split(thousand_sep)\n if len(chunks[0].lstrip('-')) &gt; 3 or any(len(c) != 3 for c in chunks[1:]):\n return None if return_the_value else False\n parts[0] = ''.join(chunks)\n obj = '.'.join(parts)\n try:\n value = float(obj)\n except ValueError:\n value = None\n return value if return_the_value else value is not None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:46:29.867", "Id": "60672", "Score": "0", "body": "Just as the original was too free with where the `thousand_sep` could occur, your code may be too strict. Notably, China appears to use groups of 4, and India uses one group of 3 but then groups of 2, so the chunk length tests would reject their conventions. [Summarized here.](http://www.statisticalconsultants.co.nz/weeklyfeatures/WF31.html) It's unclear how flexible the original intent really was." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T22:00:05.917", "Id": "60674", "Score": "0", "body": "That's a good point but it's not a `thousand_sep` if it doesn't break into threes. To read the Chinese style you'd need a `tenthou_sep` for instance. It wouldn't be hard to allow for Chinese and Indian styles through another argument. I feel that inputs like `123,4,32.1` shouldn't count though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T15:37:57.873", "Id": "36859", "ParentId": "36828", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T00:53:55.840", "Id": "36828", "Score": "1", "Tags": [ "python" ], "Title": "What is the best way to deal with multiple return types in Python's is_number?" }
36828
<p>I'm trying to port the following C loop to Python:</p> <pre><code>for (int32_t i = 32; --i &gt;= 0;) { v0 += ((v1 &lt;&lt; 4 ^ v1 &gt;&gt; 5) + v1) ^ (sum + k[sum &amp; 3]); sum -= delta; v1 += ((v0 &lt;&lt; 4 ^ v0 &gt;&gt; 5) + v0) ^ (sum + k[sum &gt;&gt; 11 &amp; 3]); } </code></pre> <p>The problem is that the these integers are 32-bit unsigned and the code above relies on integer wrapping. My first attempt was to introduce the <code>U32</code> class (see <a href="https://stackoverflow.com/q/19611001/1091116">here</a>), but after porting this code to Python 3, the solution got so ugly (see <a href="https://stackoverflow.com/questions/20430637/python-3-getattr-behaving-differently-than-in-python-2">here</a>) that I started to looking for other ones. My best idea at the moment is to wrap every expression with <code>% 2 ** 32</code>, so that it wraps around. Here's how this looks:</p> <pre><code>for _ in range(32): v0 = ( v0 + ( ( (v1 &lt;&lt; 4) % 2**32 ^ (v1 &gt;&gt; 5) % 2**32 ) % 2**32 + v1 ^ (sum_ + k[sum_ &amp; 3]) % 2**32 ) % 2**32 ) % 2**32 sum_ = (sum_ - delta) % 2 ** 32 v1 = ( v1 + ( ( ( (v0 &lt;&lt; 4) % 2**32 ^ (v0 &gt;&gt; 5) % 2**32 ) % 2**32 + v0 ) % 2**32 ^ (sum_ + k[(sum_ &gt;&gt; 11) % 2**32 &amp; 3]) % 2**32 ) % 2**32 ) % 2**32 </code></pre> <p>It looks strange and I'm not sure it's the best idea. What do you think of it? Is it something that needs improving? If so, how?</p>
[]
[ { "body": "<p>Firstly, the expensive modulo operation <code>% 2**32</code> can be replaced by a cheap bitwise and: <code>&amp; 2**32-1</code>. Make sure to familiarize yourself with operator precedence, because it's not intuitive when it comes to bitwise operators (if you haven't done that yet).</p>\n\n<p>As a next step, you could use the following properties to optimize the equations:</p>\n\n<ul>\n<li><code>(a % m + b % m) % m = (a + b) % m</code></li>\n<li><code>(a &amp; n ^ b &amp; n) &amp; n = (a ^ b) &amp; n</code></li>\n</ul>\n\n<p>That allows you get rid of many of the <code>&amp; 2**32-1</code> operations at the cost of bigger intermediate results. If you want to make sure to get the highest speed, do some perfs. In any case, it will make the code much more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T01:18:19.093", "Id": "60594", "Score": "0", "body": "Thanks. Isn't it enough to create an additional global constant, say, M?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T01:36:07.317", "Id": "60595", "Score": "0", "body": "@d33tah What for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T01:55:39.743", "Id": "60597", "Score": "0", "body": "Also, you only need to mask/truncate for operations that could overflow. So right-shifts (`>>`) don't need to be altered. Since you're dealing with \"unsigned\" values, take some time to be sure you don't end up with negative numbers due to subtractions; your shifts and modulo operations won't work the way you expect with negatives." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T01:57:52.113", "Id": "60598", "Score": "0", "body": "Note you can also spell `2**32-1` as `0xFFFFFFFF` and save the computation and/or lookup (at the cost of more places to update if you change things)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T11:39:49.603", "Id": "60716", "Score": "0", "body": "\"Firstly, the expensive modulo operation can be replaced by a cheap bitwise and\" — can you justify this claim? When I try timing them, I can find no significant difference in speed between these two operations in Python." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T01:15:04.890", "Id": "36831", "ParentId": "36830", "Score": "4" } }, { "body": "<p>The C code you quoted is part of an implementation of the <a href=\"https://en.wikipedia.org/wiki/XTEA\" rel=\"nofollow\">XTEA</a> block cipher. So the obvious thing to do is to search for existing Python implementations, and sure enough, ActiveState has <a href=\"http://code.activestate.com/recipes/496737-python-xtea-encryption/\" rel=\"nofollow\">this one</a> by Paul Chakravarti, in which the loop you quoted is translated as follows:</p>\n\n<pre><code>sum,delta,mask = 0L,0x9e3779b9L,0xffffffffL\nfor round in range(n):\n v0 = (v0 + (((v1&lt;&lt;4 ^ v1&gt;&gt;5) + v1) ^ (sum + k[sum &amp; 3]))) &amp; mask\n sum = (sum + delta) &amp; mask\n v1 = (v1 + (((v0&lt;&lt;4 ^ v0&gt;&gt;5) + v0) ^ (sum + k[sum&gt;&gt;11 &amp; 3]))) &amp; mask\n</code></pre>\n\n<p>You can see that only three truncations to 32 bits are needed, one at the end of each line. That's because:</p>\n\n<ol>\n<li><p>A right shift can't overflow, so the expressions <code>v1&gt;&gt;5</code>, <code>v0&gt;&gt;5</code> and <code>sum&gt;&gt;11</code> don't need to be truncated.</p></li>\n<li><p><code>(a &amp; mask) ^ (b &amp; mask)</code> is equal to <code>(a ^ b) &amp; mask</code>, so the truncation can be postponed until after the bitwise-exclusive-or operation.</p></li>\n<li><p><code>((a &amp; mask) + (b &amp; mask)) &amp; mask</code> is equal to <code>(a + b) &amp; mask</code>, so the truncation can be postponed until after the addition operation.</p></li>\n</ol>\n\n<p>A final point worth noting is that it makes very little difference (for this application) whether you implement truncation using the <code>&amp;</code> (bitwise-and) or <code>%</code> (integer remainder) operations:</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit('0x1234567890ABCDEF &amp; 0xffffffff')\n0.026652097702026367\n&gt;&gt;&gt; timeit('0x1234567890ABCDEF % 0x100000000')\n0.025462865829467773\n</code></pre>\n\n<p>(That's because the numbers in XTEA never get very big, no more than 2<sup>37</sup> or so. For large numbers, the bitwise-and operator is much faster than the remainder operator.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T16:56:26.623", "Id": "60731", "Score": "0", "body": "Generally, bitwise and has a smaller complexity than the modulo (O(n) vs O(n^2)), so that's an interesting find" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:37:16.573", "Id": "60740", "Score": "0", "body": "@copy: Big-O notation describes the *asymptotic* performance of algorithms (their runtime as *n* → ∞). Here *n* is small and the runtime is dominated by the Python interpreter and bignum implementation overhead." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T11:37:24.237", "Id": "36897", "ParentId": "36830", "Score": "4" } } ]
{ "AcceptedAnswerId": "36897", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T00:58:01.000", "Id": "36830", "Score": "4", "Tags": [ "python" ], "Title": "Wrapping every expression with % 2 ** 32 to get a C-like behavior" }
36830
<p>This code finds all the divisors of a given number. Can it be shortened?</p> <pre><code>import java.util.Scanner; public class PrimeNum2{ public static void main(String args[]){ Scanner x=new Scanner(System.in); System.out.print("Enter the number : "); long y=x.nextInt(),i; System.out.print("Divisors of "+y+" = 1 , "); for( i=2;i&lt;y;i++){ long z=y%i; if(z!=0)continue; System.out.print(i+" , "); }System.out.println(y); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T06:01:37.663", "Id": "60609", "Score": "0", "body": "Why do you start with i = 2? Why not change it to i = 1?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-08T06:40:19.063", "Id": "275137", "Score": "0", "body": "@Tag I suppose that's mainly because the smallest prime number, according to primality as defined by modern mathematicians, is 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-09T20:49:56.877", "Id": "275454", "Score": "0", "body": "@Dex'ter If a user enters `1` as the input then `1` is repeated multiple times in the output. This is, of course, still technically correct. By modifying the loop to start at `1` and removing the last 4 characters from the end of the Divisors string we end up with cleaner output. In hindsight, I was being pedantic." } ]
[ { "body": "<p>This code could do with some editing...</p>\n\n<p>First of all is the spacing. It is absolutely horrible (we will fix that after the edits).</p>\n\n<p>Also, the naming is horrible. <code>Scanner x</code> could be <code>scanner</code> and <code>y</code> could be <code>num</code>. As for z, it is completely unnecessary:</p>\n\n<blockquote>\n<pre><code>for (i = 2; i &lt; y; i++) {\n long z = y % i;\n if (z != 0)\n continue;\n System.out.print(i + \" , \");\n}\n</code></pre>\n</blockquote>\n\n<p>Becomes:</p>\n\n<pre><code>for (i = 2; i &lt; y; i++) {\n if (y % i != 0)\n continue;\n System.out.print(i + \" , \");\n}\n</code></pre>\n\n<p>The program can do without the continue statement:</p>\n\n<pre><code>for (i = 2; i &lt; y; i++) {\n if (y % i == 0)\n System.out.print(i + \" , \");\n}\n</code></pre>\n\n<p>It's also a good idea to put braces around statements in an <code>if</code> statement, even when there is only one:</p>\n\n<pre><code>for (i = 2; i &lt; y; i++) {\n if (y % i == 0) {\n System.out.print(i + \" , \");\n }\n}\n</code></pre>\n\n<p>You are also wasting time going through <code>for</code> loops doing nothing. After all, <code>num</code>'s largest factor before itself possible is <code>num / 2</code>, which makes it more efficient doing it like this:</p>\n\n<pre><code>for (i = 2; i &lt;= num / 2; i++) {\n if (num % i == 0) {\n System.out.print(i + \" , \");\n }\n}\n</code></pre>\n\n<p>I also noticed:</p>\n\n<blockquote>\n<pre><code> public static void main(String args[])\n</code></pre>\n</blockquote>\n\n<p>It is better to put <code>[]</code> at the type (<code>String</code>):</p>\n\n<pre><code>public static void main(String[] args)\n</code></pre>\n\n<p>But the main problem is that you have a memory leak. It could be solved by closing the <code>Scanner</code>:</p>\n\n<pre><code>scanner.close();\n</code></pre>\n\n<h2>Final code:</h2>\n\n<p>Your final code will look like this:</p>\n\n<pre><code>public class PrimeNum2 {\n public static void main(String args[]) {\n Scanner scanner = new Scanner(System.in);\n System.out.print(\"Enter the number : \");\n long num = scanner.nextInt(), i;\n System.out.print(\"Divisors of \" + num + \" = 1 , \");\n for (i = 2; i &lt;= num / 2; i++) {\n if (num % i == 0) {\n System.out.print(i + \" , \");\n }\n }\n System.out.println(num);\n scanner.close();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-20T04:00:10.957", "Id": "218193", "Score": "0", "body": "Condition in for loop should be i <=num/2 and not i <num/2. Test with num = 6. With above code: divisors of 6 will print 1, 2, 6 as loop starts from 2 and not check 3" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-20T18:25:16.793", "Id": "218320", "Score": "0", "body": "@prashantsunkari Good catch, will fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-06T00:37:30.697", "Id": "280279", "Score": "0", "body": "The only problem wiil be the special case of the number 1. Will print 'Divisors of 1 = 1 , 1'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-29T10:44:37.103", "Id": "324926", "Score": "0", "body": "`i` should be local to the `for` loop." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-01T00:59:00.850", "Id": "58711", "ParentId": "36837", "Score": "20" } }, { "body": "<p>You can actually stop checking at <code>Math.sqrt(num)</code> because the current divisor always yields its conjugate:</p>\n\n<pre><code>for (i = 2; i &lt;= Math.sqrt(num); i++) {\n if (num % i == 0) {\n System.out.print(i + \" , \");\n if (i != num/i) {\n System.out.print(num/i + \" , \");\n }\n }\n}\n</code></pre>\n\n<p>We have to add an extra check, however, to avoid duplicate output in the case where <code>num</code> is a perfect square.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-29T10:45:55.363", "Id": "324928", "Score": "0", "body": "`Math.sqrt` is an expensive operation. You should not call that function more often than necessary." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-23T20:21:24.537", "Id": "111625", "ParentId": "36837", "Score": "9" } }, { "body": "<pre><code>for( i=2; i &lt;= (y / 2); i++)\n{\n long z=y%i;\n if(z!=0)continue;\n System.out.print(i+\" , \");\n}\n</code></pre>\n\n<p>This <code>for</code> loop can be shortened, since a number's largest divisor (other than itself) will always be \\$\\frac{1}{2}\\$. So instead of <code>i &lt; y</code>, you could do <code>i &lt;= (y/2)</code>, assuming you are only counting integers, which you are since you say divisors.</p>\n\n<p>\\$136\\$: largest divisor - \\$68\\$ (\\$\\le \\frac{1}{2}\\$ of \\$136\\$)</p>\n\n<p>\\$99\\$: largest divisor - \\$33\\$ (\\$\\le \\frac{1}{2}\\$ of \\$99\\$)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-23T21:49:58.600", "Id": "111636", "ParentId": "36837", "Score": "6" } }, { "body": "<p>As far as efficiency is concerned you should first generate a list of divisors \n12-> {2,2,3} then group them -> {{2,2},{3}} then apply product of sets (see <a href=\"https://stackoverflow.com/questions/714108/cartesian-product-of-arbitrary-sets-in-java\">here</a>).</p>\n\n<p>This way you never check for divisors above n^(0.5) and make your search for divisors very efficient.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-08T01:35:06.823", "Id": "146448", "ParentId": "36837", "Score": "1" } } ]
{ "AcceptedAnswerId": "58711", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T05:12:03.177", "Id": "36837", "Score": "18", "Tags": [ "java", "beginner", "mathematics" ], "Title": "Finding divisors of a number" }
36837
Template meta-programming is a meta-programming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T05:52:04.407", "Id": "36839", "Score": "0", "Tags": null, "Title": null }
36839
<p>This week's review challenge is a poker hand evaluator. I started by enumerating the possible hands:</p> <pre><code>public enum PokerHands { Pair, TwoPair, ThreeOfKind, Straight, Flush, FullHouse, FourOfKind, StraightFlush, RoyalFlush } </code></pre> <p>Then I thought I was going to need cards... and cards have a <em>suit</em>...</p> <pre><code>public enum CardSuit { Hearts, Diamonds, Clubs, Spades } </code></pre> <p>...and a nominal value:</p> <pre><code>public enum PlayingCardNominalValue { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace } </code></pre> <p>So I had enough of a concept to formally define a <code>PlayingCard</code>:</p> <pre><code>public class PlayingCard { public CardSuit Suit { get; private set; } public PlayingCardNominalValue NominalValue { get; private set; } public PlayingCard(CardSuit suit, PlayingCardNominalValue nominalValue) { Suit = suit; NominalValue = nominalValue; } } </code></pre> <p>At this point I had everything I need to write my actual Poker hand evaluator - because the last time I implemented this (like, 10 years ago) it was in VB6 and that I'm now spoiled with .net, I decided to leverage LINQ here:</p> <pre><code>public class PokerGame { private readonly IDictionary&lt;PokerHands, Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt;&gt; _rules; public IDictionary&lt;PokerHands, Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt;&gt; Rules { get { return _rules; } } public PokerGame() { // overly verbose for readability Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; hasPair = cards =&gt; cards.GroupBy(card =&gt; card.NominalValue) .Count(group =&gt; group.Count() == 2) == 1; Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isPair = cards =&gt; cards.GroupBy(card =&gt; card.NominalValue) .Count(group =&gt; group.Count() == 3) == 0 &amp;&amp; hasPair(cards); Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isTwoPair = cards =&gt; cards.GroupBy(card =&gt; card.NominalValue) .Count(group =&gt; group.Count() &gt;= 2) == 2; Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isStraight = cards =&gt; cards.GroupBy(card =&gt; card.NominalValue) .Count() == cards.Count() &amp;&amp; cards.Max(card =&gt; (int) card.NominalValue) - cards.Min(card =&gt; (int) card.NominalValue) == 4; Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; hasThreeOfKind = cards =&gt; cards.GroupBy(card =&gt; card.NominalValue) .Any(group =&gt; group.Count() == 3); Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isThreeOfKind = cards =&gt; hasThreeOfKind(cards) &amp;&amp; !hasPair(cards); Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isFlush = cards =&gt; cards.GroupBy(card =&gt; card.Suit).Count() == 1; Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isFourOfKind = cards =&gt; cards.GroupBy(card =&gt; card.NominalValue) .Any(group =&gt; group.Count() == 4); Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isFullHouse = cards =&gt; hasPair(cards) &amp;&amp; hasThreeOfKind(cards); Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; hasStraightFlush = cards =&gt;isFlush(cards) &amp;&amp; isStraight(cards); Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isRoyalFlush = cards =&gt; cards.Min(card =&gt; (int)card.NominalValue) == (int)PlayingCardNominalValue.Ten &amp;&amp; hasStraightFlush(cards); Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isStraightFlush = cards =&gt; hasStraightFlush(cards) &amp;&amp; !isRoyalFlush(cards); _rules = new Dictionary&lt;PokerHands, Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt;&gt; { { PokerHands.Pair, isPair }, { PokerHands.TwoPair, isTwoPair }, { PokerHands.ThreeOfKind, isThreeOfKind }, { PokerHands.Straight, isStraight }, { PokerHands.Flush, isFlush }, { PokerHands.FullHouse, isFullHouse }, { PokerHands.FourOfKind, isFourOfKind }, { PokerHands.StraightFlush, isStraightFlush }, { PokerHands.RoyalFlush, isRoyalFlush } }; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T08:54:37.900", "Id": "60612", "Score": "1", "body": "What are you trying to do? Determine what hand a person has?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T09:46:38.843", "Id": "60614", "Score": "1", "body": "Your evaluator doesn't have an `evaluate` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T09:51:57.880", "Id": "60615", "Score": "1", "body": "Also is buggy: `new PokerGame().Rules[PokerHands.Straight](new PlayingCard[]{\n new PlayingCard(CardSuit.Hearts, PlayingCardNominalValue.Ace),\n new PlayingCard(CardSuit.Clubs, PlayingCardNominalValue.Two),\n new PlayingCard(CardSuit.Clubs, PlayingCardNominalValue.Three),\n new PlayingCard(CardSuit.Clubs, PlayingCardNominalValue.Four),\n new PlayingCard(CardSuit.Clubs, PlayingCardNominalValue.Five),\n }) == false`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T13:58:40.993", "Id": "60625", "Score": "0", "body": "@abuzittingillifirca oh shoot, I only accounted the Ace as a 14!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:00:10.167", "Id": "60754", "Score": "1", "body": "Down-voted this question [by request](http://chat.stackexchange.com/transcript/message/12527774#12527774)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:28:02.393", "Id": "60761", "Score": "0", "body": "@SimonAndréForsberg thanks, feels better. BTW I think I found an edge case that breaks your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:28:59.553", "Id": "60762", "Score": "0", "body": "@retailcoder What!? Tell me, tell me, tell me! What did you find?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-06T09:59:45.337", "Id": "227292", "Score": "0", "body": "https://github.com/gsteinbacher/CardGame ... Check out Obacher.CardGame.Poker for my version of the evaluations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-14T15:40:57.183", "Id": "276257", "Score": "0", "body": "Just because you have a straight and a flush does not mean you have a straight-flush. And call it NominalValue Rank" } ]
[ { "body": "<pre><code>public enum PokerHands\n</code></pre>\n\n<p>This type should be called in singular (<code>PokerHand</code>). When you have a variable of this type, it represents a single hand, not some collection of hands. Your other <code>enum</code>s are named correctly in this regard.</p>\n\n<pre><code>public enum CardSuit\npublic enum PlayingCardNominalValue\n</code></pre>\n\n<p>You should be consistent. Either start both types with <code>PlayingCard</code> or both with <code>Card</code>. I prefer the former, because this is a playing card library, there is not much chance of confusion with credit cards or other kinds of cards.</p>\n\n<pre><code>private readonly IDictionary&lt;PokerHands, Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt;&gt; _rules;\npublic IDictionary&lt;PokerHands, Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt;&gt; Rules { get { return _rules; } }\n</code></pre>\n\n<p>I would use auto-property with <code>private</code> setter (like you did in <code>PlayingCard</code>) here. It won't enforce the <code>readonly</code> constraint, but I think shorter code is worth that here.</p>\n\n<p>Also, this pretty dangerous code, any user of this class can modify the dictionary. If you're using .Net 4.5, you could change the type to <code>IReadOnlyDictionary</code> (and if you wanted to avoid modifying by casting back to <code>IDictionary</code>, also wrap it in <code>ReadOnlyDictionary</code>).</p>\n\n<p>One more thing: I question whether <code>IDictionary</code> is actually the right type here. I believe that the common operation would be to find the hand for a collection of cards, not finding out whether a given hand matches the cards.</p>\n\n<pre><code>// overly verbose for readability\n</code></pre>\n\n<p>I agree that the lambdas are overly verbose, but I'm not sure it actually helps readability. What I don't like the most is all of the <code>GroupBy()</code> repetition. What you could do is to create an intermediate data structure that would contain the groups by <code>NominalValue</code> and anything else you need and then use that in your lambdas.</p>\n\n<pre><code>Func&lt;IEnumerable&lt;PlayingCard&gt;, bool&gt; isStraight = \n cards =&gt; cards.GroupBy(card =&gt; card.NominalValue)\n .Count() == cards.Count()\n &amp;&amp; cards.Max(card =&gt; (int) card.NominalValue) \n - cards.Min(card =&gt; (int) card.NominalValue) == 4;\n</code></pre>\n\n<p>What is the <code>cards.Count()</code> supposed to mean? Don't there always have to be 5 cards? The second part of this lambda seems to indicate that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T14:00:50.897", "Id": "60626", "Score": "0", "body": "I didn't hard-code the 5 because depending on the actual game `cards.Count()` could also be 7. Thanks for the review, I admit I posted quite too early this week (the minute all tests passed), it shows." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T14:09:05.740", "Id": "60627", "Score": "1", "body": "@retailcoder So, 2,3,4,5,6,8,9 is not a straight, but 2,2,3,4,5,6,6 is? I think that's a bug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T14:26:04.127", "Id": "60632", "Score": "0", "body": "Ugh. I shouldn't have rushed this. TBH I'm not very happy with this code, it's not *my best possible code* and I feel like saying *\"scratch that, I'll post again when it meets my quality bar\"* - I didn't even do a single pass of refactoring, it's really the 1st \"draft\"... mainly I wanted to post my solution before @rolfl posted his; *and it's not a race*. :/" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T13:18:25.837", "Id": "36851", "ParentId": "36841", "Score": "5" } }, { "body": "<h2>The Design may be Incomplete</h2>\n\n<ul>\n<li>The readability concern in the <code>PokerGame</code> class can be addressed by encapsulation instead of syntactical slight of hand. <em>Push details down</em> is the mantra.</li>\n<li>Addresses the concern about a fungible <code>Dictionary</code> by enveloping (encapsulating) it.</li>\n</ul>\n\n<h3>Would a <code>HandEvaluator</code> class be helpful?</h3>\n\n<ul>\n<li>Maybe the <code>HandEvaluator</code> class could be exposed through <code>CardDeck</code>, i.e. the <code>PokerGame</code> talks to the <code>CardDeck</code> only; anyway ...</li>\n<li>The \"grunt work\" of <code>isPair</code>, etc. could go in the <code>HandEvaluator</code>. </li>\n<li>Sure, the <code>PokerGame</code> may need to know if there is a pair, but ask and return a <code>PokerHand</code> to the general question: <code>PokerHand myHand = HandEvaluator.WhatDoIHave(myHand);</code></li>\n</ul>\n\n<h3>Would a <code>Hand</code> class be helpful?</h3>\n\n<pre><code>public class Hand {\n public PokerHand Hand {get; set;}\n public Suit Suit {get; set;}\n\n public List&lt;Card&gt; Cards {get; set;}\n\n public override string ToString() {\n return string.Format(\"A {0} of {1}\", Hand.ToString(), Suit.ToString());\n }\n}\n\nCardDeck.WhatDoIHave(JoesHand);\nConsole.Writeline(\"{0} has {1}\", player1.Name, JoesHand);\n</code></pre>\n\n\n\n<ul>\n<li>Now a <code>Hand</code> is defined, encapsulated, and expressive.</li>\n<li>We can now see that the <code>enum PokerHand</code> falls short of really defining a \"hand of poker\"</li>\n<li>I suspect that the <code>_rules</code> dictionary becomes superfluous. Seems to me all it does is \"translate\" the enum value. </li>\n</ul>\n\n<h3>Just One more thing(s)</h3>\n\n<ul>\n<li>Are the <code>CardSuit</code> in the right order? Clubs = 1, Diamonds, Hearts, Spades. This is a tie breaker when, for example, both two players have a royal flush - which has happened once in a pro poker tourney.</li>\n<li><em>Highest Card</em> is missing from <code>enum PokerHands</code></li>\n<li>Make determining the winner look like magic. See below.</li>\n</ul>\n\n\n\n<pre><code>List&lt;Hand&gt; playerHands; \n// ... play a hand, then this ...\n\nplayerHands.Sort(); // the winner is on top.\n\n// because in the `Hand` class...\n\npublic Hand : IComparable&lt;Hand&gt; {\n public int CompareTo (Hand other) {\n // Assuming HandEvaluator has already done it's thing.\n\n if (other == null) return 1;\n if (this.Hand &gt; other.Hand) return 1;\n if (this.Hand == other.Hand &amp;&amp; this.Suit &gt; other.Suit) return 1;\n if (this.Hand == other.Hand &amp;&amp; this.Suit &lt; other.Suit) return -1;\n if (this.Hand &lt; other.Hand) return -1;\n return 0;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:14:23.500", "Id": "60664", "Score": "1", "body": "I do have a `CardDeck`, I edited it out because it wasn't relevant to the evaluation of the Poker hands :) Check out the [take 2 follow-up post..](http://codereview.stackexchange.com/questions/36873/poker-hand-evaluator-take-2)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:27:45.167", "Id": "60668", "Score": "0", "body": "@retailcoder, I agree. I fixed my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:55:16.387", "Id": "60673", "Score": "0", "body": "Rewrote `CompareTo`. Removed reference to HandEvaluator. Should be comparing ONLY in the context of the given class. A design flaw otherwise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T07:39:49.533", "Id": "60698", "Score": "4", "body": "Suits do not break tie. Highest hands that only differ in suits split the pot. There might be *variants* of course." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T19:40:49.343", "Id": "61062", "Score": "0", "body": "@abuzittingillifirca; \"BobPoker.\" In the spirit of [Calvin Ball](http://calvinandhobbes.wikia.com/wiki/Calvinball)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T19:43:58.237", "Id": "61064", "Score": "0", "body": "To handle rule variations one might implement multiple [`EqualityComparer`](http://msdn.microsoft.com/en-us/library/ms132123(v=vs.110).aspx) classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-28T22:44:13.257", "Id": "124475", "Score": "1", "body": "There is no casino or cardroom anywhere in the country that uses suits to break ties between poker hands. Tied hands split the pot, period. Suits *are* used for things like deciding who pays a bring-in, who deals first, who gets the extra chip in a split pot, and other things. For these uses, the suit ranking you have listed (C, H, D, S) is correct." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:11:48.847", "Id": "36874", "ParentId": "36841", "Score": "5" } } ]
{ "AcceptedAnswerId": "36851", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T06:49:31.033", "Id": "36841", "Score": "4", "Tags": [ "c#", "linq", "weekend-challenge", "playing-cards" ], "Title": "Poker Hand Evaluator Challenge" }
36841
<p>I came across an interview question, which is like this:</p> <blockquote> <p>You have an array of integers, such that each integer is present an odd number of time, except 3 of them. Find the three numbers.</p> </blockquote> <p>I tried implementing it using a <code>HashMap&lt;Integer, Integer&gt;</code>, by mapping each integer element to a number that would identify if that number occurs even number of times. I used the <code>XOR</code> logic for that. <code>5 ^ 5 = 0</code>, and <code>5 ^ anyNumberOtherThan5 != 0</code>.</p> <p>Here's my code:</p> <pre><code>public static void findEvenOccurringNum(int[] arr) { Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;(); for (int num: arr) { if (map.containsKey(num)) { map.put(num, map.get(num) ^ 1); } else { map.put(num, 1); } } for (Entry&lt;Integer, Integer&gt; entry: map.entrySet()) { if (entry.getValue() == 0) { System.out.println(entry.getKey()); } } } </code></pre> <p>What I don't like about this solution is the 2nd iteration. That would iterate over all the unique numbers in the array. Can there be any possible improvement here? May be a solution that avoids using a <code>map</code>? Or is it the best I can do?</p>
[]
[ { "body": "<p>Since your map values toggle between 0 and 1, you could just as well use a <code>Map&lt;Integer, Boolean&gt;</code> instead.</p>\n\n<p>Usually, it is good practice not to mingle your output routines into your logic. In the absence of any specific instructions from your interviewer, it would have been better to return the found values rather than print them. A reasonable return type might be <code>Set&lt;Integer&gt;</code>, since the elements to be returned will be distinct, and the order is unspecified. Another possible return type would be <code>int[]</code>, since it is similar to the array that was passed to you.</p>\n\n<p>Since we want to return a set, it would be nice if we could build the set as we go along. Building the set of numbers with odd occurrences is easy: try to add a number to a set; if it was already there (<code>Set.add()</code> returns <code>false</code>), remove it instead. The trick is that removing an entry from the odd-occurrences set means you should transfer it to the even-occurrences set.</p>\n\n<pre><code>public static Set&lt;Integer&gt; findEvenOccurrences(int[] arr) {\n // The HashSet capacity should scale with the size of the input\n Set&lt;Integer&gt; oddOccurrences = new HashSet&lt;Integer&gt;(arr.length),\n evenOccurrences = new HashSet&lt;Integer&gt;(arr.length / 2);\n for (int num : arr) {\n if (oddOccurrences.add(num)) {\n // We have seen num an odd number of times\n evenOccurrences.remove(num);\n } else {\n // We have seen num an even number of times\n oddOccurrences.remove(num);\n evenOccurrences.add(num);\n }\n }\n return evenOccurrences;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T03:43:26.740", "Id": "60687", "Score": "0", "body": "#winces# - except, you're going to be swapping elements between them many times (assuming the odd entries are present more than one time); if the set condenses/shifts entries each add/remove, this is going to be less efficient than it could. Personally, I agree with the `Map<Integer, Boolean>` idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T20:11:54.373", "Id": "61256", "Score": "0", "body": "As @rolfl has pointed out a performance problem when the input array is large and has few repetitions, I have added a hint so that the HashSet capacity scales with the size of the input." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T10:42:25.867", "Id": "36844", "ParentId": "36842", "Score": "5" } }, { "body": "<p>You ask:</p>\n\n<blockquote>\n <p>Can there be any possible improvement here?</p>\n</blockquote>\n\n<p>There is always a way to improve things. But, sometimes improvements are opinion based... ;-)</p>\n\n<p>In general I dislike solutions that use generous amounts of AutoBoxing (int to Integer, boolean to Boolean, etc.). In your case, the actual work that Java does (and memory it uses) to manage the objects required to solve the solution is far more than the actual work of the problem itself.</p>\n\n<p>I believe the following solution is faster, smaller, and all those things, but it may need a little explaining. I also like that it returns the values in sorted order, and as an int[] array which is the same format as the input.</p>\n\n<p>It's only heap-space data usage is for the copy of the input array and the small result array... (unlike all the Integers and Booleans and Map.Objects of the Collection-based solutions.</p>\n\n<pre><code>public static final int[] findDuplicates(final int[] data) {\n // take a copy of the data.\n int[] sorted = Arrays.copyOf(data, data.length);\n // sort it. This is O(n log(n)) which will be the bulk of our time.\n Arrays.sort(sorted);\n\n // now scan the sorted data for even-numbered sequences of values.\n int len = 0;\n boolean even = false;\n // sorted[0] is our first sequence, and currently it is not even.\n // note that the scan starts at position 1.\n for (int i = 1; i &lt; sorted.length; i++) {\n if (sorted[i] == sorted[len]) {\n // this element is the same as the sequence, so 'count' the even-ness.\n even = !even;\n } else {\n // this element is different to our sequence, it's a new sequence.\n if (even) {\n // the old sequence had an even count, so we 'preserve' it.\n len++;\n }\n // move the value of the new sequence to the 'beginning'.\n sorted[len] = sorted[i];\n // and the new sequence is odd.\n even = false;\n }\n }\n if (even) {\n // the last sequence was even, we preserve it.\n len++;\n }\n // return the first part of the array, which contains the even sequence values.\n return Arrays.copyOf(sorted, len);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T17:04:26.303", "Id": "60647", "Score": "0", "body": "Is it really faster, especially for long inputs? Any general-purpose sort will be at least O(_n_ log _n_). Both the original and my [`Set` solution](http://codereview.stackexchange.com/a/36844/9357) are O(_n_)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:38:08.957", "Id": "60658", "Score": "0", "body": "@200_success - I just plotted the performance metrics for our systems... FYI.... and, no, I don't know why (I can guess it's the HashSets...but) your solution is not O(n) for sparse data" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T13:42:16.457", "Id": "36852", "ParentId": "36842", "Score": "5" } }, { "body": "<h2>Wiki Answer - discussion of scalability.</h2>\n\n<p>After some investigation I thought it would be interesting to publish some of the performance results I have seen.... there are some interesting observations.</p>\n\n<p>I have taken two algorithms, both on this page, the <a href=\"https://codereview.stackexchange.com/a/36844/31503\">200_Success</a> one, and the <a href=\"https://codereview.stackexchange.com/a/36852/31503\">rolfl</a> one. I have run both algorithms through two types of tests, and for each type, I ran it through data of different sizes. I measured the actual performance.</p>\n\n<p>The two types of test are 'data complexity' related. The first test I call 'sparse', and there are very few duplicates of data. The second set of data is 'freq' which has many, many duplicates. The two data sets are constructed as (<code>1 &lt;&lt; 18</code> is 256K elements and runs in an 'about-right' time on my computer):</p>\n\n<pre><code> int[] sparse = new int[1&lt;&lt;18];\n Random rand = new Random(1); // repeatable 'random' numbers\n for (int i = 0; i &lt; sparse.length; i++) {\n sparse[i] = rand.nextInt(sparse.length);\n }\n\n int[] freq = new int[1&lt;&lt;18];\n for (int i = 0; i &lt; freq.length; i++) {\n freq[i] = rand.nextInt(10);\n }\n</code></pre>\n\n<p>So, two different datasets.... and then, I use the data in 5 different sizes.... each size is half the size of the next size.... so, I have data of 16K, 32K, 64K, 128K, and 256K.</p>\n\n<p>I then run each of the algorithms a number of times for each data size. The number of times depends on the size of the data.... The bigger the data is, the fewer times I run the loop, and, as the data size doubles, I halve the number of iterations.</p>\n\n<pre><code>iterations 256 128 64 32 16\ndata size 16384 32768 65536 131072 262144\n</code></pre>\n\n<p>In theory, in a perfectly scalable system, the data-size and iteration combinations should result in constant-time execution....</p>\n\n<p>Then I timed the actual execution times, and here are the results (on a warmed up system).</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>RLsparse,130.632,164.163,225.850,271.158,289.436,322.981,343.293,360.966,390.827,412.959\nRLfreq,60.455,66.364,53.215,76.341,82.661,85.065,88.740,87.201,89.798,87.361\n2Ssparse,157.926,184.521,214.407,242.943,256.200,286.686,352.467,438.048,420.164,666.043\n2Sfreq,152.263,155.817,158.332,160.107,158.856,157.523,159.182,158.238,158.978,157.142\ndatasize,512,1024,2048,4096,8192,16384,32768,65536,131072,262144\niterations,8192,4096,2048,1024,512,256,128,64,32,16\n</code></pre>\n\n<p>Plotting this as a graph, using the datasize as the X axis, it looks like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/JW6Yi.png\" alt=\"enter image description here\"></p>\n\n<p>The 'dip' in the performance of the 2Ssparse 'curve' is consistent... there must be some anomoly that happens in the data of that size that 'wins' for whatever reason.</p>\n\n<p>The 'obvious' observations are:</p>\n\n<ol>\n<li>both algorithms like lots of duplicate values.</li>\n<li>for high-duplicate values the 200_Success algorithm is practically <code>O(n)</code> and it appears the HashMap is <code>O(1)</code> as stated.</li>\n<li>for sparse-duplicate values the 200_Success scales <strong>worse</strong> than the rolfl version, and, although it started faster, for larger data sets it quickly degrades to be slower.</li>\n<li>for sparse-duplicate values the rolfl version is faster (runs in 2/3 of the time), but is slightly degrading in performance.... I expect that for all reasonable data sizes it will be faster.....</li>\n</ol>\n\n<h2>EDIT:</h2>\n\n<p>After a request for 'medium' amounts of duplication (the random numbers are taken from a pool of 1024 instead of just 10):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>RLsparse,124.211,147.412,216.475,273.934,293.235,330.671,346.458,372.003,399.730,407.985\nRLfreq,42.496,41.446,53.732,58.305,66.281,65.889,64.953,66.078,73.901,71.291\nRLmedium,122.813,179.644,218.106,253.908,272.583,259.016,232.671,226.121,220.121,207.180\n2Ssparse,155.091,180.669,205.877,236.890,254.193,288.193,351.495,450.381,426.626,665.759\n2Sfreq,172.426,173.460,173.988,174.462,175.049,174.477,175.384,172.826,174.230,175.976\n2Smedium,162.969,210.496,232.372,235.070,229.555,222.412,219.141,219.358,218.502,221.412\n</code></pre>\n\n<p>And the corresponding plot is:</p>\n\n<p><img src=\"https://i.stack.imgur.com/TmBI9.png\" alt=\"enter image description here\"></p>\n\n<h2>EDIT2:</h2>\n\n<p>The HashSet based implementation has been revised to include hints on th size of the HashSets. The revised performance results are:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>RLsparse,113.848,156.549,195.834,264.010,280.561,314.784,332.941,360.607,387.728,401.440\nRLfreq,50.688,45.955,61.013,59.733,74.000,68.274,69.208,70.487,76.905,74.185\nRLmedium,116.118,177.327,223.468,258.029,275.395,263.365,234.839,225.775,221.798,210.071\n2Ssparse,127.956,160.641,159.736,171.221,180.202,195.650,265.159,328.633,270.251,369.847\n2Sfreq,154.762,154.865,157.780,157.265,158.705,159.562,160.342,161.276,160.924,163.296\n2Smedium,128.366,152.183,187.613,198.995,270.550,198.450,200.526,202.244,205.382,207.368\ndatasize,512,1024,2048,4096,8192,16384,32768,65536,131072,262144\niterations,8192,4096,2048,1024,512,256,128,64,32,16\n</code></pre>\n\n<p>And the corresponding plot is (Note the scale is the same as other plots, max 700ms):</p>\n\n<p><img src=\"https://i.stack.imgur.com/5O3IS.png\" alt=\"enter image description here\"></p>\n\n<p>Here is the code I used to generate the above graph (the actual algorithms not included since they are above...).</p>\n\n<p>This code is <strong>not</strong> neat, and please do not review it .... ;-) But feel free to make any changes you like to improve it... I know it is ugly... but it works.</p>\n\n<pre><code>package dupcnt;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Random;\nimport java.util.Set;\n\npublic class CompareDups {\n\n\n public static void main(String[] args) {\n\n System.out.println(\"Building Data\");\n\n int[] sparse = new int[1&lt;&lt;18];\n int[] freq = new int[sparse.length];\n int[] medium = new int[sparse.length];\n Random rand = new Random(1); // repeatable 'random' numbers\n for (int i = 0; i &lt; sparse.length; i++) {\n sparse[i] = rand.nextInt(sparse.length);\n }\n for (int i = 0; i &lt; freq.length; i++) {\n freq[i] = rand.nextInt(10);\n }\n for (int i = 0; i &lt; medium.length; i++) {\n medium[i] = rand.nextInt(1024);\n }\n\n System.out.println(\"Built data \" + sparse.length);\n\n final int dpoints = 10;\n int[] iterations = new int[dpoints];\n for (int i = 0; i &lt; iterations.length; i++) {\n iterations[i] = 1 &lt;&lt; dpoints + 3 - i;\n }\n\n for (int i = 0; i &lt; 10; i++) {\n long[][] data = new long[8][dpoints];\n for (int dp = 0; dp &lt; dpoints; dp++) {\n int[] input = null;\n input = Arrays.copyOf(sparse, sparse.length &gt;&gt;&gt; dpoints - 1 - dp);\n data[0][dp] = processRL(input, iterations[dp]);\n data[3][dp] = process2S(input, iterations[dp]);\n input = Arrays.copyOf(freq, freq.length &gt;&gt;&gt; dpoints - 1 - dp);\n data[1][dp] = processRL(input, iterations[dp]);\n data[4][dp] = process2S(input, iterations[dp]);\n input = Arrays.copyOf(medium, medium.length &gt;&gt;&gt; dpoints - 1 - dp);\n data[2][dp] = processRL(input, iterations[dp]);\n data[5][dp] = process2S(input, iterations[dp]);\n data[6][dp] = input.length;\n data[7][dp] = iterations[dp];\n }\n String[] series = {\"RLsparse\", \"RLfreq\", \"RLmedium\", \"2Ssparse\", \"2Sfreq\", \"2Smedium\", \"datasize\", \"iterations\"};\n for (int s = 0; s &lt; series.length; s++) {\n StringBuilder sb = new StringBuilder();\n sb.append(series[s]);\n for (long l : data[s]) {\n if (s &lt; 6) {\n sb.append(\",\").append(String.format(\"%.3f\", l/1000000.0));\n } else {\n sb.append(\",\").append(String.format(\"%d\", l));\n }\n }\n System.out.println(sb.toString());\n }\n }\n }\n\n private static long processRL(final int[] input, final int iterations) {\n System.gc();\n int cnt = 0;\n long nanos = System.nanoTime();\n for (int i = 0; i &lt; iterations; i++) {\n cnt += findDuplicates(input).length;\n }\n if (cnt &lt; 0) {\n throw new IllegalStateException(\"This is just to keep things from being optimized out.\");\n }\n return System.nanoTime() - nanos;\n }\n\n private static long process2S(final int[] input, final int iterations) {\n System.gc();\n int cnt = 0;\n long nanos = System.nanoTime();\n for (int i = 0; i &lt; iterations; i++) {\n cnt += findEvenOccurrences(input).size();\n }\n if (cnt &lt; 0) {\n throw new IllegalStateException(\"This is just to keep things from being optimized out.\");\n }\n return System.nanoTime() - nanos;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T03:54:29.950", "Id": "60688", "Score": "0", "body": "What about upping the number of entries for the 'duplicates' run? So, what happens if you cut the number of duplicates in half, but up the number of entries? Because the sparse one will potentially have only one of each number..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T04:10:27.197", "Id": "60689", "Score": "0", "body": "@Clockwork-Muse Like adding a series for say 'medium' where the random numbers come from a range of about 256 instead of 10 or 256K?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T04:12:49.597", "Id": "60690", "Score": "0", "body": "Yeah, something like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T04:20:42.983", "Id": "60691", "Score": "0", "body": "@Clockwork-Muse - are you asking out of curiosity or do you suspect something (because something odd has happened....)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T04:36:21.623", "Id": "60692", "Score": "0", "body": "Mostly, I'm curious as to the 'break even' point for @200's version; I'm a little worried about it thrashing during item shifts in the backing arrays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T20:40:32.163", "Id": "61267", "Score": "0", "body": "@200_success Revised the analysis to include your latest changes." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:35:25.587", "Id": "36870", "ParentId": "36842", "Score": "7" } } ]
{ "AcceptedAnswerId": "36852", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T07:40:21.033", "Id": "36842", "Score": "7", "Tags": [ "java", "algorithm", "array", "interview-questions" ], "Title": "Find elements occurring even number of times in an integer array" }
36842
<p>In my first attempt, I have tried to load images from disk and load it to a <code>QTableView</code> using <code>QAbstractTableModel</code>. I'd like a general code review of this code.</p> <pre><code>import sys import os from PyQt4 import QtGui, QtCore class MyListModel(QtCore.QAbstractTableModel): def __init__(self, datain, col, thumbRes, parent=None): """ datain: a list where each item is a row """ self._thumbRes = thumbRes QtCore.QAbstractListModel.__init__(self, parent) self._listdata = datain self._col = col self.pixmap_cache = {} def colData(self, section, orientation, role): if role == QtCore.Qt.DisplayRole: return None def headerData(self, section, orientation, role): if role == QtCore.Qt.DisplayRole: if orientation in [QtCore.Qt.Vertical, QtCore.Qt.Horizontal]: return None def rowCount(self, parent=QtCore.QModelIndex()): return len(self._listdata) def columnCount(self, parent): return self._col def data(self, index, role): if role == QtCore.Qt.SizeHintRole: return QtCore.QSize(*self._thumbRes) if role == QtCore.Qt.TextAlignmentRole: return QtCore.Qt.AlignCenter if role == QtCore.Qt.EditRole: row = index.row() column = index.column() try: fileName = os.path.split(self._listdata[row][column])[-1] except IndexError: return return fileName if role == QtCore.Qt.ToolTipRole: row = index.row() column = index.column() try: self.selectonChanged(row,column) fileName = os.path.split(self._listdata[row][column])[-1] except IndexError: return return QtCore.QString(fileName) if index.isValid() and role == QtCore.Qt.DecorationRole: row = index.row() column = index.column() try: value = self._listdata[row][column] except IndexError: return pixmap = None # value is image path as key if self.pixmap_cache.has_key(value) == False: pixmap=self.generatePixmap(value) self.pixmap_cache[value] = pixmap else: pixmap = self.pixmap_cache[value] return QtGui.QImage(pixmap).scaled(self._thumbRes[0],self._thumbRes[1], QtCore.Qt.KeepAspectRatio) if index.isValid() and role == QtCore.Qt.DisplayRole: row = index.row() column = index.column() try: value = self._listdata[row][column] fileName = os.path.split(value)[-1] except IndexError: return return os.path.splitext(fileName)[0] def generatePixmap(self, value): pixmap=QtGui.QPixmap() pixmap.load(value) return pixmap def flags(self, index): return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable def setData(self, index, value, role=QtCore.Qt.EditRole): if role == QtCore.Qt.EditRole: row = index.row() column = index.column() try: newName = os.path.join(str(os.path.split(self._listdata[row][column])[0]), str(value.toString())) except IndexError: return self.__renameFile(self._listdata[row][column], newName) self._listdata[row][column] = newName self.dataChanged.emit(index, index) return True return False def selectonChanged(self, row, column): # TODO Image scale pass def __renameFile(self, fileToRename, newName): try: os.rename(str(fileToRename), newName) except Exception, err: print err class MyTableView(QtGui.QTableView): """docstring for MyTableView""" def __init__(self): super(MyTableView, self).__init__() self.setWindowFlags(QtCore.Qt.Widget | QtCore.Qt.FramelessWindowHint | QtCore.Qt.X11BypassWindowManagerHint) sw = QtGui.QDesktopWidget().screenGeometry(self).width() sh = QtGui.QDesktopWidget().screenGeometry(self).height() self.setGeometry(0,0,sw,sh) self.showFullScreen() thumbWidth = 300 thumbheight = 420 col = sw/thumbWidth self.setColumnWidth(thumbWidth, thumbheight) crntDir = "/Users/UserName/Pictures/" # create table list_data = [] philes = os.listdir(crntDir) for phile in philes: if phile.endswith(".png") or phile.endswith("jpg"): list_data.append(os.path.join(crntDir, phile)) _twoDLst = convertToTwoDList(list_data, col) lm = MyListModel(_twoDLst, col, (thumbWidth, thumbheight), self) self.setShowGrid(False) self.setWordWrap(True) self.setModel(lm) self.resizeColumnsToContents() self.resizeRowsToContents() def keyPressEvent(self, keyevent): """ Capture key to exit, next image, previous image, on Escape , Key Right and key left respectively. """ event = keyevent.key() if event == QtCore.Qt.Key_Escape: self.close() def convertToTwoDList(l, n): return [l[i:i+n] for i in range(0, len(l), n)] if __name__ == '__main__': app = QtGui.QApplication(sys.argv) window = MyTableView() window.show() window.raise_() sys.exit(app.exec_()) </code></pre>
[]
[ { "body": "<h2>Abstract Model</h2>\n\n<p>There are a few improvements I could see in your table model class:</p>\n\n<ol>\n<li>In <code>data()</code> you could use <code>elif</code> for all of the if-statements past the first. This will save the need to evaluate each if-condition after the first condition that was found to be <code>True</code></li>\n<li><p>Use <code>key in dict</code> notation. You have this line in your <code>data()</code> method:</p>\n\n<pre><code>if self.pixmap_cache.has_key(value) == False:\n</code></pre>\n\n<p>This can be written simpler and more Pythonic-ly as:</p>\n\n<pre><code>if not value in self.pixmap_cache:\n</code></pre></li>\n<li><p>In <code>setData()</code> you caste the result from <code>os.path.split()</code> to a <code>str</code>. This is not necessary as <code>os.path.split()</code> returns a tuple containing strings.</p></li>\n<li><p>Finally, in your <code>selectionChanged()</code> function, raise a <code>NotImplementedError</code> instead of <code>pass</code>ing. Just in case.</p></li>\n</ol>\n\n<h2>Table</h2>\n\n<ol>\n<li><p>In your <code>__init__()</code> function, you set the current directory. You have hard-coded some basic user information. Instead, use the function <code>os.path.expanduser</code>. This will expand <code>~</code> into the current user's information.</p>\n\n<pre><code>crntDir = os.path.expanduser('~/Pictures/')\n</code></pre></li>\n<li><p>In your for-loop checking for file extensions, you simply check for <code>phile.endswith('jpg')</code>. This will match <strong>anything</strong> that ends with <code>jpg</code>, including directories. Add the period and it will be fixed.</p></li>\n<li><p>There is no need to store <code>MyListModel</code> in a variable. Just go ahead and declare it in <code>self.setModel()</code>.</p></li>\n</ol>\n\n<h2>General Comments</h2>\n\n<ol>\n<li>In your <code>convertToTwoDList</code> function, make your variable names more descriptive. They are very ambiguous at the moment.</li>\n<li>Look over the PEP8 style guide. It will help your code look more Pythonic. A few examples:<br>\n<code>use_underscores</code> in variable names instead of <code>camelCase</code>. Keep consistent spacing throughout your code. Overall it looks very good, however there are times where you have double-blank lines in-between methods.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-17T01:19:36.533", "Id": "50976", "ParentId": "36843", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T10:29:40.790", "Id": "36843", "Score": "4", "Tags": [ "python", "unit-testing", "pyqt" ], "Title": "Modelview programming in PyQt4" }
36843
<p>I am having a structure of 3 tables</p> <pre><code>Table mintemp consist of matcode,min_qty,jo_no,mr_no Table min_out_body consist of matcode,out_qty,jo_no,mr_no Table eu_min_out_body consist of matcode,out_qty,jo_no,mr_no </code></pre> <p>And data as follow:</p> <pre><code>[mintemp] matcode min_qty jo_no mr_no xxx 100 1A A11 xxx 150 2A A22 [min_out_body] matcode out_qty jo_no mr_no xxx 10 1A A11 xxx 60 1A A11 xxx 100 2A A22 [eu_min_out_body] matcode out_qty jo_no mr_no xxx 20 1A A11 xxx 50 2A A22 </code></pre> <p>What i am trying to achieve is to have a result:</p> <pre><code>matcode min_qty jo_no mr_no balance xxx 100 1A A11 10 xxx 150 2A A22 0 </code></pre> <p>so far the query i am using is :</p> <pre><code>SELECT mintemp.matcode, mintemp.min_qty, (mintemp.min_qty-( select ifnull(sum(out_qty),0) FROM min_out_body WHERE matcode=mintemp.matcode and jo_no=mintemp.jo_no and mr_no=mintemp.mr_no )-( select ifnull(sum(out_qty),0) FROM eu_min_out_body WHERE matcode=mintemp.matcode and jo_no=mintemp.jo_no and mr_no=mintemp.mr_no ) ) as total FROM mintemp WHERE mintemp.matcode = 'xxx' and (mintemp.min_qty - (select ifnull(sum(out_qty),0) FROM min_out_body WHERE matcode = mintemp.matcode and jo_no = mintemp.jo_no and mr_no = mintemp.mr_no) - (select ifnull(sum(out_qty),0) FROM eu_min_out_body WHERE matcode = mintemp.matcode and jo_no = mintemp.jo_no and mr_no = mintemp.mr_no)) &gt; 0 </code></pre> <p>I can get the result, but is there any way to simplify the query and reduce the process time?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T14:16:40.373", "Id": "60630", "Score": "0", "body": "This code is not in working order. The query references min.min_no which does not exist. I vote to close... if you edit your question (to reopen it) I suggest that you change your table name 'min' to be something other than a reserved word which is a PITA to use as a table name. Also, please add a description of what you expect this SELECT statement to return." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T14:20:04.713", "Id": "60631", "Score": "1", "body": "Here is an SQLFiddle I tried to use, but failed.....: http://sqlfiddle.com/#!2/8eaee/2" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T14:53:40.780", "Id": "60633", "Score": "0", "body": "sorry for the table name, i have a `` between the table name to avoid any confusion. As for the result what i want i have state it clearly in question, i am able to get the result as what i am aiming at, but i would like to have another queries that probably can speed up, simplify the process and query" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T14:55:49.260", "Id": "60634", "Score": "1", "body": "You are missing the point... your query does not work... there is no column 'min_no'. CodeReview is for **working** code. Fix your query, and while you are at it, make it easier to use with a table name other than 'min'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T15:06:34.813", "Id": "60636", "Score": "0", "body": "sorry, i have correct the query and has been tested in http://sqlfiddle.com/#!2/4c8ee/2" } ]
[ { "body": "<p>I have had a play with your query. I don't believe there is a way to do the query without the sub-selects in the select fields... but, you can use the <code>having</code> to avoid the duplication of the code (and processing effort) to limit your results to just those with a positive target. Additionally, because there may be values with different <code>jo_no</code> and <code>mr_no</code> combinations, you should also select those values too:</p>\n\n<pre><code>SELECT\nmintemp.matcode,\nmintemp.jo_no,\nmintemp.mr_no,\nmintemp.min_qty,\n(mintemp.min_qty-(\n select ifnull(sum(out_qty),0) \n FROM min_out_body \n WHERE matcode=mintemp.matcode \n and jo_no=mintemp.jo_no \n and mr_no=mintemp.mr_no\n )-(\n select ifnull(sum(out_qty),0) \n FROM eu_min_out_body \n WHERE matcode=mintemp.matcode \n and jo_no=mintemp.jo_no \n and mr_no=mintemp.mr_no\n )\n) as total\nFROM mintemp\nWHERE mintemp.matcode = 'xxx'\nHAVING total &gt; 0\n</code></pre>\n\n<p>I have updated the fiddle:</p>\n\n<p><a href=\"http://sqlfiddle.com/#!2/5c9de/7\" rel=\"nofollow\">http://sqlfiddle.com/#!2/5c9de/7</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T15:34:44.533", "Id": "36858", "ParentId": "36847", "Score": "3" } }, { "body": "<pre><code>SELECT\n mintemp.matcode,\n mintemp.min_qty,\n (mintemp.min_qty\n - IFNULL(min_out_body.min_out_body_sum,0)\n - IFNULL(eu_min_out_body.eu_min_out_body_sum,0)\n ) as total\nFROM mintemp\nLEFT JOIN (\n SELECT jo_no, mr_no, matcode, SUM(out_qty) AS min_out_body_sum \n FROM min_out_body\n GROUP BY jo_no, mr_no, matcode\n) AS min_out_body ON min_out_body.matcode = mintemp.matcode \n AND min_out_body.jo_no = mintemp.jo_no \n AND min_out_body.mr_no = mintemp.mr_no\nLEFT JOIN (\n SELECT jo_no, mr_no, matcode, SUM(out_qty) AS eu_min_out_body_sum\n FROM eu_min_out_body\n GROUP BY jo_no, mr_no, matcode\n) AS eu_min_out_body ON eu_min_out_body.matcode = mintemp.matcode \n AND eu_min_out_body.jo_no = mintemp.jo_no \n AND eu_min_out_body.mr_no = mintemp.mr_no\nWHERE mintemp.matcode = 'xxx'\n AND (mintemp.min_qty\n - IFNULL(min_out_body.min_out_body_sum,0)\n - IFNULL(eu_min_out_body.eu_min_out_body_sum,0)\n ) &gt; 0\n</code></pre>\n\n<p>If this query performance slow then check the indexing on your server (EXPLAIN). The important thing is that with SQL server we have to work with small number of huge result sets instead of a lot of small subqueries.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T07:07:27.917", "Id": "60696", "Score": "0", "body": "That's also more or less how I would do it. I'd incorporate @rolfl's suggestion to use `HAVING total > 0` to simplify where WHERE clause." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T07:57:16.687", "Id": "60699", "Score": "2", "body": "With strict SQL query rules you can not have HAVING without a GROUP BY statement (or it will be executed as WHERE) and i think alias names can not be used in the expression. I'm not sure about these things i'm mostly working with MSSQL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T08:05:54.723", "Id": "60700", "Score": "0", "body": "You're right. [MySQL ≥ 5.0.2 supports](http://dev.mysql.com/doc/refman/5.0/en/select.html#idm47613761414512) `HAVING total > 0` even though it's not standard SQL." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T06:44:15.517", "Id": "36887", "ParentId": "36847", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T12:39:26.747", "Id": "36847", "Score": "3", "Tags": [ "mysql", "sql" ], "Title": "Optimized Query" }
36847
<p>I have a nested array that returns objects which are then traversed to retrirve the <code>id</code>s, which are then used to retrieve another array, which is traversed and the values returned are echoed out.</p> <p>The problem is this seems to take ages in the browser to work across. How do I go about speeding this up?</p> <p>This is the first function: </p> <pre><code> /** * Get a page of Campaigns * @param string $page - url to page of campaigns, default is first page * @return array - array of Campaign objects and a link to the next page if one exists */ public function getCampaigns($page=null){ $page = ($page) ? $this-&gt;CTCTRequest-&gt;baseUri.$page : $this-&gt;uri; $campaignsCollection = array('campaigns' =&gt; array(), 'nextLink' =&gt; ''); $response = $this-&gt;CTCTRequest-&gt;makeRequest($page, 'GET'); $parsedResponse = simplexml_load_string($response['xml']); foreach ($parsedResponse-&gt;entry as $entry){ $campaignsCollection['campaigns'][] = new Campaign(Campaign::createOverviewStruct($entry)); } $campaignsCollection['nextLink'] = Utility::findNextLink($parsedResponse); return $campaignsCollection; } </code></pre> <p>This is the second function: </p> <pre><code>/** * Get detailed Campaign object * @param string $url - url of a Campiagn * @return Campaign */ public function getCampaignDetails($url){ $response = $this-&gt;CTCTRequest-&gt;makeRequest($url, 'GET'); $parsedReturn = simplexml_load_string($response['xml']); return new Campaign(Campaign::createStruct($parsedReturn)); } </code></pre> <p>This is the code that traverses both of these and returns my values: </p> <pre><code>&lt;?php /* * * *grab the Campaign array * * */ $getallCampaigns = $ConstantContact-&gt;getCampaigns(false); ?&gt; &lt;table class="CTCTtable"&gt; &lt;tr&gt; &lt;th&gt;Campaign Name&lt;/th&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Status&lt;/th&gt; &lt;th&gt;Sent#&lt;/th&gt; &lt;th&gt;Opens&lt;/th&gt; &lt;th&gt;Clicks&lt;/th&gt; &lt;th&gt;Bounces&lt;/th&gt; &lt;th&gt;Forwards&lt;/th&gt; &lt;th&gt;OptOuts&lt;/th&gt; &lt;th&gt;SpamReports&lt;/th&gt; &lt;/tr&gt; &lt;?php foreach ($getallCampaigns as $tableName =&gt; $tableData) { // Loop outer array foreach ($tableData as $row) { // Loop table rows $originalDate = $row-&gt;campaignDate; $newDate = date("d-m-Y", strtotime($originalDate)); //get campaign details $getallCampaignevents = $ConstantContact-&gt;getCampaignDetails($row); //$getallCampaignsends = $ConstantContact-&gt;getCampaignSends($row); // //echo $getallCampaignevents-&gt;name; echo '&lt;tr&gt;'; echo '&lt;td&gt;&lt;a title="'.$getallCampaignevents-&gt;name.'"href="'.$getallCampaignevents-&gt;id.'"&gt;'.$getallCampaignevents-&gt;name.'&lt;/a&gt;&lt;/td&gt;'; echo '&lt;td&gt;'.$newDate.'&lt;/td&gt;'; echo '&lt;td&gt;'.$getallCampaignevents-&gt;status.'&lt;/td&gt;'; echo '&lt;td&gt;'.$getallCampaignevents-&gt;campaignSent.'&lt;/td&gt;'; echo '&lt;td&gt;'.$getallCampaignevents-&gt;campaignOpens.'&lt;/td&gt;'; echo '&lt;td&gt;'.$getallCampaignevents-&gt;campaignClicks.'&lt;/td&gt;'; echo '&lt;td&gt;'.$getallCampaignevents-&gt;campaignBounces.'&lt;/td&gt;'; echo '&lt;td&gt;'.$getallCampaignevents-&gt;campaignForwards.'&lt;/td&gt;'; echo '&lt;td&gt;'.$getallCampaignevents-&gt;campaignOptOuts.'&lt;/td&gt;'; echo '&lt;td&gt;'.$getallCampaignevents-&gt;campaignSpamReports.'&lt;/td&gt;'; echo '&lt;/tr&gt;'; // var_dump($getallCampaignevents); } } ?&gt; &lt;/table&gt; </code></pre> <p>Here is an example of the first returned array: </p> <pre><code> array(2) { ["campaigns"]=&gt; array(50) { [0]=&gt; object(Campaign)#68 (48) { ["name"]=&gt; string(26) "*****************************" ["id"]=&gt; string(74) "***********************************************" ["link"]=&gt; string(44) "************************" ["status"]=&gt; string(4) "Sent" ["campaignDate"]=&gt; string(24) "2013-12-05T21:28:07.330Z" ["urls"]=&gt; array(0) { } } [1]=&gt; object(Campaign)#68 (48) { ["name"]=&gt; string(26) "*****************************" ["id"]=&gt; string(74) "***********************************************" ["link"]=&gt; string(44) "************************" ["status"]=&gt; string(4) "Sent" ["campaignDate"]=&gt; string(24) "2013-12-05T21:28:07.330Z" ["urls"]=&gt; array(0) { } } } </code></pre> <p>This is the second returend array: </p> <pre><code> object(Campaign)#64 (48) { ["name"]=&gt; string(26) "*************" ["id"]=&gt; string(74) "***************" ["link"]=&gt; string(44) "************************" ["status"]=&gt; string(4) "Sent" ["campaignDate"]=&gt; string(24) "2013-12-05T21:28:07.330Z" ["lastEditDate"]=&gt; string(24) "2013-12-02T14:52:13.629Z" ["lastRunDate"]=&gt; string(24) "2013-12-05T21:28:07.327Z" ["campaignSent"]=&gt; string(2) "13" ["campaignOpens"]=&gt; string(1) "8" ["campaignClicks"]=&gt; string(1) "5" ["campaignBounces"]=&gt; string(1) "0" ["campaignForwards"]=&gt; string(1) "0" ["campaignOptOuts"]=&gt; string(0) "" ["campaignSpamReports"]=&gt; string(0) "" ["subject"]=&gt; string(33) "Offers, and your feedback please!" ["fromName"]=&gt; string(18) "***************" ["campaignType"]=&gt; string(5) "STOCK" ["hiveStatus"]=&gt; string(0) "" ["archiveUrl"]=&gt; string(0) "" } object(Campaign)#56 (56) { ["name"]=&gt; string(26) "*************" ["id"]=&gt; string(74) "***************" ["link"]=&gt; string(44) "************************" ["status"]=&gt; string(4) "Sent" ["campaignDate"]=&gt; string(24) "2013-12-05T21:28:07.330Z" ["lastEditDate"]=&gt; string(24) "2013-12-02T14:52:13.629Z" ["lastRunDate"]=&gt; string(24) "2013-12-05T21:28:07.327Z" ["campaignSent"]=&gt; string(2) "13" ["campaignOpens"]=&gt; string(1) "8" ["campaignClicks"]=&gt; string(1) "5" ["campaignBounces"]=&gt; string(1) "0" ["campaignForwards"]=&gt; string(1) "0" ["campaignOptOuts"]=&gt; string(0) "" ["campaignSpamReports"]=&gt; string(0) "" ["subject"]=&gt; string(33) "" ["fromName"]=&gt; string(18) "***************" ["campaignType"]=&gt; string(5) "STOCK" ["hiveStatus"]=&gt; string(0) "" ["archiveUrl"]=&gt; string(0) "" } </code></pre> <p>I'm using Constant Contact's OAuth's API with this PHP wrapper to return these arrays, <a href="https://github.com/shannon7wallace/OAuth-2-PHP-Example" rel="nofollow">which can be found here</a>.</p>
[]
[ { "body": "<p>It takes \"ages\" because it's having to do requests out to the Internet itself, as can be seen here</p>\n\n<pre><code>$response = $this-&gt;CTCTRequest-&gt;makeRequest($url, 'GET');\n$parsedReturn = simplexml_load_string($response['xml']);\n</code></pre>\n\n<p>These requests will quickly dominate the performance of your code. You should go through your code carefully to see where it's making requests, and see if you can eliminate some of them, say, by caching results or batching requests.</p>\n\n<p>Currently you have (at least) 1 + <em>n</em> requests made by the loop, where <em>n</em> is the number of iterations. No wonder it is slow!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T22:04:54.220", "Id": "60774", "Score": "0", "body": "how do i go about caching the results?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T01:51:06.083", "Id": "60788", "Score": "0", "body": "If you own the site in question, getting the data to be stored in a database is probably the way to go. Otherwise, do the request to the Internet and store the result locally (in a database) only if you've not done that exact same request before, and if you *have* done that request before you can avoid the request by looking up what happened last time in your database." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T09:44:52.330", "Id": "36894", "ParentId": "36860", "Score": "4" } } ]
{ "AcceptedAnswerId": "36894", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T15:56:17.470", "Id": "36860", "Score": "0", "Tags": [ "php" ], "Title": "foreach loop too slow?" }
36860
<p>I have a bit of code that converts a Sql Like expression to a regex expression for the purposes of a Linq to objects <code>Like</code> extension method. For some time I have been using <a href="http://bytes.com/topic/c-sharp/answers/253519-using-regex-create-sqls-like-like-function" rel="nofollow">this conversion</a>.</p> <p>This conversion replaces all "%" with ".*?" which works for contains patterns but is over matching for starts with or ends with patterns. So the conversion of <code>%abc</code> to <code>.*?abc</code> is capturing both "abcdef" and "123abcdef".</p> <p>I've amended the conversion algorithm to account for starts with and ends with LIKE expressions.</p> <p>Here is my code:</p> <pre><code>internal static string ConvertLikeToRegex(string pattern) { // Turn "off" all regular expression related syntax in the pattern string. StringBuilder builder = new StringBuilder(Regex.Escape(pattern)); // these are needed because the .*? replacement below at the begining or end of the string is not // accounting for cases such as LIKE '%abc' or LIKE 'abc%' bool startsWith = pattern.StartsWith("%") &amp;&amp; !pattern.EndsWith("%"); bool endsWith = !pattern.StartsWith("%") &amp;&amp; pattern.EndsWith("%"); // this is a little tricky // ends with in like is '%abc' // in regex it's 'abc$' // so need to tanspose if (startsWith) { builder.Replace("%", "", 0, 1); builder.Append("$"); } // same but inverse here if (endsWith) { builder.Replace("%", "", pattern.Length - 1, 1); builder.Insert(0, "^"); } /* Replace the SQL LIKE wildcard metacharacters with the * equivalent regular expression metacharacters. */ builder.Replace("%", ".*?").Replace("_", "."); /* The previous call to Regex.Escape actually turned off * too many metacharacters, i.e. those which are recognized by * both the regular expression engine and the SQL LIKE * statement ([...] and [^...]). Those metacharacters have * to be manually unescaped here. */ builder.Replace(@"\[", "[").Replace(@"\]", "]").Replace(@"\^", "^"); return builder.ToString(); } </code></pre> <p>My initial units test are passing but not being overly conversant in regex syntax I am wondering if this is the best approach or if there are gaps in the conversion I am not seeing.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T16:16:31.770", "Id": "60642", "Score": "0", "body": "What if it starts with and endsWith? I don't understand the need for startsWith to check that it doesn't also endWith" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T16:26:50.567", "Id": "60645", "Score": "0", "body": "LIKE '%abc%' (i.e. contains) converts to \".*?abc.*?\" which captures abcdef and 123abcdef\nThe regex ^abc$ (which is what would happen without those tests) only captures strings both starting and ending with abc." } ]
[ { "body": "<p>I think you're overcomplicating this and your code still doesn't work correctly. The LIKE pattern <code>bcd</code> shouldn't match <code>abcde</code>, but it does with your code.</p>\n\n<p>What you should do is to <em>always</em> add <code>^</code> at the start and <code>$</code> at the end.</p>\n\n<p>This means the following conversions:</p>\n\n<ul>\n<li><code>bcd</code> → <code>^bcd$</code></li>\n<li><code>%bcd</code> → <code>^.*?bcd$</code></li>\n<li><code>bcd%</code> → <code>^bcd.*?$</code></li>\n<li><code>%bcd%</code> → <code>^.*?bcd.*?$</code></li>\n</ul>\n\n<p>In the cases where the pattern starts with <code>%</code>, the <code>^</code> is not necessary (and similarly for <code>$</code> and <code>%</code> at the end), but it also doesn't do any harm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T17:12:19.173", "Id": "60650", "Score": "0", "body": "Even simpler than my suggestion. Nice!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T17:22:18.190", "Id": "60651", "Score": "0", "body": "Perfect. Works like a charm. I figured I was missing something much more straightforward." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:54:55.590", "Id": "60661", "Score": "0", "body": "nb: \"?\" is not needed since LIKE will always match the entire string anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T20:10:21.693", "Id": "60662", "Score": "0", "body": "@Sylverdrag Yeah, I think you're right, I just copied that from the code in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T17:11:49.027", "Id": "486574", "Score": "1", "body": "BUT, note that regex treats some string literals like `.` as special selectors. So, for a LIKE fragment `asdf.qwer%` with (python syntax) regex `re.match('^asdf.qwer.*$', 'asdfXqwer') ` will result in a match incorrectly because `.` means \"any single character here\". You also need to escape any regex-special chars in LIKE fragment before piping to regex. Example in this case: `re.match('^asdf\\.qwer.*$', 'asdfXqwer') ` == proper no match" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T02:41:04.397", "Id": "514589", "Score": "0", "body": "Why do you need the wildcards any of those examples? `%bcd` or _ends with_ would be the same as the regular expression `/bcd$/`, `%bcd%` is just `/bcd/`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T17:10:07.813", "Id": "36864", "ParentId": "36861", "Score": "10" } }, { "body": "<p>Your name \"startsWith\" is confusing because it looks at both ends, and controls the placement of the trailing $. I'd simplify this:</p>\n\n<pre><code>bool startsWith = pattern.StartsWith(\"%\") &amp;&amp; !pattern.EndsWith(\"%\");\nbool endsWith = !pattern.StartsWith(\"%\") &amp;&amp; pattern.EndsWith(\"%\");\n\nif (startsWith)\n{\n builder.Replace(\"%\", \"\", 0, 1);\n builder.Append(\"$\");\n}\nif (endsWith)\n{\n builder.Replace(\"%\", \"\", pattern.Length - 1, 1);\n builder.Insert(0, \"^\");\n}\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>bool leadingLiteral = !pattern.StartsWith(\"%\");\nif (leadingLiteral)\n{\n builder.Insert(0, \"^\");\n}\n\nbool trailingLiteral = !pattern.EndsWith(\"%\");\nif (trailingLiteral)\n{\n builder.Append(\"$\");\n}\n</code></pre>\n\n<p>You may also note that I left the named Boolean variables in the code. I like using \"explanatory variables\" instead of comments. The optimizer will get rid of them in a production build, so they cost nothing to the runtime. But I think they make the code more readable and therefore more maintainable. They encourage you, the developer, to think about what you're doing. And they encourage you to think of an appropriate name. If you find it hard to name a thing, that may be a sign that it's unclear, or is doing too much.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T17:10:35.540", "Id": "36865", "ParentId": "36861", "Score": "4" } }, { "body": "<p>In LIKE patterns, the interpretation of characters between square brackets is more literal than normal. What SQL dialect are you targeting? See, for example, the <a href=\"http://technet.microsoft.com/en-us/library/ms179859.aspx\" rel=\"nofollow\">T-SQL documentation for <code>LIKE</code></a> (under <em>Using Wildcard Characters as Literals</em>). <code>LIKE '5[%]'</code> should be translated as regex <code>'^5%$'</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T18:14:21.527", "Id": "60653", "Score": "0", "body": "I think a more natural (and equivalent) translation would be `^5[%]$`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T17:25:30.233", "Id": "36866", "ParentId": "36861", "Score": "3" } }, { "body": "<p>Because the <code>LIKE</code> clause has a defined syntax, to do this right (meaning no clause will be incorrectly converted), you will need to use (or create) a simple lexer to parse the <code>LIKE</code> clause. A sample grammar could look like:</p>\n\n<pre><code>expr := wild-card + expr\n | wild-char + expr\n | escape + expr\n | string + expr\n | \"\"\n\nwild-card := % \nwild-char := _ \nescape := [%|_] \nstring := [^%_]+ (One or &gt; more characters that are not wild-card or wild-char)\n</code></pre>\n\n<p>NOTE: Although the above grammar will work by default, note that SQL allows the user to specify a user-defined <code>ESCAPE</code> character (see <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql?view=sql-server-2017#pattern-matching-with-the-escape-clause\" rel=\"nofollow noreferrer\">T-SQL</a>)</p>\n\n<p>The steps to accomplish the <code>LIKE</code> syntax conversion are as follows:</p>\n\n\n\n<ol>\n<li><p>Define your Token classes:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public abstract class Token {\n private final String value;\n\n public Token(String value) {\n this.value = value;\n }\n\n public abstract String convert();\n\n public String getValue() {\n return value;\n }\n}\n\npublic class EscapeToken extends Token {\n public EscapeToken(String value) {\n super(value);\n }\n\n @Override\n public String convert() {\n return getValue();\n }\n}\n\npublic class WildcardToken extends Token {\n public WildcardToken(String value) {\n super(value);\n }\n\n @Override\n public String convert() {\n return \".*\";\n }\n}\n\npublic class WildcharToken extends Token {\n public WildcharToken(String value) {\n super(value);\n }\n\n @Override\n public String convert() {\n return \".\";\n }\n}\n\npublic class StringToken extends Token {\n public StringToken(String value) {\n super(value);\n }\n\n @Override\n public String convert() {\n return Pattern.quote(getValue());\n }\n}\n</code></pre></li>\n<li><p>Create a Lexer (or Tokenizer):</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Tokenizer {\n\n private Collection&lt;Tuple&gt; patterns = new LinkedList&lt;&gt;();\n\n public &lt;T extends Token&gt; Tokenizer add(String regex, Function&lt;String, Token&gt; creator) {\n this.patterns.add(Tuple.of(Pattern.compile(regex), creator));\n return this;\n }\n\n public Collection&lt;Token&gt; tokenize(String clause) throws ParseException {\n Collection&lt;Token&gt; tokens = new ArrayList&lt;&gt;();\n String copy = String.copyValueOf(clause.toCharArray());\n\n int position = 0;\n while (!copy.equals(\"\")) {\n boolean found = false;\n for (Tuple tuple : this.patterns) {\n Pattern pattern = tuple.get(0, Pattern.class);\n Matcher m = pattern.matcher(copy);\n if (m.find()) {\n found = true;\n String token = m.group(1);\n Function&lt;String, Token&gt; fn = (Function&lt;String, Token&gt;) tuple.get(1);\n tokens.add(fn.apply(token));\n copy = m.replaceFirst(\"\");\n position += token.length();\n break;\n }\n }\n\n if (!found) {\n throw new ParseException(\"Unexpected sequence found in input string.\", ++position);\n }\n }\n\n return tokens;\n\n }\n}\n</code></pre></li>\n<li><p>Create SQL <code>LIKE</code> to RegEx Transpiler:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class SqlLikeTranspiler {\n private static Tokenizer TOKENIZER = new Tokenizer()\n .add(\"^(\\\\[[^]]*])\", ConstantToken::new)\n .add(\"^(%)\", WildcardToken::new)\n .add(\"^(_)\", WildcharToken::new)\n .add(\"^([^\\\\[\\\\]%_]+)\", StringToken::new);\n\n public static String toRegEx(String pattern) throws ParseException {\n StringBuilder sb = new StringBuilder().append(\"^\");\n for (Token token : TOKENIZER.tokenize(pattern)) {\n sb.append(token.convert());\n }\n\n return sb.append(\"$\").toString();\n }\n}\n</code></pre></li>\n</ol>\n\n<p>NOTE: We ensure the match is not too generous by indicating the resulting regular expression has start and end tags (<code>^</code> and <code>$</code> respectively).</p>\n\n<p>By creating a lexer and converting using this methodology, we can prevent <code>LIKE</code> clauses like <code>%abc[%]%</code>, which should match any string with the sub-string <code>abc%</code> in it, from being converted to a regular expression like <code>.*abc[.*].*</code> which will match any string with either the sub-string <code>abc.</code> or <code>abc*</code>.</p>\n\n<p>The provided code is Java.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-12T16:31:01.423", "Id": "207486", "ParentId": "36861", "Score": "5" } }, { "body": "<p>See @svick excellent answer, but, note that it does not account for regex special syntax character escaping.</p>\n<p>Literals like <code>.</code> are special selectors in <strong>regex</strong>. So, for a LIKE fragment <code>asdf.qwer%</code> a (python syntax) regex <code>re.match('^asdf.qwer.*$', 'asdfXqwer')</code> would INCORRECTLY match because <code>.</code> means &quot;any single character here&quot;.</p>\n<p>You also need to escape any regex-special chars in LIKE fragment before piping to regex. Example in this case: <code>re.match('^asdf\\.qwer.*$', 'asdfXqwer')</code> == proper no match.</p>\n<p>Ansi SQL special characters <code>%</code> and <code>_</code> are wonderfully NOT regex special selector characters. So, it's super easy to escape ANSI SQL like fragments, and then replace <code>%</code> and <code>_</code> with regex eqivalents.</p>\n<pre><code># Python example\n# note that in python, you need to escape `\\` in code too :) \n# resulting in `\\\\` in code representation. print the string to see single `\\`\n\n_special_regex_chars = {\n ch : '\\\\'+ch\n for ch in '.^$*+?{}[]|()\\\\'\n}\n\ndef _sql_like_fragment_to_regex_string(fragment):\n # https://codereview.stackexchange.com/a/36864/229677\n safe_fragment = ''.join([\n _special_regex_chars.get(ch, ch)\n for ch in fragment\n ])\n return '^' + safe_fragment.replace('%', '.*?').replace('_', '.') + '$'\n</code></pre>\n<p>Or, in one go (because there is no overlap between ANSI SQL selectors and Python Regex selectors):</p>\n<pre><code>_char_regex_map = {\n ch : '\\\\'+ch\n for ch in '.^$*+?{}[]|()\\\\'\n}\n_char_regex_map['%'] = '.*?'\n_char_regex_map['_'] = '.'\n\ndef sql_like_fragment_to_regex_string(fragment):\n return '^' + ''.join([\n _char_regex_map.get(ch, ch)\n for ch in fragment\n ]) + '$'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T17:56:24.120", "Id": "248421", "ParentId": "36861", "Score": "2" } } ]
{ "AcceptedAnswerId": "36864", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T15:56:58.033", "Id": "36861", "Score": "3", "Tags": [ "c#", "sql", "linq", "regex", "converting" ], "Title": "Convert Sql LIKE to Regex" }
36861
<p>I have the following code that reads a .csv file that than outputs the result in the form of a HTML table:</p> <pre><code>$fhdrop = fopen("ac.csv", "r"); while (!feof($fhdrop) ) { $at[] = fgetcsv($fhdrop, 1024); } $fhdrop2 = fopen("rc.csv", "r"); while (!feof($fhdrop2) ) { $at2[] = fgetcsv($fhdrop2, 1024); } ?&gt; &lt;table border=1&gt; &lt;tr&gt; &lt;td&gt;a&lt;/td&gt; &lt;td&gt;b&lt;/td&gt; &lt;td&gt;c&lt;/td&gt; &lt;td&gt;d&lt;/td&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $at[0][0] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $at[0][1] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo number_format($at[0][1]*$at2[0][1],2) ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo number_format($at[0][1]*$at2[1][1],2) ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $at[1][0] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $at[1][1] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo number_format($at[1][1]*$at2[0][1],2) ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo number_format($at[1][1]*$at2[1][1],2) ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $at[2][0] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $at[2][1] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo number_format($at[2][1]*$at2[0][1],2) ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo number_format($at[2][1]*$at2[1][1],2) ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $at[3][0] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $at[3][1] ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo number_format($at[3][1]*$at2[0][1],2) ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo number_format($at[3][1]*$at2[1][1],2) ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>The contents of ac.csv are:</p> <pre><code>a, 5, b, 10, c, 24, d, 21 </code></pre> <p>The contents of rc.csv are:</p> <pre><code>not, 1.87, notatall, 1.78 </code></pre> <p>As you can guess from the original code, I need to do multiplication in the second column. In the second row and third column, for instance, I need 5*1.87 and 5*1.78. So basically <code>a</code> * <code>not</code> and <code>a</code> * <code>notatall</code>.</p> <p>My code is not very efficient. How can I make it more efficient?</p>
[]
[ { "body": "<p>Looping on feof is wrong. <code>feof</code> doesn't return return true until <em>after</em> you've hit the end of file. If the read pointer is sitting past the last character and you try to read, feof will return false, but the read will fail. At that point feof will return true.</p>\n\n<p>Example: </p>\n\n<pre><code>1, a, b, c\n2, a, b, c\n3, a, b, c\n</code></pre>\n\n<p>Then reading it:</p>\n\n<pre><code>$rows = array();\nwhile (!feof($fh)) {\n $rows[] = fgetcsv($fh);\n}\nprint_r($rows);\n</code></pre>\n\n<p>A much more natural (and correct) loop structure is as follows:</p>\n\n<pre><code>while (($row = fgetcsv($fh)) !== false) {\n $rows[] = $row;\n}\n</code></pre>\n\n<p>(You can of course use <code>fgetcsv($fh, 1024)</code> instead of <code>fgetcsv($fh)</code>. Just an example.)</p>\n\n<hr>\n\n<p>As far performance goes, you're doing what you're doing as fast as it can be done. In other words, to get a speed increase, the approach has to change, not the implementation.</p>\n\n<p>There are three main approaches that you can take (that can all be combined as desired): use caching, put the HTML output straight into the first loop so you only do one loop instead of two, and try using a fixed field-size format rather than CSV so parsing overhead can be eliminated.</p>\n\n<p>Putting the HTML output straight into the read loop is very gross from a separation of concerns perspective, and the gains would be minimal compared to the code quality hit.</p>\n\n<p>Likewise, changing to a fixed size format would be a fairly minimal performance gain for quite a bit of headache.</p>\n\n<p>Caching is what you need to do. A primitive approach is to just create an on-disk version of the array and read that rather than the CSV. A slightly more complex but much faster approach is to cache the CSV in memory using <code>apc</code> or even something like <code>memcached</code> (memcached is way overkill, as is arguably apc). Yet another approach is cache the output HTML rather than the array. This allows you to serve a static page rather than regenerate it each request. You can't get any faster than that.</p>\n\n<p>Since the idea remains largely the same, I'll show an example of the simplest one to implement: caching the array.</p>\n\n<pre><code>$csvFilePath = \"...\";\n$cacheFilePath = \"...\";\n\nif (!file_exists($cacheFilePath) || filemtime($csvFilePath) &gt; $cacheFilePath) {\n $fh = fopen($cacheFilePath, 'r');\n $rows = array();\n while (($row = fgetcsv($fh)) !== false) {\n $rows[] = $row;\n }\n file_put_contents($cacheFilePath, serialize($rows));\n} else {\n $rows = unserialize(file_get_contents($cacheFilePath));\n}\n</code></pre>\n\n<p>Though this one is very simple, it's also the least effective. I would cache the entire page output. I would probably use something like Zend_Cache or Symfony's caching component to avoid lots of nasty manual output buffer management. Alternatively, you could write your own simple page cache.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:38:56.603", "Id": "36871", "ParentId": "36863", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T17:08:57.080", "Id": "36863", "Score": "3", "Tags": [ "php", "optimization", "csv" ], "Title": "How to make this csv-reading PHP code more efficient?" }
36863
<p>I wrote this script as a proof of concept of reading a file from disk as variable-length quantities (ints encoded using 7 bits from as many bytes as required). I'm mostly making use of the file system ReadStream, for reading byte buffers from files and the <em>varint</em> package for decoding variable length values.</p> <p>This is is my first attempt at working with nodejs. When I tested it on a 1GB file read from SSD, it took about 7 minutes during which it used about 50mb of ram and saturated one CPU core.</p> <p>So my question is, is there anything I'm doing here which could be optimised for CPU load?</p> <pre><code>var fs, vi, sys, rs, ints, total, remainder; fs = require('fs'); vi = require('varint'); sys = require('sys'); rs = fs.createReadStream('/path/to/datafile'); total = 0; // a buffer for carrying over incomplete values between chunks remainder = new Buffer(0); rs.on('data', function(chunk) { var buffer, value, byteLen; buffer = Buffer.concat([remainder, chunk]); while(buffer.length){ // decode the value and check how many bytes it required value = vi.decode(buffer); byteLen = vi.decode.bytesRead; if (byteLen &lt;= buffer.length){ // keep the result and update position in the buffer total += value; } else { // result is incomplete, store remainder to be prepended to the next chunk remainder = new Buffer(buffer.length); buffer.copy(remainder); } // shift decoded bytes off the buffer buffer = buffer.slice(byteLen); } }); // display grand total after the whole file has been read rs.on('end', function() { sys.puts((total)); }); </code></pre>
[]
[ { "body": "<p>It turns out it was possible to increase the speed about <strong>12 times</strong> by using the offset argument of <code>varint.decode</code> to traverse the buffer rather than slicing read bytes off of the buffer for each value.</p>\n\n<pre><code>rs.on('data', function(buffer) {\n var buffer, value, byteLen, offset;\n\n if (remainder) {\n buffer = Buffer.concat([remainder, buffer]); \n remainder = null;\n } \n\n offset = 0;\n\n while(offset &lt; buffer.length){\n // decode the value and check how many bytes it required\n value = vi.decode(buffer, offset);\n offset += vi.decode.bytesRead;\n\n if (offset &lt;= buffer.length){\n // keep the result and update position in the buffer\n total += value;\n } else {\n // result is incomplete, store remainder to be prepended to the next chunk\n remainder = new Buffer(buffer.length - offset);\n buffer.copy(remainder, 0, offset);\n }\n }\n});\n</code></pre>\n\n<p>Much better.</p>\n\n<p>UPDATED to incorporate suggestions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:47:29.747", "Id": "60660", "Score": "1", "body": "Don't you need to clear `remainder` when `buffer` is fully read? It looks like you will end up duplicating it when the `offset` reaches `buffer.length` exactly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T00:05:58.483", "Id": "60684", "Score": "0", "body": "Good point! And clearing remainder also means I can change make buffer the argument (saving an assignment) and only perform a buffer concatenation when necessary. Which seems to offer a marginal further improvement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:30:22.213", "Id": "36869", "ParentId": "36868", "Score": "3" } }, { "body": "<p>As you found, the key is to reduce the number of buffer manipulations. You could reduce it further by inserting the remainder of the previous buffer into the beginning of the new chunk, assuming <code>Buffer</code> supports this operation and that <code>concat</code> doesn't already optimize this by keeping both buffers separate and bridging the gap in <code>decode</code>.</p>\n\n<p>I'm not familiar with any of these libraries so I won't attempt to code it up exactly.</p>\n\n<pre><code>on data\n if there is a remainder\n insert remainder before chunk\n process chunk\n calculate remainder but don't copy it to a new buffer\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:50:12.133", "Id": "36872", "ParentId": "36868", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T18:42:54.090", "Id": "36868", "Score": "2", "Tags": [ "javascript", "node.js", "stream" ], "Title": "Streaming variable length integers from a file" }
36868
<p>This is following up on my <a href="https://codereview.stackexchange.com/questions/36841/poker-hand-evaluator-challenge">previous attempt</a>, which was admittedly <em>done fast</em> and not-so-well. This code attempts to allow comparing two poker hands to determine a winner, not only evaluating a given set of cards. (this was actually edited - <a href="https://codereview.stackexchange.com/revisions/36873/2">see original take 2 here</a>).</p> <p>I'm abstracting the dirt away into an interface... and yet it doesn't look very clean to me, but maybe it's just because I don't use <code>Tuple&lt;T1,T2&gt;</code> very often. T1 is a <code>bool</code> indicating whether the hand is matched, T2 contains the winning cards.</p> <pre><code>public interface IPokerHandEvaluator { Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsPair(IEnumerable&lt;PlayingCard&gt; cards); Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsTwoPair(IEnumerable&lt;PlayingCard&gt; cards); Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsThreeOfKind(IEnumerable&lt;PlayingCard&gt; cards); Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsFourOfKind(IEnumerable&lt;PlayingCard&gt; cards); Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsFlush(IEnumerable&lt;PlayingCard&gt; cards); Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsFullHouse(IEnumerable&lt;PlayingCard&gt; cards); Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsStraight(IEnumerable&lt;PlayingCard&gt; cards); Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsStraightFlush(IEnumerable&lt;PlayingCard&gt; cards); Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsRoyalFlush(IEnumerable&lt;PlayingCard&gt; cards); } </code></pre> <p>This is my current implementation - it correctly evaluates all 5-card hands, and I've tested it correctly evaluates a <strong>Straight Flush</strong> (ace low) with a 7-card hand as well. So it works, but it doesn't make a good marketing for <code>Tuple&lt;T1,T2&gt;</code>:</p> <pre><code>public class PokerHandEvaluator : IPokerHandEvaluator { private IEnumerable&lt;IGrouping&lt;CardNominalValue, PlayingCard&gt;&gt; GroupByNominalValue(IEnumerable&lt;PlayingCard&gt; cards) { return cards.GroupBy(card =&gt; card.NominalValue); } private IEnumerable&lt;IGrouping&lt;CardNominalValue, PlayingCard&gt;&gt; Pairs(IEnumerable&lt;PlayingCard&gt; cards) { return GroupByNominalValue(cards).Where(group =&gt; group.Count() == 2); } private IEnumerable&lt;IGrouping&lt;CardNominalValue, PlayingCard&gt;&gt; Triplets(IEnumerable&lt;PlayingCard&gt; cards) { return GroupByNominalValue(cards).Where(group =&gt; group.Count() == 3); } private IEnumerable&lt;IGrouping&lt;CardSuit, PlayingCard&gt;&gt; Suits(IEnumerable&lt;PlayingCard&gt; cards) { return cards.GroupBy(card =&gt; card.Suit); } public Tuple&lt;bool,IEnumerable&lt;PlayingCard&gt;&gt; IsPair(IEnumerable&lt;PlayingCard&gt; cards) { var pairs = Pairs(cards); var result = pairs.Count() == 1 &amp;&amp; !Triplets(cards).Any(); var winningCards = result ? pairs.SelectMany(group =&gt; group.Select(card =&gt; card)) : null; return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(result, winningCards); } public Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsTwoPair(IEnumerable&lt;PlayingCard&gt; cards) { var pairs = Pairs(cards); var result = pairs.Count() == 2; var winningCards = result ? pairs.SelectMany(group =&gt; group.Select(card =&gt; card)) : null; return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(result, winningCards); } public Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsThreeOfKind(IEnumerable&lt;PlayingCard&gt; cards) { var triplets = Triplets(cards); var result = triplets.Count() == 1 &amp;&amp; !Pairs(cards).Any(); var winningCards = result ? triplets.SelectMany(group =&gt; group.Select(card =&gt; card)) : null; return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(result, winningCards); } public Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsFourOfKind(IEnumerable&lt;PlayingCard&gt; cards) { var values = GroupByNominalValue(cards); var result = values.Any(group =&gt; group.Count() &gt;= 4); var winningCards = result ? values.Where(group =&gt; group.Count() &gt;= 4).SelectMany(group =&gt; group.Select(card =&gt; card)) : null; return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(result, winningCards); } public Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsFlush(IEnumerable&lt;PlayingCard&gt; cards) { var winningSuit = Suits(cards).Where(suit =&gt; suit.Count() &gt;= 5); var result = winningSuit.Any(); var winningCards = result ? winningSuit.SelectMany(group =&gt; group.Select(card =&gt; card)) : null; return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(result, winningCards); } public Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsFullHouse(IEnumerable&lt;PlayingCard&gt; cards) { var pairs = Pairs(cards); var triplets = Triplets(cards); var result = pairs.Any() &amp;&amp; triplets.Any(); if (!result) return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(false, null); var winningPair = pairs.OrderByDescending(group =&gt; group.Key).FirstOrDefault().Select(card =&gt; card); var winningTriplet = triplets.OrderByDescending(group =&gt; group.Key).FirstOrDefault().Select(card =&gt; card); var winningCards = winningPair.Concat(winningTriplet); return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(true, winningCards); } public Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsStraight(IEnumerable&lt;PlayingCard&gt; cards) { var distinctValues = GroupByNominalValue(cards); var isStraightNoAce = IsStraightNoAce(distinctValues); if (isStraightNoAce.Item1) { return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(true, isStraightNoAce.Item2); } var isStraightWithAce = IsStraightWithAce(distinctValues); if (isStraightWithAce.Item1.Item1) { return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(true, isStraightWithAce.Item1.Item2); } return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(false, null); } private enum AceKind { AceLow, AceHigh } private Tuple&lt;Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;, AceKind?&gt; IsStraightWithAce(IEnumerable&lt;IGrouping&lt;CardNominalValue, PlayingCard&gt;&gt; distinctValues) { // if has no ace, don't bother if (!distinctValues.Any(group =&gt; group.Key == CardNominalValue.Ace)) return new Tuple&lt;Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;, AceKind?&gt;(new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(false, null), null); var ace = distinctValues.Where(group =&gt; group.Key == CardNominalValue.Ace).Select(group =&gt; group.First()).First(); var aceRemoved = distinctValues.Where(group =&gt; group.Key != CardNominalValue.Ace); var ascending = aceRemoved.OrderBy(value =&gt; value.Key).Take(4); if (ascending.Max(group =&gt; group.Key) == CardNominalValue.Five) { var winningCards = ascending.Select(group =&gt; group.First()).Concat(new List&lt;PlayingCard&gt; {ace}); var result = new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(true, winningCards); return new Tuple&lt;Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;, AceKind?&gt;(result, AceKind.AceLow); } var descending = aceRemoved.OrderByDescending(value =&gt; value.Key).Take(5); if (descending.Min(group =&gt; group.Key) == CardNominalValue.Ten) { var winningCards = descending.Select(group =&gt; group.First()); var result = new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(true, winningCards); return new Tuple&lt;Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;, AceKind?&gt;(result, AceKind.AceHigh); } return new Tuple&lt;Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;, AceKind?&gt;(new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(false, null), null); } private Tuple&lt;Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;, AceKind?&gt; IsStraightWithAce(IEnumerable&lt;PlayingCard&gt; cards) { return IsStraightWithAce(GroupByNominalValue(cards)); } private Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsStraightNoAce(IEnumerable&lt;IGrouping&lt;CardNominalValue, PlayingCard&gt;&gt; distinctValues) { // if has ace, don't bother if (distinctValues.Any(group =&gt; group.Key == CardNominalValue.Ace)) return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(false, null); var sortedValues = distinctValues.OrderBy(group =&gt; (int)group.Key); var possibleLows = sortedValues.Take(5 - sortedValues.Count() + 1); var skippedCards = 0; foreach (var possibleLow in possibleLows) { var theCards = sortedValues.Skip(skippedCards).Take(5).Select(group =&gt; group.First()); var isStraight = theCards.Max(card =&gt; card.NominalValue) == possibleLow.Key + 4; if (isStraight) { return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(true, theCards); } skippedCards++; } return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(false, null); } public Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsStraightFlush(IEnumerable&lt;PlayingCard&gt; cards) { var isFlush = IsFlush(cards); if (!isFlush.Item1) return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(false, null); var isStraight = IsStraight(cards); if (!isStraight.Item1) return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(false, null); return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(true, isStraight.Item2); } public Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt; IsRoyalFlush(IEnumerable&lt;PlayingCard&gt; cards) { var straightWithAceResult = IsStraightWithAce(cards); var result = IsFlush(cards).Item1 &amp;&amp; straightWithAceResult.Item1.Item1 &amp;&amp; straightWithAceResult.Item2 == AceKind.AceHigh; return new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(result, straightWithAceResult.Item1.Item2); } } </code></pre> <p>So the <code>PokerGame</code> class is now much more focused at knowing what the rules are and in which order they're evaluated; the dictionary of rules/hands has turned into a private field, there's no need to expose it at all - given the new <code>PokerHand EvaluateHand()</code> method: </p> <pre><code>public class PokerGame { private readonly IPokerHandEvaluator _evaluator; private readonly Dictionary&lt;PokerHand, Func&lt;IEnumerable&lt;PlayingCard&gt;, Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;&gt;&gt; _hands; public PokerGame(IPokerHandEvaluator evaluator) { _evaluator = evaluator; _hands = new Dictionary&lt;PokerHand, Func&lt;IEnumerable&lt;PlayingCard&gt;, Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;&gt;&gt; { { PokerHand.HighCard, cards =&gt; new Tuple&lt;bool, IEnumerable&lt;PlayingCard&gt;&gt;(true, null) }, { PokerHand.Pair, _evaluator.IsPair }, { PokerHand.TwoPair, _evaluator.IsTwoPair }, { PokerHand.ThreeOfKind, _evaluator.IsThreeOfKind }, { PokerHand.Straight, _evaluator.IsStraight }, { PokerHand.Flush, _evaluator.IsFlush }, { PokerHand.FullHouse, _evaluator.IsFullHouse }, { PokerHand.FourOfKind, _evaluator.IsFourOfKind }, { PokerHand.StraightFlush, _evaluator.IsStraightFlush }, { PokerHand.RoyalFlush, _evaluator.IsRoyalFlush } }; } public PokerHandEvaluationResult EvaluateHand(IEnumerable&lt;PlayingCard&gt; cards) { var winningHand = _hands.OrderByDescending(hand =&gt; hand.Key) .FirstOrDefault(hand =&gt; hand.Value.Invoke(cards).Item1).Key; var redundantCall = _hands[winningHand].Invoke(cards); var winningCards = redundantCall.Item2; var otherCards = cards.Where(card =&gt; !winningCards.Contains(card)); return new PokerHandEvaluationResult(winningHand, winningCards, otherCards); } } </code></pre> <p>For this to work I had to add <code>PokerHand.HighCard</code>:</p> <pre><code>public enum PokerHand { HighCard, Pair, TwoPair, ThreeOfKind, Straight, Flush, FullHouse, FourOfKind, StraightFlush, RoyalFlush } </code></pre> <p>The <code>CardSuit</code> enum was reordered, in prevision for when I want to modify this code to compare two hands - the suit would be a tiebreaker:</p> <pre><code>public enum CardSuit { Clubs, Diamonds, Hearts, Spades } </code></pre> <p>I also added a <code>PokerHandEvaluationResult</code> class:</p> <pre><code>public class PokerHandEvaluationResult : IComparable&lt;PokerHandEvaluationResult&gt; { public PokerHand Result { get; private set; } public IEnumerable&lt;PlayingCard&gt; ResultCards { get; private set; } public IEnumerable&lt;PlayingCard&gt; HighCards { get; private set; } public PokerHandEvaluationResult(PokerHand result, IEnumerable&lt;PlayingCard&gt; resultCards, IEnumerable&lt;PlayingCard&gt; highCards) { Result = result; ResultCards = resultCards; HighCards = highCards; } public int CompareTo(PokerHandEvaluationResult other) { int result; if (Result == other.Result) { result = ResultCards == null ? 0 : ResultCards.Max().CompareTo(other.ResultCards.Max()); if (result == 0) result = HighCards.Max().CompareTo(other.HighCards.Max()); } else { result = Result.CompareTo(other.Result); } return result; } } </code></pre> <hr> <p>So I'm not sure whether this code is getting better, or if it's taking a direction that will make me wish we had implemented a Black Jack game this week. I think <code>Tuple</code> feels like a hack, that the code is begging for something but I can't put my finger on it. Could it be the <code>enum</code>s shooting myself in the foot?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:37:28.697", "Id": "60670", "Score": "0", "body": "Looking at @radarbob's answer on the first post, I suspect upcoming [tag:weekend-challenge] posts will push it to *determining the winning hand out of two*..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T05:54:17.450", "Id": "60695", "Score": "0", "body": "...so I did it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-06T10:01:37.800", "Id": "227293", "Score": "0", "body": "github.com/gsteinbacher/CardGame ... Check out Obacher.CardGame.Poker for my version of the evaluations." } ]
[ { "body": "<ol>\n<li><p>The idiomatic way of creating <code>Tuple</code>s is to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.tuple%28v=vs.110%29.aspx\"><code>Create</code></a> factory method. This should remove a fair amount of type clutter from the code.</p></li>\n<li><p>Tuples are great when you want to bunch up some values and pass them around together. Unfortunately the <code>Tuple</code> properties <code>Item1</code>, <code>Item2</code>, etc. are not very descriptive. You also use the the same type of <code>Tuple</code> in a lot of places so I think the excessive use of it could warrant its own class.</p></li>\n<li><p>Your <code>PokerGame</code> class is a weird abstraction. A poker game consists of 2 or more players, each of them having a hand and the one with the highest wins. Your <code>PokerGame</code> class evaluates only a single hand. <code>PokerPlayer</code> or so might have been a better name.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T10:40:15.947", "Id": "36895", "ParentId": "36873", "Score": "7" } }, { "body": "<p>I have this in my hand class so you can see a very simple algorithm\nThis calculates it all in one spot\nFor the sake a brevity I left out some parts out </p>\n\n<p>The reason for the new solution is to show the simplicity of the problem instead of making it overly complex. The old solution was doing was doing way to much work</p>\n\n<p>This sets a property HandRank</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Possible hands\n/// &lt;/summary&gt;\npublic enum HandType\n{\n HighCard = 1,\n Pair,\n TwoPair,\n ThreeOfAKind,\n Straight,\n Flush,\n FullHouse,\n FourOfAKind,\n StraightFlush\n}\n\n // create holders for rank and suit counts\n private int[] suitCount = new int[NumSuits];\n private int[] rankCount = new int[RanksPerSuit];\n\n /// &lt;summary&gt;\n /// Evaluate Hand\n /// Set HandRank. AceLow, OrderedCards\n /// &lt;/summary&gt;\n public void EvaluateHand()\n {\n // default to Ace High\n AceIsLow = false;\n\n for (int index = 0; index &lt; suitCount.Length; index++)\n {\n suitCount[index] = 0;\n }\n for (int index = 0; index &lt; rankCount.Length; index++)\n {\n rankCount[index] = 0;\n }\n\n // init result to just a Hight Card\n var result = HandType.HighCard;\n\n // count the ranks and suits\n foreach (var card in Cards)\n {\n suitCount[(int)card.Suit]++;\n rankCount[(int)card.Rank]++;\n }\n\n // These are used to determine a straight\n var numInaARow = 0;\n var maxNumInARow = 0;\n\n // loop through each rank count\n for (var rankIndex = 0; rankIndex &lt; RanksPerSuit; rankIndex++)\n {\n // count of cards that are the rank rankIndex\n var count = rankCount[rankIndex];\n\n // if the count is 1 then increment num in a row\n // if max num in a row is 5 then we have a straight\n if (count == 1)\n {\n // increment num in a row\n numInaARow++;\n if (numInaARow &gt; maxNumInARow)\n {\n // set max num in a row\n maxNumInARow = numInaARow;\n }\n }\n else\n {\n // reset counter to 0\n numInaARow = 0;\n }\n\n // look for pairs, two pairs, three of a kind, full house or four of a kind \n switch (count)\n {\n case 2:\n // we have a pair\n // if pair is already set then this is a second pair\n if (result == HandType.Pair)\n {\n result = HandType.TwoPair;\n }\n // if we already have three of a kind then we have a full house\n else if (result == HandType.ThreeOfAKind)\n {\n result = HandType.FullHouse;\n }\n else\n {\n // just a pair\n result = HandType.Pair;\n }\n break;\n\n case 3:\n // we have three of a kind\n // if we already have a low pair we have a full house \n result = (result == HandType.Pair) ? HandType.FullHouse : HandType.ThreeOfAKind;\n break;\n\n case 4:\n // we have four of a kind\n result = HandType.FourOfAKind;\n break;\n }\n }\n\n // check for a straight\n var straight = maxNumInARow == CardsPerHand;\n var aceHightStraight = (maxNumInARow == (CardsPerHand - 1)) &amp;&amp; (rankCount[(int)Rank.Ace] == 1 &amp;&amp; rankCount[(int)Rank.Ten] == 1 &amp;&amp; rankCount[(int)Rank.King] == 1);\n if (straight || aceHightStraight)\n {\n result = HandType.Straight;\n if (straight &amp;&amp; rankCount[(int)Rank.Ace] == 1)\n {\n AceIsLow = true;\n }\n }\n\n // check for a flush\n foreach (var count in suitCount)\n {\n switch (count)\n {\n case CardsPerHand:\n // if we already have a straight then we have a straight flush\n result = result == HandType.Straight ? HandType.StraightFlush : HandType.Flush;\n break;\n }\n }\n // save the result\n HandRank = result;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-26T22:46:14.927", "Id": "296080", "Score": "1", "body": "Welcome to CR! If you have code you want peer reviewed, feel free to ask a new question; answers on this site are meant to critique/review the code in the OP; independent solutions with no justification or relation to the OP do not constitute a code review, and may be removed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-26T22:40:54.447", "Id": "156397", "ParentId": "36873", "Score": "0" } } ]
{ "AcceptedAnswerId": "36895", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T20:44:28.793", "Id": "36873", "Score": "11", "Tags": [ "c#", "linq", "weekend-challenge", "playing-cards" ], "Title": "Poker Hand Evaluator, take 2" }
36873
<p>I am working with an encryption algorithm that looks like this</p> <ol> <li>The key is a number stored in 4 bytes.</li> <li>For each byte in the message, XOR it with the corresponding byte in the key</li> <li>When you reach the end of the key, multiply the key by 13, and then continue looping</li> </ol> <p>Translated, it looks like this</p> <pre><code>for (int i = 0; i &lt; dataSize; i++) { // Increase the key as per the algorithm if (i &gt; 0 &amp;&amp; (i % 4 == 0)) { key *= 13 } // Shift over i bytes, as per the algorithm data[i] ^= key &gt;&gt; (8 * (i % 4)); } </code></pre> <p>What I don't like is that check for <code>i &gt; 0</code>, as it looks like wasteful processing. How can I modify this code so that I don't have that extra check that is basically redundant after the first iteration of the loop?</p> <p>If the size of the data is 5 MB I don't want to run an extra 5 million or so <code>i &gt; 0</code> checks when <code>i</code> is always increasing.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T22:07:05.557", "Id": "60677", "Score": "1", "body": "It should be an easy branch prediction, so I wouldn't expect it to influence actual performance. (But profile both ways to be certain.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T22:11:56.980", "Id": "60680", "Score": "0", "body": "Performance-wise it may be negligible, but for future maintenance, it might also benefit to not have a weird check in there. I've found myself adding an extra, seemingly redundant check in several of my loops because I wasn't sure how to deal with it." } ]
[ { "body": "<p>Initialize the first byte, and then start the loop from 1.....</p>\n\n<p>You may also want to do a bit-check instead of modulo, but they may be equally fast...</p>\n\n<pre><code>if (dataSize &gt; 0) {\n data[0] ^= key;\n}\nfor (int i = 1; i &lt; dataSize; i++) {\n\n // Increase the key as per the algorithm\n if (i &amp; 3 == 0) {\n key *= 13\n }\n\n // Shift over i bytes, as per the algorithm\n data[i] ^= key &gt;&gt; (8 * (i % 4));\n}\n</code></pre>\n\n<h2>EDIT:</h2>\n\n<p>I have seen the following done (translating from memory of a C program)... this has been known to be able to compile down to SIMD-using instructions on supporting compilers, etc.</p>\n\n<pre><code>for (int i = 0; i &lt; dataSize - 3; i+=4) {\n\n // Shift over i bytes, as per the algorithm\n data[i + 0] ^= key; // &gt;&gt; ( 0);\n data[i + 1] ^= key &gt;&gt; ( 8);\n data[i + 2] ^= key &gt;&gt; ( 16);\n data[i + 3] ^= key &gt;&gt; ( 24);\n\n key *= 13\n\n}\n\n// handle up to 3 remaining bytes.....\nfor (int i = dataSize - (dataSize &amp; 3); i &lt; dataSize; i++) {\n data[i] ^= key &gt;&gt; (8 * (i &amp; 3));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T22:09:45.567", "Id": "60678", "Score": "0", "body": "Consider also avoiding the other modulus (`data[i] ^= key >> ((i & 3) << 3);`), depending on what profiling says." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T22:11:14.097", "Id": "60679", "Score": "0", "body": "@MichaelUrman -- I was just thinking that... and I edited my post.... comments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T22:54:14.770", "Id": "60681", "Score": "0", "body": "There is one C# specific performance issue with loop unrolling: The JITter can eliminate bounds checks for the standard loop `for(int i=0; i < array.Length; i++)`, but it can't with most other patterns. In this case it's probably still beneficial, but often it's not." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:49:28.520", "Id": "36876", "ParentId": "36875", "Score": "6" } } ]
{ "AcceptedAnswerId": "36876", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:30:21.263", "Id": "36875", "Score": "6", "Tags": [ "c#", "optimization" ], "Title": "Running a block of code on every interval except the first iteration" }
36875
<p>I'm developing an application that receives and manages e-mails from a server. I manage only XML files and organize, by sender, the e-mails that have XML attachments, while the others are deleted. I create a list of files and create them in the temporary folder. I have a feeling my JavaMail process is slow because it accesses every message. Can I make my process faster?</p> <pre><code>public static void main(String[] args) { try { Properties properties = System.getProperties(); properties.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(properties, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", "login", "password"); Folder inbox = store.getDefaultFolder(); inbox = inbox.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); if (EmailUtil.hasMessage(inbox)) { List&lt;Message&gt; listMessages = new ArrayList&lt;&gt;(Arrays.asList(inbox.getMessages())); Iterator&lt;Message&gt; iterator = listMessages.iterator(); while (iterator.hasNext()) { Message message = iterator.next(); if (EmailUtil.hasNoAttachment(message.getContentType())) { EmailUtil.deleteMessage(message); iterator.remove(); } } if (EmailUtil.hasMessagesWithAttachment(listMessages)) { Set&lt;String&gt; setSender = new HashSet&lt;&gt;(); List&lt;File&gt; listFiles = new ArrayList&lt;&gt;(); listMessages = getAttachmentFiles(listMessages, setSender, listFiles); if (EmailUtil.hasXmlAttachments(listFiles)) { Set&lt;Folder&gt; setFolder = getFolderSet(store); List&lt;String&gt; listFolderName = getFoldersName(setFolder); removeExistingFoldersInSet(setSender, listFolderName); if (foldersNotExist(setSender)) { createFolder(store, setSender); } moveMessagesToFolders(listMessages, store); } } } EmailUtil.closeFolder(inbox); } catch (MessagingException | IOException e) { e.printStackTrace(); } } private static void removeExistingFoldersInSet(Set&lt;String&gt; setSender, List&lt;String&gt; listFolderName) { setSender.removeAll(listFolderName); } private static void createFolder(Store store, Set&lt;String&gt; setSenders) throws MessagingException { for (String sender : setSenders) { store.getFolder(sender).create(Folder.HOLDS_MESSAGES); } } private static boolean foldersNotExist(Set&lt;String&gt; setSenders) throws MessagingException { return (setSenders.size() &gt; 0); } private static Set&lt;Folder&gt; getFolderSet(Store store) throws MessagingException { return new HashSet&lt;&gt;(Arrays.asList(store.getDefaultFolder().list())); } private static List&lt;String&gt; getFoldersName(Set&lt;Folder&gt; setFolder) throws MessagingException { List&lt;String&gt; listFolderName = new ArrayList&lt;&gt;(); for (Folder folder : setFolder) { listFolderName.add(folder.getName()); } return listFolderName; } private static List&lt;Message&gt; getAttachmentFiles(List&lt;Message&gt; listMessages, Set&lt;String&gt; senders, List&lt;File&gt; listFile) throws IOException, MessagingException { List&lt;Message&gt; listMessagesWithXmlAttachment = new ArrayList&lt;&gt;(listMessages.size()); for (Message message : listMessages) { Multipart multipart = (Multipart) message.getContent(); for (int i = 0; i &lt; multipart.getCount(); i++) { MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(i); if (Part.ATTACHMENT.equalsIgnoreCase(mimeBodyPart.getDisposition())) { if (FileUtil.isXmlFile(mimeBodyPart.getFileName())) { listMessagesWithXmlAttachment.add(message); senders.add(EmailUtil.getSender(message)); File file = generateFile(mimeBodyPart); listFile.add(file); } } } } removeMessagesWithoutXmlFile(listMessages, listMessagesWithXmlAttachment); return listMessagesWithXmlAttachment; } private static File generateFile(BodyPart bodyPart) throws IOException, MessagingException { String path = FileUtil.createFile("", bodyPart.getFileName()); Files.copy(bodyPart.getInputStream(), Paths.get(path), StandardCopyOption.REPLACE_EXISTING); return new File(path); } private static void removeMessagesWithoutXmlFile(List&lt;Message&gt; listMessages, List&lt;Message&gt; listMessagesWithXmlAttachment) throws MessagingException { listMessages.removeAll(listMessagesWithXmlAttachment); for (Message message : listMessages) { message.setFlag(Flags.Flag.DELETED, true); } } private static void moveMessagesToFolders(List&lt;Message&gt; listMessages, Store store) throws MessagingException { HashMap&lt;String, List&lt;Message&gt;&gt; mapMessages = separeteMessagesBySender(listMessages); Folder folder = null; for (Entry&lt;String, List&lt;Message&gt;&gt; mapMessage : mapMessages.entrySet()) { Message[] messageArray = mapMessage.getValue().toArray(new Message[mapMessage.getValue().size()]); folder = store.getDefaultFolder().getFolder(mapMessage.getKey()); folder.open(Folder.READ_WRITE); folder.appendMessages(messageArray); EmailUtil.deleteListMessage(mapMessage.getValue()); } } private static HashMap&lt;String, List&lt;Message&gt;&gt; separeteMessagesBySender(List&lt;Message&gt; listMessages) throws MessagingException { HashMap&lt;String, List&lt;Message&gt;&gt; mapMessages = new HashMap&lt;&gt;(); List&lt;Message&gt; listMessageSeparetad = null; for (Message message : listMessages) { String sender = EmailUtil.getSender(message); if (!mapMessages.containsKey(sender)) { listMessageSeparetad = new ArrayList&lt;&gt;(); mapMessages.put(sender, listMessageSeparetad); } listMessageSeparetad = mapMessages.get(sender); listMessageSeparetad.add(message); } return mapMessages; } </code></pre>
[]
[ { "body": "<p>I have a feeling your application is slow because it does a lot of network access ... ;-)</p>\n\n<p>The amount of time in your code will be a very small fraction of the actual 'latency'. So, the question is not \"How can we make your code faster?\" but rather it is \"How can we reduce the amount of network traffic?\"</p>\n\n<p>I am not very well versed with managing the performance of the javamail API. When I have used it the Mail servers have been local, and not really a factor in performance... But, without actually trying it myself, you <strong>should</strong> be using the <code>fetch(...,...)</code> method.</p>\n\n<p>Also, there's no real need for the outside <code>if (EmailUtil.hasMessages(inbox))...</code>.</p>\n\n<p>Sometimes it is better to explain with code, rather than with blurb:</p>\n\n<pre><code>// clear out any delete-marked messages - no need to process them....\ninbox.expunge();\n// by convention, this should be a lightweight process...\n// hopefully GMail does it right.\nMessage[] messages = inbox.getMessages();\nif (messages.length &gt; 0) {\n Message[] todelete = new Message[messages.length];\n deletecount = 0;\n // now, instead of doing a loop through all the messages,\n // do a bulk 'get' operation to get the fields we know we will need:\n FetchProfile profile = new FetchProfile();\n // add the headers we know we will need:\n profile.add(FetchProfile.Item.CONTENT_INFO);\n // this is a bulk operation that should get the content-type,\n // and other things.\n inbox.fetch(messages, profile);\n for (int m = 0; m &lt; messages.length; m++) {\n if (EmailUtil.hasNoAttachment(messages[m].getContentType())) {\n todelete[deletecnt++] = messages[m];\n messages[m] = null;\n }\n }\n // OK, do a bulk delete operation\n if (deletecnt &gt; 0) {\n todelete = Arrays.copyOf(todelete, deletecnt);\n Flags delflags = new Flags(Flags.Flag.DELETED);\n inbox.setFlags(todelete, delflags, true);\n inbox.expunge();\n }\n\n}\n</code></pre>\n\n<p>From this you can get the idea of what you should do....</p>\n\n<p>I realize I kept the <code>Message[]</code> as an array, and you have it as a List. I kept it as an array because it is the input mechanism for the bulk methods of the API... but, in fairness, I think you should keep using the List format (the <code>iterator.remove()</code> is useful). Then, convert the List to an array when you need it.</p>\n\n<p>Also, look in to the FetchProfile object/method, you can add any header fields you want to it...</p>\n\n<p>Also, you can filter out messages that do not meet certain criteria, and then fetch additional data for the next set of tests, and do it that way.</p>\n\n<p>Bottom line is that you want to access the server as few times as possible, and when you access it, you should get as little data as you need, but, group all similar requests in to a sigle operation.....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T00:10:01.550", "Id": "60781", "Score": "0", "body": "Sorry, but I forgot to view this post, I´ve update my code today including some threads...Yes my problem is to reduce time access to mail box for my operation" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T15:24:52.133", "Id": "36902", "ParentId": "36878", "Score": "5" } }, { "body": "<p>After finally reading the advice of @rolfl and doing my own testing, I came up with this code. I hope someone can use or improve my code and share. I don't request any further reviews of it, though.</p>\n\n<p>This code has some methods that I put in util´s classes but the name tells what he do.</p>\n\n<pre><code>public class Email {\n\n private static List&lt;File&gt; listFile = new ArrayList&lt;&gt;();\n private static final int threadQuantity = ThreadUtil.quantityOfThreads();\n\n public static void main(String[] args) {\n\n try {\n\n Properties properties = System.getProperties();\n properties.setProperty(\"mail.store.protocol\", \"imaps\");\n properties.put(\"mail.imap.fetchsize\", \"819200\"); \n properties.setProperty(\"mail.imap.partialfetch\", \"false\");\n properties.setProperty(\"mail.imaps.partialfetch\", \"false\"); \n Session session = Session.getDefaultInstance(properties, null);\n Store store = session.getStore(\"imaps\");\n store.connect(\"imap.gmail.com\", \"login\", \"password\");\n\n Folder inbox = store.getDefaultFolder();\n inbox = inbox.getFolder(\"INBOX\");\n inbox.open(Folder.READ_WRITE);\n\n FetchProfile fetchProfile = new FetchProfile();\n fetchProfile.add(FetchProfile.Item.CONTENT_INFO);\n\n Message[] messages = inbox.getMessages();\n Message[] messagesToDelete = new Message[messages.length];\n int countToDelete = 0;\n\n inbox.fetch(messages, fetchProfile);\n\n countToDelete += EmailUtil.separteMessagesWithoutAttachment(messages, messagesToDelete);\n countToDelete += separteMessagesWithoutXmlAttachment(messages, messagesToDelete);\n\n if (hasMessagesWithoutXmlAttachment(countToDelete)) {\n deleteMessagesWithoutXmlAttachment(messagesToDelete, countToDelete, inbox);\n messages = separateMessagesWithAttachment(messages, countToDelete);\n }\n\n Set&lt;String&gt; setSender = getMessagesSender(messages);\n Set&lt;String&gt; setFolderName = getFoldersName(store);\n\n if (foldersNotExist(setFolderName, setSender)) {\n createFolder(store, setSender);\n }\n\n moveMessagesToFolders(messages, store, setSender);\n deleteMessages(messages, inbox);\n\n } catch (MessagingException | IOException e) {\n e.printStackTrace();\n }\n }\n\n private static int separteMessagesWithoutXmlAttachment(Message[] messages, Message[] messagesToDelete) throws IOException, MessagingException {\n\n List&lt;MimeBodyPart&gt; listMimeBodyPart = new ArrayList&lt;&gt;();\n int countToDelete = 0;\n\n for (int i = 0; i &lt; messages.length; i++) {\n\n if (!NullUtil.isNull(messages[i])){\n if (hasNoXmlAttachment(messages[i], listMimeBodyPart)) {\n messagesToDelete[countToDelete++] = messages[i];\n messages[i] = null;\n } \n }\n }\n processAttachmentXml(listMimeBodyPart);\n\n return countToDelete;\n }\n\n private static boolean hasNoXmlAttachment(Message message, List&lt;MimeBodyPart&gt; listMimeBodyPart) throws IOException, MessagingException {\n\n Multipart multipart = (Multipart) message.getContent();\n boolean hasNoXmlAttachment = true;\n\n for (int i = 0; i &lt; multipart.getCount(); i++) {\n\n MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(i);\n\n if (Part.ATTACHMENT.equalsIgnoreCase(mimeBodyPart.getDisposition())) {\n\n if (FileUtil.isXmlFile(mimeBodyPart.getFileName())) {\n hasNoXmlAttachment = false;\n listMimeBodyPart.add(mimeBodyPart);\n\n }\n }\n }\n\n return hasNoXmlAttachment;\n }\n\n private static void processAttachmentXml(List&lt;MimeBodyPart&gt; listMimeBodyPart) throws MessagingException, IOException {\n\n MimeBodyPart[] mimeBodyPartsArray = listMimeBodyPart.toArray(new MimeBodyPart[listMimeBodyPart.size()]);\n List&lt;Thread&gt; listThread = ThreadUtil.creatPoolThread();\n int[] indexThread = ThreadUtil.generateThreadsIndex(mimeBodyPartsArray);\n\n int indexStart = 0;\n int indexEnd = 0;\n\n for (int i = 0; i &lt; threadQuantity; i++) {\n indexEnd += indexThread[i];\n MimeBodyPart[] mimeBodyPartsArrayCopy = (MimeBodyPart[]) ThreadUtil.sliceArray(mimeBodyPartsArray, indexStart, indexEnd);\n indexStart = indexEnd;\n listThread.add(new ThreadGenerateFile(mimeBodyPartsArrayCopy, listFile));\n }\n\n ThreadUtil.startThreads(listThread);\n }\n\n private static boolean hasMessagesWithoutXmlAttachment(int countToDelete) {\n return countToDelete &gt; 0;\n }\n\n private static void deleteMessagesWithoutXmlAttachment(Message[] messagesToDelete, int countToDelete, Folder inbox) throws MessagingException {\n\n messagesToDelete = Arrays.copyOf(messagesToDelete, countToDelete);\n Flags flagToDelete = new Flags(Flag.DELETED);\n\n inbox.setFlags(messagesToDelete, flagToDelete, true);\n inbox.expunge();\n }\n\n private static Message[] separateMessagesWithAttachment(Message[] messages, int countToDelete) {\n\n List&lt;Message&gt; listMessage = new ArrayList&lt;&gt;(Arrays.asList(messages));\n listMessage.removeAll(Collections.singleton(null));\n return listMessage.toArray(new Message[listMessage.size()]);\n }\n\n private static Set&lt;String&gt; getMessagesSender(Message[] messages) throws MessagingException {\n\n Set&lt;String&gt; setSender = new HashSet&lt;&gt;();\n\n for (Message message : messages) {\n if(!NullUtil.isNull(message)){\n setSender.add(EmailUtil.getSender(message));\n }\n }\n\n return setSender;\n }\n\n private static Set&lt;String&gt; getFoldersName(Store store) throws MessagingException {\n\n Set&lt;Folder&gt; setFolder = new HashSet&lt;&gt;(Arrays.asList(store.getDefaultFolder().list()));\n Set&lt;String&gt; setFolderName = new HashSet&lt;&gt;();\n\n for (Folder folder : setFolder) {\n setFolderName.add(folder.getName());\n }\n\n return setFolderName;\n }\n\n private static void createFolder(Store store, Set&lt;String&gt; setSenders) throws MessagingException {\n\n String[] senderArray = setSenders.toArray(new String[setSenders.size()]);\n\n List&lt;Thread&gt; listThread = ThreadUtil.creatPoolThread();\n int[] indexThread = ThreadUtil.generateThreadsIndex(senderArray);\n\n int indexStart = 0;\n int indexEnd = 0;\n\n for (int i = 0; i &lt; threadQuantity; i++) {\n indexEnd += indexThread[i];\n String[] senderArrayCopy = (String[]) ThreadUtil.sliceArray(senderArray, indexStart, indexEnd);\n indexStart = indexEnd;\n listThread.add(new ThreadCreateFolder(senderArrayCopy, store));\n }\n\n ThreadUtil.startThreads(listThread);\n }\n\n private static boolean foldersNotExist(Set&lt;String&gt; setFolderName, Set&lt;String&gt; setSenders) throws MessagingException {\n return !(setFolderName.containsAll(setSenders));\n }\n\n private static void moveMessagesToFolders(Message[] messages, Store store, Set&lt;String&gt; setSender) throws MessagingException {\n\n HashMap&lt;String, List&lt;Message&gt;&gt; mapMessages = separeteMessagesBySender(messages, setSender);\n\n for (Entry&lt;String, List&lt;Message&gt;&gt; mapMessage : mapMessages.entrySet()) {\n\n Message[] messageArray = mapMessage.getValue().toArray(new Message[mapMessage.getValue().size()]);\n\n List&lt;Thread&gt; listThread = ThreadUtil.creatPoolThread();\n int[] indexThread = ThreadUtil.generateThreadsIndex(messageArray);\n\n int indexStart = 0;\n int indexEnd = 0;\n\n for (int i = 0; i &lt; threadQuantity; i++) {\n indexEnd += indexThread[i];\n Message[] messageArrayCopy = (Message[]) ThreadUtil.sliceArray(messageArray, indexStart, indexEnd);\n indexStart = indexEnd;\n listThread.add(new ThreadMoveMessages(messageArrayCopy, mapMessage.getKey(), store));\n }\n\n ThreadUtil.startThreads(listThread);\n }\n }\n\n private static HashMap&lt;String, List&lt;Message&gt;&gt; separeteMessagesBySender(Message[] messages, Set&lt;String&gt; setSender) throws MessagingException {\n\n HashMap&lt;String, List&lt;Message&gt;&gt; mapMessages = new HashMap&lt;&gt;();\n List&lt;Message&gt; listMessage = null;\n\n for (String sender : setSender) {\n listMessage = new ArrayList&lt;&gt;();\n mapMessages.put(sender, listMessage);\n }\n\n for (Message message : messages) {\n if (!NullUtil.isNull(message)) {\n listMessage = mapMessages.get(EmailUtil.getSender(message));\n listMessage.add(message); \n }\n }\n\n return mapMessages;\n }\n\n private static void deleteMessages(Message[] messages, Folder inbox) throws MessagingException {\n inbox.setFlags(messages, new Flags(Flag.DELETED), true);\n inbox.expunge();\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-15T18:46:16.957", "Id": "61923", "Score": "0", "body": "Thanks for posting your revisions back here. Can you give some indication of how much your performance improved ... was it just a 'little' or was it a lot?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-16T17:47:34.853", "Id": "62126", "Score": "0", "body": "I can´t tell how much improved, but what you told me to do improved..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-31T07:40:28.617", "Id": "63878", "Score": "0", "body": "@rolfl I´ve tested my code with sequencial and parallel, my test was with around 400 e-mails with attatchments or no, and with threads I got less 4 minutos than sequencial. I got in sequencial 19 minutes and parallel 15 minutes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-31T08:06:43.050", "Id": "63879", "Score": "0", "body": "I advise you to change your Google account password immediately!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-31T08:08:10.900", "Id": "63880", "Score": "1", "body": "Furthermore, this being Code Review, I'll point out that usernames and passwords should be stored in configuration files, not in the source code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T19:35:58.623", "Id": "37373", "ParentId": "36878", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T23:01:23.377", "Id": "36878", "Score": "5", "Tags": [ "java", "email" ], "Title": "Is there any way to make this JavaMail code faster?" }
36878
<p>This is the most basic code to join two tables in a database. For tables it uses a simple list. Solved this using brute force, sorting and using hashtable.</p> <pre><code>final class SportsMan { private final String name; private final int rank; private final String sport; public SportsMan (String name, int rank, String sport) { this.name = name; this.rank = rank; this.sport = sport; } public String getName() { return name; } public int getRank() { return rank; } public String getSport() { return sport; } } final class Sport { private final String sport; private final int numberOfPlayers; public Sport(String sport, int numberOfPlayers) { this.sport = sport; this.numberOfPlayers = numberOfPlayers; } public String getSport() { return sport; } public int getNumberOfPlayers() { return numberOfPlayers; } } final class Result { private final String name; private final int rank; private final String sport; private final int numberOfPlayers; public Result (String name, int rank, String sport, int numberOfPlayers) { this.name = name; this.rank = rank; this.sport = sport; this.numberOfPlayers = numberOfPlayers; } public String getName() { return name; } public int getRank() { return rank; } public String getSport() { return sport; } public int getNumberOfPlayers() { return numberOfPlayers; } } public final class Joins { private Joins () {} public static List&lt;Result&gt; innerJoinBruteForce(List&lt;SportsMan&gt; sportsMen, List&lt;Sport&gt; sportList) { final List&lt;Result&gt; resultSet = new ArrayList&lt;Result&gt;(); for (SportsMan sportsMan : sportsMen) { for (Sport sport : sportList) { if (sportsMan.getSport().equals(sport.getSport())) { resultSet.add(new Result(sportsMan.getName(), sportsMan.getRank(), sport.getSport(), sport.getNumberOfPlayers())); } } } return resultSet; } public class SportsMenComparator implements Comparator&lt;SportsMan&gt; { @Override public int compare(SportsMan s1, SportsMan s2) { return s1.getSport().compareTo(s2.getSport()); } } public class SportComparator implements Comparator&lt;Sport&gt; { @Override public int compare(Sport sport1, Sport sport2) { return sport1.getSport().compareTo(sport2.getSport()); } } public static List&lt;Result&gt; innerJoinSort(List&lt;SportsMan&gt; sportsMansList, List&lt;Sport&gt; sportList) { List&lt;Result&gt; result = new ArrayList&lt;Result&gt;(); Collections.sort(sportsMansList, new Joins().new SportsMenComparator()); Collections.sort(sportList, new Joins().new SportComparator()); int sportsManCtr = 0; int sportsCtr = 0; while (sportsManCtr &lt; sportsMansList.size() &amp;&amp; sportsCtr &lt; sportList.size()) { SportsMan sportsMan = sportsMansList.get(sportsManCtr); Sport sport = sportList.get(sportsCtr); if (sportsMan.getSport().compareTo(sport.getSport()) &gt; 0) { sportsCtr++; } else if (sportsMan.getSport().compareTo(sport.getSport()) &lt; 0) { sportsManCtr++; } else { result.add(new Result(sportsMan.getName(), sportsMan.getRank(), sport.getSport(), sport.getNumberOfPlayers())); sportsManCtr++; sportsCtr++; } } return result; } public static List&lt;Result&gt; innerJoinHash(List&lt;SportsMan&gt; sportsManList, List&lt;Sport&gt; sportList) { List&lt;Result&gt; result = null; Map hashMap; if (sportsManList.size() &lt; sportList.size()) { hashMap = new HashMap(); for (SportsMan sportsman : sportsManList) { hashMap.put(sportsman.getSport(), sportsman); } for (Sport sport : sportList) { if (hashMap.containsKey(sport.getSport())) { SportsMan sportsMan = (SportsMan) hashMap.get(sport.getSport()); result.add(new Result(sportsMan.getName(), sportsMan.getRank(), sportsMan.getSport(), sportsMan.getRank())); } } } else { hashMap = new HashMap(); for (Sport sport : sportList) { hashMap.put(sport.getSport(), sport); } for (SportsMan sportsMan : sportsManList) { if (hashMap.containsKey(sportsMan.getSport())) { Sport sport = (Sport) hashMap.get(sportsMan.getSport()); result.add(new Result(sportsMan.getName(), sportsMan.getRank(), sportsMan.getSport(), sportsMan.getRank())); } } } return result; } public static void main(String[] args) { List&lt;SportsMan&gt; sportsMenList = new ArrayList&lt;SportsMan&gt;(); sportsMenList.add(new SportsMan("sachin", 1, "cricket")); sportsMenList.add(new SportsMan("nadal", 1, "tennis")); sportsMenList.add(new SportsMan("tiger", 1, "golf")); sportsMenList.add(new SportsMan("pele", 1, "soccer")); List&lt;Sport&gt; sportList = new ArrayList&lt;Sport&gt;(); sportList.add(new Sport("cricket", 11)); sportList.add(new Sport("tennis", 2)); sportList.add(new Sport("golf", 1)); List&lt;Result&gt; resultSet1 = innerJoinBruteForce(sportsMenList, sportList); for (Result result : resultSet1) { System.out.print(result.getSport() + " : "); } List&lt;Result&gt; resultSet2 = innerJoinSort(sportsMenList, sportList); for (Result result : resultSet2) { System.out.print(result.getSport() + " : "); } List&lt;Result&gt; resultSet3 = innerJoinSort(sportsMenList, sportList); for (Result result : resultSet3) { System.out.print(result.getSport() + " : "); } } } </code></pre>
[]
[ { "body": "<p>Right now you aren't using <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/generics.html\">generics</a>:</p>\n\n<pre><code>Map hashMap; // no generics :o\nMap&lt;String, Object&gt; hashMap; // generics :D\n</code></pre>\n\n<hr>\n\n<p>The variable <code>result</code> can only be <code>null</code> in the function <code>innerJoinHash()</code>:</p>\n\n<pre><code>result.add(new Result(sportsMan.getName(), sportsMan.getRank(), sportsMan.getSport(), sportsMan.getRank()));\n</code></pre>\n\n<p>This is because you are initializing <code>result</code> to <code>null</code>:</p>\n\n<pre><code>List&lt;Result&gt; result = null;\n</code></pre>\n\n<p>You should initiate the list right away:</p>\n\n<pre><code>List&lt;Result&gt; result = new ArrayList&lt;Result&gt;();\n</code></pre>\n\n<hr>\n\n<p>The value of the local variable <code>sport</code> is not used, and therefore can be removed:</p>\n\n<pre><code>Sport sport = (Sport) hashMap.get(sportsMan.getSport());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T03:33:13.790", "Id": "36885", "ParentId": "36879", "Score": "5" } } ]
{ "AcceptedAnswerId": "36885", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T00:06:00.797", "Id": "36879", "Score": "2", "Tags": [ "java", "join" ], "Title": "Join of two databases" }
36879
<p>I have an homework as follows:</p> <blockquote> <p>Write a program where you enter from the keyboard a number n. Then n stars are drawn onto the screen, circling around the center of your screen. You can assume that 1 &lt; n &lt; 20.</p> </blockquote> <p>The solution I came up with is below.</p> <pre><code>import turtle window=turtle.Screen() window.screensize(1200,1200) draw=turtle.Turtle() draw.pensize(2) draw.speed('fastest') angle = [36,144,144,144,144] GetNumber = int(input("Enter a number: ")) while GetNumber &lt;= 1 or GetNumber &gt;= 20: print("Enter a number between from 2 to 19") GetNumber = int(input("Enter a number: ")) for shape in range(GetNumber): for i in angle: draw.left(i) draw.forward(180) draw.penup() draw.forward(60) draw.pendown() draw.left(170) </code></pre> <p>Is there any way to improve this code? I think my code is OK, but I believe there are perhaps more concise or better solutions (working faster perhaps?)</p> <p>Perhaps angle (currently 170) should be changed or perhaps an dynamic angle changer code can be implemented for the sake of improving the solutions. What do you think?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-18T21:32:10.957", "Id": "88164", "Score": "0", "body": "Circling around the screen? What does that actually mean? I would put them all at the same distance from the center (and thus, if there are a lot of stars, I'd guess they would have a limited size so we can fit them all) or is it supposed to create some kind of spiral? [I'm working on my own implementation, I'll give comments about how to improve your code, the good habits to have, etc]" } ]
[ { "body": "<p>is using <code>turtle</code> a requirement? otherwise you could use plotting libraries such as <code>matplotlib</code>:</p>\n\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure( figsize=(8, 8) ).patch.set_alpha( 0 )\n\ntheta = np.linspace( 0, 2 * np.pi, 16, endpoint=False)\nx, y = np.cos( theta ), np.sin( theta )\n\nplt.scatter( x, y, marker='*', s=1e3, edgecolors='Yellow' )\nplt.axis( 'off' )\nplt.show( )\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/mpSQO.png\" alt=\"output for n=16\"></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T00:34:31.783", "Id": "61985", "Score": "0", "body": "Yes. The assignment was about Turtle. However, thank you so much for informing me about this possibility!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T00:28:23.097", "Id": "37462", "ParentId": "36880", "Score": "1" } }, { "body": "<p>It would be user friendly and make testing easier if the program accepted the input number as a command line argument too, for example:</p>\n\n<pre><code>import sys\n\n\ndef main():\n if sys.argv[1:]:\n num = int(sys.argv[1])\n if not is_valid_number(num):\n warn_invalid_number()\n sys.exit(1)\n else:\n num = prompt_valid_number()\n\n draw_stars_in_a_spiral(num)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>While doing this, to avoid code duplication, I split the original functionality to multiple functions, which is a good practice in general anyway.</p>\n\n<p>For validating the number, the <code>N &lt; var &lt; M</code> operator of Python is very handy:</p>\n\n<pre><code>def is_valid_number(num):\n return 1 &lt; num &lt; 20\n</code></pre>\n\n<p>Then the warning and prompting functions:</p>\n\n<pre><code>def warn_invalid_number():\n print(\"Number must between 2 to 19 (inclusive)\") \n\n\ndef prompt_number():\n return int(input(\"Enter a number: \"))\n</code></pre>\n\n<p>When prompting the user until he gives a valid number, change to a <code>while True</code> loop to avoid the duplication when asking for a number:</p>\n\n<pre><code>def prompt_valid_number():\n while True:\n num = prompt_number()\n if is_valid_number(num):\n return num\n warn_invalid_number()\n</code></pre>\n\n<p>Finally, the main method to draw the stars:</p>\n\n<pre><code>def draw_stars_in_a_spiral(num):\n window = turtle.Screen()\n window.screensize(1200, 1200)\n\n draw = turtle.Turtle()\n draw.pensize(2)\n\n draw.speed('fastest')\n\n for _ in range(num):\n for angle in angles:\n draw.left(angle)\n draw.forward(180)\n draw.penup()\n draw.forward(60)\n draw.pendown()\n draw.left(170)\n</code></pre>\n\n<p>Some points to note:</p>\n\n<ul>\n<li>I moved all the drawing operations here. If validation fails when invoking with command line parameters, there's no need to open a window and draw anything.</li>\n<li>I replaced the unused <code>shape</code> variable in <code>for shape in range(num)</code> with <code>_</code></li>\n<li>I replaced the <code>angle</code> array with <code>angles</code> to be more intuitive, and the loop variable <code>i</code> with the more intuitive name <code>angle</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-17T07:27:29.590", "Id": "109034", "Score": "1", "body": "I would suggest using the `argparse` module instead of manually writing your own command-line parsing code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-17T09:06:34.933", "Id": "109046", "Score": "1", "body": "I agree, but that would be really taking it to a next level, and he didn't ask for command line parsing at all, not sure if he's interested at all" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-17T07:26:19.643", "Id": "60275", "ParentId": "36880", "Score": "6" } }, { "body": "<p>I would extract the code which draws a single star in its own function. Also I think it is important that such function will draw a star centered in the current position and leaves the turtle in the same position it has found it. </p>\n\n<p>Otherwise I think that the stars you are drawing are not centered exactly around the center of the screen... or at least it is not clear to me why they should.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-17T13:42:34.787", "Id": "60294", "ParentId": "36880", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T00:21:17.973", "Id": "36880", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Drawing stars around the center of the screen" }
36880
<p>I'm working on a page using AJAX that will get an entire .php page when the navigation button is clicked. I have that set up and working right. But this is my first time using AJAX, so I'm not sure what the best practices are and what I can do to prevent failures and display error messages.</p> <pre><code> $(document).ready(function() { //set your initial page when website loads $("#content-container").load("content/corporate.php"); // content container load content based on nav tab clicked $("#nav-tabs-list li").click(function() { var page = $("a", this).attr("href"); // get the url of the tab clicked $("#content-container").load("content/" + page); // load content return false; }); // sidebar container load content $("#sidebar-container #sidebar-content-container").load("content/sidebar-content/poll-faq.php"); // set your sidebar initial tab $("#sidebar-container #sidebar-tabs-container a").click(function() { var page = $(this).attr("href"); //get the url of the tab clicked $("#sidebar-container #sidebar-content-container").load("content/sidebar-content/" + page); //load content return false; }); }); </code></pre>
[]
[ { "body": "<p>There isn't too much wrong. Your containers (<code>#sidebar-container</code> and <code>#sidebar-content-container</code>) really shouldn't need to be accessed by Ids, but more-so classes. For those types of DOM elements, <a href=\"http://css-tricks.com/the-difference-between-id-and-class/\" rel=\"nofollow\">utilize classes</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T08:31:43.773", "Id": "72458", "Score": "0", "body": "It's not obvious from the jQuery documentation, but [`return false` suppresses both the default action and event bubbling](http://stackoverflow.com/a/1357151/1157100)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T08:33:26.850", "Id": "72459", "Score": "0", "body": "Well thank you for pointing that out to me! I appreciate it!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T04:34:32.767", "Id": "42103", "ParentId": "36881", "Score": "5" } }, { "body": "<p>I am puzzled by the way you add a <code>content/</code> or <code>content/sidebar-content/</code> prefix to the <code>href</code> attributes to form the URL to load. Why don't you render the page such that the <code>href</code> already contain the correct URL to load?</p>\n\n<p>You don't need to comment every line of code. Just one comment per \"paragraph\" of code is sufficient.</p>\n\n<p>Also, fix your indentation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T08:44:25.360", "Id": "42116", "ParentId": "36881", "Score": "5" } }, { "body": "<p>Sometimes you don't need to write comments when your code is clear enough. For example, you have : </p>\n\n<pre><code>// content container load content based on nav tab clicked\n$(\"#nav-tabs-list li\").click(function() {\n var page = $(\"a\", this).attr(\"href\"); // get the url of the tab clicked\n $(\"#content-container\").load(\"content/\" + page); // load content\n return false;\n});\n</code></pre>\n\n<p>Just by reading the line <code>$(\"#content-container\").load(\"content/\" + page);</code> I can understand that you are loading the content. You don't need to repeat yourself in a comment. Comment should help understand the code, not repeat it. </p>\n\n<p>Also note that comments can be \"dangerous\", there is no guarantee that when the code change you will update the comment. Be sure that the comments add value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T15:49:04.893", "Id": "42160", "ParentId": "36881", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T03:08:19.280", "Id": "36881", "Score": "8", "Tags": [ "javascript", "jquery", "beginner", "ajax" ], "Title": "Fail-proof AJAX" }
36881
<p>I'm working my way through <em>The Java Programming Language, Fourth Edition - The Java Series</em>. This is Exercise Exercise 20.3:</p> <blockquote> <p>Create a pair of Filter stream classes that encrypt bytes using any algorithm you choose—such as XORing the bytes with some value—with your DecryptInputStream able to decrypt the bytes that your EncryptOutputStream class creates.</p> </blockquote> <p>Is the following an adequate solution? I understand that the key should be randomly generated and at least as long as the message. They key used is just for illustration.</p> <p>EncryptOutputStream.java</p> <pre><code>import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; public class EncryptOutputStream extends FilterOutputStream { private final static int XOR_KEY = 1; public EncryptOutputStream(OutputStream out) { super(out); } @Override public void write(int b) throws IOException { super.write(b ^ XOR_KEY); } } </code></pre> <p>DecryptInputStream.java</p> <pre><code>import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; public class DecryptInputStream extends FilterInputStream { private final static int XOR_KEY = 1; protected DecryptInputStream(InputStream in) { super(in); } @Override public int read() throws IOException { int b = super.read(); return (b != -1 ? b ^ XOR_KEY : b); } } </code></pre> <p>EncryptionTest.java</p> <pre><code>import org.junit.Test; import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FilterInputStream; import java.io.FilterOutputStream; import java.io.InputStream; import java.io.OutputStream; public class EncryptionTest { @Test public void testEncryptOutputStream() throws Exception { String testStr = "The quick brown fox jumps over the lazy dog."; InputStream in = new ByteArrayInputStream(testStr.getBytes("UTF-8")); OutputStream out = new ByteArrayOutputStream(); FilterOutputStream encryptOut = new EncryptOutputStream(out); int b; while ((b = in.read()) != -1) { encryptOut.write(b); } assertEquals("Uid!pthbj!csnvo!gny!ktlqr!nwds!uid!m`{x!enf/", out.toString()); in.close(); encryptOut.close(); } @Test public void testDecryptInputStream() throws Exception { String testStr = "Uid!pthbj!csnvo!gny!ktlqr!nwds!uid!m`{x!enf/"; InputStream in = new ByteArrayInputStream(testStr.getBytes("UTF-8")); FilterInputStream decryptIn = new DecryptInputStream(in); OutputStream out = new ByteArrayOutputStream(); int b; while ((b = decryptIn.read()) != -1) { out.write(b); } assertEquals("The quick brown fox jumps over the lazy dog.", out.toString()); decryptIn.close(); out.close(); } @Test public void testEncryptDecrypt() throws Exception { String testStr = "The quick brown fox jumps over the lazy dog."; OutputStream out = new ByteArrayOutputStream(); InputStream in = new ByteArrayInputStream(testStr.getBytes("UTF-8")); FilterOutputStream encryptOut = new EncryptOutputStream(out); int b; while ((b = in.read()) != -1) { encryptOut.write(b); } assertEquals("Uid!pthbj!csnvo!gny!ktlqr!nwds!uid!m`{x!enf/", out.toString()); String resultStr = out.toString(); InputStream inResult = new ByteArrayInputStream(resultStr.getBytes("UTF-8")); FilterInputStream decryptIn = new DecryptInputStream(inResult); OutputStream outResult = new ByteArrayOutputStream(); b = 0; while ((b = decryptIn.read()) != -1) { outResult.write(b); } assertEquals(testStr, outResult.toString()); encryptOut.close(); decryptIn.close(); outResult.close(); } } </code></pre>
[]
[ { "body": "<p>It looks like you have covered the bases quite well. There are some things I would like to suggest, and the first one is the most important:</p>\n\n<blockquote>\n <p>The performance of Input/Output Streams that read/write 1 byte at a time is really, really bad. You should also override the <strong>bulk</strong> read(...)/write(...) methods.</p>\n</blockquote>\n\n<p>Now, when you get around to doing the bulk methods, you will have some challenges with getting the byte manipulation right, but that's another problem.... ;-)</p>\n\n<p>Now in your decrypt routine you have:</p>\n\n<pre><code>int b = super.read();\nreturn (b != -1 ? b ^ XOR_KEY : b);\n</code></pre>\n\n<p>I don't like this. The reason is that it has too much negative logic..... and even though it relates b to a constant <code>-1</code> you return <code>b</code> instead of <code>-1</code>. Consider the following alternative:</p>\n\n<pre><code>return b == -1 ? -1 : b ^ XOR_KEY;\n</code></pre>\n\n<p>I know it is a minor nit-pick, but it <strong>does</strong> make a difference.</p>\n\n<p>On that note, you had better make sure that XOR_KEY is always positive... a negative XOR_KEY will cause the result to be negative, and break all sorts of InputStream readers.</p>\n\n<p>Now, you say the key should be as long as the message... that's not true. Even some of the best algorithms use 2048-bit keys (256 bytes). and many of them use much less (16 bytes...).</p>\n\n<p>Additionally, you hint that you know that storing the key the way you do is incorrect ... It should be passed in as a constructed value or something, and not hard-coded as a static variable.</p>\n\n<p>What you have is more than 'adequate', it is neat, and appears to be fully accurate... but, in order to be good, or great, it needs to do the bulk-operations...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T05:15:43.877", "Id": "36886", "ParentId": "36884", "Score": "2" } } ]
{ "AcceptedAnswerId": "36886", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T03:31:50.750", "Id": "36884", "Score": "2", "Tags": [ "java", "cryptography", "stream" ], "Title": "Critique of FilterInputStream and FilterOutputStream classes" }
36884
<p>In collision detection problems, the challenge is to determine when shapes intersect each other, especially when moving shapes first make contact.</p> <p>Related tag: <a href="/questions/tagged/computational-geometry" class="post-tag" title="show questions tagged &#39;computational-geometry&#39;" rel="tag">computational-geometry</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T07:55:49.900", "Id": "36888", "Score": "0", "Tags": null, "Title": null }
36888
In collision detection problems, the challenge is to determine when shapes intersect each other.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T07:55:49.900", "Id": "36889", "Score": "0", "Tags": null, "Title": null }
36889
<p>Is there a better algorithm for finding the common divisors of two numbers? Can this code be shortened?</p> <pre><code>import java.util.*; public class Testing1 { public static void main (String args[]){ Scanner x=new Scanner(System.in); System.out.print("Enter the 1st number(larger number) : "); int y=x.nextInt(); System.out.print("Enter the 2nd number : "); int z=x.nextInt(); int ar1[]=new int[y]; int ar2[]=new int[z]; for( int i=1;i&lt;y;i++){ //puts the divisors of the larger number to an array ar1[] int l=y%i; if(l==0) ar1[i]=i;} for( int i=1;i&lt;z;i++){//puts the divisors of the other number to an array ar2[] int l=z%i; if(l==0) ar2[i]=i;}System.out.print("Common divisors of "+y+", "+z+" = "); for(int i=1;i&lt;=ar2.length-1;i++){ //printing the common elements of both arrays. if((ar1[i]==ar2[i])&amp;&amp;ar2[i]!=0) System.out.print(i+" "); }}} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T14:54:52.313", "Id": "60720", "Score": "4", "body": "You have already accepted an answer, and I don't code in java, but as a mathematician, I would like to point out that there is a very nice recursive algorithm which is much shorter; the Euclidean Algorithm: http://www.math.rutgers.edu/~greenfie/gs2004/euclid.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:37:00.463", "Id": "60891", "Score": "0", "body": "(the common divisors are necessarily the divisors of the greatest common divisor)" } ]
[ { "body": "<p>There are few improvements you can do in your code:</p>\n\n<ul>\n<li><p>First choose better variable names. I would name the <code>Scanner</code> type variable as <code>scanner</code> rather than <code>x</code>. Really, <code>x</code>, <code>y</code>, <code>z</code> are the worst variable name, which doesn't give any idea as to what they denote. </p></li>\n<li><p>Secondly, I won't force user to pass larger number first, and then smaller number. I would take the burden of finding that out myself.</p></li>\n<li><p>There is no need of storing all the divisors of both the numbers in two different arrays. Suppose you have to find common divisor of <code>2</code> and <code>2132340</code>. Will you store all the divisors of <code>2132340</code>, or simply check that the common divisor cannot be greater than the divisor of <code>2</code>, and use that fact?</p></li>\n<li><p>Another fact is, all the divisors of <code>num1</code> will be less than or equal to <code>num1 / 2</code>. Now, if <code>num1 &lt; num2</code>, then the common divisors all must be <code>&lt; num1 / 2</code>. So, iterate the loop till <code>min / 2</code>.</p></li>\n<li><p>Of course, you can move the code that finds the common divisor in a different method, and store them in a <code>List&lt;Integer&gt;</code>.</p></li>\n<li><p>Lastly, it might be possible that the smaller number itself is a divisor of larger number. So, you need to store that too.</p></li>\n</ul>\n\n<p>Here's the modified code which looks a bit cleaner:</p>\n\n<pre><code>public static void main (String args[]){\n Scanner scanner = new Scanner(System.in);\n\n System.out.print(\"Enter the 1st number : \");\n int num1 = scanner.nextInt();\n System.out.print(\"Enter the 2nd number : \");\n int num2 = scanner.nextInt();\n\n List&lt;Integer&gt; commonDivisor = getCommonDivisor(num1, num2);\n System.out.println(commonDivisor);\n}\n\npublic static List&lt;Integer&gt; getCommonDivisor(int num1, int num2) {\n\n List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();\n\n int min = minimum(num1, num2);\n\n for(int i = 1; i &lt;= min / 2; i++) { \n if (num1 % i == 0 &amp;&amp; num2 % i == 0) {\n list.add(i);\n }\n }\n\n if (num1 % min == 0 &amp;&amp; num2 % min == 0) {\n list.add(min);\n }\n\n return list;\n}\n\npublic static int minimum(int num1, int num2) {\n return num1 &lt;= num2 ? num1 : num2;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T09:12:09.160", "Id": "60705", "Score": "0", "body": "Thank you for your advice.I will go through this and try to improve myself.:)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T09:35:12.750", "Id": "60706", "Score": "0", "body": "I get a run time error in this code saying \"the method minimum(int, int) is undefined for the type ComDivi\" . My class name was ComDivi. How can i solve this problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T10:09:49.733", "Id": "60714", "Score": "0", "body": "@Razor1692 You forgot to add the `minimum` method. Check the complete code in my answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T08:57:57.753", "Id": "36892", "ParentId": "36890", "Score": "7" } }, { "body": "<ol>\n<li><p>This might have been mentioned before but here it is anyway: You should format your code. Badly formatted code is hard to read - it might be the most efficient code in the world but it's still hard to read and maintain and easy to miss bugs or easy to add bugs.</p>\n<p>It also shows a lack of attention to detail and programming is all about attention to detail. It basically demonstrates that not much care has been put into. Whenever you write some code imagine you'd have to show it as an example of your work for your next job interview.</p>\n</li>\n<li><p>You should name your classes and variables better. While <code>i</code> is acceptable for a loop variable <code>l</code>, <code>x</code>, <code>y</code>, and <code>z</code> should be renamed to reflect what their meaning is. It is especially confusing since <code>x</code> suggests to have a similar meaning to <code>y</code> and <code>z</code> while it actually is completely different (it represents a form of input rather than a number).</p>\n</li>\n<li><p>You should use an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html\" rel=\"noreferrer\"><code>ArrayList</code></a> rather than a fixed size array to store the divisors. If someone inputs <code>2147483647</code> then your program would try to allocate an array with 2,147,483,647 elements - approx. 8GB of memory even though it's a prime number.</p>\n<p>If you change this then your check for the common divisors need to check the common subset s of both lists instead.</p>\n</li>\n<li><p>Your two <code>for</code> loops do the exact same thing except on different inputs. They should be refactored into one common method which performs the calculation and gets the number to check as input.</p>\n</li>\n<li><p>Your algorithm is buggy. For example if you check <code>2</code> and <code>4</code> you will not find <code>2</code> as a common divisor.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T08:58:06.000", "Id": "36893", "ParentId": "36890", "Score": "5" } }, { "body": "<p>You should factor out your code for finding one number's divisors into an own function like:</p>\n\n<pre><code>List&lt;Integer&gt; getDivisors(Integer number) {\n List&lt;Integer&gt; divisors = new List&lt;Integer&gt;();\n for(int currentDivisor = 1; currentDivisor &lt;= number; currentDivisor++)\n if(number % currentDivisor == 0)\n divisors.add(currendDivisor);\n return divisors;\n}\n</code></pre>\n\n<p>Instead of just using this function in the code you should also revise the algorithm a bit. As indicated by jpreen in a comment you should use Euclid's algorithm for finding the gcd of two numbers.</p>\n\n<p>Once you have the gcd you can derive all further common divisors from it because all common divisors of two numbers are divisors of the gcd of the two numbers.</p>\n\n<p>Thus your code would become:</p>\n\n<pre><code>List&lt;Integer&gt; getCommonDivisors(Integer x, Integer y) {\n return getDivisors(gcd(x, y));\n}\n</code></pre>\n\n<p>The advantages of this approach are: </p>\n\n<ul>\n<li>the gcd does not depend on the order of the arguments</li>\n<li>the gcd is always at most the minimum of the arguments (which makes it effiecient in the case 2, 2132340 mentioned in another answer)</li>\n<li>the code is short and concise (however it should be documented why the trick with the gcd works)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T15:25:24.480", "Id": "36903", "ParentId": "36890", "Score": "5" } } ]
{ "AcceptedAnswerId": "36892", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T08:09:10.843", "Id": "36890", "Score": "7", "Tags": [ "java", "optimization", "beginner", "mathematics" ], "Title": "Determining common divisors of two numbers" }
36890
<p>Testing on localhost, it takes a bit longer to get the results than I would like and gives me this PHP error:</p> <blockquote> <p>Fatal error: Maximum execution time of 30 seconds exceeded</p> </blockquote> <p>I am wondering if there is any way to stop that error from happening, as well as making my class faster to fetch results.</p> <pre><code>&lt;?php class MinecraftAPI { private function getAPI($type, $server) { $url = 'http://api.iamphoenix.me/' . $type . '/?server_ip=' . $server; $file = file_get_contents($url); $file = json_decode($file); if (property_exists($file, 'error')) { return false; } return $file; } /* Fetch Server Information for each server. APIs: http://api.iamphoenix.me/ */ private function statusCheck($server) { $status = $this-&gt;getAPI('status', $server); if ($status != false) { if ($status-&gt;status == 'true') { return true; } return false; } } public function getStatus($server) { $status = $this-&gt;getAPI('status', $server); if ($status != false) { if ($status-&gt;status == 'true') { return '&lt;strong class="status-online"&gt; Online :]&lt;/strong&gt;'; } elseif ($status-&gt;status == 'false') { return '&lt;strong class="status-offline"&gt; Offline :[&lt;/strong&gt;'; } else { return 'Not sure. Check the forums.'; } } } public function getVersion($server) { if ($this-&gt;statusCheck($server) != false) { $version = $this-&gt;getAPI('version', $server); if ($version != false) { return '&lt;span&gt;&lt;strong&gt;' . $version-&gt;version . '&lt;/strong&gt;&lt;/span&gt;'; } else { return false; } } } public function getPlayerCount($server) { if ($this-&gt;statusCheck($server) != false) { $playerCount = $this-&gt;getAPI('players', $server); if ($playerCount != false) { $playersOnline = $playerCount-&gt;players; $playersMax = $playerCount-&gt;players_max; if ($playersOnline == 0) { return ' &lt;span&gt;Players Online: &lt;strong&gt;' . $playersOnline . '/' . $playersMax . '&lt;/strong&gt; &lt;!-- &lt;em class="empty-server"&gt;Server Depleted. Come fill it up!&lt;/em&gt; --&gt;&lt;/span&gt;'; } return '&lt;span&gt;Players Online: &lt;strong&gt;' . $playersOnline . '/' . $playersMax . '&lt;/strong&gt;&lt;/span&gt;'; } } } public function getPlayers($server) { if ($this-&gt;statusCheck($server) != false) { $playersList = $this-&gt;getAPI('list', $server); if ($playersList != false &amp;&amp; $playersList != "") { $players = explode(',', $playersList-&gt;players); if (is_array($players) &amp;&amp; !empty($players)) { foreach ($players as $player) { if ($player !== '') { echo '&lt;img data-tooltip class="has-tip" title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32"&gt;'; } } } else { return false; } } else { return false; } } } } // Initiate the class $api = new MinecraftAPI(); // Define servers $server = [ 'craftblock' =&gt; 'craftblock.me', 'nanoblock' =&gt; 'craftblock.me:25585', 'chocoblock' =&gt; 'craftblock.me:25564' ]; </code></pre> <p><strong>HTML:</strong></p> <pre><code> &lt;div class="server-info"&gt; &lt;span&gt;Status: &lt;?php echo $api-&gt;getStatus($server['craftblock']); ?&gt;&lt;/span&gt; &lt;?php echo $api-&gt;getVersion($server['chocoblock']); ?&gt; &lt;?php echo $api-&gt;getPlayerCount($server['chocoblock']); ?&gt; &lt;/div&gt; &lt;div class="players-online"&gt; &lt;?php $api-&gt;getPlayers($server['craftblock']); ?&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T07:57:10.247", "Id": "61156", "Score": "0", "body": "Have you consider use javascript ajax? If api.iamphoenix.me support CORS, it can be a good solution: you won't need php (at least, for these operations) and most important you can retry servers informations asynchronously" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T08:29:03.030", "Id": "61157", "Score": "1", "body": "Maybe he wants to use PHP or he has too. Telling someone that the solution to their problem is to switch language is not a very good solution IMO." } ]
[ { "body": "<p>I'd imagine your timeout is due to server lag, your code doesn't look to be something that should take anywhere near 30 seconds to execute. You might want to look at using set_time_limit() which has a pretty self explanatory name.</p>\n\n<p>A few other quick observations if i may:</p>\n\n<p>I'd separate out the HTML from the class logic more, in an MVC paradigm one would instantiate the class and assign the output of your methods to variables that you then include in your templates, this way if your class changes you don't need to change your view (the HTML) you can call completely different methods and your HTML can remain unchanged.</p>\n\n<p>e.g. <code>&lt;?php echo $api-&gt;getPlayerCount($server['chocoblock']); ?&gt;</code></p>\n\n<p>Could simply be <code>&lt;?php print $playerCount; ?&gt;</code></p>\n\n<p>Some of your methods return HTML, you might want to consider methods that return just a value, for example</p>\n\n<p><code>$status = $api-&gt;getStatus();</code> and use that in the HTML</p>\n\n<p>I'd refactor <code>getPlayers</code> to not return HTML, rather the values and use limited logic in your template, something like (untested)</p>\n\n<pre><code>/**\n* get players\n* @return array players\n*/\npublic function getPlayers($server)\n{\n $players = array();\n if ($this-&gt;statusCheck($server) != false) \n {\n $playersList = $this-&gt;getAPI('list', $server);\n if ($playersList != false &amp;&amp; $playersList != \"\") \n {\n $players = explode(',', $playersList-&gt;players);\n } \n }\n return $players;\n}\n</code></pre>\n\n<p>and in your template you could loop over players knowing it's always an array (but that sometimes it may have no values).</p>\n\n<p>Finally be sure your use of <code>!= false</code> and <code>!= \"\"</code>, for example, is giving the required results. You might want to look at using <code>!== false</code> just in case you're actually getting a value that equates to false in PHP (e.g. 0 or \"\").</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T20:03:08.977", "Id": "37160", "ParentId": "36891", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T08:19:50.487", "Id": "36891", "Score": "4", "Tags": [ "php", "optimization" ], "Title": "Getting JSON from a remote API sometimes hangs. Can I make this any faster?" }
36891
<p>I'm currently reading a certain pixels color from a process window like this: </p> <pre><code>[DllImport("gdi32.dll")] private static extern int BitBlt(IntPtr srchDc, int srcX, int srcY, int srcW, int srcH, IntPtr desthDc, int destX, int destY, int op); public static Color GetPixel(IntPtr hwnd, int x, int y) { var screenPixel = new Bitmap(1, 1); using (Graphics gdest = Graphics.FromImage(screenPixel)) { using (Graphics gsrc = Graphics.FromHwnd(MemoryHandler.GetMainWindowHandle())) { IntPtr hsrcdc = gsrc.GetHdc(); IntPtr hdc = gdest.GetHdc(); BitBlt(hdc, 0, 0, 1, 1, hsrcdc, x, y, (int)CopyPixelOperation.SourceCopy); gdest.ReleaseHdc(); gsrc.ReleaseHdc(); } } return screenPixel.GetPixel(0, 0); } </code></pre> <p>It seems to be working. </p> <p>I would like to know if I'm disposing everything that I use correctly to avoid memory leaks. If I inspect my app in the task manager I notice that the memory use is increasing a bit for each time i fetch a pixel, but I suppose the garbage collector will kick in when it's supposed to?</p> <p>Also, is there any obvious "better" way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T14:38:25.510", "Id": "60718", "Score": "0", "body": "You're not disposing the `Bitmap`." } ]
[ { "body": "<p>You'll actually need to wrap the <code>Bitmap</code> in a <code>using</code> as well because its base class, <code>Image</code>, implements <code>IDisposable</code>:</p>\n\n<pre><code>public static Color GetPixel(IntPtr hwnd, int x, int y)\n{\n using (Bitmap screenPixel = new Bitmap(1, 1);\n {\n using (Graphics gdest = Graphics.FromImage(screenPixel))\n {\n using (Graphics gsrc = Graphics.FromHwnd(MemoryHandler.GetMainWindowHandle()))\n {\n IntPtr hsrcdc = gsrc.GetHdc();\n IntPtr hdc = gdest.GetHdc();\n BitBlt(hdc, 0, 0, 1, 1, hsrcdc, x, y, (int)CopyPixelOperation.SourceCopy);\n gdest.ReleaseHdc();\n gsrc.ReleaseHdc();\n }\n }\n\n return screenPixel.GetPixel(0, 0);\n }\n}\n</code></pre>\n\n<p>Further, the garbage collector works almost immediately. Or more simply put, if you use a memory allocation tool like MemProfiler, the memory will get cleaned up by GC faster than you can collect it with a snapshot. The <code>Bitmap</code> is likely where you are seeing the little tick.</p>\n\n<p>It may also be worth wrapping the API call in a <code>try ... finally</code>:</p>\n\n<pre><code>IntPtr hsrcdc = gsrc.GetHdc();\nIntPtr hdc = gdest.GetHdc();\n\ntry\n{\n using (Graphics gsrc = Graphics.FromHwnd(MemoryHandler.GetMainWindowHandle()))\n {\n BitBlt(hdc, 0, 0, 1, 1, hsrcdc, x, y, (int)CopyPixelOperation.SourceCopy);\n }\n}\nfinally\n{\n gdest.ReleaseHdc();\n gsrc.ReleaseHdc();\n}\n</code></pre>\n\n<p>to ensure the <code>ReleaseHdc</code> gets called.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:23:32.043", "Id": "60835", "Score": "0", "body": "Yeah, the \"not-disposing-the-bitmap\"-part was a blunder on my end. However, after trying this yesterday (the disposing of the bitmap), the memory usage still increases with each timer tick that I run this in. I only tried running it for a few seconds, so perhaps the GC will kick in if I wait long enough? I don't see the point of the last code snippet. Can you give me an example where `gdest.ReleaseHdc(); gsrc.ReleaseHdc();` wouldn't get called? Thanks for the feedback - much appreciated!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:31:11.113", "Id": "60837", "Score": "1", "body": "@Johan, they wouldn't get called in the current code if an unhandled exception were thrown. Therefore, handling the possible exception means that even if an exception is thrown they'll get disposed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:09:58.507", "Id": "36964", "ParentId": "36899", "Score": "5" } } ]
{ "AcceptedAnswerId": "36964", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T13:09:11.810", "Id": "36899", "Score": "5", "Tags": [ "c#", "winforms" ], "Title": "Reading a certain pixels color from a window" }
36899
<p>first time visiting Code Review. I figured this was a more appropriate spot than SO for this question. Here goes...</p> <p>Currently, I have a php function that converts bbcode format text in to HTML (among other things). A code snippet is as follows...</p> <pre><code>function bbcode_format ($str) { $simple_search = array( '/\[b\](.*?)\[\/b\]/is', // bold '/\[i\](.*?)\[\/i\]/is', // italics '/\[u\](.*?)\[\/u\]/is', // underline ) $simple_replace = array( '&lt;strong&gt;$1&lt;/strong&gt;', '&lt;em&gt;$1&lt;/em&gt;', '&lt;u&gt;$1&lt;/u&gt;' ) $str = preg_replace ($simple_search, $simple_replace, $str); return $str; } </code></pre> <p>The code itself works fine. However, in my actual code, there are currently around 60 items in each array I'm checking for, as I also used it to convert smileys, for example. </p> <p>My concern is that this approach doesn't seem to be scalable, at least in the sense that the array just keeps growing and growing. </p> <p>I'm wondering if anyone has another approach as to how this might be done, or any suggestions to improve my current method. Thanks!</p> <p><strong>Additional Info</strong></p> <p>Thanks for the suggestions so far... I may not have used the best examples above, as b / i / u are only a small set of what I'm replacing. I probably have more "smiley" replacements, than anything, so those generally look like this...</p> <pre><code>'/:\)/is', // smiley :) '/:d/is', // laugh smiley :D '/\:gift1\:/is', // Holiday Gift 1 :gift1: '/\:gift2\:/is', // Holiday Gift 2 :gift2: </code></pre> <p>Each of those is then replaced with an tag. </p>
[]
[ { "body": "<p>You have two issues: how to represent all of the desired transformations as code, and how to perform the substitutions efficiently.</p>\n\n<p>To address the data representation issue — you want to use an <a href=\"http://php.net/array\" rel=\"nofollow\">associative array</a>.</p>\n\n<pre><code>$simple_replacement_patterns = array(\n '/\\[b\\](.*?)\\[\\/b\\]/is' =&gt; '&lt;strong&gt;$1&lt;/strong&gt;',\n '/\\[i\\](.*?)\\[\\/i\\]/is' =&gt; '&lt;em&gt;$1&lt;/em&gt;',\n '/\\[u\\](.*?)\\[\\/u\\]/is' =&gt; '&lt;u&gt;$1&lt;/u&gt;',\n);\n</code></pre>\n\n<p>However, there is a lot of redundancy there, which violates the Don't Repeat Yourself principle. Ideally, your source code should contain just</p>\n\n<pre><code>$simple_tag_translations = array(\n 'b' =&gt; 'strong',\n 'i' =&gt; 'em',\n 'u' =&gt; 'u',\n);\n</code></pre>\n\n<p>… and the computer build <code>$simple_replacement_patterns</code> for you.</p>\n\n<p>Consider mapping <code>[b]bold text[/b]</code> to <code>&lt;b&gt;bold text&lt;/b&gt;</code>, <code>[i]italic text[/i]</code> to <code>&lt;i&gt;italic text&lt;/i&gt;</code>, and <code>[u]underlined text[/u]</code> to <code>&lt;u&gt;underlined text&lt;/u&gt;</code>. Not only would the mapping be trivial (BBCode is inspired by HTML designed to be easily translated, after all), you would also not be inferring semantic value into the style. For example, maybe the BBCode text was italicized because it is a title in a bibliography entry, not because it is to be emphasized.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:25:17.617", "Id": "60759", "Score": "0", "body": "Thanks for the info here... I like the use of the associative array. This definitely keeps readability up... as most of the comments in my arrays are there so that I can keep track of which line is which between them. Using this would help a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:26:49.047", "Id": "60760", "Score": "0", "body": "Also, until you mentioned it, I always thought the use of <i> and <b> were deprecated, or at least frowned upon. But I read up on it on MDN a bit, and your suggestions are definitely valid." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:27:33.217", "Id": "36914", "ParentId": "36901", "Score": "2" } }, { "body": "<p>I suspect that you might get better performance by performing one substitution rather than one per tag. You'll have to use <a href=\"http://php.net/manual/en/regexp.reference.back-references.php\" rel=\"nofollow\">PCRE back references</a> and <a href=\"http://php.net/preg_replace_callback\" rel=\"nofollow\"><code>preg_replace_callback()</code></a>.</p>\n\n<pre><code>$simple_tag_translations = array(\n 'b' =&gt; 'strong',\n 'i' =&gt; 'em',\n 'u' =&gt; 'u',\n);\n\n# $bb_pattern = '#\\[(b|i|u)\\](.*?)\\[/\\1\\]#is';\n$bb_pattern = '#\\[(' .\n implode('|', array_keys($simple_tag_translations)) .\n ')\\](.*?)\\[/\\1\\]#is';\n\nreturn preg_replace_callback(\n $bb_pattern,\n function($matches) {\n $bb_tag = $matches[1];\n $body = $matches[2];\n $html_tag = $simple_tag_translations[$bb_tag];\n return \"&lt;$html_tag&gt;$body&lt;/$html_tag&gt;\";\n },\n $str\n);\n</code></pre>\n\n<p>The usual <code>/</code> is a poor choice for your PCRE delimiter since you are trying to match closing tags. You might as well pick <a href=\"http://php.net/manual/en/regexp.reference.delimiters.php\" rel=\"nofollow\">another character</a> to help avoid <a href=\"http://en.wikipedia.org/wiki/Leaning_toothpick_syndrome\" rel=\"nofollow\">Leaning Toothpick Syndrome</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T18:02:55.270", "Id": "36917", "ParentId": "36901", "Score": "2" } } ]
{ "AcceptedAnswerId": "36914", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T15:01:55.300", "Id": "36901", "Score": "2", "Tags": [ "php", "optimization" ], "Title": "Looking for a better way to handle this growing array used for preg_replace" }
36901
<p>While coding today, I came across the following loop in C#:</p> <pre><code>for(int x = 0; x &lt; max_x_index; x++){ for(int y = 0; y &lt; max_y_index; y++, count++){ some2DarrayRepresentedBy1D[count] = ...; } } </code></pre> <p>Would this be consider bad practice? Would the following be a better way to achieve the same result: </p> <pre><code>for(int x = 0; x &lt; max_x_index; x++){ for(int y = 0; y &lt; max_y_index; y++){ some2DarrayRepresentedBy1D[count] = ...; count++; } } </code></pre> <p>Would you allow both through, for example, a code review or would you tag the first example for being obscure? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:43:50.347", "Id": "60741", "Score": "1", "body": "I see this question has been tagged with both \"C\" and \"Java\". Idiomatic code in the two languages is different, so the best answer may well be different in different languages - for example, rolfl's `some2Darray[count++]` is common in C, but I don't see it very often in Java." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:47:50.187", "Id": "60743", "Score": "0", "body": "Ah, I see it wasn't you, but @200_success that added the tags..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T18:05:13.907", "Id": "60746", "Score": "1", "body": "@Izkata `some2Darray[count++]` is just as valid in Java as in C. There's no reason or evidence to suggest that it's less prevalent in Java." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T18:57:13.930", "Id": "60750", "Score": "2", "body": "@200_success I never said anything about validity, I know it's valid in both languages. But idiomatic usage isn't always cross-language." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T19:07:46.810", "Id": "60751", "Score": "0", "body": "@Izkata Fair point. I've removed [tag:c] and [tag:java] tags." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T19:30:28.400", "Id": "61454", "Score": "0", "body": "In this question, it's not clear why the separate `count` variable is needed. I'm sure there's a good reason, but why not just use `y`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T21:23:53.043", "Id": "61510", "Score": "0", "body": "@neontapir - because `y` resets every iteration of `x`. `count` will end with a value of `x * y`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T21:31:11.230", "Id": "61517", "Score": "2", "body": "Duh, of course it would. Thank you, @afuzzyllama." } ]
[ { "body": "<p>I would agree with the OP in that the second code block would be the best approach. </p>\n\n<p><strong>Reason</strong> - readability. In my opinion, the variable incremented in the for loop statement should only be used for keeping count of how many times we're looping. <code>count</code> might be set before the loop, it might also be incremented / decremented in several different loops. But in either case, <code>count</code> isn't used to keep track of the progress of the current loop - <code>y</code> is in this case.</p>\n\n<p>So, I would say that it's best practice, for readability sake, to only increment the variable used to loop through the for loop in the for loop line itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T15:49:37.337", "Id": "36906", "ParentId": "36904", "Score": "27" } }, { "body": "<p>Of all the answers so far, I think that Charlie74 is closest to reasoning the same way I do.</p>\n\n<p>The for loop consists of three segments:</p>\n\n<pre><code>for (initialization; termination; increment) {\n statement(s)\n}\n</code></pre>\n\n<p>it is my opinion that only things that affext the termination should be part of the increment.... In other words, if the value is not part of the termination condition then it should not be part of the increment.</p>\n\n<p>In this case, the count does not affect the termination condition, and as a result it does not belong in the increment section..</p>\n\n<p>For what it's worth, there are a couple of things I would do differently still:</p>\n\n<ol>\n<li>you have a typos in your second example.... (missing <code>x</code> in <code>x &lt;</code> and missing <code>y &lt;</code>) <em>[This has been fixed in the question now.]</em></li>\n<li>I would include the count++ as part of the array assignment (which is where I think it belongs):</li>\n</ol>\n\n\n\n<pre><code>for(int x = 0; x &lt; max_x_index; x++){\n for(int y = 0; y &lt; max_y_index; y++){ \n some2Darray[count++] = ...;\n }\n}\n</code></pre>\n\n<hr>\n\n<h1>Discussion on <code>++count</code> vs. <code>count++</code> in this context</h1>\n\n<blockquote>\n <p>is this one of those instances where if you change <code>i++</code> to <code>++i</code> it will change what is assigned in the array? could you explain that a little more ... ?</p>\n</blockquote>\n\n<p>Here goes.... Yes, this is one of the situations where the the pre-increment or post-increment difference is significant. <a href=\"http://en.wikipedia.org/wiki/Increment_and_decrement_operators\" rel=\"nofollow noreferrer\">Wikipedia has a section</a> on this.</p>\n\n<p>The pre-increment operator <code>++count</code> increments the count variable. The post-increment operator <code>count++</code> also increments the count variable. The difference is that while both <code>++count</code> and <code>count++</code> <a href=\"http://en.wikipedia.org/wiki/Expression_%28computer_science%29\" rel=\"nofollow noreferrer\">are <strong>expressions</strong></a>, the <strong>resulting values</strong> of the expressions are different.</p>\n\n<p>It is important to understand what it means that <code>count++</code> is an expression. An expression is something that produces a value. In the context <code>array[count] = 1</code>, the <code>count</code> is an expression, it is something with a value. That expression could instead be a constant (<code>array[0]</code>), a function (<code>array[getNextIndex()]</code>, or even a more complex expression consisting of sub-expressions and operators (<code>array[5 - 3]</code>).</p>\n\n<p>So, <code>count++</code> is an expression. It is also something that modifies the value in the <code>count</code> variable. Similarly, <code>++count</code> is an expression, and it also modifies the value of <code>count</code>. The difference between them is <strong>not</strong> what they do to <code>count</code>, but it is <strong>the value of the expression</strong>.</p>\n\n<p>With <code>count++</code> the value of the expression is the value of <code>count</code> <strong>before</strong> it is incremented.</p>\n\n<p>With <code>++count</code> the value of the expression is the value of <code>count</code> <strong>after</strong> it is incremented.</p>\n\n<p>Thus, in the example above, compare two different situations:</p>\n\n<pre><code>int count = 0;\narray[count++] = 1;\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>int count = 0;\narray[++count] = 1;\n</code></pre>\n\n<p>In the first example, the value of the expression <code>count++</code> is 0 (the value before the increment) and as a result, the value at index <code>0</code> of the <code>array</code> is set to <code>1</code>. I.e. it is equivalent to:</p>\n\n<pre><code>int count = 0;\narray[count] = 1;\ncount = count +1;\n</code></pre>\n\n<p>in the second example, the value of the expression <code>++count</code> is 1 (the value after the increment) and as a result, the value at index <code>1</code> of the <code>array</code> is set to <code>1</code>. I.e. it is equivalent to:</p>\n\n<pre><code>int count = 0;\ncount = count + 1;\narray[count] = 1;\n</code></pre>\n\n<p>It is obvious, that by using <code>++count</code> we will start adding data at index 1 instead of 0, and we run the risk of an out-of-bounds operation when we get to the end of the data.</p>\n\n<p>In the case of adding data to an array (like what this question is doing), it makes sense to set a counter to the 'next' slot to use, and then do a post-increment so that you 'use' the next slot, and then increment it so it is pointing to the next slot again.</p>\n\n<p>A bonus of doing things this way is that, at the end, the <code>count</code> is also the number of slots in the array that you have used.</p>\n\n<p>Serendipitously, another question came up ( <a href=\"https://codereview.stackexchange.com/questions/37201/finding-all-indices-of-largest-value-in-an-array\">Finding all indices of largest value in an array</a> ) where one potential answer <a href=\"https://codereview.stackexchange.com/questions/37201/finding-all-indices-of-largest-value-in-an-array/37231#37231\">illustrates this point nicely</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T16:19:02.043", "Id": "60728", "Score": "1", "body": "So you would put `count++` into the increment section if the loop condition would contain for example `&& count < maxCount`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T16:27:38.470", "Id": "60729", "Score": "1", "body": "Absolutely, yes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T19:02:37.907", "Id": "61050", "Score": "0", "body": "@rolfl, is this one of those instances where if you change `i++` to `++i` it will change what is assigned in the array? could you explain that a little more, so someone doesn't get confused when they put `[++count]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T19:42:40.043", "Id": "61063", "Score": "3", "body": "@Malachi it will change **where** in the array it is assigned. For `x=0;y=0` you will assign to position 0 with `count++`, and to position 1 with `++count`. (Assuming count=0 before the loop.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T16:14:01.883", "Id": "36910", "ParentId": "36904", "Score": "14" } }, { "body": "<p>There is a correctness concern with such a change. In the example given, the transformed loop is equivalent (aside from the order in which the increments occur; I'm assuming these are both <code>int</code> variables, so is unlikely to matter).</p>\n\n<p>However if the body of the loop can contain the <code>continue</code> statement, suddenly there's a very large difference between these two:</p>\n\n<pre><code>int count = 0;\nfor (int x = 0; x &lt; MAX; ++x, ++count)\n{\n : : :\n if (sometest())\n continue;\n : : :\n}\n</code></pre>\n\n\n\n<pre><code>int count = 0;\nfor (int x = 0; x &lt; MAX; ++x)\n{\n : : :\n if (sometest())\n continue;\n : : :\n ++count;\n}\n</code></pre>\n\n<p>In the latter code block, <code>count</code> is only incremented if the loop body completes. In the former code block, <code>count</code> is incremented whenever starting the next loop iteration. The use case may determine which of these is correct, and the decision between these may deserve a comment to help avoid breaking it later.</p>\n\n<p>Note that moving <code>++count</code> to the beginning of the second example would make it somewhat more similar to the first example, but in your example would require indexing your array with <code>count - 1</code>. As a similar alternative if you only use the index once, you could use a construct such as <code>some2Darray[count++]</code> instead of either, although like the original second code block this risks misbehavior from an early <code>continue</code> as well, and some would consider it less readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:19:04.807", "Id": "36913", "ParentId": "36904", "Score": "5" } }, { "body": "<p>I think that @rolfl is on the right track with</p>\n\n<pre><code>for (int x = 0; x &lt; max_x_index; x++) {\n for (int y = 0; y &lt; max_y_index; y++) {\n some2Darray[count++] = ...;\n }\n}\n</code></pre>\n\n<p>A good reason for using a for-loop rather than</p>\n\n<pre><code>/* initialization */;\nwhile (/* condition */) {\n /* body */;\n\n /* increment */;\n}\n</code></pre>\n\n<p>is to give your code an immediately recognizable appearance that matches its purpose. Therefore, the initialization, condition, and increment parts should all contribute to the same purpose. You should avoid introducing \"off-topic\" code in the for-loop header.</p>\n\n<p>Additionally, <code>some2Darray[count++] = ...</code> effectively conveys, in just one line, that you want to populate the array — write an element, then move on to the next.</p>\n\n<hr>\n\n<p>Other users here have objected that the <code>count++</code> might be bypassed due to some unexpected flow control in the loop body. The goal of the code appears to be producing a flat 2D array, so I doubt that there would be any <code>break</code> or <code>continue</code> involved. However, if you are still concerned about consistency, you could use an assertion.</p>\n\n<pre><code>int count = 0;\nfor (int x = 0; x &lt; max_x_index; x++) {\n for (int y = 0; y &lt; max_y_index; y++) {\n some2Darray[count++] = ...;\n }\n}\nDebug.Assert(count == max_x_index * max_y_index);\n</code></pre>\n\n<p>Alternatively, eliminate <code>count</code> altogether and just use <code>x * max_y_index + y</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T22:24:46.977", "Id": "60775", "Score": "1", "body": "As one of those pointing out that flow control can miss a trailing increment, I agree that in the given usage this isn't going to happen. But the point must be considered when giving general guidance about what to accept in a code review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T01:54:28.227", "Id": "60789", "Score": "0", "body": "\"Count\" is more clear than \"x * max_x_index + y\", and it continues to work if the array becomes more complicated (for example if some iterations push zero elements or more than one element)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T18:41:05.837", "Id": "36920", "ParentId": "36904", "Score": "7" } }, { "body": "<p>Several people on this thread have talked about how a <em>for</em> loop <em>works</em>, but few have mentioned the <em>semantic</em> difference between a <em>for</em> loop and a <em>while</em> loop.</p>\n\n<p>When a programmer encounters a <em>for</em> loop when reading code, the semantic is that the loop <em>definitely terminates</em> and <em>iterates</em> over some range of numbers or some list of elements. That's why all programmers immediately know what the following loops do, and they are very easy to mentally understand and parse.</p>\n\n<pre><code>// iterate over the integer range N...M\nfor(int i = N; i &lt; M; i++)\n func(N)\n\n// iterate over every element in array\nfor(int i = 0; i &lt; array.length; i++)\n func(array[i]);\n\n// iterate over some singly linked list\nfor(item = list; item != NULL item=item-&gt;Next)\n func(item);\n\n// iterate over some doubly linked list:\nfor(item = listHead-&gt;Next; item != listHead; item = item-&gt;Next)\n func(item);\n</code></pre>\n\n<p>For this reason, both of your first two arrays are well designed, and are quick and easy to understand during a code-review. The two lists are iterating x and y over all of the items [0,0] to [max_x_index, max_y_index].</p>\n\n<p>But if you <em>poison</em> one of the two for loops so that they no longer look normal by adding some semantically unrelated variable (count) to one of the loops, suddenly the entire loop becomes harder to mentally understand. <em>count</em> is not related to [x,y] iterating over the loop. It's semantically related to how many elements are in <em>some2DArray</em>, and moving them far from each other makes the code as a whole harder to read, and inevitably, harder to maintain and debug as well.</p>\n\n<p>Instead, good practice is to modify variables close to their semantic meaning, which aids comprehension of the code. To do this, you should modify <em>count</em> at the point where <em>count</em> ought to change - not when the loop iterates, but when you modify <em>some2DArray</em> either via inline increment:</p>\n\n<pre><code> some2DArray[count++] = ...\n</code></pre>\n\n<p>or immediately afterwards:</p>\n\n<pre><code> some2DArray[count] = ...\n count++\n</code></pre>\n\n<p>So in answer to your question, it's almost never a good idea to increment multiple variables within a for loop. The for loop should deal exclusively with modifying elements that are <em>being iterated</em>, and leave other variables well alone. Violation of this confuses the semantic of the program, and makes it much harder to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T02:12:17.317", "Id": "36933", "ParentId": "36904", "Score": "5" } }, { "body": "<h2>UPDATE</h2>\n\n<p>Matt made a really good point, but I still believe that the two following code blocks will sit well with what Matt said in his answer.</p>\n\n<p><code>count</code> is incremented every iteration of the inside for loop so it is changing where it should be changed in both blocks of code.</p>\n\n<p>you should not increment a variable that is not declared in the Declaration of the For loop.</p>\n\n<p>that said, you could do it like this</p>\n\n<pre><code>for(int x = 0, int count = 0; x &lt; max_x_index; x++){\n for(int y = 0; y &lt; max_y_index; y++, count++){ \n {\n some2DarrayRepresentedBy1D[count] = ...;\n }\n}\n</code></pre>\n\n<p>this is fairly confusing if you didn't write the code though, and thus violates the KISS Principle and/or the <a href=\"http://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow\">POLS/POLA</a> Principle (Principle of Least Surprise/Astonishment)</p>\n\n<p>going off the Answer given by Rolfl, this would be less code to write and probably slightly cleaner code, again, you should comment this code with what you did and why you do it this way.</p>\n\n<pre><code>for(int x = 0, int count = 0; x &lt; max_x_index; x++){\n for(int y = 0; y &lt; max_y_index; y++){ \n {\n some2DarrayRepresentedBy1D[count++] = ...;\n }\n}\n</code></pre>\n\n<hr>\n\n<hr>\n\n<h1>Random bit of knowledge</h1>\n\n<p>what you could do with this</p>\n\n<pre><code>for(int x = 0; x &lt; max_x_index; x++){\n for(int y = 0; y &lt; max_y_index; y++){ \n {\n some2DarrayRepresentedBy1D[count] = ...;\n count++;\n }\n}\n</code></pre>\n\n<p>because it the incrementers are only used to progress the loops (depending on what you are counting, [this example will give you a completely different result])</p>\n\n<pre><code>for (int x = 0, int y = 100;x &lt; max_x_index, y &gt; max_y_index; x++, y--){\n some2DarrayRepresentedBy1D[count] = ... ;\n count++;\n}\n</code></pre>\n\n<p><strong>I only give this as an example that you can use two incrementers in one for loop, but what the OP posted is not one of those instances.</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T18:57:22.627", "Id": "61048", "Score": "2", "body": "I think rather than KISS you mean principle of least surprise?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T19:06:17.497", "Id": "61051", "Score": "0", "body": "@Nobody that is exactly what I was going to comment: \"you mean POLS\" :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T19:26:56.873", "Id": "61057", "Score": "0", "body": "it is the best way to increment that variable if you want to put it into the for loop and eliminate extra lines, maybe not extra comments or characters. I would love to see the stats on performance pitting the two ways against each other though" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T18:54:57.150", "Id": "37068", "ParentId": "36904", "Score": "2" } }, { "body": "<p>You mentioned in a comment that ultimately the end result will be setting every member of an array up to <code>x * y</code></p>\n\n<blockquote>\n <p>@neontapir - because <code>y</code> resets every iteration of <code>x</code>. <code>count</code> will end with a value of <code>x * y</code>. – afuzzyllama 1 hour ago</p>\n</blockquote>\n\n<p>so here is my thought, Instead of doing this:</p>\n\n<pre><code>for(int x = 0; x &lt; max_x_index; x++){\n for(int y = 0; y &lt; max_y_index; y++, count++){ \n {\n some2DarrayRepresentedBy1D[count] = ...;\n }\n} \n</code></pre>\n\n<p>Do this</p>\n\n<pre><code>for (int i = 0; i &lt; max_x_index * max_y_index; i++)\n{\n some2DarrayRepresentedBy1D[i] = ...;\n}\n</code></pre>\n\n<p>obviously I don't know what you are doing in <code>...</code> but if you are nested in two <code>For</code> loops and there isn't much else going on here then I assume that you are doing the same thing every time. this looks like the answer that you may be looking for, <strong>if not you need to show more code</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T23:16:57.410", "Id": "61540", "Score": "0", "body": "Presumably, the ellipsis in the original code was `someProcess(someMatrix[x][y])`. With this proposal, it would have to be `someProcess(someMatrix[i / max_y_index][i % max_y_index])`. I wouldn't consider that an improvement in either clarity or performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T23:21:39.397", "Id": "61541", "Score": "0", "body": "@200_success, that formula doesn't seem right to me, but if that was the case then it would make sense to perform it like my other answer. but that information should be in the question, even though OP is asking something else entirely" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T00:56:20.630", "Id": "61556", "Score": "0", "body": "@Malachi - the point of the question is to ask about the placement of `count` in the for declaration and if it was common or not" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T03:27:54.517", "Id": "61578", "Score": "0", "body": "@afuzzyllama I know, I read the question after words and realized I was very far from what you were asking. but I hope that it gives you another way to look at your code as well. from what 200_success commented though I don't think this specific answer will work. my other answer should work nicely for you and doesn't seem to break any rules" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T23:00:59.137", "Id": "37263", "ParentId": "36904", "Score": "2" } } ]
{ "AcceptedAnswerId": "36906", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T15:28:56.333", "Id": "36904", "Score": "26", "Tags": [ "c#" ], "Title": "Is it bad practice to increment more than one variable in a for loop declaration?" }
36904
<p>I've written a very basic Python 3 script to search ThePirateBay. Since the tracker doesn't have an API, I had to parse the HTML using BeautifulSoup. I'd like to get some reviews, I'm pretty sure the code is crap, so fire away. I'm also interested in projects I could read to improve my Python.</p> <pre><code>#!/usr/bin/env python3 from urllib.parse import quote from urllib.request import urlopen from bs4 import BeautifulSoup from constants import * import re import webbrowser class Torrent: def __str__(self): return "(%s / %s) (%s) (%s) (%d SE / %d LE) %s" % (self.category, self.subcategory, self.size, self.date, self.seeders, self.leeches, self.name) def download(self): webbrowser.open(self.magnet, autoraise=False) def search(keywords, categories=[ALL, ], order=SEED_DESC): url = '%s/search/%s/0/%d/%s' % (TPB_DOMAIN, quote(keywords), order, ','.join([str(x) for x in categories])) return parse(url) def parse(url): META_REGEX_FORMAT = "Uploaded (.*), Size (.*), ULed by (.*)" UNICODE_BLANK = '\xa0' BLANK = ' ' ROWS = 'tr' DATA = 'td' soup = BeautifulSoup(urlopen(url).read()) torrents = [] for result in soup.find_all(ROWS)[1:]: torrent = Torrent() data = result.find_all(DATA) a = data[0].find_all('a') torrent.category = a[0].string torrent.subcategory = a[1].string a = data[1].find_all('a') torrent.link = a[0]['href'] torrent.name = a[0].string torrent.magnet = a[1]['href'] torrent.user = data[1].font.a if torrent.user is not None: torrent.user = torrent.user.text else: torrent.user = data[1].font.i.text pattern = re.compile(META_REGEX_FORMAT) match = pattern.match(data[1].font.text) torrent.date = match.group(1).replace(UNICODE_BLANK, BLANK) torrent.size = match.group(2).replace(UNICODE_BLANK, BLANK) torrent.seeders = int(data[2].text) torrent.leeches = int(data[3].text) torrents.append(torrent) return torrents def get_query(): text = input("Search: ") pattern = re.compile('"(.+)" \-(.*) \-(.*)') m = pattern.match(text) cat = [] for x in m.group(2).upper().split(','): try: cat.append(globals()[x]) except KeyError: pass try: order = globals()[m.group(3).upper()] except KeyError: order = SEED_DESC return m.group(1), cat, order def search_engine(): try: while True: kw, cat, order = get_query() i = 0 results = search(kw, cat, order) for result in results: i += 1 print("[%2d] %s" % (i, result)) i = int(input('Torrent: ')) if i &gt; 0: results[i - 1].download() except EOFError: pass if __name__ == '__main__': search_engine() </code></pre> <p><strong>constants.py</strong></p> <pre><code>""" CATEGORIES """ ALL = 0 AUDIO = 100 MUSIC = 101 AUDIO_BOOKS = 102 SOUND_CLIPS = 103 FLAC = 104 AUDIO_OTHER = 199 VIDEO = 200 MOVIES = 201 MOVIES_DVDR = 202 MUSIC_VIDEOS = 203 MOVIE_CLIPS = 204 TV_SHOWS = 205 HANDHELD = 206 HDMOVIES = 207 HDTV = 208 VIDEO_OTHER = 299 APPS = 300 WINDOWS = 301 APPS_MAC = 302 UNIX = 303 HANDHELD = 304 APPS_IOS = 305 APPS_ANDROID = 306 APPS_OTHER = 399 GAMES = 400 PC = 401 GAMES_MAC = 402 PSX = 403 XBOX360 = 404 WII = 405 HANDHELD = 406 GAMES_IOS = 407 GAMES_ANDROID = 408 GAMES_OTHER = 499 OTHER = 600 EBOOKS = 601 COMICS = 602 PICTURES = 603 COVERS = 604 PHYSIBLES = 605 """ ORDER """ NAME_DESC = 1 NAME_ASC = 2 DATE_DESC = 3 DATE_ASC = 4 SIZE_DESC = 5 SIZE_ASC = 6 SEED_DESC = 7 SEED_ASC = 8 LEEC_DESC = 9 LEEC_ASC = 10 USER_DESC = 11 USER_ASC = 12 """ MISCELLANEOUS """ TPB_DOMAIN = "http://thepiratebay.sx" # Not using HTTPS because of speed </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:05:23.577", "Id": "60734", "Score": "0", "body": "@200_success I did post the code, what do you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:10:02.533", "Id": "60736", "Score": "0", "body": "I embedded the code and removed the link. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:14:45.787", "Id": "60737", "Score": "0", "body": "For completeness, could you post your `constants` as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:23:54.450", "Id": "60739", "Score": "0", "body": "Here they are! It's pretty basic, although I could find a way to actually generate them from the site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T18:36:55.250", "Id": "60749", "Score": "0", "body": "If you're \"pretty sure the code is crap\" then this is not ready for review! You need to improve it to the point where you're pretty sure it's not crap *before* asking us to review it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T19:55:36.777", "Id": "60753", "Score": "1", "body": "Well, I don't have ideas for improvements, but I'm sure there are things I could do more effectively." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T21:02:16.437", "Id": "60768", "Score": "1", "body": "\"pretty sure the code is crap\" says more about *your self-confidence as a programmer* than about your code." } ]
[ { "body": "<p>By reading the code the only thing i could \nthought to improve your code is to change this </p>\n\n<pre><code>def search_engine():\n try:\n pattern = re.compile('\"(.+)\" \\-(.*) \\-(.*)')\n while True:\n kw, cat, order = get_query(pattern)\n</code></pre>\n\n<p>and this one </p>\n\n<pre><code>def get_query(pattern):\n text = input(\"Search: \")\n m = pattern.match(text)\n</code></pre>\n\n<p>So you won't have to compile your regex each time</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T11:42:25.517", "Id": "38681", "ParentId": "36909", "Score": "2" } }, { "body": "<p>I'm no Python expert, but I would definitely extract <code>parse_torrent(data)</code> from the <code>for</code> loop. </p>\n\n<p>I wouldn't make it a <code>@staticmethod</code> on <code>Torrent</code> though, because if you ever need to extend you code to support other trackers, <code>Torrent</code> shouldn't “know” about parsing one specific tracker's response.</p>\n\n<p>So I would just place <code>parse_torrent</code> alongside other functions.</p>\n\n<p>Also, your use of <code>globals</code> looks fishy: from my understanding it is <a href=\"https://stackoverflow.com/a/12694065/458193\">more of a debugging tool</a> than something you should use in production code. It also took me a while to realize you're using it to get constant values.</p>\n\n<p>This has several downsides:</p>\n\n<ul>\n<li><p>It's not evident that imported <code>constants</code> are used at all (since symbol search won't find 'em), so there's a risk someone will remove the import (with all the good intentions of course);</p></li>\n<li><p>Imagine there is a new category on Pirate Bay. Your code breaks. Another team member sees <code>globals()[x]</code> and now has to <em>guess</em> where to put the missing constant. Also, I'm sure the error message will be pretty confusing at first.</p></li>\n<li><p>It's unlikely to happen, but what if Pirate Bay adds a category called <code>Torrent</code> and you don't update your code? <code>globals()[x]</code> will return <code>Torrent</code> type, and your code will break with all the stranger symptoms.</p></li>\n</ul>\n\n<p>In short, <strong>don't use <code>globals()</code> for this</strong>.</p>\n\n<p>Instead, change</p>\n\n<pre><code>from constants import *\n\n# ...\n\n cat.append(globals()[x])\n\n# ...\n\n order = globals()[m.group(3).upper()]\n</code></pre>\n\n<p>to</p>\n\n<pre><code>import constants\n\n# ...\n\n cat.append(constants[x])\n\n# ...\n\n order = constants[m.group(3).upper()]\n</code></pre>\n\n<p>Finally, <code>x</code> and <code>m</code> are bad names for variables because they are not obvious on the first read. I understand <code>m</code> stands for “matches” but I have no idea what your regex is supposed to represent (since it's called just <code>pattern</code>). So I'm pretty much lost on what's happening inside <code>get_query</code>.</p>\n\n<p>You have an extra indentation in <code>search_engine</code>.</p>\n\n<p>Otherwise, the code seems fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T12:14:54.257", "Id": "38688", "ParentId": "36909", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T16:08:01.990", "Id": "36909", "Score": "5", "Tags": [ "python", "parsing", "python-3.x" ], "Title": "Python Script to Search PirateBay" }
36909
<p><strong>Weekend Challenge #2 - <a href="https://codereview.meta.stackexchange.com/questions/1218/proposals-for-weekly-challenge-topics/1220#1220">Poker Hand Evaluation</strong></a></p> <p><strong>Finding a straight with wildcards</strong></p> <p>Because of a size limit on Code Review I have to split my <a href="https://codereview.stackexchange.com/questions/36916/weekend-challenge-poker-hand-evaluation">weekly challenge result</a> in two, and here is a part where I think there is some room for speed optimization. I started writing this method in another approach, but after several hours it still didn't work as expected so I threw it away and started writing this method which directly worked as I wanted it to.</p> <p>The method should take an int array as input, loops through the array to find the highest possible straight (at least five consecutive values of > 0). If encountering a <code>0</code> and it has a wildcard to use, it should use the wildcard to "fill in the gap". For example, the array <code>1 0 1 1 1</code> with one wildcard is a straight, while the array <code>1 0 0 1 1</code> with a wildcard is <em>not</em> a straight.</p> <p>There is no limit to how many wildcards can be used, but if there are five or more wildcards then the wildcards themselves should return the highest possible straight.</p> <p>I'm not quite sure what the time complexity is in this method I have written, but I think worst case is between \$O(n)\$ and \$O(n^2)\$, I think it is about \$O(n^2 / 2)\$ or something. If anyone knows, please let me know.</p> <p>Is it possible to write this method with worst case not higher than \$O(n)\$?</p> <pre><code>/** * Checks for a normal STRAIGHT. Returns null if no straight was found */ public class PokerStraight implements PokerHandResultProducer { /** * Scans an array of ints to search for sequence of 1s. Can fill in gaps by using wildcards * @param ranks An array of the ranks provided by {@link PokerHandAnalyze} * @param wildcards Number of usable wildcards to fill gaps for the straight * @return The highest rank (index + 1) for which the straight started */ public static int findHighestIndexForStraight(int[] ranks, int wildcards) { return findHighestIndexForStraight(ranks, ranks.length - 1, wildcards); } private static int findHighestIndexForStraight(int[] ranks, int startIndex, int wildcards) { int wildsLeft = wildcards; for (int i = startIndex; i &gt;= 0; i--) { int count = ranks[i]; if (count &gt; 0) { // do nothing } else if (wildsLeft &gt; 0) { wildsLeft--; } else { return findHighestIndexForStraight(ranks, startIndex - 1, wildcards); } if (startIndex - i + 1 &gt;= PokerHandResultProducer.HAND_SIZE) return startIndex + 1; } return -1; } @Override public PokerHandResult resultFor(PokerHandAnalyze analyze) { int straight = findHighestIndexForStraight(analyze.getRanks(), analyze.getWildcards()); if (straight != -1) return new PokerHandResult(PokerHandType.STRAIGHT, straight, 0, null); // We don't need to provide any kickers since we have a straight of 5 cards. return null; } } </code></pre> <p>Here is some code to test the method, also showing what I expect it will return:</p> <pre><code>private int findHighestIndexForStraight(int[] ranks, int wildcards) { int res = PokerStraight.findHighestIndexForStraight(ranks, wildcards); return res == -1 ? res : res - 1; // For testing, I want to know the index and not the "rank" } @Test public void straights() { assertEquals(7, findHighestIndexForStraight(new int[]{ 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0 }, 0)); assertEquals(7, findHighestIndexForStraight(new int[]{ 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1 }, 0)); assertEquals(7, findHighestIndexForStraight(new int[]{ 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1 }, 0)); assertEquals(-1, findHighestIndexForStraight(new int[]{ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0 }, 1)); assertEquals(8, findHighestIndexForStraight(new int[]{ 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 }, 1)); assertEquals(6, findHighestIndexForStraight(new int[]{ 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0 }, 1)); assertEquals(10, findHighestIndexForStraight(new int[]{ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }, 1)); assertEquals(4, findHighestIndexForStraight(new int[]{ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, 1)); assertEquals(8, findHighestIndexForStraight(new int[]{ 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0 }, 1)); assertEquals(10, findHighestIndexForStraight(new int[]{ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0 }, 1)); assertEquals(-1, findHighestIndexForStraight(new int[]{ 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1 }, 0)); } </code></pre>
[]
[ { "body": "<p>In this case bit-wise manipulation is your friend .... (as it often is...)....</p>\n\n<p>I believe the following solution makes the combination/permutation expense a 1-off setup problem, and using the <code>Integer.bitCount(...)</code> makes it almost trivial ...</p>\n\n<p>The code I hacked up appears to have a time-complexity of O(n) related to the size of the rank, and a small penalty for the number of wild-cards.... but, in essence, the method runs O(1) since those things will never change much....</p>\n\n<p>but the code looks like:</p>\n\n<pre><code>private static final int[][] WILDCARDS = buildWildCards();\n\nprivate static int[][] buildWildCards() {\n // up to 5 wild cards\n // that is up to 0x1f or 32 values (counting 0).\n int[] pos = new int[6];\n int[][] ret = new int[6][];\n ret[0] = new int[1]; // one value with no bits set. 0x00\n ret[1] = new int[5]; // 5 with 1 bits set 0b10000, 0b01000, 0b00100, 0b00010, 0b00001\n ret[2] = new int[10]; // 10 with 2 bits set ....\n ret[3] = new int[10]; // 10 with 3 bits set ....\n ret[4] = new int[5]; // 5 with 4 bits set 0b01111, 0b10111, 0b11011, 0b11101, 0b11110\n ret[5] = new int[1]; // one value with all bits set. 0x1f\n for (int i = 0; i &lt;= 0x1f; i++) {\n // cout the bits that are set in this number.\n final int bc = Integer.bitCount(i);\n // load this number in to the slot matching the set bit count.\n ret[bc][pos[bc]++] = i;\n }\n return ret;\n}\n\n\n\n/**\n * Scans an array of ints to search for sequence of 1s. Can fill in gaps by using wildcards\n * @param ranks An array of the ranks provided by {@link PokerHandAnalyze}\n * @param wildcards Number of usable wildcards to fill gaps for the straight\n * @return The highest rank (index + 1) for which the straight started\n */\npublic static int findHighestIndexForStraight(int[] ranks, int wildcards) {\n if (wildcards &lt; 0 || wildcards &gt;= WILDCARDS.length) {\n throw new IllegalArgumentException(\"WildCard count is not valid. Input \" + \n wildcards + \" should be between 0 and \" + (WILDCARDS.length - 1));\n }\n\n int hand = 0;\n for (int r : ranks) {\n hand &lt;&lt;= 1;\n hand |= r != 0 ? 1 : 0;\n }\n // OK, the `hand` is set up so that the bits represent the hand.\n // for example, an input array of [0,1,0,0,1,1,1,1,0,0,1] will become:\n // 0b01001111001 or 0x0279\n\n // We now shift off the hand to see if we can make a match;\n // position is a backward-count of the number of shifts we have to do.\n // it starts off at the ranks's length -1, and counts back down.\n // when it is less than 5 (or actually 4 because the condition is checked\n // before the decrement)\n // there cannot possibly be a 5-card match, so there is thus no match. \n int position = ranks.length;\n\n // choose the set of wild-card options that match the input value.\n int[] wildcardoptions = WILDCARDS[wildcards];\n\n while (position-- &gt;= 5) {\n // OK, so 'hand' is a bit-pattern with the most 'valuable' cards on the right.\n // if the right-5 bits are all set then there's a straight.\n for (int wcpattern : wildcardoptions) {\n // Look at our combinations of wild-card options.\n if (((hand | wcpattern) &amp; 0x1f) == 0x1f) {\n // return the position if a wild-card match makes 5-in-a-row.\n // what we do is 'OR' all of the wild-card patterns (for the number of\n // wildcards we have), with the 5-right bits, and if any of the results\n // have all the 5-right bits set, then there's a match.\n return position;\n }\n }\n // OK, so none of the wild-cards matched this 5 bits... so we shift the hand\n // right once, and try all the patterns again.\n // shift the hand ....\n hand &gt;&gt;&gt;= 1;\n }\n // could not match a consecutive set of straights.\n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T22:55:05.093", "Id": "60776", "Score": "0", "body": "It wasn't the solution I expected but it certainly works. If anyone finds a different way to do it, I'd welcome that answer a lot (and actually *might* switch the \"accepted\" answer)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T19:19:17.300", "Id": "36923", "ParentId": "36915", "Score": "6" } }, { "body": "<h2>Call me a necromancer</h2>\n\n<p>I realize this answer is a year and a half too late, but this question showed up in the sidebar, so I clicked on it. After I read the question and the answer, I couldn't help myself. So here is my version, which is quite a bit simpler.</p>\n\n<h2>The original version</h2>\n\n<p>The original code has \\$O(n*m)\\$ complexity, where \\$n\\$ is the number of ranks and \\$m\\$ is the number of cards in a hand. Given that these are 13 and 5 respectively, this isn't too far off from an \\$O(n)\\$ solution. One thing that could have been changed is to remove the recursive call and simply back up the loop to the proper position, resetting the number of wildcards (or equivalently to use two loops). Either way the code would have the same time complexity, but the recursive might use an extra \\$O(n)\\$ stack space (or might not if there was a tail recursion optimization).</p>\n\n<h2>The revised version</h2>\n\n<p>My revised version does pretty much what the original version does in terms of checking ranges of cards from the highest to the lowest. The key difference is that it makes use of the fact that when you reject one set of cards, you can move onto the next set without starting over. For example, if you know you have 4 cards in the 10..Ace range, then you can move to the 9..K range by adding in one card if you have a 9 and subtracting one if you have an Ace. So this version runs in \\$O(n)\\$ time.</p>\n\n<pre><code>public static final int HAND_SIZE = 5;\n\n/**\n * This function finds a straight by examining a range of HAND_SIZE\n * cards. It starts with the topmost HAND_SIZE cards and counts how\n * many cards are in that range. If at any point in time, the number\n * of cards in the range plus the number of wildcards becomes HAND_SIZE,\n * then a straight has been found. If no straight is found, the range\n * slides down by one rank. The number of cards in the new range is\n * simply the previous count plus the new lowest card entering the range\n * minus the high card that is leaving the range.\n */\npublic static int findHighestIndexForStraight(int[] ranks, int wildcards) {\n // Sanity check.\n if (HAND_SIZE &gt; ranks.length)\n return -1;\n\n int numCardsInRange = wildcards;\n int lowestCardInRange = ranks.length;\n\n // Start by counting the cards in the topmost range.\n for (int i=0;i&lt;HAND_SIZE;i++)\n numCardsInRange += ranks[--lowestCardInRange];\n\n while (true) {\n // Check if we found a straight.\n if (numCardsInRange &gt;= HAND_SIZE)\n return lowestCardInRange + HAND_SIZE;\n // Slide the range down by one rank. If the lowest card goes\n // below 0, there are no straights.\n if (--lowestCardInRange &lt; 0)\n return -1;\n numCardsInRange += ranks[lowestCardInRange] -\n ranks[lowestCardInRange+HAND_SIZE];\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-16T05:34:39.030", "Id": "90888", "ParentId": "36915", "Score": "3" } }, { "body": "<h3>Separation of responsibilities</h3>\n\n<p>The <code>findHighestIndexForStraight</code> method is a bit confusing,\nbecause there are several elements entangled in it:</p>\n\n<ul>\n<li>It contains the logic of exploring <code>ranks</code> for a straight (loop from the end to start)</li>\n<li>It contains the logic of checking if a sequence is straight or not</li>\n<li>Somewhere in the middle of it all it references a global constant (<code>HAND_SIZE</code>)</li>\n</ul>\n\n<p>These could be separated in a more readable way:</p>\n\n<pre><code>public static int findHighestIndexForStraight(int[] ranks, int wildcards) {\n for (int endIndex = ranks.length - 1; endIndex &gt;= 0; --endIndex) {\n if (straightExists(ranks, endIndex, HAND_SIZE, wildcards)) {\n return endIndex + 1;\n }\n }\n return -1;\n}\n\npublic static boolean straightExists(int[] ranks, int endIndex, int targetCount, int wildcards) {\n if (targetCount == 0) {\n return true;\n }\n if (targetCount &gt; endIndex + 1) {\n return false;\n }\n int wildcardsLeft = wildcards;\n if (ranks[endIndex] &lt;= 0) {\n if (wildcards == 0) {\n return false;\n }\n --wildcardsLeft;\n }\n return straightExists(ranks, endIndex - 1, targetCount - 1, wildcardsLeft);\n}\n</code></pre>\n\n<p>In this version the responsibilities are better separated:</p>\n\n<ul>\n<li><code>straightExists</code> checks if a straight of given target size exists from a given end-position</li>\n<li><code>findHighestIndexForStraight</code> contains the logic of searching from the end</li>\n<li>The reference to <code>HAND_SIZE</code> is no longer buried in the middle, it's more visible at a more central place in the code, where its purpose is easier to understand</li>\n</ul>\n\n<h3>Empty block with <code>// do nothing</code> comment</h3>\n\n<p>Empty blocks are not great. Although the comment <code>// do nothing</code> makes it clear that the empty block is not an accident, it's still not great.\nThe code can be rearranged without the empty block,\nand then it can speak for itself without necessitating a comment:</p>\n\n<pre><code>if (count &lt;= 0) {\n if (wildsLeft &gt; 0) {\n wildsLeft--;\n } else {\n return findHighestIndexForStraight(ranks, startIndex - 1, wildcards);\n }\n}\nif (startIndex - i + 1 &gt;= HAND_SIZE) {\n return startIndex + 1;\n}\n</code></pre>\n\n<h3>Using the right types</h3>\n\n<p>Given this function and its doc string:</p>\n\n<blockquote>\n<pre><code>/**\n * Scans an array of ints to search for sequence of 1s. [...]\n */\npublic static int findHighestIndexForStraight(int[] ranks, int wildcards) {\n</code></pre>\n</blockquote>\n\n<p>The implementation doesn't really use the integer values in the <code>int[]</code> parameter,\nit could work just as well with a <code>boolean[]</code>.\nHaving a signature for exactly what's needed would make the code slightly easier to understand.</p>\n\n<p>That said, I haven't looked at the rest of the implementation,\nand maybe this makes perfect sense and everything's fine.\nFor example it might be too tedious and inefficient to add a filtering step for the <code>ranks</code> parameter, in which case the current version would be still overall more readable.\nIn that case ignore my comment, I leave it up to your judgment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-16T17:35:00.090", "Id": "90924", "ParentId": "36915", "Score": "3" } } ]
{ "AcceptedAnswerId": "36923", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:42:39.070", "Id": "36915", "Score": "10", "Tags": [ "java", "performance", "playing-cards", "community-challenge" ], "Title": "Poker Hand Evaluation - Finding a straight" }
36915
<h1>Weekend Challenge #2 - <a href="https://codereview.meta.stackexchange.com/questions/1218/proposals-for-weekly-challenge-topics/1220#1220">Poker Hand Evaluation</a></h1> <p>Very early I decided to support the usage of wild jokers, even though I knew that this was going to lead to <s>trouble</s> more work. I also wanted to support big collection of cards, for example if you have 7 cards and choose the best 5-card poker hand of these. Of course, combinatorics can be used for this (7 nCr 5 = 35 combinations), but I wanted a better approach.</p> <p>So to check for possible poker hands, I really didn't want to make the same mistake <a href="http://chat.stackexchange.com/rooms/11760/conversation/the-retailcoder-trap">someone else did</a>. And as usual, I also tend to prefer flexible solution. So pretty soon, the <a href="http://altreus.github.io/qi-klaxon/?Strategy+Pattern" rel="noreferrer">strategy pattern alarm</a> went off in my head.</p> <p>I have spent a lot of time writing tests to make sure that it works as it should. Now, I believe it works as it should (or at least the way I want it to).</p> <h1>Class overview</h1> <ul> <li><code>AceValue</code> - enum to define what the value of an ace is (not so useful here, but very used in other card projects)</li> <li><code>Suite</code> - enum for hearts, spades, diamonds, clubs + one for wildcards and other fun stuff</li> <li><code>ClassicCard</code> - class that contains a <code>Suite</code> and a rank (<code>int</code>). Also contains constants for the different ranks</li> <li><code>PokerHandEval</code> - class that is responsible for determining the <code>PokerHandResult</code> given an array of <code>ClassicCard</code></li> <li><code>PokerHandAnalyze</code> - class used by <code>PokerHandEval</code> to analyze an array of cards and structure data into integer arrays of used ranks and suits.</li> <li><code>PokerHandType</code> - enum for the standard type of poker hands available</li> <li><code>PokerHandResult</code> - comparable class that holds the result of a poker hand. Includes <code>PokerHandType</code> + parameters ("full house of what?") + "kickers" (pair of 6s, sure, but what are your other highest cards?)</li> <li><code>PokerHandResultProducer</code> - interface for declaring the method used by the strategy pattern that the below three classes implements <ul> <li><code>PokerPair</code> - strategy for finding pairs, two-pair, three-of-a-kind, four-of-a-kind, and full house</li> <li><code>PokerStraight</code> - strategy for finding straight</li> <li><code>PokerFlush</code> - strategy for finding flush, straight flush, and royal flush - uses <code>PokerStraight</code> for determining the straights.</li> </ul></li> </ul> <h1>Some already existing code</h1> <p>Since I have been using cards earlier in Java, and I thought the result of this weekend challenge would come in handy at some point later in time, I decided to use Java again, and to use some code I already had.</p> <p>ClassicCard.java</p> <pre><code>public class ClassicCard { private final Suite suite; private final int rank; public static final int RANK_ACE_LOW = 1; public static final int RANK_2 = 2; public static final int RANK_3 = 3; public static final int RANK_4 = 4; public static final int RANK_5 = 5; public static final int RANK_6 = 6; public static final int RANK_7 = 7; public static final int RANK_8 = 8; public static final int RANK_9 = 9; public static final int RANK_10 = 10; public static final int RANK_JACK = 11; public static final int RANK_QUEEN = 12; public static final int RANK_KING = 13; public static final int RANK_ACE_HIGH = 14; public static final int RANK_WILDCARD = 20; public ClassicCard(Suite suite, int rank) { if (suite == null) throw new NullPointerException("Suite cannot be null"); if (!suite.isWildcard() &amp;&amp; rank == RANK_WILDCARD) throw new IllegalArgumentException("Rank cannot be RANK_WILDCARD when suite is " + suite); this.suite = suite; this.rank = rank; } public int getRank() { return rank; } public int getRankWithAceValue(AceValue aceValue) { if (isAce()) return aceValue.getAceValue(); return rank; } public boolean isAce() { return this.rank == RANK_ACE_LOW || this.rank == RANK_ACE_HIGH; } public boolean isWildcard() { return suite.isWildcard(); } public Suite getSuite() { return suite; } } </code></pre> <p>AceValue.java</p> <pre><code>public enum AceValue { LOW(ClassicCard.RANK_ACE_LOW), HIGH(ClassicCard.RANK_ACE_HIGH); private final int aceValue; private final int minRank; private final int maxRank; private final int[] ranks; private AceValue(int value) { this.aceValue = value; this.minRank = Math.min(2, getAceValue()); this.maxRank = Math.max(ClassicCard.RANK_KING, getAceValue()); this.ranks = new int[52 / 4]; for (int i = 0; i &lt; ranks.length; i++) ranks[i] = this.minRank + i; } public int getMaxRank() { return maxRank; } public int getMinRank() { return minRank; } public int getAceValue() { return this.aceValue; } public int[] getRanks() { return Arrays.copyOf(this.ranks, this.ranks.length); } } </code></pre> <p>Suite.java</p> <pre><code>public enum Suite { SPADES, HEARTS, DIAMONDS, CLUBS, EXTRA; public boolean isBlack() { return this.ordinal() % 2 == 0 &amp;&amp; !isWildcard(); } public boolean isWildcard() { return this == EXTRA; } public boolean isRed() { return !isBlack() &amp;&amp; !isWildcard(); } public static int suiteCount(boolean includingWildcards) { int i = 0; for (Suite suite : Suite.values()) { if (!suite.isWildcard() || includingWildcards) { ++i; } } return i; } } </code></pre> <h1>The Code</h1> <p>Total length: 309 lines of code (comments and whitespace excluded) in 8 files.</p> <p>PokerFlush.java</p> <pre><code>/** * Checks for FLUSH, ROYAL_FLUSH and STRAIGHT_FLUSH. Depends on {@link PokerStraight} for the straight analyze. */ public class PokerFlush implements PokerHandResultProducer { private final PokerHandResultProducer straight = new PokerStraight(); @Override public PokerHandResult resultFor(PokerHandAnalyze analyze) { List&lt;PokerHandResult&gt; results = new ArrayList&lt;PokerHandResult&gt;(); for (Suite suite : Suite.values()) { if (suite.isWildcard()) continue; PokerHandAnalyze suiteHand = analyze.filterBySuite(suite); if (suiteHand.size() &lt; HAND_SIZE) continue; // Not enough cards to make a complete hand // We have a complete hand, now let's create a HandResult for it. PokerHandResult straightResult = straight.resultFor(suiteHand); if (straightResult != null) { PokerHandType type = straightResult.getPrimaryRank() == AceValue.HIGH.getAceValue() ? PokerHandType.ROYAL_FLUSH : PokerHandType.STRAIGHT_FLUSH; results.add(new PokerHandResult(type, straightResult.getPrimaryRank(), 0, null)); // We have a straight so we don't need to provide any kickers. } else results.add(new PokerHandResult(PokerHandType.FLUSH, 0, 0, suiteHand.getCards())); } if (results.isEmpty()) return null; return PokerHandResult.returnBest(results); } } </code></pre> <p>PokerHandAnalyze.java</p> <pre><code>/** * A helper class to analyze ranks and suits for an array of {@link ClassicCard}s. Create new using the static method {@link #analyze(ClassicCard...)} */ public class PokerHandAnalyze { private final int[] ranks = new int[ClassicCard.RANK_ACE_HIGH]; private final int[] suites = new int[Suite.values().length]; private final ClassicCard[] cards; private int wildcards; private PokerHandAnalyze(ClassicCard[] cards2) { this.cards = Arrays.copyOf(cards2, cards2.length); } /** * Create a new instance and analyze the provided cards * @param cards The cards to analyze * @return Organized analyze of the provided cards */ public static PokerHandAnalyze analyze(ClassicCard... cards) { PokerHandAnalyze hand = new PokerHandAnalyze(cards); for (ClassicCard card : cards) { if (card.isWildcard()) { hand.wildcards++; } else if (card.isAce()) { hand.ranks[AceValue.HIGH.getAceValue() - 1]++; hand.ranks[AceValue.LOW.getAceValue() - 1]++; } else hand.ranks[card.getRank() - 1]++; hand.suites[card.getSuite().ordinal()]++; } return hand; } public int[] getRanks() { return ranks; } public int getWildcards() { return wildcards; } public ClassicCard[] getCards() { return cards; } public int size() { return cards.length; } /** * Create a sub-analyze which only includes wildcards and the specified suite. Useful to check for the FLUSH {@link PokerHandType} * @param suite The suite to filter by * @return A new analyze object */ public PokerHandAnalyze filterBySuite(Suite suite) { List&lt;ClassicCard&gt; cards = new ArrayList&lt;ClassicCard&gt;(); for (ClassicCard card : this.cards) { if (card.isWildcard() || card.getSuite().equals(suite)) { cards.add(card); } } return analyze(cards.toArray(new ClassicCard[cards.size()])); } } </code></pre> <p>PokerHandEval.java</p> <pre><code>/** * Class to analyze poker hands by using a collection of {@link PokerHandResultProducer}s and return a {@link PokerHandResult} */ public class PokerHandEval { public void addTest(PokerHandResultProducer test) { this.tests.add(test); } private final List&lt;PokerHandResultProducer&gt; tests = new ArrayList&lt;PokerHandResultProducer&gt;(); private PokerHandResult evaluate(PokerHandAnalyze analyze) { if (tests.isEmpty()) throw new IllegalStateException("No PokerHandResultProducers added."); List&lt;PokerHandResult&gt; results = new ArrayList&lt;PokerHandResult&gt;(); for (PokerHandResultProducer test : tests) { PokerHandResult result = test.resultFor(analyze); if (result != null) results.add(result); } return PokerHandResult.returnBest(results); } /** * Test a bunch of cards and return the best matching 5-card {@link PokerHandResult} * @param cards The cards to test * @return The best matching 5-card Poker Hand */ public PokerHandResult test(ClassicCard... cards) { return evaluate(PokerHandAnalyze.analyze(cards)); } /** * Factory method to create an evaluator for the default poker hand types. * @return */ public static PokerHandEval defaultEvaluator() { PokerHandEval eval = new PokerHandEval(); eval.addTest(new PokerPair()); eval.addTest(new PokerStraight()); eval.addTest(new PokerFlush()); return eval; } } </code></pre> <p>PokerHandResult.java</p> <pre><code>/** * Data for a found poker hand. Provides data for the type of poker hand, the primary rank and secondary rank, and kickers. Including methods for sorting. Also implements hashCode and equals. */ public class PokerHandResult implements Comparable&lt;PokerHandResult&gt; { private final PokerHandType type; private final int primaryRank; private final int secondaryRank; private final int[] kickers; public PokerHandResult(PokerHandType type, int primaryRank, int secondaryRank, ClassicCard[] cards) { this(type, primaryRank, secondaryRank, cards, PokerHandResultProducer.HAND_SIZE); } public PokerHandResult(PokerHandType type, int primaryRank, int secondaryRank, ClassicCard[] cards, int numKickers) { this.type = type; this.primaryRank = primaryRank; this.secondaryRank = secondaryRank; this.kickers = kickers(cards, new int[]{ primaryRank, secondaryRank }, numKickers); Arrays.sort(this.kickers); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + primaryRank; result = prime * result + secondaryRank; result = prime * result + Arrays.hashCode(kickers); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof PokerHandResult)) return false; PokerHandResult other = (PokerHandResult) obj; if (type != other.type) return false; if (primaryRank != other.primaryRank) return false; if (secondaryRank != other.secondaryRank) return false; if (!Arrays.equals(kickers, other.kickers)) return false; return true; } private static int compareKickers(int[] sorted1, int[] sorted2) { int index1 = sorted1.length - 1; int index2 = sorted2.length - 1; int compare = 0; while (compare == 0 &amp;&amp; index1 &gt;= 0 &amp;&amp; index2 &gt;= 0) { // If one of them is bigger than another we will stop comparing, so decreasing both indexes is perfectly OK. compare = Integer.compare(sorted1[index1--], sorted2[index2--]); } return compare; } @Override public int compareTo(PokerHandResult other) { // compare order: HandType, primary rank (int), secondary (used for two pair and full house), kickers int compare = this.type.compareTo(other.type); if (compare == 0) compare = Integer.compare(this.primaryRank, other.primaryRank); if (compare == 0) compare = Integer.compare(this.secondaryRank, other.secondaryRank); if (compare == 0) compare = compareKickers(this.kickers, other.kickers); return compare; } public PokerHandType getType() { return type; } /** * Return the best {@link PokerHandResult} of a list of results. The method first orders the list and then returns the last result. * @param results A list of PokerHandResults * @return The best result from the list */ public static PokerHandResult returnBest(List&lt;PokerHandResult&gt; results) { if (results.isEmpty()) return null; Collections.sort(results); return results.get(results.size() - 1); } /** * Create an integer array of "kickers", to separate FOUR_OF_A_KIND with Ace-kicker vs. King-kicker * @param cards The cards in your hand. If null, an empty array will be returned * @param skip Ranks that will be skipped (for example, if you have a pair of 4s then you can skip those 4s) * @param count How many kickers that should be included. This should ideally be 5 - number of cards required for the {@link PokerHandType} the kickers are provided for * @return An array of the ranks that will be used as kickers. Wildcards and the ranks in the skip array are excluded */ private static int[] kickers(ClassicCard[] cards, int[] skip, int count) { if (cards == null) return new int[]{}; int[] result = new int[cards.length]; Arrays.sort(skip); for (int i = 0; i &lt; cards.length; i++) { int rank = cards[i].getRankWithAceValue(AceValue.HIGH); // Check if we should skip this rank in the kicker-data. if (cards[i].isWildcard() || Arrays.binarySearch(skip, rank) &gt;= 0) continue; result[i] = rank; } Arrays.sort(result); return Arrays.copyOfRange(result, Math.max(result.length - count, 0), result.length); } public int getPrimaryRank() { return primaryRank; } public int getSecondaryRank() { return secondaryRank; } @Override public String toString() { return String.format("PokerHand: %s. %d, %d. Kickers: %s", type, primaryRank, secondaryRank, Arrays.toString(kickers)); } } </code></pre> <p>PokerHandResultProducer.java</p> <pre><code>/** * Interface for scanning for Poker hands. */ public interface PokerHandResultProducer { /** * Constant for how big our hands should be. */ final int HAND_SIZE = 5; /** * Method which does the job of finding a matching Poker hand for some analyze data. * @param analyze {@link PokerHandAnalyze} object containing data for which we should try to find a matching Poker hand. * @return {@link PokerHandResult} for the best poker hand we could find. */ PokerHandResult resultFor(PokerHandAnalyze analyze); } </code></pre> <p>PokerHandType.java</p> <pre><code>public enum PokerHandType { HIGH_CARD, PAIR, TWO_PAIR, THREE_OF_A_KIND, STRAIGHT, FLUSH, FULL_HOUSE, FOUR_OF_A_KIND, STRAIGHT_FLUSH, ROYAL_FLUSH; } </code></pre> <p>PokerPair.java</p> <pre><code>/** * Checks for PAIR, THREE_OF_A_KIND, FOUR_OF_A_KIND, and FULL_HOUSE. Returns HIGH_CARD if nothing better was found. */ public class PokerPair implements PokerHandResultProducer { @Override public PokerHandResult resultFor(PokerHandAnalyze analyze) { List&lt;PokerHandResult&gt; results = new ArrayList&lt;PokerHandResult&gt;(); List&lt;PokerHandResult&gt; pairs = new ArrayList&lt;PokerHandResult&gt;(); List&lt;PokerHandResult&gt; threeOfAKinds = new ArrayList&lt;PokerHandResult&gt;(); int[] ranks = analyze.getRanks(); int remainingWildcards = analyze.getWildcards(); // Find out how many we should look for, primarily int[] sortedCounts = Arrays.copyOf(ranks, ranks.length); Arrays.sort(sortedCounts); int countForWildcards = sortedCounts[sortedCounts.length - 1]; for (int index = ranks.length - 1; index &gt;= 0; index--) { int count = ranks[index]; int useWildcards = (count == countForWildcards ? remainingWildcards : 0); if (count + useWildcards &gt;= 4) { remainingWildcards += count - 4; results.add(new PokerHandResult(PokerHandType.FOUR_OF_A_KIND, index + 1, 0, analyze.getCards(), 1)); } // If there already exists some four of a kinds, then there's no need to check three of a kinds or pairs. if (!results.isEmpty()) continue; if (count + useWildcards == 3) { remainingWildcards += count - 3; threeOfAKinds.add(new PokerHandResult(PokerHandType.THREE_OF_A_KIND, index + 1, 0, analyze.getCards(), 2)); } else if (count + useWildcards == 2) { remainingWildcards += count - 2; pairs.add(new PokerHandResult(PokerHandType.PAIR, index + 1, 0, analyze.getCards(), 3)); } } return checkForFullHouseAndStuff(analyze, pairs, threeOfAKinds, results); } private PokerHandResult checkForFullHouseAndStuff(PokerHandAnalyze analyze, List&lt;PokerHandResult&gt; pairs, List&lt;PokerHandResult&gt; threeOfAKinds, List&lt;PokerHandResult&gt; results) { if (!results.isEmpty()) return PokerHandResult.returnBest(results); PokerHandResult bestPair = PokerHandResult.returnBest(pairs); PokerHandResult bestThree = PokerHandResult.returnBest(threeOfAKinds); if (bestPair != null &amp;&amp; bestThree != null) { return new PokerHandResult(PokerHandType.FULL_HOUSE, bestThree.getPrimaryRank(), bestPair.getPrimaryRank(), null, 0); // No kickers because it's a complete hand. } if (bestThree != null) return bestThree; if (pairs.size() &gt;= 2) { Collections.sort(pairs); int a = pairs.get(pairs.size() - 1).getPrimaryRank(); int b = pairs.get(pairs.size() - 2).getPrimaryRank(); return new PokerHandResult(PokerHandType.TWO_PAIR, Math.max(a, b), Math.min(a, b), analyze.getCards(), 1); } if (bestPair != null) return bestPair; // If we have a wildcard, then we always have at least PAIR, which means that it's fine to ignore wildcards in the kickers here as well return new PokerHandResult(PokerHandType.HIGH_CARD, 0, 0, analyze.getCards()); } } </code></pre> <p>PokerStraight.java - <strong>(removed)</strong> because of question size limit. <a href="https://codereview.stackexchange.com/questions/36915/poker-hand-evaluation-finding-a-straight">See separate question</a></p> <h1>The Test</h1> <p>PokerHandTest.java (175 lines)</p> <pre><code>public class PokerHandTest { private static final ClassicCard WILDCARD = new ClassicCard(Suite.EXTRA, ClassicCard.RANK_WILDCARD); private int findHighestIndexForStraight(int[] ranks, int wildcards) { int res = PokerStraight.findHighestIndexForStraight(ranks, wildcards); return res == -1 ? res : res - 1; } @Test public void moreCards() { PokerHandEval eval = PokerHandEval.defaultEvaluator(); assertPoker(PokerHandType.THREE_OF_A_KIND, 2, eval.test(card(DIAMONDS, RANK_JACK), card(HEARTS, RANK_ACE_HIGH), card(SPADES, RANK_7), card(DIAMONDS, RANK_2), card(HEARTS, RANK_2), card(DIAMONDS, RANK_4), WILDCARD)); assertPoker(PokerHandType.TWO_PAIR, 12, 10, eval.test(card(DIAMONDS, RANK_3), card(SPADES, RANK_2), card(DIAMONDS, RANK_10), card(CLUBS, RANK_10), card(CLUBS, RANK_7), card(SPADES, RANK_5), card(SPADES, RANK_QUEEN), card(HEARTS, RANK_QUEEN), card(HEARTS, RANK_ACE_HIGH), card(DIAMONDS, RANK_7))); PokerHandResult eq1; PokerHandResult eq2; eq1 = eval.test(card(CLUBS, RANK_10), card(CLUBS, RANK_7), card(SPADES, RANK_KING), card(SPADES, RANK_QUEEN), card(HEARTS, RANK_QUEEN), card(HEARTS, RANK_ACE_HIGH), card(DIAMONDS, RANK_ACE_HIGH)); eq2 = eval.test(card(CLUBS, RANK_JACK), card(CLUBS, RANK_7), card(SPADES, RANK_KING), card(SPADES, RANK_QUEEN), card(HEARTS, RANK_QUEEN), card(HEARTS, RANK_ACE_HIGH), card(DIAMONDS, RANK_ACE_HIGH)); assertEquals(eq1, eq2); eq1 = eval.test(WILDCARD, card(SPADES, RANK_QUEEN), card(HEARTS, RANK_QUEEN), card(HEARTS, RANK_7), card(DIAMONDS, RANK_4)); eq2 = eval.test(card(DIAMONDS, RANK_QUEEN), card(CLUBS, RANK_QUEEN), card(SPADES, RANK_QUEEN), card(HEARTS, RANK_7), card(DIAMONDS, RANK_4)); assertPoker(PokerHandType.THREE_OF_A_KIND, RANK_QUEEN, eq1); assertEquals(eq2, eq1); PokerHandResult result; result = eval.test(WILDCARD, WILDCARD, WILDCARD, WILDCARD, card(DIAMONDS, RANK_6)); assertPoker(PokerHandType.STRAIGHT_FLUSH, result); result = eval.test(WILDCARD, WILDCARD, WILDCARD, card(HEARTS, RANK_10), card(DIAMONDS, RANK_6)); assertPoker(PokerHandType.FOUR_OF_A_KIND, result); result = eval.test(WILDCARD, WILDCARD, WILDCARD, WILDCARD, WILDCARD); assertPoker(PokerHandType.ROYAL_FLUSH, result); result = eval.test(WILDCARD, WILDCARD, WILDCARD, WILDCARD, card(SPADES, RANK_10)); assertPoker(PokerHandType.ROYAL_FLUSH, result); } public void assertPoker(PokerHandType type, int primary, PokerHandResult test) { assertPoker(type, test); assertEquals(primary, test.getPrimaryRank()); } public void assertPoker(PokerHandType type, int primary, int secondary, PokerHandResult test) { assertPoker(type, primary, test); assertEquals(secondary, test.getSecondaryRank()); } @Test public void royalAndFlushStraights() { PokerHandEval eval = PokerHandEval.defaultEvaluator(); PokerHandResult result = eval.test(card(HEARTS, RANK_10), card(HEARTS, RANK_JACK), card(HEARTS, RANK_QUEEN), card(HEARTS, RANK_KING), card(HEARTS, RANK_ACE_LOW)); assertPoker(PokerHandType.ROYAL_FLUSH, result); result = eval.test(card(HEARTS, RANK_2), card(HEARTS, RANK_3), card(HEARTS, RANK_4), card(HEARTS, RANK_5), card(HEARTS, RANK_6)); assertPoker(PokerHandType.STRAIGHT_FLUSH, result); } @Test public void rankHands() { PokerHandEval eval = PokerHandEval.defaultEvaluator(); PokerHandResult highCard = eval.test(card(HEARTS, RANK_7), card(CLUBS, RANK_JACK), card(HEARTS, RANK_6), card(HEARTS, RANK_4), card(DIAMONDS, RANK_2)); PokerHandResult pairLowKicker = eval.test(card(HEARTS, RANK_7), card(CLUBS, RANK_7), card(HEARTS, RANK_6), card(HEARTS, RANK_4), card(HEARTS, RANK_2)); PokerHandResult pairHighKicker = eval.test(card(HEARTS, RANK_7), card(CLUBS, RANK_7), card(HEARTS, RANK_KING), card(HEARTS, RANK_4), card(HEARTS, RANK_2)); PokerHandResult pairHigher = eval.test(card(HEARTS, RANK_KING), card(CLUBS, RANK_KING), card(HEARTS, RANK_6), card(HEARTS, RANK_4), card(HEARTS, RANK_2)); PokerHandResult twoPair = eval.test(card(HEARTS, RANK_KING), card(CLUBS, RANK_KING), card(HEARTS, RANK_6), card(DIAMONDS, RANK_6), card(HEARTS, RANK_2)); PokerHandResult threeOfAKind = eval.test(card(HEARTS, RANK_KING), card(CLUBS, RANK_KING), card(SPADES, RANK_KING), card(HEARTS, RANK_4), card(HEARTS, RANK_2)); PokerHandResult flush = eval.test(card(HEARTS, RANK_7), card(HEARTS, RANK_2), card(HEARTS, RANK_6), card(HEARTS, RANK_9), card(HEARTS, RANK_QUEEN)); PokerHandResult fourOfAKind = eval.test(card(HEARTS, RANK_7), card(SPADES, RANK_7), card(DIAMONDS, RANK_7), card(CLUBS, RANK_7), card(HEARTS, RANK_QUEEN)); PokerHandResult straight = eval.test(card(HEARTS, RANK_2), card(CLUBS, RANK_3), card(HEARTS, RANK_4), card(HEARTS, RANK_5), card(DIAMONDS, RANK_6)); PokerHandResult straightWild = eval.test(card(HEARTS, RANK_2), card(CLUBS, RANK_3), WILDCARD, card(HEARTS, RANK_5), card(DIAMONDS, RANK_6)); assertEquals(straight, straightWild); PokerHandResult straightLow = eval.test(card(HEARTS, RANK_ACE_HIGH), card(CLUBS, RANK_2), card(HEARTS, RANK_3), card(HEARTS, RANK_4), card(DIAMONDS, RANK_5)); PokerHandResult straightFlush = eval.test(card(HEARTS, RANK_8), card(HEARTS, RANK_9), card(HEARTS, RANK_10), card(HEARTS, RANK_JACK), card(HEARTS, RANK_QUEEN)); PokerHandResult royalFlush = eval.test(card(HEARTS, RANK_10), card(HEARTS, RANK_JACK), card(HEARTS, RANK_QUEEN), card(HEARTS, RANK_KING), WILDCARD); PokerHandResult fullHouse = eval.test(card(HEARTS, RANK_10), card(CLUBS, RANK_10), WILDCARD, card(HEARTS, RANK_KING), card(HEARTS, RANK_KING)); assertPoker(PokerHandType.FULL_HOUSE, fullHouse); assertEquals(RANK_KING, fullHouse.getPrimaryRank()); assertEquals(RANK_10, fullHouse.getSecondaryRank()); // Add hands to list List&lt;PokerHandResult&gt; results = new ArrayList&lt;PokerHandResult&gt;(); assertAdd(results, PokerHandType.HIGH_CARD, highCard); assertAdd(results, PokerHandType.PAIR, pairLowKicker); assertAdd(results, PokerHandType.PAIR, pairHighKicker); assertAdd(results, PokerHandType.PAIR, pairHigher); assertAdd(results, PokerHandType.TWO_PAIR, twoPair); assertAdd(results, PokerHandType.THREE_OF_A_KIND, threeOfAKind); assertAdd(results, PokerHandType.FLUSH, flush); assertAdd(results, PokerHandType.FOUR_OF_A_KIND, fourOfAKind); assertAdd(results, PokerHandType.STRAIGHT, straightLow); assertAdd(results, PokerHandType.STRAIGHT, straight); assertAdd(results, PokerHandType.STRAIGHT, straightWild); assertAdd(results, PokerHandType.STRAIGHT_FLUSH, straightFlush); assertAdd(results, PokerHandType.ROYAL_FLUSH, royalFlush); // Shuffle just for the fun of it Collections.shuffle(results); // Sort the list according to the HandResult comparable interface Collections.sort(results); // Assert the list Iterator&lt;PokerHandResult&gt; it = results.iterator(); assertEquals(highCard, it.next()); assertEquals(pairLowKicker, it.next()); assertEquals(pairHighKicker, it.next()); assertEquals(pairHigher, it.next()); assertEquals(twoPair, it.next()); assertEquals(threeOfAKind, it.next()); assertEquals(straightLow, it.next()); assertEquals(straight, it.next()); assertEquals(straightWild, it.next()); assertEquals(flush, it.next()); assertEquals(fourOfAKind, it.next()); assertEquals(straightFlush, it.next()); assertEquals(royalFlush, it.next()); // Make sure that we have processed the entire list assertFalse("List is not completely processed", it.hasNext()); } private static void assertAdd(List&lt;PokerHandResult&gt; results, PokerHandType type, PokerHandResult result) { assertPoker(type, result); results.add(result); } private static void assertPoker(PokerHandType type, PokerHandResult result) { if (type == null) { assertNull(result); return; } assertNotNull("Expected " + type, result); assertEquals(result.toString(), type, result.getType()); } private static ClassicCard card(Suite suite, int rank) { return new ClassicCard(suite, rank); } } </code></pre> <h1>Code Review Question(s)</h1> <p>I have tried to make good use of strategy pattern and some factory methods (<code>PokerHandAnalyze</code> and <code>PokerHandEval</code>), I'd like to know if these are "correct". If you see any other common patterns that I have used without knowing it, I'd also like to hear that.</p> <p>But most importantly: Is there anything that I could have done better here? And <a href="http://chat.stackexchange.com/transcript/message/12533653#12533653">can you find any mistakes?</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:31:46.850", "Id": "60764", "Score": "0", "body": "And is it me or no \"kicker\" for a straight is assuming you're playing 5-cards (the rest of your code isn't...)? You couldn't tell the winner of a 7-card deal where the two players had the same straight, even if one's 6th card was an Ace of Hearts and the other player's 6th card was a 2 of clubs. Right or wrong? :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:33:51.740", "Id": "60765", "Score": "0", "body": "@retailcoder [tag:status-bydesign](http://meta.codereview.stackexchange.com/questions/tagged/status-bydesign). I only consider a complete \"Poker Hand\" to be five cards. If you have seven cards, then only five of those will be included in a poker hand. Therefore, if you have a straight (five cards), you don't have a kicker. (I'm thinking Texas Hold 'em here, there might be other variations)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:35:57.110", "Id": "60766", "Score": "2", "body": "@retailcoder Flexible code, **correct** code (coughs), short code - Can't have it all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:51:19.417", "Id": "60893", "Score": "1", "body": "Do not use prefixes in stead of a package name. That is put class `PokerXyz` to package `poker` and use `Xyz` only." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:08:23.683", "Id": "60896", "Score": "0", "body": "@abuzittingillifirca Interesting suggestion. I have put the classes inside a package, `net.zomis.cards.poker.validation`, but when pressing `Ctrl + Shift + T` in Eclipse I often forget the classnames, and I find it much easier to write `Poker` to find my classes. This is not something I always do for all other projects though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T02:31:52.157", "Id": "61741", "Score": "1", "body": "Nitpicking: the term is **suit**, not *suite*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-04T02:53:52.670", "Id": "118477", "Score": "0", "body": "@Jamel Your PokerHandType enum is lacking five of a kind. You are using a joker, five of a kind is the best hand in poker, beats a royal. You also use Royal_Flush In the enum, but a Royal is simply a straight flush, just the highest straight flush so it has code smell that you might be doing something with a royal flush, that you could adequately do treating it as a straight flush." } ]
[ { "body": "<h2>AceValue</h2>\n\n<p>This class has me confused. I am not sure what the <code>ranks[]</code> is for.... and there are magic numbers, and no comments? </p>\n\n<h2>Suite</h2>\n\n<p>This has an <code>isBlack()</code> method, but that indicates that DIAMONDS are black... but they are red!</p>\n\n<p><code>suiteCount(boolean)</code> could be much simpler:</p>\n\n<pre><code>return Suite.values - (includingWildcards ? 0 : 1);\n</code></pre>\n\n<h2>General</h2>\n\n<p>Right, after this, it becomes very complicated to review... Frankly too much to understand in 30 minutes or less... and pulling the code locally so I can run it through is not easy as well... and by the time I decided to do that, I had spent too long on it already. This, in itself, is an interesting observation. I tried to read through the classes, and understand how 'it hangs together', and then decided that the only way to understand the code is to 'debug' it and step through.</p>\n\n<p>Then I realized there's no main method, and I guess you use JUnit to run it?</p>\n\n<p>Finally, I have just never played poker... (not even strip...) so I don't have an instinctual idea of where the code should be going.</p>\n\n<p>Bottom line is that the code requires a native/instinctual understanding of the problem in order to make sense of the code.</p>\n\n<p>This in itself suggests there is a structural/presentation problem.</p>\n\n<p>The only reasonable thing to do is a face-value review, and not as in-depth as I would like...</p>\n\n<h2>PokerFlush</h2>\n\n<p>I dislike constants that are pulled 'implicitly' from other classes. In this case, <code>HAND_SIZE</code> 'magically' appears, and I see it is a constant in the <code>PokerHandResultProducer</code> interface the <code>PokerFlush</code> class implements. This is a poor location for the <code>HAND_SIZE</code>, and a poor way to reference it. It should be something like <code>PokerRules.HAND_SIZE</code>.</p>\n\n<p>I don't like the results <code>List</code> and the <code>PokerHandResult.returnBest</code> combination. I think there is a better way. A class called <code>Best&lt;T&gt;</code> that simply chooses the best hand as hands are added... and then has a <code>best()</code> method. Your code becomes:</p>\n\n<pre><code>Best&lt;PokerHandResult&gt; results = new Best&lt;PokerHandResult&gt;();\n....\nreturn results.best();\n</code></pre>\n\n<p>The <code>PokerHandResult</code> instances have a 'natural order' (implement Comparable), so the generic class <code>Best&lt;T&gt;</code> only has to run the <code>compareTo()</code> method and keep the best.</p>\n\n<h2>PokerHandAnalyze</h2>\n\n<pre><code>private final int[] ranks = new int[ClassicCard.RANK_ACE_HIGH]\n</code></pre>\n\n<p>it took me some minutes to understand that... I know it may make sense to you, but, even when I look at it carefully, I cannot understand why it's not <code>ClassicCard.RANK_WILDCARD</code>. At minimum this line needs a good comment, better would be a constant with a better name.... i.e. wtf does <code>RANK_ACE_HIGH</code> have to do with an array-size?</p>\n\n<p>I know you use the factory method here, but it is being used wrong...</p>\n\n<p>Factory method is good for obscuring the physical implementation of an interface, or for creating otherwise complicated immutables. In this case, the factory method is really just making the constructor simpler.... by moving all the logic to the factory method. This does not, in fact make the class simpler, but just moves the constructor logic in to a non-logical place.</p>\n\n<p>In my assessment, that factory method should be removed and the logic moved to the constructor. Then make all the instance-fields final, and you have a nice immutable class. If you really want to keep the factory method, then your fields should still be final, but you need to pass them all in to the constructor.</p>\n\n<p><code>getRanks()</code> should return a copy of the array so that it's immutable state is preserved (you have marked the array as final, but you are not protecting the final-state of the data in the array)</p>\n\n<p>As far as I can tell, the <code>suites[]</code> array is 'dead' code (completely unused).</p>\n\n<p><code>getCards()</code> should also protect the data by returning a copy of the array.</p>\n\n<h2>PokerHandEval</h2>\n\n<p>Never, under any circumstance, use classes/methods with the name 'test' unless it is designed to test your code (not test the data).... ;-) This just leads to confusion. The Class is called \"...Eval\" so why can you not use <code>evaluate</code> or some variant?</p>\n\n<p>From what I can tell, your tests are ordered in the reverse order to what they should be... you look for the lowest-ranking results first, and then the increasingly-higher results. If you reverse the order, you can 'short-circuit' the process and exit when you have your first result (i.e. why should you look for a pair if you already have a flush?).</p>\n\n<p>Again, here you could also use the 'Best' class to only keep the best result.</p>\n\n<h2>PokerHandResult</h2>\n\n<p>Looks like a reasonably clean immutable class... but should be declared final (<code>public final class PokerHandResult</code>)</p>\n\n<p>I don't like the <code>returnBest(List&lt;PokerHandResult&gt; results)</code> on this class. Should be replaced with <code>Best&lt;T&gt;</code> or moved to a central <code>PokerRules</code> static class</p>\n\n<h2>PokerHandResultProducer</h2>\n\n<p>As I have said, the <code>HAND_SIZE</code> does not belong here. Otherwise it's a fine interface (not much to it...).</p>\n\n<h2>PokerHandType</h2>\n\n<p>fine ... ;-)</p>\n\n<h2>PokerPair</h2>\n\n<p>You have split this method in two parts, and it's just a cheap way to reduce 'complexity'. But, in reality, it has added complexity.... <code>checkForFullHouseAndStuff</code> ... really? There is no added value from that method, and it just creates two levels of 'return' to the user. Sometimes methods just have to be complicated....</p>\n\n<p>The first thing that does is return if another result was already found. Other than that, it does not use the <code>results</code> list.</p>\n\n<p>Like other occasions, a <code>Best&lt;T&gt;</code> class would be useful... for <code>results</code>, <code>pairs</code>, and <code>threeOfAKind</code>.</p>\n\n<h2>Conclusion</h2>\n\n<p>I can't really help too much on your questions about other patterns used, and as for how you use the strategy and factory patterns, I feel the strategy is fine (except for the <code>HAND_SIZE</code> and the order-of-evaluation). The Factory patterns are cumbersome in places.</p>\n\n<p>I did not see any bugs that would affect your game play. The Black-Diamond is the only issue I see... (and that's good for skiing).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T03:30:59.177", "Id": "60793", "Score": "0", "body": "We're lucky to have you @rolfl. Awesome review!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:30:29.707", "Id": "60836", "Score": "4", "body": "Diamonds are black and violets are blue, I write a wrong method and I thank you. I'm never gonna use `this.ordinal()` for such a method again! There's always gonna be someone (myself, that is) that sooner or later will swap the elements to make it incorrect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:51:28.643", "Id": "60842", "Score": "0", "body": "`AceValue` is for handling both card games where ace is highest and where it's lowest. `getRanks` returns an array that can be looped through which provides all the available ranks (2 to ACE_HIGH or ACE_LOW to KING). Since the challenge was to make an evaluator, I just wrote the code and didn't care about adding any UI for the user to interact with. But yes, that would probably make the code more understandable as there would be a more clear \"entry point\" (Yes, I currently just use unit tests)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:19:57.357", "Id": "60857", "Score": "0", "body": "`PokerHandAnalyze`: ACE_HIGH is there because I want the array to contains the number of each rank, from ACE_LOW to ACE_HIGH. Wildcards are handled separately. Wouldn't make sense to treat wildcards as the others. `PokerHandEval`: The code for finding PAIR is the same code that can also find FULL_HOUSE, or FOUR_OF_A_KIND, therefore that part cannot be short-circuited since those are better than FLUSH." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:40:37.633", "Id": "60861", "Score": "1", "body": "@SimonAndréForsberg . OK, these comments clear up the issues I mentioned. On the other hand, you did have to **comment** to make them clear, so the code itself should probably have had the comments in to start with ;-) ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:46:41.857", "Id": "60864", "Score": "0", "body": "Your poetry is doggerel. <br/> Haiku is supreme <br/> why rhyme?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T17:50:04.280", "Id": "60878", "Score": "2", "body": "@rolfl It's hard to write the correct comments without being asked the right questions." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-12-09T02:41:10.883", "Id": "36936", "ParentId": "36916", "Score": "25" } }, { "body": "<p><em>Almost four years later...</em> I discovered a bug. Consider the following tests:</p>\n\n<pre><code>assertEquals(PokerHandType.THREE_OF_A_KIND, eval.evaluate(\n card(Suite.CLUBS, ClassicCard.RANK_ACE_HIGH),\n card(Suite.HEARTS, ClassicCard.RANK_5),\n card(Suite.SPADES, ClassicCard.RANK_KING),\n card(Suite.DIAMONDS, ClassicCard.RANK_ACE_HIGH),\n card(Suite.SPADES, ClassicCard.RANK_ACE_HIGH)\n).getType());\n</code></pre>\n\n<p>That's a three of a kind and should pass, right? Actually yes, it does.</p>\n\n<p>Next one:</p>\n\n<pre><code>assertEquals(PokerHandType.THREE_OF_A_KIND, eval.evaluate(\n card(Suite.CLUBS, ClassicCard.RANK_ACE_HIGH),\n card(Suite.SPADES, ClassicCard.RANK_ACE_HIGH),\n card(Suite.SPADES, ClassicCard.RANK_KING),\n card(Suite.HEARTS, ClassicCard.RANK_8),\n card(Suite.HEARTS, ClassicCard.RANK_5),\n card(Suite.SPADES, ClassicCard.RANK_2),\n card(Suite.EXTRA, ClassicCard.RANK_WILDCARD)\n).getType());\n</code></pre>\n\n<p>Oh, a wildcard! But this is still considered a three of a kind, right? Wrong. It should be a three of a kind, but the code considers this a full house because ace can be both high (14) and low (1), so we have a full house with three 14's and two 1's.</p>\n\n<p>We can even get rid of a few extra cards and take a look at this one:</p>\n\n<pre><code>assertEquals(PokerHandType.THREE_OF_A_KIND, eval.evaluate(\n card(Suite.CLUBS, ClassicCard.RANK_ACE_HIGH),\n card(Suite.SPADES, ClassicCard.RANK_ACE_HIGH),\n card(Suite.EXTRA, ClassicCard.RANK_WILDCARD)\n).getType());\n</code></pre>\n\n<p>The code still considers this a full house of both high and low aces.</p>\n\n<p>How about something simpler then?</p>\n\n<pre><code>assertEquals(PokerHandType.PAIR, eval.evaluate(\n card(Suite.CLUBS, ClassicCard.RANK_ACE_HIGH),\n card(Suite.DIAMONDS, ClassicCard.RANK_ACE_HIGH)\n).getType());\n</code></pre>\n\n<p>That's got to be one pair right? Nope, the code says that is two pair. Again, two pair of both high and low aces.</p>\n\n<p>So what is a possible fix for this? In <code>checkForFullHouseAndStuff</code> in <code>PokerPair</code>, pass the results first through the following method:</p>\n\n<pre><code>private PokerHandResult fixDoubleAce(PokerHandResult result, PokerHandAnalyze analyze) {\n if (result.getPrimaryRank() != ClassicCard.RANK_ACE_HIGH || result.getSecondaryRank() != ClassicCard.RANK_ACE_LOW) {\n return result;\n }\n switch (result.getType()) {\n case FULL_HOUSE:\n return new PokerHandResult(PokerHandType.THREE_OF_A_KIND, result.getPrimaryRank(), 0, analyze.getCards());\n case TWO_PAIR:\n return new PokerHandResult(PokerHandType.PAIR, result.getPrimaryRank(), 0, analyze.getCards());\n default:\n throw new IllegalStateException(\"Unexpected scenario cleaning double ace from \" + result);\n }\n}\n</code></pre>\n\n<p>This method first checks if the result is for both high and low aces and if it is, it returns a degraded poker hand of only the primary rank. So full house becomes three of a kind and two pair becomes one pair.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-11-05T15:26:56.510", "Id": "179676", "ParentId": "36916", "Score": "11" } } ]
{ "AcceptedAnswerId": "36936", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T17:45:18.320", "Id": "36916", "Score": "35", "Tags": [ "java", "game", "weekend-challenge", "playing-cards" ], "Title": "Weekend Challenge - Poker Hand Evaluation" }
36916
<p>I'm trying to teach myself Objective-C/Cocoa for eventual iPhone development but I figured I would start with a terminal app. It takes a user input, strips everything but numerics, then displays PI to the number that is left over.</p> <p>Could anyone have a quick look over my code and see if there's any optimisations I could make or bad practises I could avoid?</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; int main(int argc, const char * argv[]) { @autoreleasepool { int i; char userInput[10]; printf ("Enter a number: "); scanf("%s",userInput); NSString * number = [NSString stringWithUTF8String:userInput]; NSString * strippedNumber = [number stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])]; i = [strippedNumber intValue]; printf("%d\n", i); if (i == 0) { printf("Enter a numeric character\n"); } else { printf("%.*f \n", M_PI, i); } } return 0; } </code></pre>
[]
[ { "body": "<p>BTW: I'm answering from a strong C perspective and weak Objective-C one</p>\n\n<p>To avoid unexpected input and avoid string overflow:</p>\n\n<pre><code>//scanf(\"%s\",userInput);\nif (1 != scanf(\"%9s\",userInput)) handle_error();\n</code></pre>\n\n<p>I'm sure you want:<br>\n<a href=\"https://stackoverflow.com/questions/8761527/variable-interpolation-inside-printf-style-formatting-functions\">ref</a></p>\n\n<pre><code>// printf(\"%.*f \\n\", M_PI, i);\nprintf(\"%.*f \\n\", i, M_PI);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:00:52.550", "Id": "60814", "Score": "0", "body": "Thank you for your reply chux, In regards to the if statement, when i try it I get \"Implicit declaration of function 'handle_error' is invalid in C99\", Also with the printf that removes the formatting error i was getting, although the result was still the same as before which leaves me a bit confused." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:10:14.677", "Id": "60816", "Score": "0", "body": "I used scanf(\"%9s\", userInput); so it only takes the first 9 digits and no more errors come up when I enter a 10+ String so thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:03:18.960", "Id": "60848", "Score": "0", "body": "@Jacob2471 `handle_error()` is simple a random function name I made up to represent code you would write to handle the occurrence of bad input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:06:34.023", "Id": "60850", "Score": "0", "body": "@Jacob2471 \"removes the formatting error i was getting\" and \"the result ... same as before\" are 2 things not in your post. T'would be easier to assist if I knew what these 2 were." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T19:35:52.607", "Id": "61457", "Score": "0", "body": "I was getting a string format error, int cannot be assigned to float but swapping them around fixed it. What i meant by the results are the same as before was that no matter which way round the 'i' and the 'M_PI' was it would print PI to the 'i'th decimal place, I just found it strange that if they were the wrong way round why it wasn't printing i to the 'pi'th decimal place, which should be 'i' as it was an int. Also thank you for your help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T19:54:56.630", "Id": "61471", "Score": "0", "body": "@Jacob2471 when you have the parameters in the wrong order, (let's assume a 4-byte `int` and 8-byte `double`), `printf()` took 4 bytes from `M_PI` (it was expecting an `int`) and tried to interpret that as a precision specification. Then it took the remaining 4 bytes of `M_PI` concatenated with the 4-byte `i` to form _some_ `double`. This is what _might_ have happed, but its Undefined Behavior, so other possibilities exist.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T21:42:03.607", "Id": "61523", "Score": "0", "body": "Ah i see, thank you very much. I can't +rep you right now but you deserve it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T21:51:32.820", "Id": "61527", "Score": "0", "body": "@Jacob2471 When you hit 15+, I think up-vote ability kicks in." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T03:08:43.073", "Id": "36937", "ParentId": "36919", "Score": "2" } } ]
{ "AcceptedAnswerId": "36937", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T18:20:33.127", "Id": "36919", "Score": "4", "Tags": [ "beginner", "objective-c", "floating-point" ], "Title": "Pi to the Nth Digit" }
36919
<p>I have a small module that gets the lemma of a word and its plural form. It then searches through sentences looking for a sentence that contains both words (singular or plural) in either order. I have it working but I was wondering if there is a <strong>more elegant</strong> way to build this expression.</p> <p>Note: Python2</p> <pre><code>words = ((cell,), (wolf,wolves)) string1 = "(?:"+"|".join(words[0])+")" string2 = "(?:"+"|".join(words[1])+")" pat = ".+".join((string1, string2)) +"|"+ ".+".join((string2, string1)) # Pat output: "(?:cell).+(?:wolf|wolves)|(?:wolf|wolves).+(?:cell)" </code></pre> <p>Then the search:</p> <pre><code>pat = re.compile(pat) for sentence in sentences: if len(pat.findall(sentence)) != 0: print sentence+'\n' </code></pre> <p>Alternatively, would this be a good solution?</p> <pre><code>words = ((cell,), (wolf,wolves)) for sentence in sentences: sentence = sentence.lower() if any(word in sentence for word in words[0]) and any(word in sentence for word in words[1]): print sentence </code></pre>
[]
[ { "body": "<p>Maybe, you will find this way of writing more easy to read:</p>\n\n<pre><code>words = (('cell',), ('wolf','wolves'))\n\nstring1 = \"|\".join(words[0]).join(('(?:',')'))\nprint string1\n\nstring2 = \"|\".join(words[1]).join(('(?:',')'))\nprint string2\n\npat = \"|\".join((\n \".+\".join((string1, string2)) ,\n \".+\".join((string2, string1))\n ))\nprint pat\n</code></pre>\n\n<p>My advice is also to use <code>'.+?'</code> instead of just <code>'.+'</code>. It will spare time to the regex motor when it will run through the analysed string: it will stop as soon as it will encouters the following unary pattern.</p>\n\n<p>Another adavantage is that it can be easily extended when there are several couples noun/plural.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T19:50:18.377", "Id": "60752", "Score": "0", "body": "Silly question but isn't \".+?\" the same thing as \".*\" ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:06:14.950", "Id": "60755", "Score": "1", "body": "@Josay No. See in this link : (http://docs.python.org/2/library/re.html#regular-expression-syntax) ``.+`` is greedy, ``.+?`` is ungreedy. It means that in case of ``'..cell....wolf.......'`` analysed, the regex motor of pattern ``(?:cell).+(?:wolf|wolves)`` will match **cell** and then ``.+`` will match all the subsequent characters, dots and **wolf** comprised, until the end of the string; there it will realize that it can't match ``(?:wolf|wolves)`` with anything else. So it will move backward and to search again in order to find such a pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:09:43.463", "Id": "60756", "Score": "1", "body": "Then pattern ``(?:cell).+(wolf\\d|wolves)`` will match ``'wolf2'`` in ``',,cell,,wolf1,,,wolf2,,,'`` while ``(?:cell).+?(wolf\\d|wolves)`` will match ``'wolf1'``" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T21:43:23.990", "Id": "60771", "Score": "0", "body": "Thank you, I will use .+?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T19:48:52.023", "Id": "36925", "ParentId": "36922", "Score": "1" } }, { "body": "<p>You could use <code>findall</code> with a pattern like <code>(cell)|(wolf|wolves)</code> and check if every group was matched:</p>\n\n<pre><code>words = ((\"cell\",), (\"wolf\",\"wolves\"))\npat = \"|\".join((\"({0})\".format(\"|\".join(forms)) for forms in words))\nregex = re.compile(pat)\nfor sentence in sentences:\n matches = regex.findall(sentence)\n if all(any(groupmatches) for groupmatches in zip(*matches)):\n print sentence\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:17:25.227", "Id": "60758", "Score": "0", "body": "A step further than me. Seems good to me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:02:14.563", "Id": "36926", "ParentId": "36922", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T19:08:28.343", "Id": "36922", "Score": "3", "Tags": [ "python", "regex" ], "Title": "Either or case in Python and Regex" }
36922
<p>I have created the following code:</p> <pre><code>class Club(object): def __init__(self, name, points=1000): self.name = name self.points = points def __eq__(self, other): return self.name == other.name def __gt__(self, other): return self.points &gt; other.points def compute_points(self, opponent, is_home, result): rating_diff = self.points - opponent.points + (100 if is_home else -100) expected = 1 / (1 + 10**(-rating_diff/400)) return 32 * (result-expected) def play_match(home, away, result): home_change = int(home.compute_points(away, True, result)) away_change = int(away.compute_points(home, False, 1-result)) home.points += home_change away.points += away_change def club_index(club_to_find, clubs): index = 0 while index &lt; len(clubs): club = clubs[index] if club.name == club_to_find: return index index += 1 return -1 def main(): clubs = [] with open("matches.txt") as file: matches = file.readlines() for match in matches: (home_str, away_str, result) = match.split(" ") index = club_index(home_str, clubs) if index == -1: home = Club(home_str) clubs.append(home) else: home = clubs[index] index = club_index(away_str, clubs) if index == -1: away = Club(away_str) clubs.append(away) else: away = clubs[index] play_match(home, away, float(result)) clubs = sorted(clubs) clubs.reverse() with open("ranking.txt", "w") as file: for club in clubs: file.write(club.name + ": " + str(club.points) + "\n") if __name__ == "__main__": main() </code></pre> <p>which takes a file containing match results, and creates a file containing a ranking based on the Elo Ranking System. However, I feel like my <code>main()</code> method could've been implemented in a better way, so I came here to see for some pointers as to how I can better implement it or pick up any other good practices.</p> <p><strong>EDIT</strong>: Here's an example of the input file:</p> <pre><code>Swansea ManUtd 0 WestHam Cardiff 1 WestBrom Southampton 0 Sunderland Fulham 0 Norwich Everton 0.5 Arsenal AstonVilla 0 Liverpool Stoke 1 Chelsea Hull 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T21:56:44.713", "Id": "60772", "Score": "0", "body": "Watch out when implementing only some of `__eq__`, `__ne__`, `__lt__`, `__gt__`, etc., or `__eq__` and `__hash__`. It can make a class harder to use correctly." } ]
[ { "body": "<p>In <code>play_match</code>, the <code>Club</code> class should be responsible for updating its own score. You could define an <code>update_points</code> method taking the same parameter as the <code>computes_point</code> one (and calling it). Also, shouldn't <code>compute_points</code> be responsible for the conversion to <code>int</code> ?</p>\n\n<p>I find it a bit awkward to have the <code>__eq__</code> and the <code>__gt__</code> base their logic on completely different fields.</p>\n\n<p>In a <code>club_index</code> : as a general rule, you do not iterate that way over object in Python.\nThe pythonic way to write</p>\n\n<pre><code>def club_index(club_to_find, clubs):\n index = 0\n while index &lt; len(clubs):\n club = clubs[index]\n if club.name == club_to_find:\n return i\n index += 1\n return -1\n</code></pre>\n\n<p>is</p>\n\n<pre><code>def club_index(club_to_find, clubs):\n for i,club in enumerate(clubs)\n if club.name == club_to_find:\n return index\n return -1\n</code></pre>\n\n<p>Now, if I was to write such a program, I wouldn't even create a class ( you can have a look at <a href=\"http://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow\">http://www.youtube.com/watch?v=o9pEzgHorH0</a> ). A dictionnary to map club names to score is pretty much everything you need but that's a different way to see the problem I guess.</p>\n\n<p>Edit : Actual tested code added.</p>\n\n<pre><code>def get_new_scores(home_score,away_score,result):\n rating_diff = home_score - away_score + 100\n home_expected = 1 / (1 + 10**(-rating_diff/400))\n away_expected = 1 / (1 + 10**(+rating_diff/400))\n home_return = int(32 * ((result )-home_expected))\n away_return = int(32 * ((1-result)-away_expected))\n return home_score+home_return,away_score+away_return\n\ndef main():\n with open(\"club.txt\") as file:\n matches = file.readlines()\n\n clubs = dict()\n for match in matches:\n (home_str, away_str, result) = match.split(\" \")\n clubs[home_str],clubs[away_str] = get_new_scores(clubs.setdefault(home_str,1000), clubs.setdefault(away_str,1000), float(result))\n\n for club in sorted(clubs, key=clubs.get, reverse=True):\n print(club + \": \" + str(clubs[club]) + \"\\n\")\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T21:57:57.813", "Id": "60773", "Score": "0", "body": "Could you please provide an explanation or link as to what `setdefault` is because I've never seen it before and can't quite make sense of it by Googling it or trying to find it in the docs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T10:19:59.123", "Id": "60801", "Score": "1", "body": "@LazySloth13 See http://docs.python.org/2/library/stdtypes.html#dict.setdefault" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T17:05:54.937", "Id": "60867", "Score": "0", "body": "The pythonic loop should return its index variable `i` rather than the undefined `index` on finding a match. And in your tested code, the first line of `main()` seems useless, since `clubs = dict()` will discard the existing value, which has never been used." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:45:40.623", "Id": "36928", "ParentId": "36927", "Score": "6" } } ]
{ "AcceptedAnswerId": "36928", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T20:18:56.953", "Id": "36927", "Score": "4", "Tags": [ "python" ], "Title": "Football Elo Rankings" }
36927
<p>This might be a basic question for C. I'm making a struct called <code>check_t</code> and I want to make an array whose elements are of type <code>check_t</code>. This array is called <code>enqueued</code>. The struct <code>check_t</code> contains an integer x and a lock (for multi-threading).</p> <pre><code>typedef struct _check_t{ int x; pthread_mutex_t lock; } check_t; void *check_init(check_t *c) c-&gt;x = 0; pthread_mutex_init(&amp;c-&gt;lock,NULL); } check_t **enqueued; for(i=0;i&lt;w*h;i++){ enqueued[i] = (check_t *)malloc(sizeof(check_t)); check_init(&amp;enqueued[i]); } </code></pre> <p>Mostly, I'm wondering if this is the correct way to make/allocate space for an array of <code>check_t</code>s.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T00:46:40.200", "Id": "60783", "Score": "0", "body": "`check_t **enqueued;` is how you'd declare a pointer to a 2D array of `check_t`. Is that what you want?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T01:05:30.753", "Id": "60784", "Score": "0", "body": "enqueued is supposed to be a 1D array. However, I know that I need to stars; one to make it an array, and the other to indicate that I want pointers to each check_t. I can't do enqueued[i] if I say check_t *enqueued." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T01:11:26.497", "Id": "60786", "Score": "0", "body": "`*enqueued` and `enqueued[0]` mean the same thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T02:28:23.723", "Id": "60790", "Score": "1", "body": "You probably want the return type of check_init to be defined as void and not void* as well, since you're not returning anything from that method." } ]
[ { "body": "<p>1D array:</p>\n\n<pre><code>check_t *enqueued = malloc(N * sizeof(*enqueued));\nenqueued[0].x = 5;\nenqueued[N - 1].x = 2;\n</code></pre>\n\n<p>2D array:</p>\n\n<pre><code>check_t **enqueued = malloc(N * sizeof(*enqueued));\nfor(int i = 0; i &lt; N; i++)\n enqueued[i] = malloc(M * sizeof(**enqueued));\nenqueued[0][0].x = 5;\nenqueued[N - 1][M - 1].x = 2;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T01:10:22.997", "Id": "60785", "Score": "0", "body": "I'm much more familiar with spelling the `sizeof` parts as `sizeof(struct check_t)` than `sizeof(*[*]enqueued)`, but I've used similar approaches for `countof` style macros. Interesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T01:14:46.997", "Id": "60787", "Score": "0", "body": "It's safer in case `enqueued` changes types. From `check_t` to some other `struct`, for example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T02:51:40.873", "Id": "60791", "Score": "0", "body": "@Bit Fiddling Code Monkey I concur about the `A = malloc(N *sizeof *A)` idiom. But then why not `enqueued[i] = malloc(M * sizeof *(enqueued[i]))`?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T00:55:51.073", "Id": "36931", "ParentId": "36929", "Score": "5" } }, { "body": "<p>Firstly, decide whether your program <em>actually</em> needs to be C and not C++. It's much safer and generally easier to use a std::vector&lt;check_t> than a manually allocated region, as std::vector does automatic memory management for you (it makes it hard to memory leak) and it makes it hard to index the vector outside of bounds, which would cause a potentially exploitable memory corruption vulnerability in your program.</p>\n\n<p>If for some reason you <em>must</em> do this without the standard template, next decide whether you can't use <em>new[]</em> in C++. This will simplify your code and be more clear what you're doing:</p>\n\n<pre><code>void main()\n{\n check_t* myArray = new check_t[count];\n}\n</code></pre>\n\n<p>Finally, if you're <em>absolutely positively 100% sure</em> you can't use std::vector or <em>new[]</em>, ask yourself if you can do it via <em>calloc</em>:</p>\n\n<pre><code>void main()\n{\n check_t* myArray = calloc(nElements, sizeof(check_t));\n}\n</code></pre>\n\n<p>But if, heaven forbid, you're doing some assignment that explicitly states that <em>you must use</em> <strong><em>malloc</em></strong> on pain of death that you ever use any of the multiple better alternatives that have so kindly been made available to you, this is how you do it:</p>\n\n<pre><code>#include &lt;a_safe_int_library.h&gt;\ncheck_t* CreateAndInitializeCheckTArray\n(\n /* IN */ size_t nElements\n)\n{\n size_t cbSize;\n check_t* array = NULL;\n size_t i;\n\n // avoid an exploitable integer/heap overflow first:\n if(SafeMultiply(&amp;cbSize, sizeof(check_t), nElements) == OVERFLOW) \n return NULL;\n\n array = (check_t*)malloc(cbSize);\n if(array == NULL)\n return NULL;\n\n // clear all of the elements:\n memset(array, 0, cbSize);\n\n // initialize the array:\n for(i = 0; i &lt; nElements; i++)\n {\n check_init(&amp;array[i]);\n }\n\n return array;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T02:25:01.813", "Id": "36934", "ParentId": "36929", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T22:59:47.323", "Id": "36929", "Score": "4", "Tags": [ "c", "multithreading" ], "Title": "Making an array whose elements are defined by a struct" }
36929
<p><strong>Question:</strong> Is having a master class bad practice? I am making a simple pong game, but I'm writing the code as if I were making for something that might be for something more complicated I want to create in the future. Also, am I not doing it in a good manner? </p> <p><strong>What I am doing:</strong> I have a class, in this case "engine", which basically holds everything and runs all of its referenced objects logic inside of its own functions. All of the other objects are then linked to each other by holding the data of the "world or engine" object and use it as a linker to other objects that it can interact with. </p> <p><strong>NOTE:</strong> The <a href="http://www.sfml-dev.org/resources.php" rel="nofollow">sfml media library</a> was used with this project. <br><em>note: if you need the ball definitions i'll post them</em></p> <pre><code>#include &lt;SFML/Graphics.hpp&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;stdlib.h&gt; class paddle; class ball; class enemy; class player; class engine{ ball *gameBall; enemy *enemyPaddle; player *playerPaddle; Clock gameClock; RenderWindow &amp;refWindow; int gameSpeed; Event windowEvent; void eventDraw(); void eventUpdate(); void handleWindow(); public: engine( RenderWindow &amp;rendy); ~engine(); bool start(); Vector2f getWindowSize(); void drawPart(Drawable &amp;art); Time getGameClock(){ return gameClock.getElapsedTime(); } }; class ball{ private: CircleShape myShape; engine&amp; world; int radius; Color color; Vector2f position, velocity; short signed int dirX, dirY; short signed int getDirection(); void wallBounce(); public: ball( engine&amp; gameEngine); void draw(); CircleShape getCircle(){ return myShape; } void pop(); void update(); }; int main() { RenderWindow window(VideoMode(640, 480), "Pong"); engine gameEngine( window ); return (int)gameEngine.start(); } // Class Prototyes // Engine engine::engine(RenderWindow &amp;rendy):refWindow(rendy){ gameBall = new ball(*this); enemyPaddle = new enemy; playerPaddle = new player; gameClock = Clock(); gameSpeed = (1000/60.0); windowEvent = Event(); } engine::~engine(){ delete enemyPaddle; delete playerPaddle; delete gameBall; } void engine::handleWindow(){ if ( refWindow.pollEvent( windowEvent ) ) { if ( windowEvent.type == Event::Closed ) refWindow.close(); } } bool engine::start() { while( refWindow.isOpen() ) { while( gameClock.getElapsedTime().asMilliseconds() &gt; gameSpeed ) { eventUpdate(); eventDraw(); // Restart Clock gameClock.restart(); } handleWindow(); } return true; } void engine::eventUpdate(){ gameBall-&gt;update(); } void engine::eventDraw(){ refWindow.clear( Color::Black ); gameBall-&gt;draw(); refWindow.display(); } Vector2f engine::getWindowSize(){ Vector2f tempVec; tempVec.x = refWindow.getSize().x; tempVec.y = refWindow.getSize().y; return tempVec; } void engine::drawPart(Drawable &amp;art){ refWindow.draw( art ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T03:57:17.550", "Id": "60794", "Score": "2", "body": "Look up the [God Object](http://en.wikipedia.org/wiki/God_object)" } ]
[ { "body": "<p>A \"master class\" is a very close relative to a singleton or a global. It can easily be a design which violates the Dependency Injection principle, and leaves you with non-modular code. In this case your engine is also violating the Single Responsibility principle, as it's doing a lot of unrelated tasks: it's handling windows, providing the game's main driver, moving the ball, drawing the screen, and hosting all kinds of different data.</p>\n\n<p>Try this task: write a unit test that exercises just the engine::handleWindow() routine without needing to create a real ball, enemy, or player. It's hard, because your constructor builds all of those objects.</p>\n\n<p>You've already got a start. For example, you can easily write a unit test that tests engine::eventDraw without creating a real RenderWindow, because you can pass a mock RenderWindow on the engine constructor. You're using dependency injection.</p>\n\n<p>As you're going to have a singleton in main (and every program does at some level), I recommend you try to keep that singleton as thin as possible.</p>\n\n<p>It's not that your existing code isn't going to work, but it's going to be a problem to maintain, especially as you extend it to add functionality. Where does scorekeeping come in? Player preferences? High score table? Head-to-head play with two people? The more you want to add to this, the more you're going to need to change engine, and the less confident you're going to be that you aren't breaking something else.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:28:28.307", "Id": "60822", "Score": "0", "body": "Thanks, this is a very insightful answer! So I am just a bit confused on how I can make a better game engine though. I see what you mean on how it may clunk of just a bit, but I don't understand how I can link all the objects together and how I can leave out the engine when all of them draw themselves. Should I be splitting them up in to more manageable objects?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T17:07:43.390", "Id": "60869", "Score": "0", "body": "I would recommend you try some refactoring to keep related responsibilities together, and to split out unrelated logic. A good way is to write unit tests that test just your logic (not the external libraries). At first the tests will be hard to write, but as you remove unrelated objects, the more you find the tests will become easy to write. As you progress, you will likely become more practiced at Dependency Injection. Your game is a good candidate to practice on, as it's quite simple." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T04:03:47.727", "Id": "36941", "ParentId": "36935", "Score": "5" } }, { "body": "<p>John Deters did a great job answering this; I just have a couple more comments I'd like to make:</p>\n\n<p>You can start off by creating an EntityManager class that you put all your game entities in (player, ball, enemy paddle). This will take out the </p>\n\n<pre><code>ball *gameBall; \nenemy *enemyPaddle; \nplayer *playerPaddle;\n</code></pre>\n\n<p>code, and instead, you could have</p>\n\n<pre><code>EntityManager m_entityManager;\n</code></pre>\n\n<p>instead.</p>\n\n<p>Also, a bit of style that I've always found helpful (I know that style differs between every programmer), but adding the \"m_\" prefix to member variables helps to distinguish between local variables and class data.</p>\n\n<pre><code>//for example\n//instead of:\nClock gameClock;\n\n//you could have\nClock m_gameClock;\n//or\nClock mGameClock;\n</code></pre>\n\n<p>the point is that you're reminding yourself that you're working on member variables rather than local variables/function parameters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:19:36.823", "Id": "60909", "Score": "0", "body": "What is the intended use of the EntityManager? It feels a lot to me like the service locator pattern which is a well known anti-pattern. If something needs a dependency, it should be injected directly, not have to pull it out of something. Also, the m_ or m prefix seems a bit odd to me. In any kind of modern environment, it's very easy to tell the difference between local and object variables. And, if there are so many variables that it becomes difficult to keep track, that's a code smell of the SRP being violated. I guess to each his own though. Maybe just not my style :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:25:34.700", "Id": "60910", "Score": "0", "body": "I'm very new to programming in general, I've been scripting my whole life and haven't been to the level at which c++ is used. So my credibility isn't high. But I do like the idea of an entity manager, just to hold the data in a more structured format. I wouldn't use a class though, instead I imagine a struct would be better used in place because all I would want it to do is hold the objects in a more organized mater. But then again, I haven't learned all the concepts behind object orientated programming, I'm a total noob." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T01:19:03.807", "Id": "60942", "Score": "0", "body": "@Corbin, all that is very true - but for someone that's just starting out & writing a pong game I don't think he needs to try to follow ALL the guidelines/idioms. Most game programmers begin with a very simple EntityManager design and branch out from there." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:14:41.413", "Id": "36980", "ParentId": "36935", "Score": "5" } }, { "body": "<p>You can break up your engine class based upon the responsibilities you have given it.</p>\n\n<p>Namely:\nDraw\nUpdate\nHandleWindow</p>\n\n<p>These tasks can be handled by separate modules.\nYou may at some point decide to build a graphics engine to handle the Draw aspect of the game,\na physics or logic engine to handle the Update aspect of the game,\nand potentially an input engine or UI engine to handle the HandleWindow portion of the game.\nThis would allow you to update the graphics engine in the future (maybe implementing a 3D version of pong) without needing to change any other piece of the engine.\nYou could add logic to handle collision with power-up items in the future in the logic engine of your game with a minimal impact on how the graphics are actually rendered or the input is managed.\nYou could also then add support for different input devices such as a joystick without having any impact at all on the graphics system or the game logic.</p>\n\n<p>Ultimately, the engine could be responsible solely for telling the game to run and delegate all other responsibilities to systems that are better equipped to handle the specifics.</p>\n\n<p>Finally, when you decide to make a game that is not Pong any more, all you have to do is switch out the appropriate subsystems to make a new game. For example, if you wanted to make a breakout game, the UI and graphics systems might be identical to your pong game and reused, but the logic system would be switched out to support logic for breakout.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T17:57:27.927", "Id": "37234", "ParentId": "36935", "Score": "2" } } ]
{ "AcceptedAnswerId": "36941", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T02:41:05.060", "Id": "36935", "Score": "4", "Tags": [ "c++", "object-oriented", "game", "sfml" ], "Title": "Master engine class for a Pong game" }
36935
<p>I have started some experiments with node.js.<br /> Any comment on style (especially the callbacks) and best practice is appreciated:</p> <h3>PassportControl.js</h3> <pre><code>/* * Export single function that creates the passportControl object * * The passport control object is supposed to be a wrapper for * nodejs/express/passport authentication. * * When the object is created it adds two end points to the server * /auth?type=&lt;AuthenticationType&gt; * /auth/callback?type=&lt;AuthenticationType&gt; * * Where AuthenticationType is the service doing the authentication. * Eg Facebook/Twitter/Amazon etc * * This object has two public methods: * checkPassport(req, res) * registerGuest(req, res) * * req: http request received from node. * res: response object we use to reply to the request. * * These are automatically hooked up to the exposed endpoints. * To extend this for any particular service just add the appropriate * objects to the array built with buildData() * */ module.exports = function(app, register) { // App: Application object // register: The user registration service // This has been abstracted from the passport authentication code. // I will document this interface separately. // Get the passport object we reap // Correctly initialize and turn on sessions. var passport = require('passport'); app.use(passport.initialize()); app.use(passport.session()); // Set passport to only save the user ID to the session passport.serializeUser(function(localUser, done) { done(null, localUser.id); }); // Set passport to retrieve the user object using the // saved id (see serializeUser). passport.deserializeUser(function(localUserId, done) { register.getSavedUser(localUserId, function(localUser) { done(null, localUser); }); }); // Create the passport control object passportControl = { data: buildData(passport, register), checkPassport: function(req, res) { return this.getItem(this.data[0], req, res); }, registerGuest: function(req, res) { return this.getItem(this.data[1], req, res); }, getItem: function getItem(dataItem, req, res) { item = dataItem[req.query.type]; if (item == null) { item = dataItem['default']; } return item(req, res); } }; // register the service endpoints // This will control all authentication. app.get('/auth', function(req, res) { passportControl.checkPassport(req, res);}); app.get('/auth/callback', function(req, res) { passportControl.registerGuest(req, res);}); return passportControl; } // Global object for correctly escaping URL var querystring = require('querystring'); // Private Method // This builds the data object central to &quot;passportControl&quot; // It is basically a two element array containing two maps. // The Key: Is the name of the &quot;AuthenticationType&quot; the value is the passport object that does the authentication. // The first object handles the initial authentication request. // The second object handles the callback from the authentication service function buildData(passport, register) { // Set Up facebook authentication strategy. var FacebookStrategy = require('passport-facebook').Strategy; passport.use(new FacebookStrategy({ clientID: &quot;XXXXXX&quot;, clientSecret: &quot;YYYYYY&quot;, callbackURL: &quot;http://iPubCrawlMaps.com:3000/auth/callback?type=facebook&quot; }, function(accessToken, refreshToken, profile, done) { register.updateUser({ provider: profile.provider, providerId: profile.id, displayName:profile.displayName}, function(localUser) { done(null, localUser); }); }) ); // Add more strategies as required here. return [ { default: function(req, res) {res.redirect('/login?'+querystring.stringify({reg_error:'Invalid Authentication Type (attempt)'}));}, facebook: passport.authenticate('facebook'), }, { default: function(req, res) {res.redirect('/login?'+querystring.stringify({reg_error:'Invalid Authentication Type (callback)'}));}, facebook: passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' }), } ]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:41:18.393", "Id": "60899", "Score": "0", "body": "Also See: http://codereview.stackexchange.com/q/36940/507" } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>Your indenting is a mix of 4 space and 8 space tabbing, please stick at all times to either 4 or 2 spaces. Looking at <code>deserializeUser</code> is aneurysm inducing.</li>\n<li>You have a ton of comments, which I like, authentication can always use tons of comment</li>\n<li><code>data[0]</code> and <code>data[1]</code> both use a crucial magic constant, how about <code>data[AUTHENTICATION]</code> and <code>data[CALLBACK]</code> or some such ?</li>\n<li>I do not like the <code>registerGuest</code> name, <code>registerUser</code> maybe?</li>\n<li>I also do not like <code>getItem</code>, this function is not getting an item..</li>\n<li>I am not a big fan of putting clientSecret in your code, it should get this from an environment variable really, otherwise anybody with access to your version control system knows your clientSecret..</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:19:17.937", "Id": "39885", "ParentId": "36938", "Score": "6" } } ]
{ "AcceptedAnswerId": "39885", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T03:14:18.963", "Id": "36938", "Score": "11", "Tags": [ "javascript", "node.js", "passport", "authentication" ], "Title": "node.js passport wrapper" }
36938
<p>More javascript (nodejs) to go with the passport wrapper I just posted:</p> <h3>UserBook.js</h3> <pre class="lang-js prettyprint-override"><code>/* * A wrapper for user Registration for a web site. * This is an MYSQL version of the client to provide persistent state. * * Exports a single function that returns the object (UserBook) that does the work. * UserBook exposes two public methods: * * updateUser(profile, userRegister(profile)) * profile: An object with information about the user. * From this we will try and retrieve the local-id of the user. * If there is no local-user we create one. * userRegister: A callback used when the user-id is found. * The id is added to the profile and this is passed as the * parameter to the callback. * getSavedUser(localId, userRegister(profile)) * localId: The local-id of a user retrieved from the session information. * userRegister: A callback used when the user information is found. * */ module.exports = function() { // Local DB connection var mysql = require('mysql'); var theDB = mysql.createConnection({ host: '127.0.0.1', user: 'user', password: 'password', database: 'db' }); // Create the UserBook object return { // The db object kept locally db: theDB, updateUser: function(profile, userRegistered) { var db = this.db; // See if the user exists. db.query( 'SELECT * FROM Users WHERE Provider=? AND ProviderId=? LIMIT 1', [profile.provider, profile.providerId], function(err, rows) { if (err) throw err; if (rows.length == 1) { // If we have found a local user the set the ID profile.id = rows[0].ID; if (profile.displayName != rows[0].DisplayName) { // See if we need to update the display name. db.query( 'UPDATE Users SET DisplayName=? WHERE Provider=? AND ProviderId=?', [profile.displayName, profile.provider, profile.providerId], function(err) { if (err) throw err; }); } // Callback when user is identified. userRegistered(profile); } else { // No local user found. // So lets create a new one. db.query( 'INSERT INTO Users (Provider, ProviderId, DisplayName) VALUES(?,?,?)', [profile.provider, profile.providerId, profile.displayName], function(err, result) { if (err) throw err; profile.id=result.insertId; // Callback when new user is created userRegistered(profile); }); } }); }, getSavedUser: function(localId, userRegistered) { var db = this.db; // get the local user from the DB db.query( 'SELECT * FROM Users WHERE ID=? LIMIT 1', [localId], function(err, rows) { if (err) throw err; if (rows.length == 1) { profile = { id: rows[0].ID, provider: rows[0].Provider, providerId: rows[0].ProviderId, displayName:rows[0].DisplayName}; // Callback when information is retrieved. userRegistered(profile); } }); }, }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:05:28.710", "Id": "60880", "Score": "0", "body": "would you please include a link to the other questions that you posted, it seems that they might be relevant when reviewing the code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:41:02.610", "Id": "60898", "Score": "1", "body": "@Malachi: http://codereview.stackexchange.com/q/36938/507" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T22:52:33.810", "Id": "61736", "Score": "0", "body": "@LokiAstari The code is highlighted as SQL, it needs to be highlighted as JavaScript." } ]
[ { "body": "<p>I have never seen so relatively little code with so much indentation before. There are many acceptable style choices, but I think you'll regret this one.</p>\n\n<p>Personally I usually avoid inlining functions, I know it is what all the cool kids are doing, but I find that it makes it harder to spot function boundaries.</p>\n\n<p>So instead of:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>foo(bar,function(){\n //code\n})\n</code></pre>\n\n<p>I would do:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>foo(bar,name)\nfunction name(){\n //code\n}\n</code></pre>\n\n<p>Alternately, if you do want functions inline take a lineshift to get the function beginning back to a reasonable spot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T21:28:59.353", "Id": "61697", "Score": "0", "body": "I agree with the indentation (totally bad (in my version)). But using named functions I know is a bad idea as it causes clashes. Best practice is to use unamed functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T22:46:57.387", "Id": "61734", "Score": "0", "body": "@LokiAstari Clashes? You do know that you can make inner functions that only take up namespace in the local scope?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T18:17:17.350", "Id": "61797", "Score": "0", "body": "No I was note. But that is the kind of detailed explanation that would be good inside a code review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-14T18:47:34.293", "Id": "61812", "Score": "0", "body": "@LokiAstari I can't know for sure where the holes in your knowledge is. But discussing my answer bore fruit, and you gained a new piece of knowledge. You can read more about scope and closures on a load of sites, you might as well Google it as me. The most relevant thing for me to add is probably that Node has an extra scope layer, a module's root scope is local to that module, but there is also a global scope that you can access through the `global` object, or by simply not declaring a variable with `var`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-13T21:01:05.007", "Id": "37324", "ParentId": "36940", "Score": "2" } }, { "body": "<h3>Indentation</h3>\n<p>The rightward drift in callback code makes code very hard to read—you're making the problem worse by choosing such large indentation. Most JS projects I've seen use 2 spaces.</p>\n<p>Personally, I find this much easier to read:</p>\n<pre><code>module.exports = function() {\n // Local DB connection\n var mysql = require('mysql');\n var theDB = mysql.createConnection({\n host: '127.0.0.1',\n user: 'user',\n password: 'password',\n database: 'db'\n });\n\n // Create the UserBook object\n return {\n // The db object kept locally\n db: theDB,\n\n updateUser: function(profile, userRegistered) {\n var db = this.db;\n\n // See if the user exists.\n var selectArgs = [profile.provider, profile.providerId];\n db.query('SELECT * FROM Users WHERE Provider=? AND ProviderId=? LIMIT 1', selectArgs, function(err, rows) {\n if (err) throw err;\n\n if (rows.length == 1) {\n // If we have found a local user the set the ID\n profile.id = rows[0].ID;\n if (profile.displayName != rows[0].DisplayName) {\n // See if we need to update the display name.\n var updateArgs = [profile.displayName, profile.provider, profile.providerId];\n db.query('UPDATE Users SET DisplayName=? WHERE Provider=? AND ProviderId=?', updateArgs, function(err) {\n if (err) throw err;\n });\n }\n\n // Callback when user is identified.\n userRegistered(profile);\n } else {\n // No local user found.\n // So lets create a new one.\n var insertArgs = [profile.provider, profile.providerId, profile.displayName];\n db.query('INSERT INTO Users (Provider, ProviderId, DisplayName) VALUES(?,?,?)', insertArgs, function(err, result) {\n if (err) throw err;\n\n profile.id=result.insertId;\n // Callback when new user is created\n userRegistered(profile);\n });\n }\n });\n },\n\n getSavedUser: function (localId, userRegistered) {\n var db = this.db;\n // get the local user from the DB\n db.query('SELECT * FROM Users WHERE ID=? LIMIT 1', [localId], function (err, rows) {\n if (err) throw err;\n\n if (rows.length == 1) {\n profile = {\n id: rows[0].ID,\n provider: rows[0].Provider,\n providerId: rows[0].ProviderId,\n displayName:rows[0].DisplayName\n };\n\n // Callback when information is retrieved.\n userRegistered(profile);\n }\n });\n }\n };\n};\n</code></pre>\n<p>Instead of wrapping <code>query</code> params each on a line I extracted SQL arguments into variables. I think it's reasonable given that it also allowed me to fit <code>query</code> call on one line, and thus avoid additional indentation inside a function.</p>\n<p>Still, I don't think this is good either—<strong>we need to go deeper</strong>.</p>\n<h3>Callbacks</h3>\n<p>Why are you <em>throwing</em> errors instead of returning them to the caller in callback as first argument, like <code>query</code> itself does? <a href=\"http://www.wekeroad.com/2012/02/25/nodejs-callback-conventions-and-your-app/\" rel=\"noreferrer\">NodeJS's convention is <code>function(err, result)</code></a>, you should follow it. Otherwise, <strong>the client code won't be able to catch them.</strong></p>\n<p>Also, in your code, <code>getSavedUser</code> never calls the callback if there is no such user. Which means <strong>the client will just hang forever</strong> waiting for result.</p>\n<p>Personally, I try to avoid callbacks when they represent an asynchronous operation that can fail or succeed, and use <a href=\"http://www.html5rocks.com/en/tutorials/es6/promises/\" rel=\"noreferrer\">promises</a> instead. They reduce nesting and allow much easier control flow, especially with regards to error handling.</p>\n<p>AFAIK Promises are not yet supported out of the box in Node.js, but there are plenty libraries like <a href=\"https://github.com/kriskowal/q\" rel=\"noreferrer\">Q</a>. It's easy to “translate” NodeJS-style functions to promise-returning functions, for example Q has a method called <a href=\"https://github.com/kriskowal/q/wiki/API-Reference#qdenodeifynodefunc-args\" rel=\"noreferrer\"><code>Q.denodeify</code></a> that does just that.</p>\n<p>This is your code rewritten to use promises. The problems with non-bubbling errors and hanging <code>getSavedUser</code> are solved here:</p>\n<pre><code>var mysql = require('mysql'),\n Q = require('q'),\n\nvar db = mysql.createConnection({\n host: '127.0.0.1',\n user: 'user',\n password: 'password',\n database: 'db'\n});\n\nvar promiseQuery = Q.denodeify(db.query.bind(db));\n\nfunction updateUser(profile) {\n var selectArgs = [profile.provider, profile.providerId];\n\n return promiseQuery('SELECT * FROM Users WHERE Provider=? AND ProviderId=? LIMIT 1', selectArgs)\n .then(function (rows) {\n if (rows.length == 1) {\n // If we have found a local user the set the ID\n profile.id = rows[0].ID;\n\n if (profile.displayName == rows[0].DisplayName) {\n return;\n }\n\n // See if we need to update the display name.\n var updateArgs = [profile.displayName, profile.provider, profile.providerId];\n return promiseQuery('UPDATE Users SET DisplayName=? WHERE Provider=? AND ProviderId=?', updateArgs);\n }\n\n // No local user found.\n // So lets create a new one.\n\n var insertArgs = [profile.provider, profile.providerId, profile.displayName];\n return promiseQuery('INSERT INTO Users (Provider, ProviderId, DisplayName) VALUES(?,?,?)', insertArgs)\n .then(function (result) {\n profile.id = result.insertId;\n });\n })\n .thenResolve(profile);\n}\n\nfunction getSavedUser(localId) {\n return promiseQuery('SELECT * FROM Users WHERE ID=? LIMIT 1', [localId])\n .then(function (rows) {\n if (rows.length !== 1) {\n throw new Error('Could not find user');\n }\n\n return {\n id: rows[0].ID,\n provider: rows[0].Provider,\n providerId: rows[0].ProviderId,\n displayName:rows[0].DisplayName\n };\n });\n}\n\nmodule.exports = function() {\n return {\n updateUser: updateUser,\n getSavedUser: getSavedUser\n };\n};\n</code></pre>\n<p>To use this code, instead of supplying a callback in the client code, you'll need to consume a promise by calling <code>then</code> to handle result, optionally <code>catch</code> to catch an error, and <code>done</code> to prevent errors from being unobserved.</p>\n<p><a href=\"http://www.html5rocks.com/en/tutorials/es6/promises/\" rel=\"noreferrer\">Read more about promises.</a> (This article is focused on native promises that just arrived to V8, but <a href=\"https://github.com/kriskowal/q\" rel=\"noreferrer\">Q</a> promises act the same.)</p>\n<h3>Minor considerations</h3>\n<ul>\n<li><p><code>theDB</code> is a bad name, why not just <code>db</code>? Also,</p>\n<pre><code> var db = this.db;\n</code></pre>\n<p>is useless inside the methods since you can just use <code>db</code> variable from outer scope. (See my second example.)</p>\n</li>\n<li><p>Why do you expose the DB to client at all? This breaks encapsulation and doesn't seem safe.</p>\n</li>\n<li><p>I removed useless comments from the second code snippet: some of them just repeat the code. Comments must specify <em>why</em> the code does what it does, not just rephrase the code in human language.</p>\n<p>Comments like</p>\n</li>\n</ul>\n<pre><code> // Local DB connection\n var mysql = require('mysql');\n\n // Create the UserBook object\n return {\n\n // Callback when user is identified.\n userRegistered(profile);\n</code></pre>\n<p>serve no valuable purpose, they only litter the code.</p>\n<p>(And when someone changes the code, they often forget to change the comments, resulting in inconsistency.)</p>\n<ul>\n<li>In the second example, I moved functions out of the <code>module.exports</code> to reduce nesting even further. This will work just as fine.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T22:31:17.700", "Id": "64248", "Score": "0", "body": "Thanks. Working through your comments. I was told by another JS expert to avoid named functions (ie prefer anonymous) as the names can potentially clash with other code (which is a real problem as the code grows in size). In your second example are the names not exposed beyond the module? or is there a technique to make them not exposed further?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T22:40:49.090", "Id": "64249", "Score": "2", "body": "@Loki: Read about [scoping in JS](https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures). All variables declared with `var` (or `function`, for that matter) are **local to the function they are declared inside of**. So in your case named functions will be local to `updateUser` and `getSavedUser`, so there can be no clash with other parts of code. [Moreover, **what you declare inside NodeJS module is local to that module**](http://51elliot.blogspot.ru/2012/01/simple-intro-to-nodejs-module-scope.html), unless you put it in `exports`. So no, it isn't a problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T21:00:52.523", "Id": "64632", "Score": "1", "body": "OK. Java Expert redeemed. My interpretation of his instructions was off. I have fixed my assumptions." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T15:47:50.753", "Id": "38504", "ParentId": "36940", "Score": "6" } } ]
{ "AcceptedAnswerId": "38504", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T03:49:20.597", "Id": "36940", "Score": "8", "Tags": [ "javascript", "mysql", "sql", "node.js" ], "Title": "Local user registration" }
36940
<p>This program is compiling just fine, and the variables and such seem to be passing through. However, when I open the text file there is no data. Can anyone point me in the right direction or nudge my brain into the right process thought? </p> <pre><code>package dvdlogger; import java.util.*; import java.io.*; public class DVDLogger { public DVDLogger() throws IOException { String title = null; double price = 0; storeDVDInfo(title, price); } private void storeDVDInfo(String title, double price) throws IOException { File path = new File("C:\\users\\crazy\\desktop\\dvd.txt"); PrintWriter output = new PrintWriter(path); output.printf("%1$s %2$.2f", title, price); } public static void main(String[] args) throws IOException{ DVDLogger dvd; String title; double price; try (Scanner read = new Scanner(System.in)) { dvd = new DVDLogger(); System.out.printf("%nPlease enter the title of the DVD: "); title = read.nextLine(); System.out.printf("%nPlease enter the price of the DVD: "); price = read.nextDouble(); } dvd.storeDVDInfo(title, price); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T04:20:59.370", "Id": "60795", "Score": "0", "body": "Your question is not suited to CodeReview, it is not working code. Still this is a really common mistake that java programmers make, and the answer is more than can fit in a comment..... will answer anyway...." } ]
[ { "body": "<p>With any Java Writer or Stream... <strong>YOU MUST PROPERLY FLUSH AND CLOSE</strong> it.</p>\n\n<p>The documentation is not fantastically clear... but:</p>\n\n<p>when you exit the method, you must ensure that the file is flushed and closed. you are exiting your program before the data is written to disk.</p>\n\n<p>Always use the following pattern when doing IO (if you are using Java7) :</p>\n\n<pre><code>try (PrintWriter output = new PrintWriter(path)) {\n output.printf(\"%1$s %2$.2f\", title, price);\n output.flush();\n}\n</code></pre>\n\n<p>This is a <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">'try-with-resource' block</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T04:30:44.263", "Id": "60796", "Score": "0", "body": "And that nailed it. I had reviewed tons of examples, and don't recall seeing a flush() anywhere. But it now works. Thanks much, and in the future I'll keep posts like these on stackoverflow." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T04:26:26.420", "Id": "36943", "ParentId": "36942", "Score": "2" } } ]
{ "AcceptedAnswerId": "36943", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T04:11:25.367", "Id": "36942", "Score": "1", "Tags": [ "java", "file", "io" ], "Title": "Java PrintWriter not printing data to file" }
36942
<p>I wrote a Heap, but the judge system reports "time limit exceeded" in some tests. I use a <code>sift_down</code> to build, so I don't know why.</p> <p>Maybe I can improve the build? Or do I have a bad <code>sift_down</code>?</p> <blockquote> <p><strong>Input:</strong></p> <p><code>n</code> commands</p> <p><strong>Commands:</strong></p> <p>0 xxx, where xxx is a number to add to heap <br> 1 - extract maximum from heap</p> </blockquote> <pre><code>#include &lt;iostream&gt; using namespace std; int j = 0; int sift_down(long long int *a, int i, int n){ int l = 2 * i; int r = 2 * i + 1; int largest = i; if (l &lt;= n &amp;&amp; a[l] &gt; a[i]) largest = l; else largest = i; if (r &lt;= n &amp;&amp; a[r] &gt; a[largest]) largest = r; if (largest != i){ long long int x = a[i]; a[i] = a[largest]; a[largest] = x; sift_down(a, largest, n); } return largest; } void sift_up(long long int *a, int i){ long long x = a[i]; while (i &gt; 1 &amp;&amp; a[i / 2] &lt; x){ a[i] = a[i / 2]; i /= 2; } a[i] = x; // cout &lt;&lt; i &lt;&lt; endl; } void Extract_Max(long long int *a, int *n){ long long int z = a[1]; a[1] = a[*n]; (*n)--; sift_down(a, j = 1, *n); cout &lt;&lt; z &lt;&lt; endl; } int main(){ int n = 0; int k = 0; int l = 0; //len int command = 0; cin &gt;&gt; k; long long int *a = new long long int[k + 1]; // n &lt;= k for (int i = 0; i &lt; k; i++){ cin &gt;&gt; command; if (command == 0){ cin &gt;&gt; a[++n]; } else { for(int i = n - 1; i &gt;= 1; i--) sift_down(a, i, n); Extract_Max(a, &amp;n); } } delete []a; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T08:07:42.413", "Id": "60797", "Score": "4", "body": "It may be tough for others to read your code since you use many one-letter variable names. I'm also not sure why you're using a global variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T12:34:46.687", "Id": "60811", "Score": "0", "body": "Shouldn't you do a `sift_up` after you have inserted an item at the end of the heap in your main? `sift_up` is never used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:24:18.153", "Id": "60821", "Score": "0", "body": "Also you don't need to `sift_down` n-1 times before `Extract_Max`. The one `sift_down` in `Extract_Max` should be sufficient to reorder the heap after deleting the root." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:38:03.633", "Id": "60823", "Score": "0", "body": "The global `j` is not necessary. It is set once in `Extract_Max` but never read. You can replace in `Extract_Max` `sift_down(a, j = 1, *n);` with `sift_down(a, 1, *n);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T14:24:01.060", "Id": "60825", "Score": "0", "body": "I've rolled back the code to the non-working version. If you can answer your question your own, please to so by providing an appropriate answer." } ]
[ { "body": "<p>Some generic comments about your code, not related to your problem.</p>\n\n<hr>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>There are some developers which consider importing a whole namespace (overwriting some standard functions with imported ones) as very bad practice. I'm not qualified enough to make comments on that, but it's something you should keep in mind.</p>\n\n<hr>\n\n<p>You're inconsistent about your usage of letter casing.</p>\n\n<pre><code>int sift_down( ...\nvoid Extract_Max( ...\n</code></pre>\n\n<p>That's one of the things you should fix first, there is no standard for C/C++ when it comes to casing, but at least be consistent within your source code. And even better, have a look at what everyone else in your environment does and copy that.</p>\n\n<hr>\n\n<pre><code>int sift_down(long long int *a, int i, int n){\n int l = 2 * i;\n int r = 2 * i + 1;\n</code></pre>\n\n<p>To abuse a very popular movie quote:</p>\n\n<blockquote>\n <p>I find your lack of properly named variables disturbing.</p>\n</blockquote>\n\n<p>There is absolutely <strong><em>no</em></strong> valid reason to use single letter variable names in production code, with the only exception of dimensions (x, y, z) and loop variables (i, j, k).</p>\n\n<p>You might also notice that, normally, an integer with the name <code>i</code> is only used inside loops. Seeing it as a parameter to a function is...disturbing.</p>\n\n<hr>\n\n<p>The lack of comments is also problematic, especially when it comes to rather complex implementations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:42:16.817", "Id": "60892", "Score": "1", "body": "C/C++ doesn't have any particular convention for function names. Win32, for instance, is written with CapitalCasing but is entirely in C, whereas the standard libraries is mostly loweralltheway (e.g. atexit) but with a light sprinkling of lower_with_underscores (e.g. va_list)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:52:37.300", "Id": "60901", "Score": "0", "body": "@Matt: Oh, wasn't sure about that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T14:22:10.177", "Id": "36960", "ParentId": "36947", "Score": "3" } }, { "body": "<p>I believe you are not using the <code>sift_up</code> and <code>sift_down</code> properly. As you can see from this <a href=\"http://en.wikipedia.org/wiki/Binary_heap\" rel=\"nofollow\">Wikipedia article</a> <code>sift_up</code> should be used after an insertion and <code>sift_down</code> after a deletion in order to reorganize the heap. Both only once. </p>\n\n<p>In your code you have omitted to use <code>sift_up</code> after your insertion, instead you used n-1 <code>sift_down</code>'s which have lead incidentally to the same result as one <code>sift_up</code> but with a much higher processing time.</p>\n\n<p>So your <code>main</code> should look like this:</p>\n\n<pre><code>int main(){\n int n = 0;\n int k = 0;\n int l = 0; //len\n int command = 0;\n cin &gt;&gt; k;\n\n long long int *a = new long long int[k + 1]; // n &lt;= k\n for (int i = 0; i &lt; k; i++){\n cin &gt;&gt; command;\n if (command == 0){\n cin &gt;&gt; a[++n];\n sift_up(a, n);\n }\n else {\n Extract_Max(a, &amp;n);\n }\n }\n\n\n delete []a;\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:23:26.837", "Id": "36974", "ParentId": "36947", "Score": "2" } }, { "body": "<p>First off, you're probably better off using what the standard library provides, when appropriate. For example use a <a href=\"http://www.cplusplus.com/reference/queue/priority_queue/\" rel=\"nofollow\"><code>priority_queue</code></a> or at least <a href=\"http://www.cplusplus.com/reference/algorithm/push_heap/\" rel=\"nofollow\"><code>push_heap</code></a>, <a href=\"http://www.cplusplus.com/reference/algorithm/pop_heap/\" rel=\"nofollow\"><code>pop_heap</code></a>, etc. on a <code>vector</code>, so there's almost nothing you have to build.</p>\n\n<p>If you do build your own (to learn, or to satisfy certain rules), here's some things I would change about your existing code.</p>\n\n<ul>\n<li>As other people mentioned, better variable names and/or comments are a big help. But especially avoid naming a variable <code>l</code> (or for that matter <code>I</code>). Not only does it not convey anything, but it's too hard to tell apart from <code>1</code> in many fonts. As examples, in <code>sift_down</code> I would consider changing <code>l</code> to <code>left_child</code>, <code>r</code> to <code>right_child</code>, <code>a</code> to <code>heap</code> and <code>n</code> to <code>heap_length</code>.</li>\n<li><p>You can remove the else branch of this code; it will never change the value of <code>largest</code>.</p>\n\n<pre><code>int largest = i;\nif (l &lt;= n &amp;&amp; a[l] &gt; a[i])\n largest = l;\nelse\n largest = i;\n</code></pre></li>\n<li><p>You can avoid a local temporary by using <code>std::swap(a[i], a[largest]);</code> in place of the following:</p>\n\n<pre><code>long long int x = a[i];\na[i] = a[largest];\na[largest] = x;\n</code></pre></li>\n<li>If you're looking for performance, recursion is probably not the best way to get it in C++. You may be better off writing a loop that exits once it can no longer search deeper in the heap. (Note that this is likely to be a micro-optimization, and you're probably looking for an algorithmic problem.)</li>\n<li>With either a recursive or iterative <code>sift_down</code>, you're likely to want to return the final location. If you keep the recursion I would expect <code>largest = sift_down(a, largest, n)</code> to provide this. But since the return value isn't used, and there are no comments, it's unclear what the return value should report, or if it should be <code>void</code>.</li>\n</ul>\n\n<p>Finally as an overall comment, I don't think you're approaching the problem the way it's intended to be approached. You should probably maintain a valid heap at all times (or at least after the first extract command), and each extract should probably remove the number it extracts. Your implementation might remove the extracted number, but it also appears to rebuild a heap whenever the extract is requested. Doing so throws away the algorithmic advantages of using a heap.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:03:47.300", "Id": "36988", "ParentId": "36947", "Score": "2" } } ]
{ "AcceptedAnswerId": "36974", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T07:53:29.437", "Id": "36947", "Score": "4", "Tags": [ "c++", "programming-challenge", "heap", "time-limit-exceeded" ], "Title": "Time limit exceeded in Heap" }
36947
<p>I am now working on a Node.js project, and on my ejs view page, I'm retrieving this array of objects, like:</p> <pre><code>[{ name: 'Andy', age: 20, username: 'andygoodluck'}, {name: 'Terry', age: 21, username: 'terrygoodnight'}] </code></pre> <p>My objective is to make use of this data to dynamically create and inject content using JavaScript. My existing approach is:</p> <ol> <li>Put this data into a variable, say <code>usersObjArr</code>.</li> <li>Set number of user blocks to be shown per row with a variable, say <code>numUsersPerRow=3</code>.</li> <li>Calculate the number of rows I will need, like <code>numRows=getNumRows(usersObjArr.length);</code></li> <li><p>If there is only one row of content needed, simply go through the array of objects and push them into the row:</p> <pre><code>for(var j=0;j&lt;usersObjArr;j++){ insertUserBlock();//pushes user objects one by one into the row } </code></pre></li> <li><p>Else if there is more than one row, check that I am not working with the last row. As long as it is not the last row, insert the predetermined number of user blocks using the array of objects. Like:</p> <pre><code>for(var i=0;i&lt;numRows;i++){ if(i!=(numRows-1)){ //as long as it's not the last row, insert 3 users for(var k=0;k&lt;numUsersPerRow;k++){ insertUserBlock(i); //insert 3 blocks into the row specified by the argument } </code></pre></li> <li><p>On the other hand, if it is the last row, then I will insert the number of users equivalent to the remainder:</p> <pre><code>else{ for(var k=0;k&lt;usersObjArr.length%numGamesPerRow;k++){ insertUserBlock(i); } } </code></pre></li> </ol> <p>I can't help but feel that this is not the most efficient approach. I am a web designer turned frontend developer and have a weak programming background, so I can really do with some advice on how to improving my coding above.</p> <p>==========UPDATED==========</p> <p>Here's the full code:</p> <pre><code>function getNumRows(numOfUsers){ return Math.ceil(numOfUsers/3); } function insertUserBlocks(usersObjArr){ var numUsersAdded=0, numUsersPerRow=3, numRows=getNumRows(usersObjArr.length); if(usersObjArr.length&lt;numUsersPerRow){ //if only one row worth of users, then insert just one row and push userblocks based on number of users insertUserRow(); for(var j=0;j&lt;usersObjArr.length;j++){ insertUserBlock(); } } else{ //if more than 3 users, we need to insert more than one row, and insert users into first row, then second, and so on var numUsers=usersObjArr.length; for(var i=0;i&lt;numRows;i++){ insertUserRow(i); if(i!=(numRows-1)){ //as long as it's not the last row, insert 3 users for(var k=0;k&lt;numUsersPerRow;k++){ insertUserBlock(i); insertUserBlockContent(i,k,usersObjArr[numUsers-1]);//insert userContent based on last index of usersObjArr; minus one because of zero-based index numUsersAdded++; numUsers--; } } else{ //otherwise, insert number of users equivalent to the remainder for(var l=0;l&lt;usersObjArr.length%numUsersPerRow;l++){ insertUserBlock(i); insertUserBlockContent(i,l,usersObjArr[numUsers-1]); numUsersAdded++; numUsers--; } } } } } function insertUserRow(rowNumber){ if(arguments.length==0) $('#main').append('&lt;div class="row-fluid" /&gt;'); else $('#main').append('&lt;div class="row-fluid" id="row'+rowNumber+'" /&gt;'); } function insertUserBlock(rowNum){ if(arguments.length==0){ $('#main .row-fluid').append('&lt;div class="span4 user-block" /&gt;'); } else{ $('#row'+rowNum).append('&lt;div class="span4 user-block" /&gt;'); } } function insertUserBlockContent(rowNum,blockNum,userObj){ var userName=userObj['name'], userPic=userObj['pic'], userNickname=userObj['nickname'], userUrl=userObj['url']; $('#row'+rowNum+' .span4').eq(blockNum).append('&lt;img src="'+userPic+'" /&gt;').append('&lt;div /&gt;'); $('#row'+rowNum+' .span4 div').eq(blockNum).append('&lt;h2&gt;'+userName+'&lt;/h2&gt;').append('&lt;p&gt;'+userNickname+'&lt;/p&gt;').append('&lt;a target="_blank" class="center btn btn-danger" href="'+ userUrl +'"&gt;Website&lt;/a&gt;'); } </code></pre> <p>Basically what I'm trying to achieve is to extract the data and use it to insert rows of user content into the page. Maybe it's because of the rigid HTML structure in place? (I'm using Bootstrap.) I feel like my approach isn't quite efficient. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:16:02.367", "Id": "60819", "Score": "0", "body": "Hello and welcome to Code Review! I'm not sure I understand what you're trying to do. Can you describe a bit more your goal here? What does insertUserBlock do? Can we see all the code you're describing here? Thank you." } ]
[ { "body": "<p>The most simple and probably what will save you some time in the future is to wrap every JSON object into a <code>&lt;div&gt;</code> and add all of your wrapper divs into another div (or whatever element that might be best for your purpose). Then just style it using CSS. </p>\n\n<p><a href=\"http://jsfiddle.net/5AnC8/2/\" rel=\"nofollow\">Here is an jsfiddle example</a> (this could be improved ten-folds, as it's just a proof of concept) </p>\n\n<p>So as you can see, a very simple <code>holder</code> div (rename as you see fit), the given <code>data</code>, an (unoptimized) loop to iterate every item in your array, and a very small CSS. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T09:53:03.093", "Id": "37023", "ParentId": "36948", "Score": "1" } }, { "body": "<pre><code>function createUserList(users) {\n var $table = $('&lt;div class=\"user-table\"&gt;');\n for (var i = 0; i &lt; users.length; i++) {\n if (i % 3 === 0) {\n var $row = $('&lt;div class=\"row\"&gt;').appendTo($table);\n }\n $row.append(createUserBlock(users[i]));\n }\n return $table;\n}\n\nfunction createUserBlock(user) {\n return $('&lt;div&gt;', {'class': 'user-block', 'text': user.name});\n}\n\n$('#main').append(createUserList(users));\n</code></pre>\n\n<p>Instead of querying and updating elements in the document with <code>$('#row'+rowNum+' .span4 div')</code> try to build a detached fragment, and insert it as one whole. The difference in speed is very noticeable on large data sets.</p>\n\n<p>Try to access elements through variables. You can create a row and then store it in a variable <code>$row</code>, and then access it as <code>$row.append(...)</code>. This is both easier to read and faster than <code>$('#row'+rowNum+' .span4').append(...)</code>.</p>\n\n<p><code>'&lt;h2&gt;'+userNickname+'&lt;/h2&gt;'</code> - there are several reasons why you shouldn't concatenate unescaped plain text with HTML, but the main reason is <a href=\"http://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow\">cross-site scripting</a>. Imagine if some user's nickname is <code>&lt;script&gt;location = 'http://pwned.com/'&lt;/script&gt;</code>. You probably don't want to allow someone to redirect your visitors to another site, or create fake login forms, or steal cookies. Here's how you can avoid that: <code>$('&lt;h2&gt;').text(userName)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-23T09:13:37.830", "Id": "63140", "Score": "0", "body": "Thank you for your advice! Your code is so much more compact and cleaner compared to mine. I especially love the line `if (i % 3 === 0)` that checks if we are coming to a new row. I've learned a lot through your code. Cheers. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T00:37:43.590", "Id": "37095", "ParentId": "36948", "Score": "2" } } ]
{ "AcceptedAnswerId": "37095", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T08:58:02.020", "Id": "36948", "Score": "5", "Tags": [ "javascript", "optimization", "node.js" ], "Title": "A more efficient approach to existing JavaScript coding" }
36948
<p>I've just created a small class to reverse date in PHP. I'd like to see whether or not it's good and can be improved.</p> <pre><code>&lt;?php /** * Reverse date and hour */ class ReverseDate { var $date; var $hour; var $error; /** * Checks if the date has hours */ function exec($data = null, $timestamp = false, $debug = false) { $this-&gt;date = $data; // Checks if the date is not null if (empty($this-&gt;date)) { // Debug - not activated buy default $this-&gt;error = 'Date is null.'; $this-&gt;debug($debug); return false; } // Verify the date to brazilian or international format $braRegExp = '/^([0-9]{2}[\-|\/|\.]{1}[0-9]{2}[\-|\/|.]{1}[0-9]{4})/'; $othRegExp = '/^([0-9]{4}[\-|\/|\.]{1}[0-9]{2}[\-|\/|.]{1}[0-9]{2})/'; if (!preg_match($braRegExp, $this-&gt;date)) { if (!preg_match($othRegExp, $this-&gt;date)) { // Debug - not activated buy default $this-&gt;error = 'Invalid date.'; $this-&gt;debug($debug); return false; } else { // Fix the day lenth for brazilian dates $d2len = 2; } } else { // Fix the year lenth for brazilian dates $d2len = 4; } // Get the date spliter (. or / or -) $s = preg_replace('/[a-zA-Z0-9]/', '', $this-&gt;date); $s = substr($s, 0, 1); // Explode the date into an array $d = explode($s, $this-&gt;date); // Checks if the date has hours if (strlen($d[2]) &gt; 4) { // Get the hour $this-&gt;hour = trim(substr($d[2], $d2len, strlen($d[2]))); // This is the year withou the hour $d[2] = explode(' ', $d[2]); $d[2] = $d[2][0]; } // Reverse the date $this-&gt;date = array_reverse($d); // Join the array $data = implode($s, $this-&gt;date); // Join date and hour $this-&gt;date = trim($data . ' ' . $this-&gt;hour); // Return if ($timestamp) { // Timestamp return strtotime($this-&gt;date); } else { // Or the date return $this-&gt;date; } } // Debug function debug($val = false) { // Checks if the val is true if ( $val ) { // Kills the script exit($this-&gt;error); } } } </code></pre> <p>And then use it:</p> <pre><code>$reverseDate = new ReverseDate(); $data = $reverseDate-&gt;exec('06/12/2013 17:30', false, true); echo $data . '&lt;br&gt;'; // 2013/12/06 17:30 $data = $reverseDate-&gt;exec('2013/12/01 08:25:10', false, true); echo $data . '&lt;br&gt;'; // 01/12/2013 08:25:10 $data = $reverseDate-&gt;exec('06/12/2013 17:30', true, true); echo $data . '&lt;br&gt;'; // 1386347400 $data = $reverseDate-&gt;exec('2013-12-01', false, true); echo $data . '&lt;br&gt;'; // 01-12-2013 17:30 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T11:31:59.063", "Id": "60804", "Score": "0", "body": "struggling to see the need for this at all since you can do exactly this with the built in php date functions which are much more powerful and allow you to change the format and layout of the date as you see fit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T11:51:37.203", "Id": "60805", "Score": "0", "body": "PHP doesn't understand our date format, for example, today: 09/12/2013. So, date('Y-m-d', strtotime('09/12/2013')); won't solve my problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T11:54:49.980", "Id": "60806", "Score": "0", "body": "What do you mean php doesn't understand your date format ? You just posted a UK date stamp dd/mm/yyyy which is perfectly understood by php I use it every day converting UK to mysql formats and mysql formats to uk. infact there's very very few date formats that php won't understand" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T11:58:23.193", "Id": "60807", "Score": "0", "body": "Take a look: echo date('Y-m-d', strtotime('20/12/2013')); // Output 1970-01-01" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T12:14:13.977", "Id": "60808", "Score": "0", "body": "Works just fine. raw code - http://phpfiddle.org/api/raw/ipv-mrt Execution results - http://phpfiddle.org/api/run/ipv-mrt Gist https://gist.github.com/hinch/7871334" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T12:33:08.677", "Id": "60810", "Score": "0", "body": "For this date, but when you use a date like 13/12/2013, it doesn't work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T12:36:06.453", "Id": "60812", "Score": "0", "body": "thats because php assumes american date format when using / I guess for strtotime convert to using the php date object and all is good http://www.php.net/manual/en/datetime.createfromformat.php I've updated the gist above to demonstrate" } ]
[ { "body": "<p>If you want to do it this way, then:</p>\n\n<ol>\n<li><p>Change your <code>var</code> to <code>public</code> (I hope it is not PHP4 code):</p>\n\n<pre><code>public $date;\n</code></pre></li>\n<li><p>In the <code>exec()</code> function, I would first check <code>$data</code>:</p>\n\n<pre><code>// Checks if the date is not null\nif (empty($data)) {\n // Debug - not activated buy default\n $this-&gt;error = 'Date is null.';\n $this-&gt;debug($debug);\n return false;\n}\n$this-&gt;date = $data;\n</code></pre></li>\n</ol>\n\n<p>I did not check your code after those lines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T10:44:20.890", "Id": "36952", "ParentId": "36951", "Score": "1" } }, { "body": "<p>I'll comment on the general appearance and structure of your code, show you some problems with it and then throw it out and present you with an easier implementation with the caveat that it behaves slightly differently.</p>\n\n<p>You'll notice that I use a modified K&amp;R style with the opening braces on the same line, this is only the style I choose because I do not know of an \"official\" style-documentation for PHP and I have adopted the Java style for my PHP projects.</p>\n\n<p>Also, your brace-style does change half-way through.</p>\n\n<hr>\n\n<p>Let's have a look at the first few lines to start with:</p>\n\n<pre><code>/**\n * Reverse date and hour \n */\nclass ReverseDate\n{\n // ...snip\n\n /**\n * Checks if the date has hours\n */\n function exec($data = null, $timestamp = false, $debug = false)\n {\n</code></pre>\n\n<p>The following problems here:</p>\n\n<ul>\n<li>The class has a function name</li>\n<li>The function is not static</li>\n<li>The function has a completely irrelevant name</li>\n<li>The parameters are not well named</li>\n<li>The documentation is plain out wrong.</li>\n</ul>\n\n<p>The first few questions that are raised are:</p>\n\n<ul>\n<li>Why is this called <code>exec()</code>? (Remember that <code>exec</code> is a pretty negative word in the PHP world, same as <code>eval</code> or <code>system</code>)</li>\n<li>It does check something?</li>\n<li>What is <code>$data</code>?</li>\n<li>What is <code>$timestamp</code>?</li>\n<li>What is <code>$debug</code>?</li>\n</ul>\n\n<p>If you're going to create helper classes it should be clear that this is a helper class.</p>\n\n<pre><code>/**\n * A small helper class for working with Dates.\n */\nclass DateHelper {\n</code></pre>\n\n<p>At the moment you also need to create an instance of your class just to use <em>one</em> function, it should be static (and have correct documentation).</p>\n\n<pre><code>/**\n * Reverses the date part of the given DateTime-String. The DateTime-String\n * needs to be in the format \"Y/m/d h:i:s\".\n * @var string $datetime\n * @return string\n */\nstatic function reverseDate($datetime) {\n</code></pre>\n\n<hr>\n\n<pre><code>$this-&gt;date = $data;\n</code></pre>\n\n<p>Is this a typo?</p>\n\n<p>You should also not make variables more accessible then necessary. <code>$this-&gt;date</code> is never used outside of the <code>exec()</code> function, so it's scope should be limited to that function.</p>\n\n<hr>\n\n<pre><code>$s = preg_replace('/[a-zA-Z0-9]/', '', $this-&gt;date);\n</code></pre>\n\n<p>Whenever you have the urge to use one-letter-variable names, take a deep breath and ask yourself:</p>\n\n<blockquote>\n <p>What does this variable hold?</p>\n</blockquote>\n\n<p>And then you name it according to what it holds.</p>\n\n<hr>\n\n<p>Your function does either return a string or an int based on a parameter passed in, that's bad. That is ambiguity you should avoid.</p>\n\n<blockquote>\n <p>This function does return a datetime-string with the date part reversed, except if a parameter is passed in, then it does return an int/timestamp.</p>\n</blockquote>\n\n<p>So code would look like this:</p>\n\n<pre><code>$reverseDate = new ReverseDate();\n$data = $reverseDate-&gt;exec('06/12/2013 17:30', $timestamp, false);\n</code></pre>\n\n<p>Quick: What value does <code>$data</code> hold?</p>\n\n<p>Someone unfamiliar with the internals of this function would say \"2013/12/06 17:30\" and that's a problem.</p>\n\n<hr>\n\n<pre><code>function debug($val = false)\n{\n // Checks if the val is true\n if ( $val ) {\n // Kills the script\n exit($this-&gt;error);\n</code></pre>\n\n<p>You should not hide calls to <code>exit</code> or <code>die</code> in a function which does not clearly state that this will happen.</p>\n\n<hr>\n\n<p>Personally I think this function does too much and tries too hard. Always keep in mind that you should write code for the problem you face right now.</p>\n\n<p>Here is a much simplified solution (with caveats, follows):</p>\n\n<pre><code>/**\n * A helper class for Date and Time.\n */\nclass DateHelper {\n /**\n * Reverses the date part of the given DateTime-String. The DateTime-String\n * needs to start with the date string, otherwise this will fail.\n * @var string $datetime\n * @return string\n */\n static function reverseDate($datetime) {\n // Will hold the result of the match.\n $result = NULL;\n\n // Match this against what we've got.\n //\n // ([0-9]+) The first part (year?)\n // ([^0-9]{1}) Separator\n // ([0-9]+) The second part (month?)\n // ([^0-9]{1}) Separator\n // ([0-9]+) The third part (day?)\n // (.*) Everything else.\n if (preg_match(\"/^([0-9]+)([^0-9]{1})([0-9]+)([^0-9]{1})([0-9]+)(.*)/\", $datetime, $result) === 0) {\n // Chicken out if there were 0 matches.\n // preg_match does handle NULL for us.\n return false;\n }\n\n // Now we put it together backwards.\n return $result[5] . $result[4] . $result[3] . $result[2] . $result[1] . $result[6];\n }\n}\n</code></pre>\n\n<p>This does not have neither your error handling nor your debug support and especially not the \"tag\" parameter. Ideally you would add this Helper class to your project, write a few unittests for it and be done with it.</p>\n\n<p>Is there a problem with your error handling? No, not at all, but it's absolutely unnecessary in this implementation. Compare these use cases:</p>\n\n<pre><code>$reverseDate = new ReverseDate();\n$data = $reverseDate-&gt;exec($input, false, true);\nif (!$data) {\n // Error handling goes here.\n $reverseDate-&gt;debug();\n}\n</code></pre>\n\n<p>With this:</p>\n\n<pre><code>if (!($date = DateHelper::reverseDate($input))) {\n // Error handling goes here.\n die(\"Parsing of \" . ($input === NULL ? \"NULL\" : \"'$input'\") . \" failed.\");\n}\n</code></pre>\n\n<p>There's no need for fine grained error messages, as looking at the passed in value should be enough to determine why the parsing failed.</p>\n\n<p>Is there a problem with your debug parameter? Yes! If you need a function to behave differently whenever you want to debug it or not, and especially need a parameter for this, then there's something wrong with your design of said function. Also your parameter does not change the behavior of the function <em>at all</em>, it changes the behavior <em>of a completely different function</em>, which is evil (speaking from a design point of view).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:14:52.493", "Id": "60818", "Score": "0", "body": "@Foreba: Just as a note: There's no need to post \"thank you\" or \"good answer\" comments at all here on Stack Exchange. You express both with upvotes and/or accepting the answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T13:00:21.140", "Id": "36957", "ParentId": "36951", "Score": "4" } } ]
{ "AcceptedAnswerId": "36957", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T10:27:53.037", "Id": "36951", "Score": "2", "Tags": [ "php", "datetime" ], "Title": "Reverse date in PHP" }
36951
<p>I'm trying to use the good parts of Javascript and dont follow the classical inheritance. I studied and created this example of compose in Javascript, <a href="https://gist.github.com/fernandoperigolo/7789866" rel="nofollow">https://gist.github.com/fernandoperigolo/7789866</a>.</p> <p>My question is. You think this example have a good implementations of composition? Can i go ahead with it? If not, What you suggest?</p> <pre><code>(function(){ // Adding compose to Function prototype Function.prototype.compose = function(argFn) { var fnToCall = this; return function() { // This line is really complex and i don't know exactly what this line do return fnToCall.call(this, argFn.apply(this,arguments)); } } // Eletronic atributes and methods var asEletronic = function(){ this.voltage = '220v'; this.power = false; this.switchPower = function(){ if (this.power === true) { this.power = false; console.info('Eletronic are off now.'); }else{ this.power = true; console.info('Eletronic are on now.'); }; } return this; }; // Sound Reproducer atributes and methods var asSoundReproducer = function(){ this.watts = 60; this.playSound = function(sound){ console.info('Playing the sound: '+sound); }; return this; }; // All sound reproducer is a eletronic // Composing first level asSoundReproducer = asSoundReproducer.compose(asEletronic) // Micro System atributes and methods // Not used, just example var asMicroSystem = function(){ this.cd = false; this.mp3 = true; return this; }; // TV atributes and methods var TV = function(){ this.pol = 42; this.hdmi = true; return this; }; // Compose a TV with full resources // Compose second level, asSoundReproducer is a composed object // This line looks me strange... TV = TV.compose(asSoundReproducer); // Create a new TV var myTV = new TV(); // Looking my TV console.log(myTV); // Call a Eletronic method myTV.switchPower(); // Call a Sound Reproducer method myTV.playSound('guitar.mp3'); })(); </code></pre>
[]
[ { "body": "<p>Interesting question,</p>\n\n<p>from your comments inside the code you seem to not have written the code or have heavily borrowed from somebody else's code..</p>\n\n<p>From a high level I have only a few misgivings:</p>\n\n<ul>\n<li>Do not modify standard JS objects, so do not add <code>compose</code> to the prototype of <code>Function</code>, I grant you that it looks cool but it will bite you at some point</li>\n<li><code>myTV instanceof asSoundReproducer</code> does not work, so figuring what kind of object you are dealing with can be painful ( this is a drawback from not using standard js OO )</li>\n<li>You have some provision for passing parameters to functions with <code>argFn.apply(this,arguments)</code> but the function signatures might look ugly since you do not cut out <code>argFn</code> from <code>arguments</code></li>\n<li>When reading up on composing, I prefer much to be able to compose in one go like <code>TV = compose( asSoundReproducer, asMicroSystem );</code></li>\n<li>I am not sure what <code>as</code> stands for in your function names, I would drop anything that resembles Hungarian notation.</li>\n</ul>\n\n<p>This counter proposal is more complicated, but handles multiple constructors in 1 go, amd provides support for parameters and <code>typeof</code>.</p>\n\n<pre><code>function merge(object, boltOn) {\n //Simply merge the properties of boltOn into object, overriding existing properties\n for(var property in boltOn)\n if(boltOn.hasOwnProperty(property))\n object[property] = boltOn[property];\n return object;\n}\n\nfunction compose(/*Constructor1, Constructor2, ..*/) {\n //Keep a closure reference for later\n var constructorReferences = arguments;\n\n return function ComposedConstructor(/*parameter1, parameter2, ..*/) {\n\n //Clone the constructors, we will modify the clones\n var constructorClones = Array.prototype.slice.call(constructorReferences).map(function(Constructor) {\n return new Object(Constructor);\n });\n\n var constructor = constructorClones.pop();\n //Set up the prototype chain, without loosing the original prototypes thru `merge`\n while(constructorClones.length) {\n\n var nextConstructor = constructorClones.pop();\n nextConstructor.prototype = merge(new constructor(arguments), nextConstructor.prototype);\n constructor = nextConstructor;\n\n }\n //Call the first constructor with the arguments provided to the constructor\n constructor = constructor.bind.apply(constructor, [null].concat(Array.prototype.slice.call(arguments)));\n return new constructor();\n };\n}\n\n\nfunction A(name) {\n this.a = name;\n console.log(arguments);\n}\nA.prototype.sayA = function() {};\n\nfunction B() {\n this.b = 2;\n console.log(arguments);\n}\nB.prototype.sayB = function() {};\n\nfunction C() {\n this.c = 3;\n console.log(arguments);\n}\nC.prototype.sayC = function() {};\n\nvar O = compose(A, B, C);\nvar o = new O('Samsung');\n\n// {[object Object] { a: \"Samsung\",b: 2,c: 3,sayA: function,sayB: function,sayC: function}\nconsole.log(o); \nconsole.log(o instanceof A); //true\nconsole.log(o instanceof B); //true\nconsole.log(o instanceof C); //true\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-19T18:43:03.990", "Id": "60499", "ParentId": "36965", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:33:36.023", "Id": "36965", "Score": "3", "Tags": [ "javascript", "design-patterns" ], "Title": "Compose in Javascript - Go ahead with this example?" }
36965
<p>I'm writing a SDK for a NFC device in .NET so I don't have to import the SDK from C++. Right now I'm working on the ISO14443-3 part which is just simple Halt, Request, and Anticollision commands. The communication part between the device and computer is simple enough so I'm not going to post any of that. Just know that it is a serial device and that the command I send to it gets built before I write it to the SerialPort.</p> <p>We have 2 different NFC devices with completly different SDK's. I plan on making them identical, but when I first started I was main concerned with only one of them and I was basing all my methods off of the SDK that came with the device. Note that this is not a debate about if I should use the SDK or not. When I first started I figured that I would only have 1 method with a simple structure. It looked like this. <code>private void BuildAndSendCommand(MasterRDCommands command, params byte[] data)</code></p> <p>MasterRDCommands is a simple enum. I decided that was a bad idea when I started work on the sound and light commands.. it was super hard to read something like</p> <p><code>nfc.BuildAndSendCommand(MasterRDCommands.SetLED, RFIDLED.Blue, 0x01, 0x10);</code></p> <p>it's like..HUH???</p> <p>so I made the BuildAndSendCommands private and made methods to make the code more clear.. Now I have the method signature like this..</p> <p><code>public void SetLED(RFIDLED led, byte flashes, byte duration)</code></p> <p>that sure make it much nicer at the top most level, but the middle man I'm concerned if I should still use a enum. I feel that it would much more clean if I would just put a region at the bottom or top of my code with a few private constants so that things like the RATS command would switch from</p> <pre><code> public byte[] SendRATS_TypeA() { BuildAndSendCommand(MasterRDCommands.RATS); byte[] RATS = GetResponse(10); return RATS; } </code></pre> <p>to say something like this</p> <pre><code> private const byte RATScmd = 0x1F; public byte[] SendRATS_TypeA() { BuildAndSendCommand(RATScmd); byte[] RATS = GetResponse(10); return RATS; } </code></pre> <p>it's not much different, but I don't plan on exposing any of the commands from my Enum to the user since most if not all of the commands require a certain order. Where as the LED example is a good example (to me atleast) of when to use a enum. The user has to choose a very narrow set of LED's.</p> <p>in the end the user still only sees the few methods that I mark as public and would still never know if I ever deleted the Commands enum or not. What do you think? Keep them or remove them? </p>
[]
[ { "body": "<p>I've never been a fan of a global constants file. It's a good idea to keep enums defined close to where they are needed. Makes it a little more apparent how enum is used. This helps keep the code clean as you mentioned, and also helps improve maintainability, since there's not a long, master list of enums that need to be mentally processed in order to confidently make a change.</p>\n\n<p>On a side note, I would go ahead and put them in separate files. This will also help with maintainability later, in case a move becomes necessary.</p>\n\n<p>If you can eliminate the enum and just use a private variable, then you've made it even better. Code is more readable, and it doesn't imply that the particular value is shared across larger portions of code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:58:16.027", "Id": "60846", "Score": "0", "body": "I like your comment about how it doesn't imply that this particular value is shared across larger portions of code. It's true it is not. Infact it is specific to only this device. Private constant it is, just not in a separate file. I also don't like global constants... As I just got done creating a DeviceConstants file..hahahaha." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:36:47.673", "Id": "60890", "Score": "2", "body": "Why have a private variable when you can have a private enum?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:05:03.883", "Id": "60895", "Score": "0", "body": "@Matt I guess because I'm just so used to having a seperate file for all of my enums and structures that I didn't even think of having a private enum" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:08:24.590", "Id": "60897", "Score": "0", "body": "Variable was probably the wrong choice of word, but it sounded like he's dealing with only one single value instead of choosing from a list of values. In that case a private (const) is probably better choice than an enum." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T20:01:20.610", "Id": "61068", "Score": "0", "body": "A constant is a value, but an enum is a type, effectively. It gives a built-in definition to a group of values and so [embiggens](http://en.wiktionary.org/wiki/embiggen) the domain model." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:44:14.307", "Id": "36969", "ParentId": "36966", "Score": "3" } }, { "body": "<p>I think you should keep the enums, they should be used when we need to choose from a set of values, as </p>\n\n<ul>\n<li>They are self documenting</li>\n<li>IDE will autmotically pop up the available options</li>\n<li>Have better maintainability</li>\n</ul>\n\n<p>We should use consts when we have a single value and it can't be changed. These are read only variables.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:10:13.543", "Id": "60852", "Score": "0", "body": "I agree with self-documenting and the better maintainability. I am keeping the LED enum, however I think I am going to make the device specific commands private and constant since they will only ever change for firmware updates (which is going to be rare)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:05:03.340", "Id": "36973", "ParentId": "36966", "Score": "3" } }, { "body": "<p>I think that using an enum is better. The main reason is that it it more type-safe.</p>\n\n<p>When a parameter is <code>byte</code>, you can pass any numeric value in the <code>byte</code> range to it or a constant that logically belongs to another <code>enum</code>.</p>\n\n<p>With <code>enums</code>, such accidents are not possible*, though you still can pass any value to it if you need to by using casting. (This can be useful in some relatively rare cases; most of the time, it's just annoying.)</p>\n\n<p>* There is one exception, <code>0</code> is valid value for any <code>enum</code>. This means you can write <code>BuildAndSendCommand(0)</code>, no matter whether the parameter is a <code>byte</code> or an <code>enum</code>. It's good to keep this in mind when debugging weird <code>enum</code>-related errors.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:10:59.627", "Id": "36979", "ParentId": "36966", "Score": "2" } }, { "body": "<h2>Clean interface</h2>\n\n<pre><code>nfc.BuildAndSendCommand(MasterRDCommands.SetLED, RFIDLED.Blue, 0x01, 0x10);\n</code></pre>\n\n<blockquote>\n <p>it's like..HUH???</p>\n</blockquote>\n\n<p>Some issues with the interface: </p>\n\n<ul>\n<li><p>Many parameters: usually means parameters wants to be extracted into a domain class.</p></li>\n<li><p><code>BuildAndSend...</code> : Method name of form <code>Verb1AndVerb2</code> usually indicates either violation of single responsibility principle, or leaking of implementation details to interface.</p></li>\n<li><p><code>...SendCommand</code> : <code>VerbNoun(x, y, z)</code> form indicates unnecessary verbosity if x is of type Noun and y,z are options. Or x, y, z are components of a domain object Noun and interface should be changed to <code>Verb(new Noun(x, y, z))</code>. (See <em>Many Parameters</em> above) In your case it looks like the second. <code>(MasterRDCommands.SetLED, RFIDLED.Blue, 0x01, 0x10)</code> is your command and <code>MasterRDCommands.SetLED</code> is your Opcode. I'm thinking chip instructions here.</p></li>\n<li><p><code>... , 0x01, 0x10)</code> : This is called <a href=\"http://c2.com/cgi/wiki?PrimitiveObsession\" rel=\"nofollow\">primitive obsession</a>. You can overcome this by encapsulating values in domain value objects, or <code>Enum</code>s where suitable. eg compare with <code>SetLED(LEDColor.Blue, new Flashes(true), new Duration(0x10));</code> It also ensures swapping parameters by mistake is compilation error.</p></li>\n</ul>\n\n<p>Usually, when no of handler methods is manageable and new commands being added to interface does not present much challenge you would collect above handling to an interface s.a. this:</p>\n\n<pre><code>interface ICommandHandler {\n void SetLED(LedColor ledColor, Flashes flashes, Duration duration);\n void SetLED(Flashes flashes, Duration duration);\n\n void RATS();\n\n // etc ........\n}\n</code></pre>\n\n<p>However if number of different commands is large you might want to use Command pattern to keep the interface simple.</p>\n\n<pre><code>// high level interface\ninterface ICommand\n{\n}\n\nclass RATS : ICommand\n{\n}\n\nclass SetLED : ICommand\n{\n public bool Flashes {get; set;} \n public byte Duration {get; set;}\n}\n\ninterface ICommandHandler {\n void Handle&lt;T&gt; (T command) where T : ICommand;\n}\n</code></pre>\n\n<p>This interface can be used like this:</p>\n\n<pre><code> // example\n ICommandHandler sender = new CommandSender(serializer, byteLevelIO);\n\n sender.Handle(new RATS());\n sender.Handle(new SetLED(){Flashes = true, Duration = (byte)10});\n</code></pre>\n\n<p>Ideally commands would be immutable and their fields would be domain value types, but I intentionally left above not as such to demonstrate another readability option. </p>\n\n<pre><code>new SetLED(){Flashes = true, Duration = (byte)10}\n</code></pre>\n\n<p>vs </p>\n\n<pre><code>new SetLED(new Flashes(true), new Duration(10))\n</code></pre>\n\n<p>This option saves some typing in exchange for losing some type safety.</p>\n\n<p>Opcodes are a concern of lower level and can be defined elsewhere like this:</p>\n\n<pre><code>enum Opcodes : byte\n{\n // opcodes from datasheet\n RATS = 0x1F,\n SetLED = 0x20,\n // .......\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T19:16:56.730", "Id": "61053", "Score": "0", "body": "This looks very nice. I like your approach. Only difference is with the definition of flashes. It's a value of 0-255 and will flash that many times for x duration. I do like your approach of the duration though. I see WPF in your blood :) I think when it is said and done I will make a Duration type class but i'm unsure of how I want to implement it. The duration needs to be converted to a byte, and the largest timespan is 12.75 seconds (approx)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T16:29:00.380", "Id": "37053", "ParentId": "36966", "Score": "2" } } ]
{ "AcceptedAnswerId": "36969", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T15:35:42.467", "Id": "36966", "Score": "2", "Tags": [ "c#", "enum", "constants" ], "Title": "Enum or Constant" }
36966
<p>Sometimes, when you're doing something like displaying a bunch of elements, you can avoid running a function entirely if an object is <code>hidden</code>.</p> <p>So you can either write the check from the loop:</p> <pre><code>for( Displayable * d : displayables ) if( d-&gt;isShowing() ) d-&gt;draw() ; </code></pre> <p>Or you can put an "early return" in <code>d-&gt;draw()</code> if <code>d</code> is hidden:</p> <pre><code>void Displayable::draw() { if( !isShowing() ) return ; // continue with draw.. } </code></pre> <p>With this 2nd way, you don't have to check any condition when looping, so the loop "looks cleaner"</p> <pre><code>for( Displayable * d : displayables ) d-&gt;draw() ; </code></pre> <p>But with the 1st way, you don't have to check <code>isShowing()</code> at the beginning of the function, so then that looks cleaner,</p> <pre><code>void Displayable::draw() { // simply draw } </code></pre> <p>Which is better? Is the latter an antipattern of sorts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:11:34.193", "Id": "60882", "Score": "0", "body": "what language is this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:11:57.957", "Id": "60883", "Score": "2", "body": "The question itself is language agnostic - you can do this type of thing in any language; but the code in the post is C++" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:13:11.763", "Id": "60884", "Score": "0", "body": "if you don't specify a language it's harder to get people to look at the question, and it might be closed as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:13:48.623", "Id": "60885", "Score": "2", "body": "I also added a `language-agnostic` tag" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:23:53.930", "Id": "60887", "Score": "0", "body": "The question is not quite language agnostic if you include performance considerations, since some languages are better than others at inlining function calls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:35:37.113", "Id": "60888", "Score": "1", "body": "http://codereview.stackexchange.com/questions/11544/is-it-better-practice-to-return-if-false-or-execute-an-if-statement-if-true" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:36:37.160", "Id": "60889", "Score": "0", "body": "The answer could vary according to context. How many kinds of `Displayable`s are there, and are you implementing them all yourself? Would you ever be interested in optimizations such as [occlusion culling](http://en.wikipedia.org/wiki/Hidden_surface_determination) where you might skip rendering depending on what other objects exist?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T23:44:19.837", "Id": "60936", "Score": "0", "body": "@bagonyi, Holy Carp! I didn't think it was possible but these are almost identical except this is C++ and that is Java" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T00:07:14.820", "Id": "60938", "Score": "2", "body": "It's not the same question as that one. Here I'm asking whether the `return` early statement is better to _even be in_ the method call in question. The other option is to check the condition _before even invoking the function_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T00:08:12.230", "Id": "60939", "Score": "0", "body": "@Malachi The basic flow control structures in C++ and Java are nearly the same, only Java doesn't have `goto`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T00:12:05.080", "Id": "60941", "Score": "1", "body": "@bobobobo We've eliminated the [tag:language-agnostic] tag. This being Code Review, our mission is to review code, not dispense general advice. Therefore, questions should be specific, and answers should take the context into account. Even if the code in the question is polyglot, the advice that reviewers give could vary depending on the language in ways that you might not anticipate." } ]
[ { "body": "<p>You should focus on whatever methods avoid code duplication. </p>\n\n<pre><code>// Some code\nfor( Displayable * d : displayables )\n if( d-&gt;isShowing() )\n d-&gt;draw() ;\n\n// Some code elsewhere\nfor( Displayable * d : displayables )\n // Oops, we forgot to check if it's showing.\n d-&gt;draw() ;\n</code></pre>\n\n<p>There are two ways I can think of off the top of my head to avoid this situation. </p>\n\n<ol>\n<li>Use your second approach and perform the check in the <code>draw()</code> method.</li>\n<li>Create a <code>drawAllShowing()</code> function/method.</li>\n</ol>\n\n<p>Creating a <code>drawAllShowing()</code> function would allow you to keep the <code>draw()</code> method simple just in case there are circumstances where you do not want to perform the <code>if(d-&gt;isShowing())</code> check when calling <code>draw()</code>. If you always want to perform that check, then just put it in the <code>draw()</code> method. </p>\n\n<p>Just remember, some famous guy once said that a function should do one thing, and it should do that one thing well. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:55:09.810", "Id": "60902", "Score": "1", "body": "http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html Curly's Law: Do One Thing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:33:17.537", "Id": "36981", "ParentId": "36978", "Score": "7" } }, { "body": "<p>There's a semantic difference between the two of these. In the first, the <em>draw</em> method always draws the object whether the object is visible or not. I.e. it is the <em>caller's</em> responsibility to check the visibility of the object. In the second, the object checks it's <em>own</em> visibility and recognises that it does not need to do anything if the object is hidden.</p>\n\n<p>The difference in the loop, then, is the difference between saying \"Draw all of the non-hidden elements\", and \"Draw all of the elements, (where draw means draw the element if it is visible)\"</p>\n\n<p>One focuses on the fact that we're drawing visible elements, the other adds the concept of <em>visbility</em> to the method <em>draw</em>.</p>\n\n<p>In my opinion, the second of these better fits the semantic of what <em>draw</em> is supposed to do, and for that reason it is clearly better to perform the visibility check inside <em>draw</em> rather than inside the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T11:35:40.560", "Id": "60964", "Score": "4", "body": "And I would say the exact opposite thing. I would say `draw()` shouldn't look at `isVisible()`. If it did it should be called `drawIfVisible()`. Why? Because let's imagine I want a \"debug view\" where \"hidden\" things are at 50% opacity. I might want to draw everything visible, and then hidden things on different layer with 50% opacity. With your approach that is not possible as `draw()` will do nothing.\nOf course that depends on the rest of code/design, but I would opt for functions doing minimal amount of stuff and only stuff implied by name." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:35:35.623", "Id": "36982", "ParentId": "36978", "Score": "10" } }, { "body": "<p>I personally think that a third option would be best: <code>render()</code>.</p>\n\n<pre><code>void Displayable::render()\n{\n //this could include other checks\n if( !isShowing() ) return ;\n // call draw\n this-&gt;draw();\n}\n</code></pre>\n\n<p>This make the sole responsibility of <code>draw</code> actually drawing the object, and <code>render</code>'s job is then determining what gets drawn when.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T02:04:17.747", "Id": "60945", "Score": "0", "body": "agreed, but I prefer to avoid negative logic when possible, so I'd do \n`if(isShowing()) { \n this -> draw(); \n}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T10:47:21.163", "Id": "60959", "Score": "0", "body": "The only issue I have with this is that \"render\" and \"draw\" are basically synonyms, the functions could have been named the other way around as well. So people may call the wrong one. But naming this one \"draw_if_showing\" is ugly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T19:25:06.973", "Id": "61056", "Score": "0", "body": "@RemcoGerlich You could make `draw` protected, then possibly make a wrapper function called `forceDraw`. I agree that the names could cause some confusion, but I think there are ways around that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T23:36:27.633", "Id": "37003", "ParentId": "36978", "Score": "3" } }, { "body": "<p>I think I'd leave the responsibility with the loop, but instead of a loop with the logic in its body, I'd write an algorithm that made the intent a little more explicit:</p>\n\n<pre><code>template &lt;class InIter, class Cond, class Action&gt;\nvoid for_each_if(InIter b, InIter e, Action action, Cond cond) {\n while (b != e) {\n if (cond(*b))\n action(*b);\n ++b;\n }\n}\n</code></pre>\n\n<p>For a testing, I did a mock implementation of <code>Displayable</code>:</p>\n\n<pre><code>struct Displayable {\n bool showing;\n std::string label;\n\n Displayable(bool showing, std::string label) : showing(showing), label(label) {}\n bool isShowing() const { return showing; }\n void draw() const { std::cout &lt;&lt; label; }\n};\n</code></pre>\n\n<p>To exercise it, I wrote a simple main like:</p>\n\n<pre><code>int main(void){\n std::vector&lt;Displayable&gt; d{ { true, \"Showing\" }, { false, \"not showing\" } };\n\n for_each_if(d.begin(), d.end(), \n [](Displayable const &amp;d) { d.draw(); }, \n [](Displayable const &amp;d){return d.isShowing(); });\n}\n</code></pre>\n\n<p>Although it's even more severe overkill, and doesn't fit the scenario <em>quite</em> as portrayed above, there's another possibility that <em>might</em> be worth considering under the right circumstances. First, I'll assume that in reality, you specify some <code>surface</code> when you do drawing. This would be a class that represents a device context on Windows, a graphics context on iOS, etc.</p>\n\n<p>For the moment, I'll define a really trivial \"surface\" that just acts as a wrapper for an ostream:</p>\n\n<pre><code>struct surface {\n std::ostream &amp;os;\npublic:\n surface(std::ostream &amp;os) : os(os) {}\n\n void draw(std::string const &amp;s) { os &lt;&lt; s; }\n};\n</code></pre>\n\n<p>Using that, we can define an ostream-like interface to a surface:</p>\n\n<pre><code>struct Displayable {\n bool showing;\n std::string label;\n\n Displayable(bool showing, std::string label) : showing(showing), label(label) {}\n bool isShowing() const { return showing; }\n\n friend surface &amp;operator&lt;&lt;(surface &amp;s, Displayable const &amp;d) {\n s.draw(d.label);\n return s;\n }\n};\n</code></pre>\n\n<p>Then we get to a somewhat ugly part: defining an iterator to write <code>Displayable</code>s to a <code>surface</code>. This is quite a bit longer than we'd like, but most of it is pure boiler-plate. The only part that really matters at all is the assignment operator, which writes a <code>Displayable</code> to a <code>surface</code>:</p>\n\n<pre><code>template &lt;class T, class charT = char, class traits = std::char_traits&lt;charT&gt;&gt;\nstruct draw_iterator : public std::iterator&lt;std::output_iterator_tag, void, void, void, void&gt; {\n surface *os;\npublic:\n draw_iterator(surface&amp; s) \n : os(&amp;s)\n {}\n draw_iterator&lt;T, charT, traits&gt;&amp; operator=(T const &amp;item)\n {\n *os &lt;&lt; item;\n return *this;\n }\n\n draw_iterator&lt;T, charT, traits&gt; &amp;operator*() {\n return *this;\n }\n draw_iterator&lt;T, charT, traits&gt; &amp;operator++() {\n return *this;\n }\n draw_iterator&lt;T, charT, traits&gt; &amp;operator++(int) {\n return *this;\n }\n};\n</code></pre>\n\n<p>With those in place, we can then use a standard algorithm to write the chosen <code>Displayable</code> objects to the <code>surface</code>:</p>\n\n<pre><code>int main(void){\n std::vector&lt;Displayable&gt; d{ { true, \"Showing\" }, { false, \"not showing\" } };\n\n surface s(std::cout);\n\n std::copy_if(d.begin(), d.end(),\n draw_iterator&lt;Displayable&gt;(s),\n [](Displayable const &amp;d){return d.isShowing(); });\n}\n</code></pre>\n\n<p>Of course, the \"surface\" I've defined is extremely limited (only knows how to display strings right now), but it's intended purely as a mock-up. As I already said, in a real implementation you probably already have something that corresponds to it, so you wouldn't typically be implementing that part at all, just setting up the stream-like interface, and the iterator for it.</p>\n\n<p>The iterator, in particular is more extra work than you'd typically like. The good point, however, is that when you're done it acts like any other iterator--it'll support all the standard algorithms, not just this particular one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T16:56:30.137", "Id": "61021", "Score": "0", "body": "This is a really cool idea, but it's probably overkill for this. +1 from me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T10:58:17.760", "Id": "61349", "Score": "0", "body": "This is an interesting answer. You genericized drawing with `for_each_if` and passed the condition to draw as a functor arg. I've done something similar elsewhere in my code, but it was only where I _really_ needed a functor to figure out (if x should y)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T09:38:32.193", "Id": "37022", "ParentId": "36978", "Score": "6" } }, { "body": "<p>I'd keep it so Draw draws no matter what. That is, Draw doesn't decide if it draws, whomever called it decided to draw the object when they called draw. This gives you more flexibility because it decouples the functionality from the decision to leverage it.</p>\n\n<p>One simple advantage of doing it this way is that now you can have a debug view that draws everything no matter what.</p>\n\n<p>There is however another big reason to do it this way that really depends on the nature of the application you're developing. Lets say there are vastly more objects in existence than you will ever want to attempt to draw (or even loop over if you can help it), and you want to package up just the things you actually want to draw into a list and process that on another threading using the GPU while you do something else with the CPU. This would certainly be the case if you were developing an MMO for instance. In this scenario you're going to want the functionality to draw decoupled from decision to draw.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-28T02:38:22.523", "Id": "38207", "ParentId": "36978", "Score": "1" } } ]
{ "AcceptedAnswerId": "36982", "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T18:09:54.260", "Id": "36978", "Score": "8", "Tags": [ "c++", "object-oriented" ], "Title": "Is `if( hidden ) return;` an antipattern?" }
36978
<p>I get the following correct results from this code, but it seems incredibly clunky to me. Is there anything I could be doing more elegantly? The results can be imprecise - as long as it's the right number of returned elements, and the selection is mostly right.</p> <pre><code>$_5elements = array(1,2,3,4,5); $_10elements = array(1,2,3,4,5,6,7,8,9,10); $_14elements = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14); $_40elements = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40); $_140elements = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140); function spread_array($array = null, $target_array_length = 10) { if ($array) { $array_length = count($array); if ($array_length &gt; $target_array_length) { $return = array(); $division = round( $array_length / $target_array_length ); krsort($array); foreach ($array as $key =&gt; $value) { if (($key === count($array) - 1 || $key % $division === 0) &amp;&amp; count($return) &lt; $target_array_length) { $return[] = $value; } } $return = array_reverse($return); } else { $return = $array; } return $return; } return false; } echo "&lt;pre&gt;".print_r(spread_array($_5elements), true)."&lt;/pre&gt;"; echo "&lt;pre&gt;".print_r(spread_array($_10elements), true)."&lt;/pre&gt;"; echo "&lt;pre&gt;".print_r(spread_array($_14elements), true)."&lt;/pre&gt;"; echo "&lt;pre&gt;".print_r(spread_array($_40elements, 20), true)."&lt;/pre&gt;"; echo "&lt;pre&gt;".print_r(spread_array($_140elements), true)."&lt;/pre&gt;"; /* Results Array ( [0] =&gt; 1 [1] =&gt; 2 [2] =&gt; 3 [3] =&gt; 4 [4] =&gt; 5 ) Array ( [0] =&gt; 1 [1] =&gt; 2 [2] =&gt; 3 [3] =&gt; 4 [4] =&gt; 5 [5] =&gt; 6 [6] =&gt; 7 [7] =&gt; 8 [8] =&gt; 9 [9] =&gt; 10 ) Array ( [0] =&gt; 5 [1] =&gt; 6 [2] =&gt; 7 [3] =&gt; 8 [4] =&gt; 9 [5] =&gt; 10 [6] =&gt; 11 [7] =&gt; 12 [8] =&gt; 13 [9] =&gt; 14 ) Array ( [0] =&gt; 3 [1] =&gt; 5 [2] =&gt; 7 [3] =&gt; 9 [4] =&gt; 11 [5] =&gt; 13 [6] =&gt; 15 [7] =&gt; 17 [8] =&gt; 19 [9] =&gt; 21 [10] =&gt; 23 [11] =&gt; 25 [12] =&gt; 27 [13] =&gt; 29 [14] =&gt; 31 [15] =&gt; 33 [16] =&gt; 35 [17] =&gt; 37 [18] =&gt; 39 [19] =&gt; 40 ) Array ( [0] =&gt; 15 [1] =&gt; 29 [2] =&gt; 43 [3] =&gt; 57 [4] =&gt; 71 [5] =&gt; 85 [6] =&gt; 99 [7] =&gt; 113 [8] =&gt; 127 [9] =&gt; 140 ) </code></pre>
[]
[ { "body": "<h1><em>Ding!!</em></h1>\n<p><strong>I've got it!</strong></p>\n<p>So, I have been looking at this code for quite a while now, because <em>I knew</em> there had to be some ingenious way to do this. It seemed all to simple to need something of the opposite scale! And, after playing around, sure enough, I think I got it to it's best.</p>\n<p>However! I'd hate to just give away the answer without a bit of some code critiquing beforehand. <em>Shall we begin?...</em></p>\n<hr />\n<p>I sure hope you didn't spend to long typing out those arrays. That'd would have been a bummer! Let's take advantage of a little resource, I like to call it the <em><a href=\"http://www.php.net/manual/en/function.range.php\" rel=\"noreferrer\">fill-numeric-array-o-matic</a></em>. Switch that baby on, and bam, you get this beautiful babe:</p>\n<pre><code>$_5elements = range(1, 5);\n$_10elements = range(1, 10);\n$_14elements = range(1, 14);\n$_40elements = range(1, 40);\n$_140elements = range(1, 140);\n</code></pre>\n<p>Ain't she a beaut'?</p>\n<p><strong>Alright, next step!</strong> I see you countin' up the input array a couple times, good thing we know <a href=\"http://www.bountytowels.com/\" rel=\"noreferrer\">how to handle this</a>! That's right, it needs to <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY</a> out.</p>\n<pre><code>$array_length = count($array);\n</code></pre>\n<p>Feel free to replace all those nasty repetitions now!</p>\n<p><strong>After</strong> we've dried up that spill, let's knock off <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"noreferrer\">this arrow nonsense</a> and whip up some clean lookin' code!</p>\n<p>Watch ladies and gentlemen as we turn this snippet:</p>\n<blockquote>\n<pre><code>if ($array) {\n $array_length = count($array);\n if ($array_length &gt; $target_array_length) {\n ...\n foreach (...) {\n if (...) {\n $return[] = $value;\n }\n }\n $return = array_reverse($return);\n } else {\n $return = $array;\n }\n return $return;\n}\nreturn false;\n</code></pre>\n</blockquote>\n<p>into this gorgeous <strike>girl</strike> piece of code!</p>\n<pre><code>$array_length = count($array);\n\nif ($array_length == 0) {\n return false;\n}\n\nif ($array_length &lt;= $target_array_length) {\n return $array;\n}\n\n*insert top secret algorithm here*\n\nreturn array_reverse($output);\n</code></pre>\n<p>I hope we all got to see this amazing transformation, the original having layers and layers, <code>if</code>s and <code>else</code>s all over! To now, a clean and concise workflow...</p>\n<p><strong>Up next!</strong> The end is near, I promise! Before though, let's have a look at these formats and styles. Your code's fashion is really last year... <em>Everyone's</em> <strike>shopping at</strike> using 2014 standards.</p>\n<p>Seriously though, applying and sticking to a style will benefit everyone. I highly recommend something such as <a href=\"http://www.php-fig.org/\" rel=\"noreferrer\">PHP-FIG</a> or the <a href=\"http://framework.zend.com/manual/1.10/en/coding-standard.coding-style.html\" rel=\"noreferrer\">Zend Standards</a>.</p>\n<p>It's mostly just your naming conventions in this code that are goofy, and I have made some changes in my code below.</p>\n<p><strong>Last but not least, the algorithm!</strong> No offense, but your loop plus the conditions made everything so hard to follow. Debugging it to figure out what it did what gave me a headache. <sub>Good thing I have aspirin.</sub></p>\n<p>I found your choice of <a href=\"http://www.php.net/manual/en/array.sorting.php\" rel=\"noreferrer\"><code>krsort()</code></a> unnecessary. Well, I've been able to completely remove this!</p>\n<p>Now, here's a list of requirements that must be achieved when we do the work:</p>\n<ol>\n<li>The amount of numbers returned MUST be equal to the number specified.</li>\n<li>The interval between numbers MUST be as even as possible throughout the list.</li>\n<li>The highest integer has priority in the output over the lowest numbers. (Assumed this one based on your output)</li>\n</ol>\n<p>I'm going to use a funky lookin' <code>for</code> loop to go through the array. It's going to look confusing at parts, but I'll do my best to <strike>make it worse</strike> clear things up!</p>\n<pre><code>$output = [];\n$ratio = round($array_length / $target_array_length);\nfor ($index = $array_length - 1; count($output) &lt; $target_array_length; $index -= $ratio) {\n $output[] = $array[$index];\n}\n\nreturn array_reverse($output);\n</code></pre>\n<p>How ya like them apples! Alrighty, let's see what I've done here:</p>\n<ol>\n<li>Make a new <code>$output</code> array to hold our output.</li>\n<li>Find the <code>$ratio</code> at which we should go through the array at. This will cross off the evenly spaced requirement!</li>\n<li>We're going to set <code>$index</code> to one less than the original array's length. We do this so we can reference the highest index and not have an out of bounds error.</li>\n<li>Throughout the loop, check to make sure we have less in our output array than we want. If we have the right amount, break the loop. Cross off Req. #1!</li>\n<li>For each iteration, reduced our index by that ratio we came up with earlier.</li>\n</ol>\n<p>Inside the loop, add to our output the value from <code>$array</code> with the index that has been decreasing in the loop.</p>\n<p>Reverse it to get the desired direction, and there ya have it!</p>\n<p>Here's the full code that I came up with. Naming and all! <em>I call this one: Make-sorted-and-spread-out-array-inator.</em></p>\n<pre><code>$arrayLength5 = range(1, 5);\n$arrayLength10 = range(1, 10);\n$arrayLength14 = range(1, 14);\n$arrayLength40 = range(1, 40);\n$arrayLength140 = range(1, 140);\n\nfunction spreadOutArray(array $array, $targetOutputLength = 10) {\n\n $originalArrayLength = count($array);\n\n if ($originalArrayLength == 0) {\n return false;\n }\n\n if ($originalArrayLength &lt;= $targetOutputLength) {\n return $array;\n }\n\n $output = [];\n $interval = round($originalArrayLength / $targetOutputLength);\n for ($index = $originalArrayLength - 1; count($output) &lt; $targetOutputLength; $index -= $interval) {\n $output[] = $array[$index];\n }\n\n return array_reverse($output);\n}\n</code></pre>\n<p>I hope the galaxy is better now that this question has one hell of an answer. Live long and prosper. Writing these types of answers will help in your quest to living long and prospering much.</p>\n<p><em>I'd be happy to clarify anything.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-11T21:34:13.343", "Id": "101192", "Score": "0", "body": "This is a beautiful thing. Thank you Alex. While I certainly have a long way to go to properly structure my functions, there wasn't any part of that code (and excellent explanation) that I didn't understand. That sounds like good coding to me!\n\nDo you have any good resources on producing this kind of logical, simple and readable code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-11T23:13:24.497", "Id": "101196", "Score": "0", "body": "I thought that adding a twist of humor and not just writing out fancy acronyms would make it easier to understand :) I'm afraid I can't point you in one single direction. However, I think being an active participant here on Code Review is one of the best things you can do. The top users are a surplus of great info! If you wanna become more active, I suggest you come join us in [the 2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T09:37:09.223", "Id": "500036", "Score": "0", "body": "you sound pretty confident that this works but I see no evidence of that. A working example would be handy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:39:15.903", "Id": "500089", "Score": "0", "body": "@ashleedawg 6.5 years ago I'll admit I was an idiot, and probably shouldn't have been answering with such gusto. If the answer doesn't work, please feel free to edit. I no longer am in the php world and don't have the time to fix right now. I'd delete this but 9 people found it helpful so there must be some value?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-07-10T05:42:42.017", "Id": "56627", "ParentId": "36983", "Score": "9" } }, { "body": "<p><strong>Watch out: The algorithm!</strong></p>\n\n<p>You round too early. The steps <code>$interval</code> should be exact, because if the rounding is upward, the steps will bring you too fast to the start of the array and lead to negative indexes.</p>\n\n<p>So only use <code>round()</code> when you use the resulting index:</p>\n\n<pre><code>$output = [];\n$ratio = $array_length / $target_array_length;\nfor ($index = $array_length - 1; count($output) &lt; $target_array_length; $index -= $ratio) {\n$output[] = $array[round($index)];\n}\nreturn array_reverse($output);\n</code></pre>\n\n<p>Another good idea is to replace <code>round()</code> with <code>floor()</code>.</p>\n\n<p>But if you don't want to write complicated algorithm, just use <a href=\"http://php.net/manual/en/function.range.php\" rel=\"nofollow\"><code>range()</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-12T22:52:31.393", "Id": "144062", "ParentId": "36983", "Score": "4" } }, { "body": "<p>The selected answer looks like to me like it will grab the first 30 elements in an array of 35 elements, rather than truly spread out. What needs to happen is you should loop through the indexes of your TARGET array and then proportionally grab the index of the source array. Here is the solution in javascript, but its convertible to php:</p>\n\n<pre><code>export default function condenseArray(array, targetCount) {\n var selected = []\n for (var i = 0; i &lt; targetCount; i++) {\n let percent = i / targetCount\n let idx = Math.round(percent * array.length)\n let obj = array[idx]\n selected.push(obj)\n }\n\n return selected\n}\n</code></pre>\n\n<p>Here are tests to demonstrate how it works:</p>\n\n<pre><code>test('gets every other one when condensing in half', function(assert) {\n var array = []\n for (var i = 0; i &lt; 10; i++) {\n array.push(i)\n }\n\n let result = condenseArray(array, 5)\n assert.deepEqual(result, [0, 2, 4, 6, 8])\n})\n\ntest('spreads it out a bit when not an multiple', function(assert) {\n var array = []\n for (var i = 0; i &lt; 11; i++) {\n array.push(i)\n }\n\n let result = condenseArray(array, 5)\n assert.deepEqual(result, [0, 2, 4, 7, 9])\n})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-25T16:09:49.820", "Id": "375691", "Score": "0", "body": "Welcome to Code Review! Please read [How do I write a good answer?](https://codereview.stackexchange.com/help/how-to-answer): \"_Every answer must make at least one **insightful observation** about the code in the question._\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-25T15:57:13.993", "Id": "195169", "ParentId": "36983", "Score": "1" } } ]
{ "AcceptedAnswerId": "56627", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:08:30.880", "Id": "36983", "Score": "5", "Tags": [ "php", "array" ], "Title": "Take an array and return \"n\" elements, as evenly spaced as possible" }
36983
<p>A very simple cipher in which the letters of the alphabet are substituted by a different letter that have a fixed distance to the original letter.</p> <p>Named after <a href="http://en.wikipedia.org/wiki/Caesar_cipher" rel="nofollow">Julius Caesar</a>, because he is said to have used it.</p> <p>A special case of the Caesar cipher where every character is replaced by its 13th successor in the alphabet is known as ROT13.</p> <p>The <a href="/questions/tagged/vigenere-cipher" class="post-tag" title="show questions tagged &#39;vigenere-cipher&#39;" rel="tag">vigenere-cipher</a> is a slightly more complex variant of the Caesar cipher.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:18:06.040", "Id": "36984", "Score": "0", "Tags": null, "Title": null }
36984
A Caesar cipher is a trivial method to obfuscate text by substituting each character with it successor (or nth successor). Use this tag for questions involving a Caesar cipher or toy-grade ciphers of similar design.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:18:06.040", "Id": "36985", "Score": "0", "Tags": null, "Title": null }
36985
<p>As I am new to bash scripting, and want to use apt-get in my university. I know that many people have issues when trying to do so. My focus is simplicity and ease of use, but still need to be somewhat robust. </p> <pre><code>#!/bin/bash string="install" errormsg="\n\tInvalid input\n You should run this script with the following structure:\n\n sudo apt-proxy-install.sh install USERNAME PASSWORD\n\n " DIRECTORY=~/bin/ if [ "$1" = "$string" ] &amp;&amp; { ! ([ -z "$3" ] || [ -z "$3" ]) } then if [ ! -d "$DIRECTORY" ]; then mkdir ~/bin/ fi printf "#!/bin/bash\nhttp_proxy=""http://$2:$3@10.20.10.50:3128"" sudo apt-get \${@:2}" &gt; ~/bin/apt-proxy chmod 777 ~/bin/apt-proxy PATH=~/bin:$PATH addpath="export $PATH" sudo cat ~/.bashrc $addpath &gt; ~/.bashrc else printf "$errormsg" fi </code></pre> <p>My question is: is this code acceptable, or should I improve it? If the answer is not, then please give me some hints.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:52:37.403", "Id": "60913", "Score": "0", "body": "Assuming that apt-get should always use the HTTP proxy, configure [`/etc/apt/apt.conf`](https://help.ubuntu.com/community/AptGet/Howto#Setting_up_apt-get_to_use_a_http-proxy) with `Acquire::http::Proxy \"http://username:password@10.20.10.50:3128\"`. You _might_ consider the risk of storing a plaintext password to be acceptable if `apt.conf` is readable only by root." } ]
[ { "body": "<p><strong>NO!</strong></p>\n\n<p>Storing plaintext passwords in a world-readable file is not acceptable.</p>\n\n<p>Making an executable file world-writable is not acceptable.</p>\n\n<p>Asking for a password to be entered as a command-line parameter, where it would likely end up in ~/.bash_history, is not acceptable. The password would also be temporarily be visible to all users via <code>/bin/ps</code>, which is also bad practice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:39:51.940", "Id": "36992", "ParentId": "36986", "Score": "1" } }, { "body": "<p>Storing passwords in text files is never a good idea, <strong>especially</strong> if you give that file world-readable permissions.</p>\n\n<p>Try this:</p>\n\n<pre><code>#!/bin/bash \n\nmkdir -p ~/bin/\n\n# add ~/bin to PATH if not already there\necho '[[ :\"$PATH\": == *:\"$HOME/bin\":* ]] || PATH=\"$HOME/bin:$PATH\"' &gt;&gt; .bashrc\n\n# create the apt-proxy script\ncat &lt;&lt;'END_SCRIPT' &gt; ~/bin/apt-proxy\n#!/bin/bash\n\nstty -echo\nprintf \"Password for %s: \" \"$LOGNAME\"\nread password\nstty echo\necho\n\nexport http_proxy=\"http://${LOGNAME}:${password}@10.20.10.50:3128\"\nsudo -S apt-get \"$@\" &lt;&lt;&lt; \"$password\"\nEND_SCRIPT\n\nchmod 755 ~/bin/apt-proxy\n\ncat &lt;&lt;INSTRUCTIONS\nThe apt-proxy script has been installed. \nYou may need to log out and log back in before you can use it.\n\nusage: apt-proxy package ...\nINSTRUCTIONS\n</code></pre>\n\n<ul>\n<li><code>mkdir -p dir</code> will silently do nothing if the directory already exists</li>\n<li>you only need to add the user's <code>bin</code> dir to the PATH if it is not already there</li>\n<li>DO NOT store the user's password. Have the user enter it each time.</li>\n<li>you <em>should</em> not even need to use <code>sudo</code> to edit files in your home directory.</li>\n<li>777 permissions is overly generous: the world does not have to be able to edit the file</li>\n<li>use <code>sudo -S</code> and pass the user's password via stdin</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T23:22:49.773", "Id": "60933", "Score": "0", "body": "Additionally, you almost always want to quote `\"$@\"` to expand the command line arguments robustly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:42:08.440", "Id": "36993", "ParentId": "36986", "Score": "3" } }, { "body": "<p>This line…</p>\n\n<pre><code>sudo cat ~/.bashrc $addpath &gt; ~/.bashrc\n</code></pre>\n\n<p>… is actually <em>extremely</em> problematic.</p>\n\n<p>You will almost certainly <strong>wipe out the existing contents of <code>~/.bashrc</code></strong>: the shell will likely truncate <code>~/.bashrc</code> before it runs <code>sudo</code>, and <code>sudo</code> runs <code>cat</code>, and <code>cat</code> reads the file. See <a href=\"http://teaching.idallen.com/cst8207/12w/notes/270_redirection.txt\" rel=\"nofollow\">Unix Big Redirection Mistake #1</a>. The way to append to a file is using <code>echo \"$blah\" &gt;&gt; ~/.bashrc</code>.</p>\n\n<p>The <code>$addpath</code> variable is incorrectly defined as <code>addpath=\"export $PATH\"</code>. You would be trying to export a variable named <code>~/bin:/bin:/usr/bin</code> because there is no <code>PATH=…</code> assignment. You meant <code>addpath=\"export PATH=\\\"$PATH\\\"\"</code>.</p>\n\n<p>Furthermore, <code>cat $addpath</code> has two errors: it's the wrong command (you want <code>echo</code>), and you failed to double-quote its argument. Therefore, it will just try to read files named <code>export</code> and <code>PATH=~/bin:…</code> — if you're lucky. If you're unlucky, <code>$PATH</code> could expand to a string that contains a nasty shell command. That scenario is admittedly farfetched, but that kind of carelessness in quoting is how exploits get introduced. <strong>When writing shell scripts, double-quote <em>every</em> variable you use unless you have a good reason not to.</strong></p>\n\n<p><code>sudo</code> is unnecessary for that operation; it could even backfire if the <code>sudoers</code> doesn't allow <code>cat</code> to be executed. By the way, <code>sudo</code> would only elevate the <code>cat ~/.bashrc</code> to root privileges; the writing would still be done using output redirection in the non-elevated context.</p>\n\n<p><code>~/.bashrc</code> is not a good place to put a statement to edit <code>$PATH</code>, since it gets executed with every interactive shell. If you run <code>bash</code> from within Bash, the subshell would unexpectedly have its <code>$PATH</code> redefined. A more appropriate place might be <code>~/.bash_profile</code>.</p>\n\n<p>After correcting for the mistakes above, with the code</p>\n\n<pre><code>PATH=\"~/bin:$PATH\"\naddpath=\"export PATH=\\\"$PATH\\\"\"\necho \"$PATH\" &gt;&gt; ~/.bash_profile\n</code></pre>\n\n<p>… you would be \"freezing\" the current value of <code>$PATH</code> into <code>~/.bash_profile</code>. Instead, you probably want to prepend <code>~/bin</code> to whatever <code>$PATH</code> exists when <code>~/.bash_profile</code> is executed in the future (notice the single quotes instead of double quotes):</p>\n\n<pre><code>echo 'export PATH=~/bin:$PATH' &gt;&gt; ~/.bash_profile\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T23:50:26.613", "Id": "37004", "ParentId": "36986", "Score": "0" } }, { "body": "<p>This line has readability problems:</p>\n\n<pre><code>if [ \"$1\" = \"$string\" ] &amp;&amp; { ! ([ -z \"$3\" ] || [ -z \"$3\" ]) }\n</code></pre>\n\n<p>You put <code>$3</code> twice; I assume you meant <code>$2</code> for one of them.</p>\n\n<p>Since <code>\"$string\"</code> is just <code>install</code>, you might as well say <code>install</code> instead.</p>\n\n<p>The compound conditional is hard to understand. Apply De Morgan's laws to obtain</p>\n\n<pre><code>if [ \"$1\" = install ] &amp;&amp; ! [ -z \"$2\" ] &amp;&amp; ! [ -z \"$3\" ]\n</code></pre>\n\n<p>… which is just</p>\n\n<pre><code>if [ \"$1\" = install ] &amp;&amp; [ -n \"$2\" ] &amp;&amp; [ -n \"$3\" ]\n</code></pre>\n\n<p>I would introduce explaining variables</p>\n\n<pre><code>command=\"$1\"\nusername=\"$2\"\npassword=\"$3\"\nif [ \"$command\" = install ] &amp;&amp; [ -n \"$username\" ] &amp;&amp; [ -n \"$password\" ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T00:01:43.437", "Id": "37005", "ParentId": "36986", "Score": "1" } } ]
{ "AcceptedAnswerId": "36993", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T19:18:12.320", "Id": "36986", "Score": "5", "Tags": [ "beginner", "bash", "linux", "shell" ], "Title": "apt alternative for proxy environment with bash shell" }
36986
<p>Example Script is located in /home/insp/public_html/deploy/</p> <p>I want to return the /home/insp/ section</p> <pre><code>$path = realpath(__DIR__); $parts = explode('/', $path); $newPath = array( $parts[0], $parts[1], $parts[2], ); $realPath = implode('/', $newPath); </code></pre> <p>Is there a better/more effeicent way to acheve this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:09:57.387", "Id": "60916", "Score": "0", "body": "So you want the home directory of the user?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:11:34.150", "Id": "60918", "Score": "0", "body": "Yes @Bobby i did see that i could use a simple regex .*public_" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:12:40.507", "Id": "60919", "Score": "0", "body": "What's stopping you from using `$_SERVER['HOME']` or `getenv('HOME')`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:16:09.880", "Id": "60920", "Score": "0", "body": "That isnt an env variable in cPanel closest i get is [DOCUMENT_ROOT] => /home/insp/public_html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:24:41.533", "Id": "60922", "Score": "0", "body": "But if I read [this documentation](http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/ExpVarRef) and [this one](http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/CpanelPhp) correctly, you should be able to use `<cpanel print=\"$homedir\">` to get the home directory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T13:49:27.447", "Id": "60982", "Score": "0", "body": "@Bobby That would work but its not something i want to expose to the public. Thanks for the idea i had no idea that was possible." } ]
[ { "body": "<p>A different way:</p>\n\n<pre><code>preg_match(':^/[^/]*/[^/]*/:', realpath(__DIR__), $matches);\n$realPath = $matches[0];\n</code></pre>\n\n<p>This matches the first and second files in path, and stores them in $matches.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:19:10.990", "Id": "60921", "Score": "0", "body": "I thought about that or doing '.*public_' to get /home/insp/public_ if that's the best way i'll go with it im just farming for opinions. or this (\\/[a-zA-Z0-9]*.){3} the issue with the first is it will cause issues if tehre happens to be a folder called public_ anything" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:29:38.857", "Id": "60923", "Score": "0", "body": "Also your regex does not match anything http://regexr.com?37ir1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:35:11.647", "Id": "60924", "Score": "0", "body": "preg_match has a slightly different syntax; removing the colons will work on regexr.com :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:17:58.540", "Id": "36995", "ParentId": "36991", "Score": "0" } }, { "body": "<p>I've ended up going with this approach:</p>\n\n<pre><code>preg_match('/(\\/[a-zA-Z0-9]*){2}/', realpath(__DIR__), $homeDir);\n$homeDir = $homeDir[0];\n</code></pre>\n\n<p>Reason being this is a much stricter regex and will only match valid cPanel usernames in paths which per their docs can only contain alphanumeric characters. This also prevents the need to expose this path to the public as was recommended by another person here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T14:46:37.823", "Id": "60991", "Score": "0", "body": "You should add some information on why you chose this alternative. As your answer stands at the moment, it does not indicate why this answer is good or recommended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T14:48:45.170", "Id": "60992", "Score": "0", "body": "@rolfl you're right i've updated it now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T14:15:11.100", "Id": "37038", "ParentId": "36991", "Score": "0" } } ]
{ "AcceptedAnswerId": "37038", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:26:29.910", "Id": "36991", "Score": "1", "Tags": [ "php", "optimization", "linux" ], "Title": "Optimize this path location script?" }
36991
<p>I'm no pro in JavaScript. Please help me review this code. I would appreciate any suggestions!</p> <p><strong>JavaScript:</strong></p> <pre><code>var y_offset, /*current position of window*/ distance_from_current_position, /*different between current position and target*/ body_height, /*hight of body*/ window_height, /*height of window*/ position_of_target, /*target position*/ max_scroll, /*max position to scroll to*/ up_or_down, /*scroll up or down*/ my_classes = document.querySelectorAll('.y'); function scroll_function(target) { y_offset = window.pageYOffset; distance_from_current_position = target - window.pageYOffset; setTimeout(function () { if (distance_from_current_position !== 0) { if (up_or_down) { if (y_offset &lt; target - 5) { window.scroll(0, y_offset + (distance_from_current_position / 3)) } else { window.scroll(0, y_offset + 1) } if (y_offset &lt; position_of_target - 1) { scroll_function(target); } } else { if (y_offset &gt; target + 5) { window.scroll(0, y_offset + (distance_from_current_position / 3)) } else { window.scroll(0, y_offset - 1) } if (y_offset &gt; position_of_target + 1) { scroll_function(target); } } } }, 50) } function click_function(i) { my_classes[i].onclick = function () { body_height = document.body.clientHeight; position_of_target = document.getElementById(this.getAttribute('data-y')).offsetTop; window_height = window.innerHeight; max_scroll = body_height - window_height; if (window.pageYOffset &lt; position_of_target) { up_or_down = 1 } else { up_or_down = 0 } if (position_of_target &gt; max_scroll) { position_of_target = max_scroll; } $y_1(position_of_target); }; } for (var i = 0; i &lt; my_classes.length; i++) { click_function(i); } </code></pre> <p><strong>HTML:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;title&gt;&lt;/title&gt; &lt;ul class=ul&gt; &lt;li&gt;&lt;a class=y data-y=id1&gt;Scroll to id1&lt;/a&gt; &lt;li&gt;&lt;a class=y data-y=id2&gt;Scroll to id2&lt;/a&gt; &lt;li&gt;&lt;a class=y data-y=id3&gt;Scroll to id´3&lt;/a&gt; &lt;/li&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T23:04:52.707", "Id": "60931", "Score": "1", "body": "What are you trying to solve exactly? It seems cleaner to use built in [`window.scrollTo()`](https://developer.mozilla.org/en-US/docs/Web/API/Window.scrollTo) or even using `<a href=\"#elementid\">`. Sometimes there is a good reason not to use a built in method but sometimes not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T07:10:52.210", "Id": "60953", "Score": "0", "body": "Thanks James, I will add your changes. One thing would like is a smoother easeing effect than (distance_from_current_position / 3). Any idea on how to fixa that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T04:52:13.843", "Id": "61148", "Score": "0", "body": "Again what are you trying to solve exactly? I'd love to post an answer but I can't see any reason for the code. A code-less solution would be much better in my opinion." } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>This code does not work, you did not provide <code>$y_1</code>, I am assuming you meant <code>scroll_function</code></li>\n<li>I built a JsBin for this : <a href=\"http://jsbin.com/sihoj/1/edit\" rel=\"nofollow\">http://jsbin.com/sihoj/1/edit</a>, because you keep calling <code>scroll_function</code>, you can actually prevent the user from reaching the navigation links again, that's not a good approach</li>\n<li>As James Khoury mentioned, why not use <code>&lt;a href=\"#elementid\"&gt;</code> or <code>scrollTo</code> ?</li>\n<li>You should use lowerCamelCase</li>\n<li><p>This : </p>\n\n<pre><code>if (position_of_target &gt; max_scroll) {\n position_of_target = max_scroll;\n}\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>position_of_target = Math.min( position_of_target , max_scroll );\n</code></pre>\n\n<p>I feel this reflects better what you are trying to accomplish </p></li>\n</ul>\n\n<p><strong>Naming</strong></p>\n\n<p>I would much rather see</p>\n\n<pre><code>//Distance from currrent position\ndistance = target - window.pageYOffset; \n</code></pre>\n\n<p>than</p>\n\n<pre><code>distance_from_current_position = target - window.pageYOffset; \n</code></pre>\n\n<p>your code becomes a bit unwieldy when you have too many long variable names</p>\n\n<p>If you have <code>target</code> and would have <code>distance</code> , then I would also go for <code>offset</code>, <code>y_offset</code> looks ugly.</p>\n\n<p>Also here</p>\n\n<pre><code>position_of_target = document.getElementById(this.getAttribute('data-y')).offsetTop;\n</code></pre>\n\n<p>you should have some deep thoughts about the variable name, position implies usually an x/y coordinate, but you are really dealing here with an offset from the top.</p>\n\n<p>Finally : <code>up_or_down</code> is a terrible name, there is no logical connection for 1 being up, and 0 being down. At the very least you should consider \n<code>var UP = true, DOWN = false</code> or <code>var UP = 1, DOWN = 0</code> if you don't want to use booleans.</p>\n\n<p><strong>Magic Constants</strong></p>\n\n<p><code>/ 3</code> &lt;- That <code>3</code> should be a well named constant<br>\n<code>target - 5</code> &lt;- That <code>5</code> should be a well named constant</p>\n\n<p><strong>Fake Booleans</strong></p>\n\n<p>This:</p>\n\n<pre><code> if (window.pageYOffset &lt; position_of_target) {\n up_or_down = 1\n } else {\n up_or_down = 0\n }\n</code></pre>\n\n<p>is letting <code>up_or_down</code> be a fake boolean, you should go for </p>\n\n<pre><code> up_or_down = (window.pageYOffset &lt; position_of_target)\n</code></pre>\n\n<p>especially since you are doing falsey comparisons to <code>up_or_down</code> any way.</p>\n\n<p><strong>DRY</strong></p>\n\n<p>This:</p>\n\n<pre><code> if (up_or_down) {\n if (y_offset &lt; target - 5) {\n window.scroll(0, y_offset + (distance_from_current_position / 3))\n } else {\n window.scroll(0, y_offset + 1)\n }\n if (y_offset &lt; position_of_target - 1) {\n scroll_function(target);\n }\n } else {\n if (y_offset &gt; target + 5) {\n window.scroll(0, y_offset + (distance_from_current_position / 3))\n } else {\n window.scroll(0, y_offset - 1)\n }\n if (y_offset &gt; position_of_target + 1) {\n scroll_function(target);\n }\n }\n</code></pre>\n\n<p>could be </p>\n\n<pre><code> var vector = up_or_down ? -1 : +1; \n\n if (y_offset &lt; target + 5 * vector ) {\n window.scroll(0, y_offset + (distance_from_current_position / 3))\n } else {\n window.scroll(0, y_offset - vector)\n }\n if (y_offset &lt; position_of_target + vector) {\n scroll_function(target);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T18:05:08.067", "Id": "47807", "ParentId": "36999", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T22:11:54.193", "Id": "36999", "Score": "1", "Tags": [ "javascript", "optimization" ], "Title": "Help me optimize this scrollTo" }
36999