body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>It works just fine, but is there any other way to write this shorter?</p> <p>Nurses are only available to intensive care patients (room I) and TV's and telephones are only available to non intensive care patients (room D or room P). Also, <code>X_COST</code> has a value of 0.</p> <pre><code>if (room.equals("I")) { // if (room.equals("I")) roomCost = 395 * (double)days; //System.out.println(roomCost); TVCost = X_COST; //System.out.println(TVCost); phoneCost = X_COST; //System.out.println(phoneCost); if (nurse.equals("X")) nurseCost = X_COST; //System.out.println(nurseCost); else if (room.equals("N")) nurseCost = 250 * (double)days; //System.out.println(nurseCost); else nurseCost = 275 * (double)days; //System.out.println(nurseCost); } // if (room.equals("I")) else if (room.equals("P")) { // else if (room.equals("P")) roomCost = 350 * (double)days; //System.out.println(roomCost); nurseCost = X_COST; //System.out.println(nurseCost); if (TV.equals("V")) { // if (TV.equals("V")) TVCost = 40 * (double)days; //System.out.println(TVCost); if (phone.equals("T")) phoneCost = 15 * (double)days; //System.out.println(phoneCost); else phoneCost = X_COST; //System.out.println(phoneCost); } // if (TV.equals("V")) else { // else !(TV.equals("V")) TVCost = X_COST; //System.out.println(TVCost); if (phone.equals("T")) phoneCost = 15 * (double)days; //System.out.println(phoneCost); else phoneCost = X_COST; //System.out.println(phoneCost); } // else !(TV.equals("V")) } // else if (room.equals("P")) else { // else roomCost = 310 * (double)days; //System.out.println(roomCost); nurseCost = X_COST; //System.out.println(nurseCost); if (TV.equals("V")) { // if (TV.equals("V")) TVCost = 40 * (double)days; //System.out.println(TVCost); if (phone.equals("T")) phoneCost = 15 * (double)days; //System.out.println(phoneCost); else phoneCost = X_COST; //System.out.println(phoneCost); } // if (TV.equals("V")) else { // else !(TV.equals("V")) TVCost = X_COST; //System.out.println(TVCost); if (phone.equals("T")) phoneCost = 15 * (double)days; //System.out.println(phoneCost); else phoneCost = X_COST; //System.out.println(phoneCost); } // else !(TV.equals("V")) } // else </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T01:00:11.490", "Id": "84215", "Score": "0", "body": "After writing code that says \"if (room.equals(\"I\"))... there is absolutely no point adding a comment that says exactly the same thing. Make your code readable, so that you rarely need comments" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T01:05:30.133", "Id": "84216", "Score": "0", "body": "Inside the first check for room==\"I\", you are checking for room=\"N\". That's an impossible condition. You probably mean nurse==\"N\"" } ]
[ { "body": "<p>Code like the following ...</p>\n\n<pre><code> if (phone.equals(\"T\"))\n\n phoneCost = 15 * (double)days;\n //System.out.println(phoneCost);\n\n else\n\n phoneCost = X_COST;\n</code></pre>\n\n<p>... is copy-and-pasted into more than one type of room.</p>\n\n<p>Instead of having a structure like ...</p>\n\n<pre><code>if room type\n calculate nurse cost\n calculate phone cost\n calculate TV cost\nelse if other room type\n calculate nurse cost again\n calculate phone cost again\n calculate TV cost again\n</code></pre>\n\n<p>... I suspect it would be better to have a structure like ...</p>\n\n<pre><code>// Calculate TV cost.\nTVCost = (room.equals(\"I\") || !TV.equals(\"V\")) ? X_COST : 40 * (double)days;\n// Calculate Phone cost\n... etc ...\n// Calculate nurse cost\n... etc ...\n</code></pre>\n\n<hr>\n\n<p>Also I don't understand this ...</p>\n\n<pre><code>else if (room.equals(\"N\"))\n\n nurseCost = 250 * (double)days;\n //System.out.println(nurseCost);\n</code></pre>\n\n<p>... because that's in a place where you already decided that <code>room.equals(\"I\")</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T00:27:37.523", "Id": "47303", "ParentId": "47301", "Score": "4" } }, { "body": "<p><code>roomCost</code> is identical in all cases, so set it only once. Also, you should only check for <code>room.equals(\"I\")</code>, because that is significantly different than the other rooms.\nThen if else another room, then you only need to check if <code>TV.equals(\"V\")</code>.</p>\n\n<p>These changes will really make the resultant code much smaller and easier to support going forward. I probably would do this differently, like maybe using a switch statement (with compiler set to Java 1.7), but then my comments here are for supporting the way you would like to do it.</p>\n\n<pre><code>roomCost = 395 * (double)days;\n\nif (room.equals(\"I\")) { // if (room.equals(\"I\"))\n TVCost = X_COST;\n phoneCost = X_COST;\n\n if (nurse.equals(\"X\"))\n nurseCost = X_COST;\n else if (room.equals(\"N\"))\n nurseCost = 250 * (double)days;\n else\n nurseCost = 275 * (double)days; \n\n} // if (room.equals(\"I\"))\nelse{\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T02:31:36.837", "Id": "82867", "Score": "0", "body": "Much better, +1!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T00:30:20.410", "Id": "47304", "ParentId": "47301", "Score": "4" } }, { "body": "<p>First things first, there is <strong>room for improvement for code formatting</strong> - there's too many empty lines, if-statements without curly braces (unless this is mandated by force in your context, but absence of braces is fertile ground for bugs...) and unnecessary comments at the end of your main if-statement. The problem with the last is what happens when conditions change in the future but the comments are not? That will surely cause confusion. This is what I'm talking about:</p>\n\n<pre><code>else if (room.equals(\"P\")) { // else if (room.equals(\"P\")) \n ...\n} // else if (room.equals(\"P\")) \n\n\n\nelse { // else\n ...\n} // else\n</code></pre>\n\n<p>I did some formatting myself and shrank your code down to 48 concise lines. From there, I can see that the calculation for the phone and TV costs are the same - so you definitely should consider creating one method for each to wrap them and call them in the relevant places. This will also make future updates easier as you only need to modify two methods (which can be as simple as a one-liner method) instead of potentially six different lines.</p>\n\n<p>Why is there a need to cast the number of days as a double type?</p>\n\n<p>Also, as pointed out by @ChrisW, the first if-condition has a nested if-statement that doesn't make sense - a bug from copying-and-pasting?</p>\n\n<pre><code>if (room.equals(\"I\")) {\n ...\n if (nurse.equals(\"X\")) {\n nurseCost = X_COST;\n } else if (room.equals(\"N\")) { // room equals N?\n nurseCost = 250 * (double)days;\n } else {\n nurseCost = 275 * (double)days;\n }\n}\n</code></pre>\n\n<p>edit: just saw that <code>X_COST = 0</code>... in that case may I suggest renaming it as <code>NO_COST</code> or something along those lines?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T01:55:41.603", "Id": "47308", "ParentId": "47301", "Score": "3" } }, { "body": "<p>Your outer if statements for rooms cannot be changed, however you can change some of the inner ones to conditional assignments if you want:</p>\n\n<pre><code>if (phone.equals(\"T\"))\n\n phoneCost = 15 * (double)days;\n //System.out.println(phoneCost);\n\nelse\n\n phoneCost = X_COST;\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>phoneCost = phone.equals(\"T\") ? 15 * (double)days : X_COST;\n</code></pre>\n\n<p>You can do this with all of assignment operations where each branch is just passing a different value into the same variable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T00:06:45.433", "Id": "47998", "ParentId": "47301", "Score": "0" } }, { "body": "<p>You could place many if-else statements in switch case. \nSwitch case statements are a substitute for long if statements.\nJava supports switch case with Strings. \nHere you can find an example <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html\" rel=\"nofollow\">http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T00:07:08.093", "Id": "47999", "ParentId": "47301", "Score": "0" } }, { "body": "<p>Simple if else can be shortened by using ternary operator. If you have long if else ladder, you can use switch case.</p>\n\n<p>Links.\n<a href=\"http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html\" rel=\"nofollow\">Switch case</a>\n<a href=\"http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html\" rel=\"nofollow\">Ternary Operator</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T00:12:09.283", "Id": "48000", "ParentId": "47301", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T00:06:33.527", "Id": "47301", "Score": "8", "Tags": [ "java" ], "Title": "Conditional statements relating to hospital management" }
47301
<p>First, I've extended the String class to detect uppercase and lowercase characters:</p> <pre><code>class String def is_uppercase? self == self.upcase end def is_lowercase? self == self.downcase end end </code></pre> <p>I then use these instance methods to fulfil my main goal of transferring the format of an old string to a new string:</p> <pre><code>def maintain_format(instring, outstring) instring_array = instring.split(//) outstring_array = outstring.split(//) both_arrays = instring_array.zip(outstring_array) both_arrays.each do |character| if character[0] == nil || character[0].is_lowercase? character[1].downcase! if character[1] elsif character[0].is_uppercase? character[1].upcase! if character[1] end end outstring_array.join("") end </code></pre> <p>It works well and does exactly what I want:</p> <pre><code>2.0.0p247 :002 &gt; maintain_format('jimmy','Jam') =&gt; "jam" 2.0.0p247 :003 &gt; maintain_format('Jimmy','xam') =&gt; "Xam" 2.0.0p247 :004 &gt; maintain_format('realLylongname','shorter') =&gt; "shorTer" 2.0.0p247 :005 &gt; maintain_format('rSeHorteR','muchmuchmuchlongerfoos') =&gt; "mUcHmuchMuchlongerfoos" </code></pre> <p>However, what I love about ruby is how it is sort self-documenting if you use sensible variable and method names and hash keys. With this code it is a bit hard to follow regarding the 1character[0]<code></code>character[1]` stuff. I attempting it with hashes but got in a bit of a mess. How would you tackle this problem?</p> <p>Also interested in any ruby tricks to make this take up less lines. </p> <p>Note this is part of a rails project, so all rails methods are available to me.</p>
[]
[ { "body": "<p>First off, I'd rename those two <code>String</code> methods. You obviously had a plan in mind when you added them (i.e. that the strings you'd be checking would be 1 character long), but from a more general perspective, it's fraught with ambiguity.</p>\n\n<p>For instance, is the string <code>\"Hello, world\"</code> uppercase? Or is it lowercase? Is it sentence-case? Titlecase? So your methods, simple as they are, are perhaps <em>too</em> simple to make sense when applied outside the (narrow) usage you've tailored them for. As such, they probably shouldn't be global <code>String</code> methods. Certainly, you don't need to extend a core class like <code>String</code> just for a simple <code>==</code> comparison.</p>\n\n<p>Also, Ruby convention is to not use an <code>is_</code> prefix on interrogatory methods like those. The <code>nil?</code> method, for instance, isn't called <code>is_nil?</code>. Same for <code>one?</code>, <code>any?</code>, <code>empty?</code>, <code>include?</code> and so on.</p>\n\n<p>As for your <code>maintain_format</code> method, here's what came to mind:</p>\n\n<ul>\n<li>There's a <code>String#chars</code> method, which'll give you an array of chars - no need for split</li>\n<li>Instead of zipping, use a loop and use an index - characters in a string can be accessed just like elements in an array.</li>\n<li>And if you're going to loop, no need to loop further than the shortest of the two strings. Or, if you zip the arrays like you do right now, make sure you <code>break</code> the loop when one string or the other \"runs out\"</li>\n<li>You only need to check for uppercase. Everything else gets downcased by default. A character can only be upper or lowercase, so if it's <em>not</em> uppercase, you already know that it's lowercase; no need for extra <code>if</code>s (but see the update below)</li>\n</ul>\n\n<p>I'd suggest something like</p>\n\n<pre><code>def maintain_format(template, string)\n string = string.downcase # do this right away\n template = template[0..string.length] # shorten the template, if necessary\n template.chars.each_with_index do |char, index|\n next unless char == char.upcase # skip lowercase chars\n string[index] = string[index].upcase\n end\n string\nend\n</code></pre>\n\n<p>Perhaps there's a smarter way to detect upper-/lowercase chars, but I couldn't quite think of one that'd be as simple and handle unicode etc.</p>\n\n<p>Lastly: Naming (again). <code>maintain_format</code> is a bit off to me; you're <em>applying</em> a format, <em>copying</em> a format, or something along those lines. (The title of your question also calls it \"transfer\" rather than \"maintain\". But transfer would suggest that one string loses its format, when it's applied to the other, so it's not quite right either.)</p>\n\n<p>Ironically, it might make more sense to add <em>this</em> method to <code>String</code>, since it's somewhat more generally applicable. Besides, a call like <code>template.assimilate(other_string)</code> (besides sounding ominous, would make it much clearer which string is the template, and which string will be changed. Right now, it can quickly become confusing which argument is which. But again, better naming might alleviate that.</p>\n\n<hr>\n\n<p>Update: As 200_success rightly points out in the comments, it's surprising that a string that's longer than the template string gets downcased rather than simply keep whatever case it had. And code shouldn't surprise.</p>\n\n<p>Hence it might be better to do this:</p>\n\n<pre><code>def maintain_format(template, string)\n string = string.dup # still want a duplicate to work on\n template = template[0..string.length]\n template.chars.each_with_index do |char, i|\n string[i] = char == char.upcase ? string[i].upcase : string[i].downcase\n end\n string\nend\n</code></pre>\n\n<p>You can still achieve the original behavior by simply downcasing the string yourself before passing it to the method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T09:56:13.930", "Id": "82913", "Score": "0", "body": "I'd expect the part of the `string` that extends beyond the end of `template` to have its case preserved, not forcibly downcased." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T11:22:26.893", "Id": "82926", "Score": "0", "body": "@200_success As would I. But as far as I can tell from OP's code, case isn't preserved for the \"leftover\" string... Regardless, you're right; it's unexpected. I'll add a note - thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T11:39:01.170", "Id": "82929", "Score": "0", "body": "@Flambino could you explain the 5th line please? ` string[i] = char == char.upcase ? string[i].upcase : string[i].downcase` Literally all of it. I've got a good idea but I'd want some validation :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T12:55:31.713", "Id": "82943", "Score": "1", "body": "@Starkers It's just an assignment with [a ternary](http://en.wikipedia.org/wiki/%3F:#Ruby), i.e. `if...else` written in one line. You can spell it out in Ruby as `string[i] = (if char == char.upcase then string[i].upcase else string[i].downcase end)`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:21:15.850", "Id": "47330", "ParentId": "47305", "Score": "3" } }, { "body": "<p>My common advise is to avoid accumulator variables.</p>\n\n<pre><code>def maintain_format template, string\n string.chars.zip(template.chars).map{ |orig, char|\n char ? char == char.upcase ? orig.upcase : orig.downcase : orig\n }.join\nend\n\np maintain_format \"qWERty\", \"asDFGhJj\"\n&gt;&gt; \"aSDFghJj\"\n</code></pre>\n\n<p>Note <code>char ? ... : orig</code> since <code>zip</code> gives <code>nil</code>s instead of second array element if it's not available (if template is too short).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:49:48.490", "Id": "83194", "Score": "0", "body": "+1 for avoiding the accumulator. But that double ternary is kinda hairy. It's not _super_ complex or anything, but it's unnecessarily terse and harder to read." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:48:34.470", "Id": "47376", "ParentId": "47305", "Score": "2" } } ]
{ "AcceptedAnswerId": "47376", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T01:11:50.030", "Id": "47305", "Score": "2", "Tags": [ "ruby", "strings", "ruby-on-rails" ], "Title": "Transfer the format of an old string to a new string" }
47305
<p>I'm working on a card game in Java that simulates the drinking game Kings Cup for a school project. I'm having trouble putting the pieces together, and was wondering if someone could tell me what I could do to improve my code.</p> <pre><code> @author :Kimberly IDE :NETBEANS public class Card extends Deck { enum Rank { ACE ("Ace"), TWO ("2"), THREE ("3"), FOUR ("4"), FIVE ("5"), SIX ("6"), SEVEN ("7"), EIGHT ("8"), NINE ("9"), TEN ("10"), JACK ("Jack"), QUEEN ("Queen"), KING ("King"); String rank; Rank(String rank) { this.rank = rank; } } enum Suit { HEARTS ("Hearts"), DIAMONDS ("Diamonds"), SPADES ("Spades"), CLUBS ("Clubs"); String name; Suit(String name) { this.name = name; } } public Rank rank; public Suit suit; Card(Suit suit, Rank rank){ this.rank=rank; this.suit=suit; } public @Override String toString(){ return rank.rank + " of " + suit.name; } } </code></pre> <hr> <pre><code>public class Deck { private int dealt; /** * Shuffles the deck of cards. */ public static ArrayList&lt;Card&gt; cards; Deck() { cards = new ArrayList&lt;Card&gt;(); for (Card.Suit suit : Card.Suit.values()){ for (Card.Rank rank : Card.Rank.values()){ cards.add( new Card(suit,rank)); } } Collections.shuffle(cards, new Random()); Collections.shuffle(cards, new Random(System.nanoTime())); } public Card getCard(){ return cards.get(0); } public void removeFromDeck(){ cards.remove(0); } } </code></pre> <hr> <pre><code>public class Human extends Player{ Scanner in; public Human(boolean turn) { super("HUMAN", turn); in = new Scanner(System.in); } } </code></pre> <hr> <pre><code>public class Computer extends Player{ Random random; double cWeight; String cGender = ""; public Computer(boolean turn){ //super("COMPUTER", turn); turn = true; random = new Random(); } public double weight() { ArrayList&lt;Integer&gt; compWeight = new ArrayList&lt;&gt;(); compWeight.add(110); compWeight.add(170); compWeight.add(250); Collections.shuffle(compWeight, new Random()); for(int i = 0; i &lt; 3; i++) { cWeight = compWeight.get(i); } return cWeight; } public String gender() { ArrayList&lt;String&gt;compGender = new ArrayList&lt;&gt;(); compGender.add("male"); compGender.add("female"); Collections.shuffle(compGender, new Random()); for(int i = 0; i &lt; 2; i++) { cGender = compGender.get(i); } return cGender; } } </code></pre> <hr> <pre><code>public class Player { public static final double MAX_BAC = 0.5; public static int cardImplement = 0; public static double SD = 0.0; //amount of drinks public static double BW = 0.0; //body water constant public static final double MaleBW = 0.58; public static final double FemaleBW = 0.49; public static final double MR = 0.017; //metabolism constant public static final double DP = 2.0; //drinking period (2 hours) public static double BAC = 0.0; public boolean turn; public Player(double BAC, boolean turn) { this.BAC = BAC; this.turn = turn; } public double BAC() { if(gender.equals("male")) BW = MaleBW; else BW = FemaleBW; BAC = ((.806 * SD * 1.2) / (BW * weight)) - (MR * DP); return BAC; } public static void draw() { System.out.println(cards.get(cardImplement)); cardImplement++; } public static void sip() { if (BAC &lt; MAX_BAC) { SD += 0.2; } } public boolean switchTurn() { turn = !turn; return turn; } } </code></pre> <hr> <pre><code>public class Rules extends KingsCupGame{ private static int kings = 0; public static void setRules() { final String[] CATEGORY_WORDS = {"apple, apricot, banana, bilberry," + "blackberry, blackcurrant, blueberry, coconut, currant, cherry," + " cherimoya, clementine, date, damson, durian, elderberry, fig," + " feijoa, gooseberry, grape, grapefruit, huckleberry, jackfruit," + " jambul, jujube, kiwi, kumquat, lemon, lime, loquat, lychee," + " mango, mangostine, melon, cantaloupe, honeydew, watermelon," + " rock melon, nectarine, orange, passionfruit, peach, pear, plum," + " prune, pineapple, pomegranate, pomelo, raisin, raspberry," + " rambutan, redcurrant, satsuma, strawberry, tangerine, ugli," + "archery, badminton, basketball, volleyball, boxing, cycling, " + "diving, equestian, handball"}; final String[] RHYME_WORDS = {"bink, blink, brink, chink, cinq," + " cinque, clink, dink, finck, fincke, fink, finke, flink, frink," + " hinck, hink, inc, inc., ink, klinck, klink, klinke, krinke," + " linc, linck, link, linke, lynk, minc, mink, minke, pink," + " plink, prink, rinck, rink, rinke, schinke, schlink, shrink," + " sink, skink, slink, smink, spink, stink, swink, sync, think," + " vink, wink, zinc, zinck, zink, zinke, at, bat, batt, batte, bhatt," + " blatt,brat, bratt, catt, chat, dat, fat, flat, flatt, gat," + " gatt,glatt, gnat, hat, hatt, hnat, jagt, kat, katt, klatt," + " krat, kratt, latke, mat, matt, matte, nat, pat, patt, platt," + " platte, pratt, pratte, rat, ratte, sat, scat, schadt, shatt," + " slaght, slat, spat, splat, sprat, spratt, stat, tat, that," + " vat"}; Scanner in = new Scanner(System.in); for(Card.Rank c : Card.Rank.values()) { //Waterfalls if(c.equals("Ace")) { System.out.println("Player drew an Ace."); System.out.println("Player must drink a whole drink (5 sips)!"); Player.sip(); Player.sip(); Player.sip(); Player.sip(); Player.sip(); } //You if(c.equals("Two")) { System.out.println("Player drew a Two."); System.out.println("The other player must take a sip."); Player.sip(); } //Me if(c.equals("Three")) { System.out.println("Player drew a Three."); System.out.println("Player must take a sip."); Player.sip(); } //Women if(c.equals("Four")) { System.out.println("Player drew a Four."); System.out.println("Female players must take a sip."); if(BW == FemaleBW) { Player.sip(); } } //Rhymes if(c.equals("Five")) { System.out.println("Player drew a Five."); ArrayList &lt;String&gt; rhymeWord = new ArrayList &lt;&gt;(); rhymeWord.add("cat"); rhymeWord.add("drink"); Collections.shuffle(rhymeWord, new Random()); int count = 0; System.out.println("You have 30 seconds to type 5 words" + " that rhyme with " + rhymeWord); //JOptionPane.showMessageDialog(null, "You have 30 seconds to type 5 words" // + " that rhyme with " + rhymeWord); if (in.hasNext()) { String rhymeAnswer = in.next(); if(RHYME_WORDS[0].contains(rhymeAnswer)) { count++; if(count &gt;= 5) { System.out.println("Good Job! Computer drinks!"); //JOptionPane.showMessageDialog(null, "Good Job! Computer drinks."); Player.sip(); } } else { System.out.println("Sorry. You have to take a sip!"); //JOptionPane.showMessageDialog(null, "Sorry. You drink!"); Player.sip(); } } } //Guys if(c.equals("Six")) { System.out.println("Player drew a Six."); System.out.println("Male players must take a sip."); if(BW == FemaleBW) { Player.sip(); } } //Extra sip if(c.equals("Seven")) { System.out.println("Player drew a Seven."); System.out.println("Player must take an extra sip."); Player.sip(); Player.sip(); } //Mate if(c.equals("Eight")) { System.out.println("Player drew an Eight."); System.out.println("Both players must take a sip."); Player.sip(); } //Categories if(c.equals("Nine")) { System.out.println("Player drew a Nine."); ArrayList &lt;String&gt; categoryWord = new ArrayList &lt;&gt;(); categoryWord.add("Sports"); categoryWord.add("Fruits"); Collections.shuffle(categoryWord, new Random()); int count = 0; //JOptionPane.showMessageDialog(null, "You have 30 seconds to type 5 categories of" //+ categoryWord); System.out.println("You have 30 seconds to type 5 categories of " + categoryWord); if (in.hasNext()) { String categoryAnswer = in.next(); if(CATEGORY_WORDS[0].contains(categoryAnswer)) { count++; if(count &gt;= 5) { System.out.println("Good Job! Computer must take a sip."); //JOptionPane.showMessageDialog(null, "Good Job! Computer drinks."); Player.sip(); } } else { System.out.println("Sorry! You must take a sip!"); //JOptionPane.showMessageDialog(null, "Sorry. You drink!"); Player.sip(); } } } //Draw Again if(c.equals("Ten")) { System.out.println("Player drew a Ten."); System.out.println("Player must draw another card."); Player.draw(); } //Least Drunk if(c.equals("Jack")) { System.out.println("Player drew a Jack."); System.out.println("The Player with the lowest BAC must take a sip."); if(Human.BAC &lt; Computer.BAC) { Player.sip(); } else if(Computer.BAC &lt; Human.BAC) { Player.sip(); } else { System.out.println(""); } } //Questions if(c.equals("Queen")) { System.out.println("Player drew a Queen."); System.out.println("You must answer this question: "); String answer = ""; ArrayList&lt;String&gt; questions = new ArrayList&lt;&gt; (); questions.add("If you have a big one of these, odds are" + " you are highly educated."); questions.add("Experts say a man tends to be happier and more" + " secure if he has one of these."); questions.add("Guys think it's cool, but 60% of women think" + " it's a major turn off when a guy does this."); questions.add("What's Dr. Brown's middle name?"); questions.add(""); String answers = ("signature, sister, sisters, wink, roy"); Collections.shuffle(questions, new Random()); for(String question: questions) { JOptionPane.showMessageDialog(null, "Answer this question." + question); } if(in.hasNext()) { answer = in.next(); } if(answers.contains(answer)) { JOptionPane.showMessageDialog(null, "Correct! Computer drinks."); Player.sip(); } else { JOptionPane.showMessageDialog(null, "Wrong! Player drinks."); Player.sip(); } } //Mug int mug = 0; if(c.equals("King")) { System.out.println("Player drew a King."); if(kings == 3) { System.out.println("It's the final King! Player must drink a whole drink (5 sips)!"); Player.sip(); Player.sip(); Player.sip(); Player.sip(); Player.sip(); } else { kings++; mug++; System.out.println("Player pours some of their drink into the mug."); System.out.println(4 - kings + " out of 4 Kings remaining."); } } } } } </code></pre> <hr> <pre><code>import java.util.Scanner; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JOptionPane; public class KingsCupGame { private final Human human; private final Computer computer; public static double weight = 0.0; public static String gender = ""; private static String name = ""; private static String confirm = ""; public static int playerTurn=1; static Deck deck = new Deck(); public KingsCupGame() { human = new Human(true); computer = new Computer(false); } public static void main(String[] args) throws IOException { KingsCupGame frame = new KingsCupGame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(800, 700); frame.setVisible(true); } public static void inputs() { Scanner in = new Scanner(System.in); System.out.print("What's your first name: "); if(in.hasNext()) name = in.next(); System.out.println("Are you male or female? (Enter male or female)"); if(in.hasNext()) gender = in.next(); System.out.println("Enter your weight (don't lie): "); if(in.hasNextDouble()) weight = in.nextDouble(); System.out.println("Hello " + name + "! You are a " + gender + " who weighs " + weight + "."); System.out.println("Is this correct? (Enter yes or no)"); if(in.hasNext()) confirm = in.next(); if(confirm.equals("yes")) { } } private static int getNum(String prompt,String title) { return Integer.parseInt (JOptionPane.showInputDialog(null,prompt,title,3)); } public static String getGender() { return gender; } private static String getRule(){ return Rules.get(deck.getCard().rank.ordinal()); } private static void finalMessage() { JOptionPane.showMessageDialog(null,"Player "+playerTurn+" has died of alcohol poisoning.\n\n"+ getRule()+"\n\n", "Restart the Program to Play again",1); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T03:33:06.200", "Id": "82869", "Score": "1", "body": "well when I get some more time I will give a much more thorough review of the code but I find a few things wrong with your inheritance rules. A super class of Player being implemented by Computer and Human is a good thing. However Player not being abstract is a good way for a mistake. A deck extending a card, or vise versa does not make sense. a deck is a collection of cards, but does not extend it. Work on those for now" } ]
[ { "body": "<p>I'm probably missing a fair bit, but these are the things I picked up on:</p>\n\n<hr>\n\n<p>Why does Card extend Deck? They are both objects in their own right and don't require inheritance.</p>\n\n<p>If Player is intended to be an object it shouldn't have any static variables or methods. You might also want to consider making it an abstract class as you don't want to be able to make a new <code>Player</code>, you only want to be able to make a new instance of <code>Player</code> such as a <code>Human</code> or a <code>Computer</code></p>\n\n<p>You seem to be calling Player.sip() five times in a row manually. To make things easier, I would create another sip() method which takes an <code>int</code> parameter of how many times you want to do it, i.e:</p>\n\n<pre><code>public void sip(int times) {\n for (int i = 0; i &lt; times; i++) {\n sip();\n }\n}\n</code></pre>\n\n<p>Your rhyme words algorithm is entirely wrong. Firstly, you are only checking if the first element in the array of words contains the answer (which it won't, unless they type the same String five times)</p>\n\n<pre><code>if(RHYME_WORDS[0].contains(rhymeAnswer)) {\n</code></pre>\n\n<p>I would change RHYME_WORDS to be a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html\">HashSet</a> which actually has a <code>contains</code> method which will do what you are trying to achieve.</p>\n\n<p>Consider extracting each of the different card types to its own private method, so you don't just have one massive block of code, and it will make testing each one easier.</p>\n\n<p>I'm not entirely convinced your program works how you want it to at the moment. You should usually make sure you get everything working how it should be before you consider submitting it for code review, as we're not here to test it for you we are here to offer advice on improvement.</p>\n\n<p>Hopefully the points I've raised will give you some direction towards improvement, and then you can keep working on it and report back if you need more help.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T03:37:51.623", "Id": "47315", "ParentId": "47310", "Score": "10" } }, { "body": "<ul>\n<li><p>The indentation within <code>Card</code> is a little weird, but especially inconsistent with everything else in the other classes. If you follow the Java style guide closely, such things shouldn't stand out so easily.</p></li>\n<li><p><code>rank</code> and <code>suit</code> should be <code>private</code> as they shouldn't be exposed to the public interface like that. They should also be <code>final</code> so that they cannot be modified after initialization (it doesn't make sense to change a card's value later on, and it could make the code error-prone).</p></li>\n<li><p>You already shuffle the deck upon initialization, but shouldn't the user also be able to shuffle the deck without recreating it? In some games, I believe, the deck can be shuffled with the existing cards, up to a certain point. Having a separate method for this will help make the class more usable.</p>\n\n<pre><code>public void shuffle() {\n Collections.shuffle(cards, new Random());\n Collections.shuffle(cards, new Random(System.nanoTime()));\n}\n</code></pre>\n\n<p>Also, in order to avoid duplicating code, have the constructor call this instead.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-21T19:18:53.747", "Id": "63498", "ParentId": "47310", "Score": "6" } }, { "body": "<ul>\n<li><p><code>ArrayList&lt;String&gt;compGender = new ArrayList&lt;&gt;();</code> should be declared (on the left side) as a <code>List&lt;String&gt;</code> (keep the higher abstraction where possible). Also be careful with spacing; it does compile correctly here, but it could lead to serious problem elsewhere.</p></li>\n<li><p>In <code>Deck</code>, <code>public static ArrayList&lt;Card&gt; cards</code> should not be static. And the constructor should be public.</p></li>\n<li><p><code>Collections.shuffle(cards, new Random());\n Collections.shuffle(cards, new Random(System.nanoTime()));</code>\nshould be replaced by just one <code>Collections.shuffle(cards, random)</code> where <code>random</code> is a static <code>Random</code> member of <code>Deck</code>.</p></li>\n<li><p>In <code>Deck</code>, you should just have one method that both gets and removes the card in one atomic operation. You can get in some weird states otherwise.</p></li>\n<li><p><code>Player.draw</code> should not be static. </p></li>\n<li><p>In <code>Rules</code>, <code>CATEGORY_WORDS</code> and <code>RHYMES</code> words should just be static final member variables.</p></li>\n<li><p>In <code>Rules</code>, the long series of <code>if</code>'s should be one <code>switch</code> statement. Also, you iterate over all cards, but I assume you really want to process the player input.</p></li>\n<li><p><code>Rules</code> should not extend <code>KingsCupGame</code>. Likely it should be a member (composition) within <code>KingsCupGame</code>.</p></li>\n</ul>\n\n<p>I did not go over everything. You should read more material about both inheritance and <code>static</code> because you seem to use those two concepts randomly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-22T18:25:48.813", "Id": "116161", "Score": "0", "body": "After seeing @Jamal's answer, I noticed that there were a bunch of things to say about this code. Thanks for saying them!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-21T19:48:00.623", "Id": "63499", "ParentId": "47310", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T02:22:46.643", "Id": "47310", "Score": "8", "Tags": [ "java", "beginner", "game", "playing-cards" ], "Title": "Kings Cup drinking game" }
47310
<p>This is from my project <a href="http://corylutton.com/codecount.html">codecount</a> I use personally that is very similar to cloc.exe or SLOCCount. The part that I am questioning is where I am calculating when I am in a comment block and have deep nesting, I basically am replacing the sections with blank. I would like to deal with fixed format files at some point (RPGLE, CLP, etc) where the comments need to have characters in a specific position.</p> <p>Any review/comments/suggestions would be appreciated.</p> <pre><code>def scanfile(self, filename): """ The heart of the codecounter, Scans a file to identify and collect the metrics based on the classification. """ strblock = None endblock = None inblock = False endcode = False sha256 = hashlib.sha256() if(filename.size == 0): logging.info("Skipping File : " + filename.name) return # Identify language for l in self.langs: if(filename.extension in self.langs[l]["ext"]): filename.lang = l break # Unknown files don't need processed if(filename.lang is None): logging.info("Skipping File : " + filename.name) return # Using the with file opening in order to ensure no GC issues. with open(filename.path + "/" + filename.name, encoding="utf-8", errors='ignore') as fp: for line in fp: sha256.update(line.encode("utf-8")) filename.lines += 1 line = line.strip() identified = False if(line == ""): logging.info(" blak " + str(filename.lines)) filename.blanks += 1 continue if(endcode): filename.comments += 1 continue # Check to see if it is a block or was an opening block # ex1 = "/* */ if x;" = Code, not inblock # ex2 = "*/ if x; /*" = Code, inblock # ex3 = " if x; /*" = Code, inblock # ex4 = "/* */ if x; /* */ .." = Code, not inblock # ex4 = "*/" = Comment, not inblock # ex5 = "/* */" = Comment, not inblock # ex6 = "/*" = Comment, inblock # Two scenarios, # 1 - comments removed, code remains # 2 - Comments removed but block is open if(not inblock): for token in self.langs[filename.lang]["bcomm"]: strblock = token endblock = self.langs[filename.lang]["bcomm"][token] while token in line: # If a block has started then check for an exit if(endblock in line): line = line.replace( line[line.find(strblock): line.find(endblock) + len(endblock)], "", 1) else: line = line.replace( line[line.find(strblock):], "", 1) inblock = True # left open else: # Continue until the block ends... when left open if(endblock in line): inblock = False # End the block line = line.replace( line[:line.find(endblock) + len(endblock)], "").strip() else: line = "" # From the block but no hidden code made it out the back.... if(line is ""): logging.info(" bloc " + str(filename.lines) + line) filename.comments += 1 continue # Check line comment designators for token in self.langs[filename.lang]["comment"]: if(line.startswith(token)): logging.info(" line " + str(filename.lines) + line) filename.comments += 1 identified = True break if(identified): continue # If not a blank or comment it must be code logging.info(" code " + str(filename.lines) + line) filename.code += 1 # Check for the ending of code statements for end in self.langs[filename.lang]["endcode"]: if(line == end): endcode = True # Store the hash of this file for comparison to others logging.info("Total " + " " + str(filename.blanks) + " " + str(filename.comments) + " " + str(filename.code)) filename.sha256 = sha256.digest() </code></pre>
[]
[ { "body": "<p>A couple of points:</p>\n\n<p>In Python there is no need to place parentheses after <code>if</code>. For example, </p>\n\n<pre><code>if(filename.size == 0):\n</code></pre>\n\n<p>Can be replaced with</p>\n\n<pre><code>if filename.size == 0:\n</code></pre>\n\n<p>In fact, the latter is the preferred style. </p>\n\n<p>Also, using <code>format</code> is preferred to using <code>+</code> to append strings. For example,</p>\n\n<pre><code>logging.info(\"Total \"\n + \" \" + str(filename.blanks)\n + \" \" + str(filename.comments)\n + \" \" + str(filename.code))\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>log_message = 'Total {blanks} {comments} {code}'.format(\n blanks=filename.blanks,\n comments=filename.comments,\n code=filename.code)\nlogging.info(log_message)\n</code></pre>\n\n<p>This has a few advantages: more readable, easier to internationalize (one single string token instead of multiple), has descriptive named place holders, and finally, will allow for easier formatting if you decide to add it at some point. For example, you can change <code>{comments}</code> to <code>{comments:05d}</code> to format it as a fixed-width number with width 5 and zeros padded on the left if necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T04:42:05.903", "Id": "82870", "Score": "2", "body": "FWIW, you can also use `'Total {fname.blanks} {fname.comments} {fname.code}'.format(fname=filename)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T02:53:47.253", "Id": "47313", "ParentId": "47311", "Score": "10" } }, { "body": "<p>Instead of having to update the number of lines each iteration through the file, you could use the <a href=\"https://docs.python.org/2/library/functions.html?highlight=enumerate#enumerate\" rel=\"nofollow\">enumerate</a> function and only assign the line number once:</p>\n\n<pre><code>with open('test_file.txt', 'r') as f:\n for line_num, line in enumerate(f):\n # Insert parsing code here\n pass\n\n # Assign line amount here. A NameError error will be thrown\n # if this code is run on a file with no lines. If this errors,\n # assign 0.\n try:\n filename.lines = line_num + 1\n except NameError:\n filename.lines = 0\n</code></pre>\n\n<p>Also, when creating filepaths, look into using <a href=\"https://docs.python.org/2/library/os.path.html#os.path.join\" rel=\"nofollow\">os.path.join</a>. This creates the normalized version of the desired filepath for the current OS:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.path.join('some_path', 'to_my', 'file.txt')\n'some_path\\\\to_my\\\\file.txt'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T15:02:03.863", "Id": "83955", "Score": "0", "body": "On the enumerate, I thought about that but thought it would be wrong if the file happens to have no lines.? I think your right on the os.path.join, I should switch that, got bit by that once before. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T15:22:36.433", "Id": "83963", "Score": "0", "body": "If the code is ran with a file with no lines, line_num will be undefined. I will update accordingly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T15:32:49.330", "Id": "47790", "ParentId": "47311", "Score": "7" } } ]
{ "AcceptedAnswerId": "47313", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T02:24:48.063", "Id": "47311", "Score": "7", "Tags": [ "python" ], "Title": "A source Code Counter" }
47311
<p>I am interested in improving my coding standards in Python so I decided to post one my more recent and smaller "for fun" projects here for review. The code below implements a rather simple backtracking algorithm to solve SAT, which is based on Knuth's SAT0W found here: <a href="http://www-cs-faculty.stanford.edu/~uno/programs.html" rel="nofollow">http://www-cs-faculty.stanford.edu/~uno/programs.html</a> (While the algorithm is essentially the same as Knuth's, my implementation is heavily simplified compared to Knuth's.)</p> <p>While I appreciate all feedback, I am more interested in improvements that are Python- or implementation-specific, as opposed to algorithmic improvements, since I know there are many ways of improving the algorithm, as discussed by Knuth as well, which I left out of the code in favour of simplicity and ease of understanding.</p> <p>First, the command-line driver:</p> <pre><code>""" Solve SAT instance by reading from stdin using an iterative or recursive watchlist-based backtracking algorithm. Iterative algorithm is used by default, unless the -r flag is given. """ from __future__ import division from __future__ import print_function from argparse import ArgumentParser from sys import stdin from sys import stderr from satinstance import SATInstance import recursive_sat import iterative_sat __author__ = 'Sahand Saba' if __name__ == '__main__': parser = ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', help='verbose output.', action='store_true') parser.add_argument('-r', '--recursive', help='use the recursive backtracking algorithm.', action='store_true') parser.add_argument('-i', '--input', help='read from given file instead of stdin.', action='store') args = parser.parse_args() instance = None if args.input: with open(args.input, 'r') as file: instance = SATInstance.from_file(file) else: instance = SATInstance.from_file(stdin) alg = recursive_sat.solve if args.recursive else iterative_sat.solve for assignment in alg(instance, args.verbose): print(instance.assignment_to_string(assignment)) else: if args.verbose: print('No satisfying assignment exists.', file=stderr) </code></pre> <p>The <code>satinstance.py</code> file:</p> <pre><code>from __future__ import division from __future__ import print_function __author__ = 'Sahand Saba' class SATInstance(object): def _parse_and_add_clause(self, line): """ Some notes on encoding: - Variables are encoded as numbers 0 to n - 1. - Literal v is encoded as 2 * v and ~v as 2 * v + 1. So the foremost bit of a literal encodes whether it is negated or not. This can be tested simply with checking if l &amp; 1 is 0 or 1. - Similarly, to negate a literal, we just have to toggle the foremost bit. This can done easily by XORing with 1: the negation l is l ^ 1. - To get a literal's variable, we just need to shift to the right. This can be done with either l &gt;&gt; 1. Example: Let's say variable b is encoded with number 3. Then literal b is encoded as 2 * 3 = 6 and ~b as 2 * 3 + 1 = 7. """ clause = [] for literal in line.split(): negated = 1 if literal.startswith('~') else 0 variable = literal[negated:] if variable not in self.variable_table: self.variable_table[variable] = len(self.variables) self.variables.append(variable) encoded_literal = self.variable_table[variable] &lt;&lt; 1 | negated clause.append(encoded_literal) self.clauses.append(tuple(set(clause))) @classmethod def from_file(cls, file): instance = cls() instance.variables = [] instance.variable_table = dict() instance.clauses = [] for line in file: instance._parse_and_add_clause(line) instance.n = len(instance.variables) return instance def literal_to_string(self, literal): s = '~' if literal &amp; 1 else '' return s + self.variables[literal &gt;&gt; 1] def clause_to_string(self, clause): return ' '.join(self.literal_to_string(l) for l in clause) def assignment_to_string(self, assignment): return ' '.join(v if assignment[i] else '~' + v for i, v in enumerate(self.variables) if assignment[i] is not None) </code></pre> <p>And the iterative algorithm:</p> <pre><code>from __future__ import division from __future__ import print_function from watchlist import setup_watchlist from watchlist import update_watchlist __author__ = 'Sahand Saba' def solve(instance, verbose=False): watchlist = setup_watchlist(instance) if not watchlist: return # The state list wil keep track of what values for which variables # we have tried so far. A value of 0 means nothing has been tried yet, # a value of 1 means False has been tried but not True, 2 means True but # not False, and 3 means both have been tried. state = [0] * instance.n assignment = [None] * instance.n d = 0 # Current depth in the backtrack tree while True: if d == instance.n: yield assignment d -= 1 continue # Let's try assigning a value to v. Here would be the place to insert # heuristics of which value to try first. tried_something = False for a in [0, 1]: if (state[d] &gt;&gt; a) &amp; 1 == 0: tried_something = True # Set the bit indicating a has been tried for d state[d] |= 1 &lt;&lt; a assignment[d] = a if not update_watchlist(instance, watchlist, d &lt;&lt; 1 | 1 ^ a, assignment, verbose): assignment[d] = None else: d += 1 break if not tried_something: if d == 0: # Can't backtrack further. No solutions. return else: # Backtrack state[d] = 0 assignment[d] = None d -= 1 </code></pre> <p>I'm skipping a few of the files like <code>watchlist.py</code> and <code>recursive_sat.py</code>.</p>
[]
[ { "body": "<p>This review will focus on <strong>the command-line driver</strong>. Others will no doubt elaborate on the rest of your code.</p>\n<h2>Piece-by-piece review</h2>\n<pre><code>if __name__ == '__main__':\n</code></pre>\n<p>The Python convention is to <strong>extract everything that follows into a function</strong>, enabling you to better organize your code. This allows you to call functions defined further down rather than only ones defined above.</p>\n<pre><code> parser = ArgumentParser(description=__doc__)\n parser.add_argument('-v',\n '--verbose',\n help='verbose output.',\n action='store_true')\n parser.add_argument('-r',\n '--recursive',\n help='use the recursive backtracking algorithm.',\n action='store_true')\n parser.add_argument('-i',\n '--input',\n help='read from given file instead of stdin.',\n action='store')\n args = parser.parse_args()\n</code></pre>\n<p>This arg-parsing code should be extracted as a function that <a href=\"http://blog.codinghorror.com/curlys-law-do-one-thing/\" rel=\"nofollow noreferrer\"><strong>does one thing, does it well, and does it only</strong></a>.</p>\n<pre><code> instance = None\n if args.input:\n with open(args.input, 'r') as file:\n instance = SATInstance.from_file(file)\n else:\n instance = SATInstance.from_file(stdin)\n\n alg = recursive_sat.solve if args.recursive else iterative_sat.solve\n</code></pre>\n<p>If you read the <a href=\"https://docs.python.org/3.4/library/argparse.html#action\" rel=\"nofollow noreferrer\"><code>argparse</code> documentation</a> more carefully, you will notice that you are not using its full capabilities. You can simplify this part of your program considerably if you let the <code>ArgumentParser</code> store the appropriate implementation of your algorithm directly. It can also handle the optional input file opening for you, falling back to <code>stdin</code> if none is supplied.</p>\n<pre><code> for assignment in alg(instance, args.verbose):\n print(instance.assignment_to_string(assignment))\n else:\n if args.verbose:\n print('No satisfying assignment exists.', file=stderr)\n</code></pre>\n<p>The <code>else</code> branch of this <code>for</code> loop <a href=\"https://stackoverflow.com/a/114420/1106367\">does not do what you think it does</a>, so <strong>here's your bug</strong>:</p>\n<blockquote>\n<p>Your program will <em>always</em> print the error message because the <code>else</code> branch of a <code>for</code> loop is always executed unless a <code>break</code> statement terminates the loop.</p>\n</blockquote>\n<h1>Improved code</h1>\n<pre><code>def main():\n args = parse_args()\n with args.input as file:\n instance = SATInstance.from_file(file)\n result = args.algorithm.solve(instance, args.verbose)\n for assignment in result:\n print(instance.assignment_to_string(assignment))\n if not result and args.verbose:\n print('No satisfying assignment exists.', file=stderr)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('-v', '--verbose',\n help='verbose output.',\n action='store_true')\n parser.add_argument('-r', '--recursive',\n help='use the recursive backtracking algorithm.',\n action='store_const',\n dest='algorithm',\n const=recursive_sat,\n default=iterative_sat)\n parser.add_argument('-i', '--input',\n help='read from given file instead of stdin.',\n type=argparse.FileType(), # opens the supplied file\n default=stdin)\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:23:19.260", "Id": "82996", "Score": "0", "body": "This is great, thank you. Just one subtle correction to your suggestion: `type=FileType()` should be `type=FileType` without the `()` since otherwise it will throw an exception saying `FileType` requires one parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T00:11:43.020", "Id": "83079", "Score": "0", "body": "On second thought, I realized you had `argparse.FileType` in mind, whereas my first thought was that it was `types.FileType`, which is the only `FileType` I knew about! With `argparse.FileType` you need the `()`. So your code is correct for Python 2 as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T00:15:06.993", "Id": "83080", "Score": "1", "body": "@Sahand ah, that makes sense. Sorry for the confusion, I should have included the full name." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T06:53:32.210", "Id": "47327", "ParentId": "47312", "Score": "3" } } ]
{ "AcceptedAnswerId": "47327", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T02:27:27.650", "Id": "47312", "Score": "3", "Tags": [ "python" ], "Title": "Simple SAT Solver In Python" }
47312
<p>I'd like to know if there's any better way to write this query:</p> <pre><code>(from a in Context.Pages join b in Context.Visitors on a.PageID equals b.PageFK join c in Context.Visits on b.VisitorID equals c.VisitorFK join d in Context.Signups on c.VisitID equals d.VisitFK where d.DateOptinUtc.HasValue &amp;&amp; a.UserFK == USER_ID group d by new { a.PageID, a.DateCreated, a.BaseName, a.Name } into g select new ListReport { DateCreated = g.Key.DateCreated, BaseName = g.Key.BaseName, Id = g.Key.PageID, Name = g.Key.Name, Optins = g.Count(), Views = (from h in Context.Visits where h.Visitors.PageFK == g.Key.PageID select h).Count() }).AsQueryable(); </code></pre> <p>Are there any performance issues writing subqueries like these? I don't how I can get that value from the groupby.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:46:49.693", "Id": "82891", "Score": "2", "body": "Doesn't necessarily look bad. What does the generated SQL look like? EF may have optimized this pretty well and the database's query optimizer may further optimize it. Is there a performance problem at all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T12:13:49.317", "Id": "82934", "Score": "0", "body": "There is no performance problem atm as we are in development stage. I was just curious / want to know it there was a better way. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T12:38:56.003", "Id": "82940", "Score": "0", "body": "A (micro) optimization might be to collect the page counts separately and join these in memory with your query." } ]
[ { "body": "<p>Aside from the performance issues you should make the query more readable by using relevant variable names instead of <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>g</code>, and <code>h</code>. In addition, the ambiguous <code>ListReport</code> class name should be changed to something more specific like <code>PageUsage</code> since it contains information about a page and how many times it has been viewed/used for signup.</p>\n\n<pre><code>(from page in Context.Pages\njoin visitor in Context.Visitors on page.PageID equals visitor.PageFK\njoin visit in Context.Visits on visitor.VisitorID equals visit.VisitorFK\njoin signup in Context.Signups on visit.VisitID equals signup.VisitFK\nwhere\nsignup.DateOptinUtc.HasValue &amp;&amp; page.UserFK == USER_ID\ngroup signup by new { page.PageID, page.DateCreated, page.BaseName, page.Name }\ninto signupsByPage\nselect\nnew PageUsage\n {\n DateCreated = signupsByPage.Key.DateCreated,\n BaseName = signupsByPage.Key.BaseName,\n Id = signupsByPage.Key.PageID,\n Name = signupsByPage.Key.Name,\n Optins = signupsByPage.Count(),\n Views =\n (from subVisit in Context.Visits\n where\n subVisit.Visitors.PageFK == signupsByPage.Key.PageID\n select subVisit).Count()\n }).AsQueryable();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:51:06.467", "Id": "83196", "Score": "0", "body": "Is there a way to modify this query to bring every record on table Pages? I tried to use defaultifempty thing but did not work as expected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:07:03.960", "Id": "83200", "Score": "0", "body": "It worked now but if i use any where clause using signup it stops working" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:09:04.160", "Id": "47473", "ParentId": "47314", "Score": "1" } } ]
{ "AcceptedAnswerId": "47473", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T03:33:04.753", "Id": "47314", "Score": "1", "Tags": [ "c#", "beginner", "entity-framework" ], "Title": "Group By And Two Counts" }
47314
<p>I've created a Java class, <code>Date</code>, in which I basically create date strings and set dates. Is there anything I can do besides adding comments to improve/shorten my code? </p> <p>I've tested all of my methods to see if they work correctly, and they all work as planned. I haven't done tests that force the <code>IllegalArgumentsException</code> to be thrown yet though.</p> <p>I've tried changing the instantiated <code>boolean</code> variable <code>shortDisplay</code> have a default value of true, which has made my program work correctly as far as I know.</p> <p>I'm assuming when you declare a <code>boolean</code> instance variable, you need to also declare what its default value should be, otherwise issues arise. If anyone could comment on why that is, that would be great.</p> <p><strong>Date.java</strong></p> <pre><code>public class Date { private int year; private int month; private int day; private boolean shortDisplay = true; public Date() { setDate(2000, 01, 01); } public Date(int yy, int mm, int dd) { setDate(yy, mm, dd); } public Date(int yy, int mm) { setDate(yy, mm); } public Date(int yy) { setDate(yy); } public Date(Date otherDate) { setDate(otherDate); } public Date(String dateStr) { setDate(dateStr); } public void setDate(int yy, int mm, int dd) { setYear(yy); setMonth(mm); setDay(dd); } public void setDate(int yy, int mm) { setYear(yy); setMonth(mm); setDay(1); } public void setDate(int yy) { setYear(yy); setMonth(1); setDay(1); } public void setDate(Date otherDate) { int yy = getYear(); int mm = getMonth(); int dd = getDay(); setYear(yy); setMonth(mm); setDay(dd); } public void setDate(String dateStr) { int length = dateStr.length(); int indexCount = 0; if (length &gt;= 0) { // basically checking to see if the date even exists if (dateStr.indexOf('/') &gt;= 0) { int index = dateStr.indexOf('/'); indexCount++; String dd = dateStr.substring(index+1, dateStr.length()); if (dd.substring(1, dd.length()).lastIndexOf('/') &gt;= 0 ) { int index2 = dd.lastIndexOf('/'); indexCount++; String yy = dd.substring(index2+1, dd.length()); if (yy.lastIndexOf('/') &gt;= 0) { indexCount++; } String mm = dateStr.substring(0, index); dd = dd.substring(0, index2); yy = yy.substring(0, yy.length()); System.out.println(mm + "\n" + dd + "\n" + yy ); int y = Integer.parseInt(yy); int d = Integer.parseInt(dd); int m = Integer.parseInt(mm); setYear(y); setMonth(m); setDay(d); } } } } public void setYear(int yy) { if (yy &gt;= 1900) { year = yy; } else { throw new IllegalArgumentException("lol"); } } public void setMonth(int mm) { if (mm &gt;= 1 &amp;&amp; mm &lt;= 12) { month = mm; } else { throw new IllegalArgumentException("not cool"); } } public void setDay(int dd) { if (dd &gt;= 1 &amp;&amp; dd &lt;= 31) { day = dd; } else { throw new IllegalArgumentException("stupid"); } } public int getYear() { return year; } public int getMonth() { return month; } public int getDay() { return day; } public void setShortDisplay() { shortDisplay = true; } public void setLongDisplay() { shortDisplay = false; } public boolean isShortDisplay() { if (shortDisplay) { return true; } else { return false; } } public void incrementDay() { day++; if (day &gt; 31) { day = 1; incrementMonth(); } } public void incrementMonth() { month++; if (month &gt; 12) { month = 1; incrementYear(); } } public void incrementYear() { year++; } public boolean equals(Object other) { Date that = (Date) other; if (this.day == that.day &amp;&amp; this.month == that.month &amp;&amp; this.year == that.year) { return true; } else { return false; } } public boolean before(Date otherDate) { Date that = otherDate; if (this.year &lt; that.year) return true; if (this.month &lt; that.month) return true; if (this.day &lt; that.day) return true; else return false; } public String toString() { boolean check = isShortDisplay(); if (check) { if (month &lt; 10 &amp;&amp; day &lt; 10) { return "0" + month + "/" + "0" + day + "/" + year; } if (month &lt; 10 &amp;&amp; day &gt; 10) { return "0" + month + "/" + day + "/" + year; } if (month &gt; 10 || day &lt; 10) { return month + "/" + "0" + day + "/" + year; } else { return month + "/" + day + "/" + year; } } else { return monthString(month) + " " + day + ", " + year; } } public static String monthString(int month) { if (month &gt;= 1 &amp;&amp; month &lt;= 12) { String[] stringMonth = {"", "January", "February", "March", "April", "June", "July", "August", "September", "October", "November", "December"}; return stringMonth[month]; } else { throw new IllegalArgumentException(); } } } </code></pre> <p><strong>DateTest.java</strong></p> <pre><code>public class DateTest { public static void main(String[] args) { // TODO Auto-generated method stub Date d = new Date(2013, 4, 9); System.out.println(d); d.setLongDisplay(); System.out.println(d); Date d1 = new Date(); if (!d1.toString().equals("01/01/2000")) { System.out.println("Error 1"); } d1.setDate("4/8/2013"); if (!d1.toString().equals("04/08/2013")) { System.out.println("Error 2"); } d1.setDay(28); for (int i = 0; i&lt;5; i++) { d1.incrementDay(); } System.out.println(d1); if (!d1.toString().equals("05/02/2013")) { System.out.println("Error 3"); } } } </code></pre>
[]
[ { "body": "<ul>\n<li><strong>Your class does not handle months with less than 31 days, in-real-life-speaking your unit test for adding five days to 28th April is already wrong</strong></li>\n<li><code>stringMonth</code> can be left as a <code>private static final</code> array, so that you are not re-creating it every time <code>monthString()</code> is called</li>\n<li><code>equals()</code> implementation does not check for null/class type, and by right you should have a corresponding <code>hashCode()</code> implementation too</li>\n<li><code>before()</code> can probably be better implemented as <code>compareTo()</code> if you can consider letting your class implement <code>Comparable</code></li>\n<li>There are better ways of formatting the <code>String</code> representation in <code>toString()</code> and parsing a <code>String</code> date in <code>setDate(String dateStr)</code></li>\n<li>Some Javadocs will be helpful too, especially to indicate the format that you are using in <code>toString()</code> (<code>\"MM/DD/YY\"</code>)</li>\n<li>Consider a proper testing framework such as JUnit or TestNG?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T05:34:41.257", "Id": "47319", "ParentId": "47316", "Score": "5" } }, { "body": "<p>Instead of putting print statements in the <code>main</code> method, it would be better to write proper unit tests. That way you don't have to read the output and understand if it's correct or not, the assertions will take care of that for you, so you can focus on just what fails after you changed something. For example using JUnit4:</p>\n\n<pre><code>public class DateTest {\n @Test\n public void testShortAndLongDisplay() {\n Date d = new Date(2013, 4, 9);\n Assert.assertEquals(\"04/09/2013\", d.toString());\n d.setLongDisplay();\n Assert.assertEquals(\"April 9, 2013\", d.toString());\n }\n\n @Test\n public void testSetDate() {\n Date d1 = new Date();\n Assert.assertEquals(\"01/01/2000\", d1.toString());\n\n d1.setDate(\"4/8/2013\");\n Assert.assertEquals(\"04/08/2013\", d1.toString());\n }\n\n @Test\n public void testIncrementDay() {\n Date d1 = new Date(2013, 4, 28);\n Assert.assertEquals(\"04/28/2013\", d1.toString());\n for (int i = 0; i &lt; 5; i++) {\n d1.incrementDay();\n }\n Assert.assertEquals(\"05/02/2013\", d1.toString());\n }\n}\n</code></pre>\n\n<hr>\n\n<p>There is a bug in the <code>before</code> method, as it fails this unit test (the second assert):</p>\n\n<pre><code>@Test\npublic void testBefore() {\n Date d1 = new Date(2013, 4, 28);\n Date d2 = new Date(2013, 5, 27);\n Assert.assertTrue(d1.before(d2));\n Assert.assertFalse(d2.before(d1));\n}\n</code></pre>\n\n<hr>\n\n<p>Some problems in the <code>setDate</code> method:</p>\n\n<ul>\n<li><code>indexCount</code> is incremented but never used</li>\n<li>You should not print things in code with <code>System.out.println</code>. You might want to use a <code>Logger</code> instead.</li>\n</ul>\n\n<hr>\n\n<p>If you don't plan to create sub-classes of this one, then it's better to access <code>shortDisplay</code> directly within the class instead of the <code>isShortDisplay</code> accessor. But if you do plan sub-classes then never mind.</p>\n\n<hr>\n\n<p>This can be simplified:</p>\n\n<blockquote>\n<pre><code>public boolean isShortDisplay() {\n if (shortDisplay) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Since <code>shortDisplay</code> is a boolean variable, you can simply return it:</p>\n\n<pre><code>public boolean isShortDisplay() {\n return shortDisplay;\n}\n</code></pre>\n\n<hr>\n\n<p>As others pointed out, the <code>equals</code> method doesn't check for null and class type. Also, the if-else there can be simplified:</p>\n\n<pre><code>@Override\npublic boolean equals(Object obj) {\n if (obj instanceof Date) {\n Date that = (Date) obj;\n return this.day == that.day\n &amp;&amp; this.month == that.month\n &amp;&amp; this.year == that.year;\n }\n return false;\n}\n</code></pre>\n\n<p>It's also nice to explicitly add the <code>@Override</code> annotation when you're overriding a superclass method, just in case somebody reads the code (or a diff) outside a nice IDE.</p>\n\n<p>And when you implement an <code>equals</code> method, you should also implement a <code>hashCode</code> method to ensure consistency, how about:</p>\n\n<pre><code>@Override\npublic int hashCode() {\n return String.format(\"%02d/%02d/%04d\", day, month, year).hashCode();\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>setDate(2000, 01, 01);\n</code></pre>\n</blockquote>\n\n<p>IntelliJ gives me a warning about this, because <code>01</code> is an octal integer... Very cosmetic, but maybe you can just drop those zeros anyway....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:11:37.900", "Id": "82885", "Score": "0", "body": "\"because `01` is an octal integer\" Good catch, this means `08` wouldn't work. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:00:01.520", "Id": "83052", "Score": "0", "body": "I had the idea of returning something like what your `hashCode()` does, but I didn't know how to properly make that work. I haven't learned about using something like `String.format`, so I tried using `printf`. Also the `print` statements were there because I was having issues with grabbing the right numbers from a given string date, and so I used them to see what was being created. Thanks for all the tips." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T20:32:13.213", "Id": "83826", "Score": "0", "body": "@h.j.k. with the `equals()` method, shouldn't I also add another `else` statement to see if the variable is also of type `String` since one of my constructors takes in a variable of type `String`? If so, is it appropriate in my `Date` class to use on of the constructors inside another method, i.e. `Date that = new Date(other)` when `other` is a string?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T01:29:23.980", "Id": "83861", "Score": "1", "body": "@cbenn95 If you consult the Javadoc for `equals()` (http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals%28java.lang.Object%29), one of this method's property should be that it is symmetric, `x.equals(y) should return true if and only if y.equals(x)`. Since we can't possibly make a `String` object be equal to your `Date` object, you should not check for equality against `String` objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T01:32:26.987", "Id": "83862", "Score": "1", "body": "Furthermore, even if a `String test = \"20140422\"` does equal to a `Date temp = new Date(2014,4,22)` in non-programming terms, the way the hash code is calculated will be different between the two.\n\n\nIt is not a convention to compare equality across different classes. It may make some sense between parent and child classes or classes meant to be used internally/strictly according to some explicit assumptions, but that's about all I can think of." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T01:38:00.863", "Id": "83863", "Score": "0", "body": "@h.j.k. is there any way that I can take in the object and make a variable of type `Date` from the object when the object's type is `String`? The only reason I'm asking about this is because I can't seem to implement any of the ways I know of to get the method to do just that. In the sample execution of DateTest.java my teacher gave me, no errors occur. In mine, when it comes to comparing a string to a string created from the date, I always get a returned value of false. I know why, and it's because my program is using the `String.equals()` method and not `Date.equals()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T02:41:02.107", "Id": "83866", "Score": "0", "body": "@cbenn95 if that's the case, I'll prefer having a new static method e.g. `isEquivalentToString()` that internally creates a `Date` object from the `String` for the comparison you require. With all these being said, at the end of the day code is just code written for your assignment and requirements, so if it's required to support `String` comparison in the `equals()` method then that should be explicitly mentioned at least. I'll certainly be puzzled if I come across such an implementation without explanation though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T03:10:10.880", "Id": "83868", "Score": "0", "body": "@h.j.k. okay. Thanks for all the advice, it's certainly helped and I appreciate you taking time to help me out!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T06:52:19.137", "Id": "47326", "ParentId": "47316", "Score": "4" } }, { "body": "<p>I don't know why you want to write your own Date class. In Java you can use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Date.html\" rel=\"nofollow\">java.util.Date</a>, or <a href=\"http://docs.oracle.com/javase/6/docs/api/java/sql/Date.html\" rel=\"nofollow\">java.sql.Date</a> with <a href=\"http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow\">java.text.SimpleDateFormat</a>. If you need your own Date class, you can write for instance a wrapper class or write an Util class.</p>\n\n<p>Java Date API is ugly. In java 8 there is a new more usable date API. In earlier versions I recommend <a href=\"http://www.joda.org/joda-time/\" rel=\"nofollow\">Joda-Time</a> 3rd party library.</p>\n\n<h2>Review of Your code:</h2>\n\n<ol>\n<li><p><strong>Unit tests</strong>:\nThere are tools such as <a href=\"http://junit.org/\" rel=\"nofollow\">JUnit</a> or <a href=\"http://testng.org/doc/index.html\" rel=\"nofollow\">TestNG</a> to test your code. This way you can write more reusable, simpler, easy-to-use, automated tests. The real unit tests help your work, for instance you can describe the the expected behaviour in a more proper way.</p></li>\n<li><p><strong>Your Date class</strong>:</p>\n\n<ul>\n<li><p><strong>Constructors</strong>\nThere are a lot of constructors with different number of parameters. You can \"embed\" them with the <code>this(...)</code> method. For example:</p>\n\n<pre><code>public Date() {\n// setDate(2000, 01, 01);\n this(2000, 1, 1);\n}\n</code></pre></li>\n<li><p><strong>Setters</strong></p>\n\n<ul>\n<li>The <code>setDate(...)</code> methods can invoke each similar as I wrote in the constructor section.</li>\n<li><p>The <code>setDate(Date otherDate)</code> method is not working now. It's setting the owned values now. Instead of you can use:</p>\n\n<pre><code>public void setDate(final Date otherDate) {\n year = otherDate.year;\n month = otherDate.month;\n day = otherDate.day;\n}\n</code></pre></li>\n<li><p>The <code>setDay(...)</code>, <code>setYear(...)</code>, <code>setMonth(...)</code> methods are invoked in the class for example in the constructors or in other setters. <em>Robert Cecil Martin: Clean Code</em> says: One Level of Abstraction per Function in Chapter 3: functions. So you can separate the validating from the setters for example this way:</p>\n\n<pre><code>private static final int MINIMUM_YEAR = 1900;\n\npublic void setYear(final int year) {\n this.year = checkYear(year);\n}\n\npublic int checkYear(final int year) {\n if (year &gt;= MINIMUM_YEAR) {\n return year;\n }\n\n throw new IllegalArgumentException(\"The year must be greater than \" + MINIMUM_YEAR);\n}\n</code></pre>\n\n<p>Here 1900 was a \"magic number\", you should name it for increase readability.\nYou should name your variables what they exactly. <code>yy</code> is ok in a date format, but as a variable it's exactly a year. Don't mind if it's hiding a field, in Java you can access your fields through <code>this.</code>. For example <code>this.year</code>.</p></li>\n<li>The <code>setDate(String dateStr)</code> method is so unreadable and splitting string with indexOf is so hard. You can use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29\" rel=\"nofollow\">String.split(...)</a> for example to get the values.\n<ul>\n<li>The <code>dateAsString</code> name is more readable than <code>dateStr</code>.</li>\n<li>The <code>indexCount</code> variable is not used so you can remove it.</li>\n<li>As Joshua Bloch's Effective Java says: Whenever possible use final variables. This minimize the scope of local variables.</li>\n</ul></li>\n<li>Your <code>setDate(...)</code> methods of your <strong>Date</strong> class has tricky name, because in proper way one setter sets one field. So the year, month, day field trio represents the date here. It's not a main problem, but decreasing the code's readability.</li>\n</ul></li>\n<li><code>monthString(int month)</code>\nYou should use a private <code>static array</code> or an <code>enum class</code>, to don't redefine the mounts on every invocation.</li>\n</ul></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T09:28:32.860", "Id": "47449", "ParentId": "47316", "Score": "2" } } ]
{ "AcceptedAnswerId": "47319", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T03:44:09.207", "Id": "47316", "Score": "6", "Tags": [ "java", "object-oriented", "datetime" ], "Title": "Creating date strings and setting dates" }
47316
<pre><code>int number; DateTime dateTime; using (var oracleConnection = new OracleConnection(ConnectionString)) using (var oracleCommand = oracleConnection.CreateCommand()) { oracleConnection.Open(); oracleCommand.CommandText = "SELECT * FROM FROM MY_TABLE"; using (var reader = oracleCommand.ExecuteReader()) { while (reader.Read()) { number = reader.GetInt32(0); dateTime = reader.GetDateTime(1); } } } </code></pre> <p>Which is a better way to avoid the calls such as <code>reader.GetInt32(0)</code>?</p> <p>This way is too hard to read. A better way would be something like <code>reader.GetInt32("ID")</code> or <code>reader.GetDateTime("Begin")</code>, where <code>ID</code> and <code>Begin</code> are column names.</p> <p>Or should I use enums?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-28T20:23:12.320", "Id": "173280", "Score": "0", "body": "The desire to improve code is implied for all questions on this site. Question titles should reflect the purpose of the code, not how you wish to have it reworked. See [ask]." } ]
[ { "body": "<p>A few comments:</p>\n<h3>Exceptions:</h3>\n<p>Keep in mind, even with using-statements, exceptions can happen. Make sure to catch them. I'd suggest, you wrap the whole snippet in a try-catch-block if that didn't happen already.</p>\n<h3>Types:</h3>\n<p>Why are you using the dynamyic type? Make it easier for readers and yourself by using the correct type. For yourself? Yes, if you use the explicit type, you get way better IntelliSense proposals.</p>\n<h3>Accessing:</h3>\n<p>reading a bit through the <a href=\"http://msdn.microsoft.com/de-de/library/system.data.oracleclient.oracledatareader(v=vs.110).aspx\" rel=\"noreferrer\">msdn documentation for OracleDataReader</a> I found, that there is a property for the reader, named <code>Item</code> with 2 overloads. One being <code>Item[String]</code>.</p>\n<p>It seems they return the Column Value &quot;in it's native format&quot;.</p>\n<pre><code>using (OracleDataReader reader = oracleCommand.ExecuteReader())\n{\n while (reader.Read())\n {\n number = reader.Item[&quot;ID&quot;];\n dateTime = reader.Item[&quot;Begin&quot;]; \n }\n}\n</code></pre>\n<p><strong>Update:</strong><br />\n@Sandeep claims that the return type is in fact <code>Object</code>. If that is the case, you will have to run a conversion: <code>number = Convert.ToInt32(reader.Item[&quot;ID&quot;]);</code></p>\n<p>Furthermore it seems that <code>reader.Item[index]</code> can actually be replaced by <code>reader[index]</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:44:29.333", "Id": "47331", "ParentId": "47322", "Score": "6" } }, { "body": "<p>One way to use an IDataReader's nice GetX methods is to start off by retrieving the indexes with GetOrdinal calls:</p>\n\n<pre><code>using (var reader = oracleCommand.ExecuteReader())\n{\n var ord_id = reader.GetOrdinal(\"ID\");\n var ord_date = reader.GetOrdinal(\"Begin\");\n\n while (reader.Read())\n {\n number = reader.GetInt32(ord_id);\n dateTime = reader.GetDateTime(ord_date);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:22:50.363", "Id": "47373", "ParentId": "47322", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T06:38:23.700", "Id": "47322", "Score": "3", "Tags": [ "c#", ".net", "oracle" ], "Title": "C# with Oracle ODP.NET" }
47322
<p>I have written a very XNA spritebatch like interface for drawing sprites in OpenGL. When begin is called the vertex data buffer is mapped to a float*. The index buffer and vertex buffer are bound in begin, and it's assumed no other drawing is done in this OpenGL context between begin and end. In between begin and end, <code>DrawSprite</code> is called. <code>DrawSprite</code> has a bunch of overloads allowing one to draw with a scale, and matrix, a source rectangle etc. However, they all take their parameters and call <code>BufferSprite</code> which actually writes the sprite data to memory (the x,y,z position, the x,y texture coordinates, and the rgba colour values.) When end is called, the vertices are drawn in as few <code>glDrawElements</code> calls as possible. </p> <p>Here is Begin:</p> <pre><code>// // Begin // Sets up the buffer for drawing. // void Nixin::Canvas::SpriteBuffer::Begin( ShaderProgram&amp; spriteShader ) { // Check that two begins have not been called without an end. if( hasBegun ) { Debug::FatalError( "Begin was called twice before an end." ); } hasBegun = true; shader = &amp;spriteShader; spriteDataBuffer.Bind(); spriteIndexBuffer.Bind(); // Bind the sprite buffer. mappedData = spriteDataBuffer.Map&lt;float&gt;(); } </code></pre> <p>Here is buffer sprite:</p> <pre><code>// // BufferSprite // Transforms a sprite, and defines the texture source. Once this is done, the sprite is buffered and is ready for drawing. // void Nixin::Canvas::SpriteBuffer::BufferSprite( const Texture&amp; texture, const Rectangle&amp; spriteBounds, const Point&amp; scale, const float rotation, const Colour&amp; tint, const Rectangle&amp; sourceBounds, const Point&amp; origin, const bool matrix, const Matrix&amp; inModelView ) { Point v1; Point v2; Point v3; Point v4; if( !hasBegun ) { Debug::FatalError( "Begin must be called before drawing a sprite." ); } // Check if we have reached the current sprite max. If so, wait for the end of the frame to draw them. // This is a compromise. We can't increase the sprite max mid-frame as that would clear all the currently // buffered sprites, so we just avoid drawing them until next frame. if( CheckSpriteBufferSize() ) { if( !matrix ) { float cosz = cos( ToRadians( rotation ) ); float sinz = sin( ToRadians( rotation ) ); modelView.SetDataAt( 0, 0, cosz * scale.x ); modelView.SetDataAt( 0, 1, -sinz * scale.x ); modelView.SetDataAt( 0, 3, spriteBounds.x ); modelView.SetDataAt( 1, 0, sinz * scale.y ); modelView.SetDataAt( 1, 1, cosz * scale.y ); modelView.SetDataAt( 1, 3, spriteBounds.y ); modelView.SetDataAt( 2, 0, 0 ); modelView.SetDataAt( 2, 1, 0 ); modelView.SetDataAt( 2, 3, 1.0f ); v1 = Point::Multiply( Point( -origin.x, -origin.y, 1.0f ), modelView ); v2 = Point::Multiply( Point( spriteBounds.width - origin.x, -origin.y, 1.0f ), modelView ); v3 = Point::Multiply( Point( -origin.x, spriteBounds.height - origin.y, 1.0f ), modelView ); v4 = Point::Multiply( Point( spriteBounds.width - origin.x, spriteBounds.height - origin.y, 1.0f ), modelView ); } else { v1 = Point::Multiply( Point( -origin.x, -origin.y, origin.z ), inModelView ); v2 = Point::Multiply( Point( spriteBounds.width - origin.x, -origin.y, origin.z ), inModelView ); v3 = Point::Multiply( Point( -origin.x, spriteBounds.height -origin.y, origin.z ), inModelView ); v4 = Point::Multiply( Point( spriteBounds.width - origin.x, spriteBounds.height - origin.y, origin.z ), inModelView ); } // Copy the vertex data into it's location in the mapped data pointer. int offset = sprites.size() * 12; mappedData[offset] = v1.x; mappedData[offset + 1] = v1.y; mappedData[offset + 2] = v1.z; mappedData[offset + 3] = v2.x; mappedData[offset + 4] = v2.y; mappedData[offset + 5] = v2.z; mappedData[offset + 6] = v3.x; mappedData[offset + 7] = v3.y; mappedData[offset + 8] = v3.z; mappedData[offset + 9] = v4.x; mappedData[offset + 10] = v4.y; mappedData[offset + 11] = v4.z; // Do the same for the texture coordinates. Here we add the max sprite count * 8, because the texture coordinate // data is stored after all the vertex data. offset = sprites.size() * 8 + ( maxSpriteCount ) * 12; mappedData[offset] = sourceBounds.x / texture.GetWidth(); mappedData[offset + 1] = ( sourceBounds.height + sourceBounds.y ) / texture.GetHeight(); mappedData[offset + 2] = ( sourceBounds.width + sourceBounds.x ) / texture.GetWidth(); mappedData[offset + 3] = ( sourceBounds.height + sourceBounds.y ) / texture.GetHeight(); mappedData[offset + 4] = sourceBounds.x / texture.GetWidth(); // Texture coordinates are defined by the triangle( srcPosition, srcSize ) mappedData[offset + 5] = sourceBounds.y / texture.GetHeight(); mappedData[offset + 6] = ( sourceBounds.width + sourceBounds.x ) / texture.GetWidth(); mappedData[offset + 7] = sourceBounds.y / texture.GetHeight(); // Save the sprite's colour. offset = sprites.size() * 16 + ( maxSpriteCount ) * 20; mappedData[offset] = tint.r; mappedData[offset + 1] = tint.g; mappedData[offset + 2] = tint.b; mappedData[offset + 3] = tint.a; mappedData[offset + 4] = tint.r; mappedData[offset + 5] = tint.g; mappedData[offset + 6] = tint.b; mappedData[offset + 7] = tint.a; mappedData[offset + 8] = tint.r; mappedData[offset + 9] = tint.g; mappedData[offset + 10] = tint.b; mappedData[offset + 11] = tint.a; mappedData[offset + 12] = tint.r; mappedData[offset + 13] = tint.g; mappedData[offset + 14] = tint.b; mappedData[offset + 15] = tint.a; // Add the sprite object. sprites.emplace_back( texture.GetID(), sprites.size() ); } } </code></pre> <p>And here is End:</p> <pre><code>// // End // void Nixin::Canvas::SpriteBuffer::End( Canvas&amp; canvas ) { // Check for validity of end call. if( !hasBegun ) { Debug::FatalError( "End was called before begin." ); } // Unmap the buffer data pointer, because we're about to draw with it. spriteDataBuffer.Unmap(); // Use custom shader. glUseProgram( shader-&gt;GetID() ); // Set the projection matrix, and vertex attributes in the shader. shader-&gt;SetUniformMatrix( "projection", canvas.camera.GetProjectionMatrix() ); shader-&gt;SetVertexAttributePointer( "vertexPosition", 3, Texture::DataType::FLOAT, 0, 0 ); shader-&gt;SetVertexAttributePointer( "texCoords", 2, Texture::DataType::FLOAT, 0, 12 * maxSpriteCount * sizeof( float ) ); shader-&gt;SetVertexAttributePointer( "tint", 4, Texture::DataType::FLOAT, 0, 20 * maxSpriteCount * sizeof( float ) ); // Sort sprites. if( spriteSortMode != SpriteSortMode::NO_SORTING ) { // Prepared for drawing. SortSprites(); OrderIndices(); } if( drawingMode == SpriteDrawingMode::DEPTH_TESTED ) { canvas.EnableDepthTesting(); } // This will be the total number of sprites draw. int count = 0; // While we haven't drawn all the sprites. while( count &lt; sprites.size() ) { // We assume that at least one sprite is going to be drawn this loop. int drawCount = 1; // Set the texture sampler. shader-&gt;SetSampler2D( "spriteTexture", 0, sprites[count].texture ); // We step through the buffer, looking for a change in texture. If we find one, then take all the sprites that are next to each, that also have the same texture. for( int i = count + 1; i &lt; sprites.size(); i++ ) { if( sprites[count].texture == sprites[i].texture ) { drawCount++; } else { break; } } // Finally, draw this group of sprites. glDrawRangeElements( GL_TRIANGLES, NULL + count * indicesPerSprite * sizeof( unsigned int ), NULL + count * indicesPerSprite * sizeof( unsigned int ) + indicesPerSprite * drawCount, indicesPerSprite * drawCount, GL_UNSIGNED_INT, ( GLvoid* )( NULL + count * indicesPerSprite * sizeof( unsigned int ) ) ); // Increase the number of sprites drawn. count += drawCount; } if( drawingMode == SpriteDrawingMode::DEPTH_TESTED ) { canvas.DisableDepthTesting(); } // Check if the sprite buffer needs to grow. if( growNextEnd ) { Grow( 2.0f ); // Set this to false, as the growing is complete. growNextEnd = false; } else { //glInvalidateBufferData( spriteBuffer-&gt;spriteDataBufferLocation ); spriteDataBuffer.BufferData( nullptr, sizeof( float ) * 36 * maxSpriteCount, VBufferAccess::STREAM_DRAW ); } // Clear the sprite list. sprites.clear(); // No longer drawing. hasBegun = false; } </code></pre> <p>I know it's a lot, but I'd appreciate it if someone could help me make this faster. If there is only one texture begin drawn over and over again in release mode, I get about 60FPS for about 33k sprites( The SAME texture ). This only gets worse as I interleave textures. I've done a bit of profiling and omitting code, and it looks to me like <code>BufferSprite</code> is taking the most time by far. I'd just like to know if there's anything obvious I'm not doing right, such as writing to the buffer in a poor way, or maybe I should be uploading different data to the shader.</p> <p>Also, I realise a lot of OpenGL stuff in this is wrapped in my own classes, so if you need any specific source code I'll edit this post.</p> <p>Also, the computer I'm testing this on has a Intel Core Quad Q8200 @ 2.33GHz, and a AMD Radeon HD 6850.</p> <p>EDIT: Sleepy profile times:</p> <p><img src="https://i.stack.imgur.com/ODKBO.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/99XkK.png" alt="enter image description here"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T11:38:20.453", "Id": "83626", "Score": "0", "body": "I don't have any answers, but is it worth breaking down BufferSprite into smaller functions (temporarily) so you can profile the separate parts of it to identify which part is slow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T09:34:15.287", "Id": "84117", "Score": "0", "body": "@githubphagocyte Thanks for the reply. I believe the profiler shows me the time per line. Edited with profile images." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T14:56:45.113", "Id": "84157", "Score": "1", "body": "C++? It looks like C#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T19:58:52.090", "Id": "84223", "Score": "0", "body": "@no1 Uhhh...It's c++, dude." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-03T17:19:56.333", "Id": "85790", "Score": "0", "body": "Take a look at http://xnatoolkit.codeplex.com/ it has the XNA spritebatch ported to C++ by a Microsoft employe who was previously on the XNA team." } ]
[ { "body": "<p>I would avoid the testing for calling <code>Begin</code> and <code>End</code> appropriately by creating a separate class that does the <code>begin</code> actions during construction and the <code>end</code> actions during destruction.</p>\n\n<p>As for speeding up the code, I think the first real step is to clarify the code a bit so it's easier to see what's really going on and what's needed. Just for example, you have:</p>\n\n<pre><code> for( int i = count + 1; i &lt; sprites.size(); i++ )\n {\n if( sprites[count].texture == sprites[i].texture )\n {\n drawCount++;\n }\n else\n {\n break;\n }\n }\n</code></pre>\n\n<p>It looks like this could be rewritten to use <code>std::find_if</code> instead, and end up quite a bit simpler and more readable.</p>\n\n<p><strike>\n if (sprites.end() != std::find_if(sprites.begin()+count=1, sprites.end(), \n [](sprite const &amp;a, sprite const &amp;b) { return a.texture == b.texture; }))\n ++drawCount;\n</strike></p>\n\n<p>[Actually, re-reading, that's wrong--the idea's correct, but I misunderstood your code a little bit, and translated it incorrectly.]</p>\n\n<p>The obvious next step to take would be to avoid the linear search for the texture for every sprite. You haven't shown enough of the rest of the system to see an obvious way to do that, but chances seem pretty decent that you can probably avoid it.</p>\n\n<p>Looking at the OpenGL part, I don't see an <em>obvious</em> way to improve performance a lot. You're already using <code>glDrawRangeElements</code> to draw all the sprites in one call. I suppose you might be able to switch from GL_TRIANGLES to something like GL_TRIANGLE_FAN or GL_TRIANGLE_STRIP to reduce the number of vertices you use, but 1) I didn't try to look at the code carefully enough to be sure you can use those, and 2) even if you can, it probably won't make a huge difference anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T03:08:03.237", "Id": "84746", "Score": "0", "body": "Thanks for the answer. I don't think using GL_TRIANGLE_FAN or GL_TRIANGLE_STRIP would be possible. Each triangle is separate from all others. If I had a separate object that does begin and end, how would that remove the testing that must be done in BufferSprite? It'll still need to check if the object's constructed right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T03:43:09.187", "Id": "84748", "Score": "0", "body": "@Ben: No--you pass it an object. The only way the object can exist is if it has been constructed. If somebody wants to badly enough, they can can use a cast to get around it and pass garbage, but there's not much you can do to stop things like that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-26T21:04:14.270", "Id": "48270", "ParentId": "47325", "Score": "3" } } ]
{ "AcceptedAnswerId": "48270", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T06:50:12.163", "Id": "47325", "Score": "10", "Tags": [ "c++", "optimization", "c++11", "opengl", "graphics" ], "Title": "Sprite drawing class" }
47325
<blockquote> <p>Given a sorted array, return the 'closest' element to the input 'x'.</p> </blockquote> <p>I do understand the merits of unit testing in separate files, but I deliberately added it to the main method for personal convenience, so don't consider that in your feedback.</p> <p>I'm looking for request code review, optimizations and best practices.</p> <pre><code>public final class ClosestToK { private ClosestToK() { } /** * Given a sorted array returns the 'closest' element to the input 'x'. * 'closest' is defined as Math.min(Math.abs(x), Math.abs(y)) * * Expects a sorted array, and if array is not sorted then results are unpredictable. * * If two values are equi-distant then the greater value is returned. * * @param a The sorted array a * @return The nearest element */ public static int getClosestK(int[] a, int x) { int low = 0; int high = a.length - 1; while (low &lt;= high) { int mid = (low + high) / 2; // test lower case if (mid == 0) { if (a.length == 1) { return a[0]; } return Math.min(Math.abs(a[0] - x), Math.abs(a[1] - x)) + x; } // test upper case if (mid == a.length - 1) { return a[a.length - 1]; } // test equality if (a[mid] == x || a[mid + 1] == x) { return x; } // test perfect range. if (a[mid] &lt; x &amp;&amp; a[mid + 1] &gt; x) { return Math.min(Math.abs(a[mid] - x), Math.abs(a[mid + 1] - x)) + x; } // keep searching. if (a[mid] &lt; x) { low = mid + 1; } else { high = mid; } } throw new IllegalArgumentException("The array cannot be empty"); } public static void main(String[] args) { // normal case. int[] a1 = {10, 20, 30, 40}; assertEquals(30, getClosestK(a1, 28)); // equidistant int[] a2 = {10, 20, 30, 40}; assertEquals(30, getClosestK(a2, 25)); // edge case lower boundary int[] a3 = {10, 20, 30, 40}; assertEquals(10, getClosestK(a3, 5)); int[] a4 = {10, 20, 30, 40}; assertEquals(10, getClosestK(a4, 10)); // edge case higher boundary int[] a5 = {10, 20, 30, 40}; assertEquals(40, getClosestK(a5, 45)); int[] a6 = {10, 20, 30, 40}; assertEquals(40, getClosestK(a6, 40)); // case equal to int[] a7 = {10, 20, 30, 40}; assertEquals(30, getClosestK(a7, 30)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:20:18.663", "Id": "82887", "Score": "0", "body": "your 'closest' definition seems queer. Are you sure you didn't mean `Math.Min(Math.Abs(x-el[i])` where `i` is all elements of the array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:36:19.697", "Id": "82888", "Score": "0", "body": "yes thats what i meant" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T10:27:14.970", "Id": "82924", "Score": "1", "body": "Are values expected to be all different ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:00:47.860", "Id": "83324", "Score": "0", "body": "not sure what you mean ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-17T08:54:00.607", "Id": "240398", "Score": "0", "body": "May we have duplicate values in the array ? ie for i < j, do we have array[i] < array[j] or array[i] <= array[j] ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-17T09:40:06.623", "Id": "240414", "Score": "0", "body": "What is the expected result of `getClosestK` for an array `{0, 1}` and `x==100`...? If I can read your code correctly, it would return `199`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-19T12:51:55.273", "Id": "240834", "Score": "0", "body": "My suspicion proven true – your code is BROKEN. It returns `199` when seeking the value closest to `100` in the `{0, 1}` array – see [ideone 6ZGXnI](http://ideone.com/6ZGXnI)." } ]
[ { "body": "<p>Here's my solution which seems to work fine :</p>\n\n<pre><code>public static int getClosestK(int[] a, int x) {\n\n int low = 0;\n int high = a.length - 1;\n\n if (high &lt; 0)\n throw new IllegalArgumentException(\"The array cannot be empty\");\n\n while (low &lt; high) {\n int mid = (low + high) / 2;\n assert(mid &lt; high);\n int d1 = Math.abs(a[mid ] - x);\n int d2 = Math.abs(a[mid+1] - x);\n if (d2 &lt;= d1)\n {\n low = mid+1;\n }\n else\n {\n high = mid;\n }\n }\n return a[high];\n}\n</code></pre>\n\n<p>Here's the principle : the interval <code>[low, high]</code> will contain the closest element to <code>x</code> at any time. At the beginning, this interval is the whole array (<code>[low, high] = [0, length-1]</code>). At each iteration, we'll make it strictly smaller. When the range is limited to a single element, this is the element we are looking for.</p>\n\n<p>In order to make the range smaller, at each iteration, we'll consider <code>mid</code> the middle point of <code>[low, high]</code>. Because of the way <code>mid</code> is computed, <code>mid+1</code> is also in the range. We'll check if the closest value is at <code>mid</code> or <code>mid+1</code> and update <code>high</code> or <code>low</code> accordingly. One can check that the range actually gets smaller.</p>\n\n<p><em>Edit to answer to comments:</em></p>\n\n<p>As spotted by @Vick-Chijwani , this code doesn't handle perfectly the scenarios where an element appears multiple times in the input. One can add the following working tests to the code :</p>\n\n<pre><code> // case similar elements\n int[] a8 = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10};\n assertEquals(10, getClosestK(a8, 9));\n assertEquals(10, getClosestK(a8, 10));\n assertEquals(10, getClosestK(a8, 11));\n</code></pre>\n\n<p>but this one will fail :</p>\n\n<pre><code> int[] a9 = {1, 2, 100, 100, 101};\n assertEquals(3, getClosestK(a9, 2)); // actually returns 100\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-13T09:32:37.937", "Id": "239880", "Score": "0", "body": "What if `a[mid] == a[mid+1]`? I imagine you'd have to walk to the left or right until they are unequal, then proceed to compute `d1` and `d2`. But then you lose the worst-case `O(log n)` guarantee." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-13T19:18:47.720", "Id": "239975", "Score": "0", "body": "Hi @VickyChijwani, thanks for your feedback. I'm AFK for a few days but I'll try to think about it and let you know asap :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-13T19:21:25.930", "Id": "239976", "Score": "0", "body": "Thanks! No hurry. The idea of walking left and right that I suggested, seems to work well enough for my use-case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-17T09:15:14.523", "Id": "240407", "Score": "0", "body": "@VickyChijwani Everything seems to work fine. I've added an edit to my answer. Please let me know if you need more details. Basically, when 2 (consecutive) elements are equal, we have `d1 == d2` (which is equal to 0 if this is the element we where looking for) and we reduce the search range accordingly : `low = mid+1;`. Please let me know if you see an issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-17T09:30:21.473", "Id": "240411", "Score": "0", "body": "Your solution returns `100` for `a = [1, 2, 100, 100, 101]` and `x = 3`, which is incorrect. The reason is that, when `d1 == d2`, you don't have enough information to decide which half of the array to check next, so you must somehow make them unequal before proceeding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-17T09:35:51.580", "Id": "240412", "Score": "0", "body": "Ho I see! Now I understand why I asked OP \"are values expected to be all different ?\" 2 years ago. Thanks for the feedback, I'll edit my answer accordingly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-17T09:37:22.740", "Id": "240413", "Score": "0", "body": "Yes. I'd been using your solution in my production code for months, and I found this bug now after observing an erroneous case :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T10:47:23.640", "Id": "47341", "ParentId": "47328", "Score": "12" } }, { "body": "<p>Are you allowed to use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html\">java.util.Arrays.binarySearch</a> ? If you don't need to detect whether or not the array is sorted, this will give you the one or two closest elements quickly.</p>\n\n<pre><code>public static int getClosestK(int[] a, int x) {\n int idx = java.util.Arrays.binarySearch(a, x);\n if ( idx &lt; 0 ) {\n idx = -idx - 1;\n }\n\n if ( idx == 0 ) { // littler than any\n return a[idx];\n } else if ( idx == a.length ) { // greater than any\n return a[idx - 1];\n }\n\n return d(x, a[idx - 1]) &lt; d(x, a[idx]) ? a[idx - 1] : a[idx];\n}\n\nprivate static int d(int lhs, int rhs) {\n return Math.abs(lhs - rhs);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T11:25:44.113", "Id": "47344", "ParentId": "47328", "Score": "6" } }, { "body": "<p>Your solution is complex because you are trying to mix at least two different problems in a single algorithm. Sorry my examples are in C++, but I hope you get the algorithmic idea.</p>\n\n<p>Here is what a standard <a href=\"http://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"noreferrer\">binary search</a> looks like:</p>\n\n<pre><code>/**\n * \\brief Find the first non-zero element of an ordered array\n *\n * @param a array to search in\n * @param s offset to start searching from\n *\n * @return offset of the first non-zero element, \\e a.size() if none found\n */\ntemplate &lt;class A&gt;\nsize_t binary_search(const A&amp; a, size_t s = 0)\n{\n size_t from = s, to = a.size(), mid;\n while (from != to) {\n mid = (from + to) / 2;\n if (a[mid]) to = mid;\n else from = mid + 1;\n }\n return from;\n}\n</code></pre>\n\n<p>If <code>a</code> is in ascending order, you will need to find the position <code>pos</code> of its first element that is <em>greater than</em> <code>x</code>, i.e. substitute</p>\n\n<pre><code>a[mid] &gt; x\n</code></pre>\n\n<p>for <code>a[mid]</code>, where <code>x</code> can be made an additional input parameter:</p>\n\n<pre><code>template &lt;class A, class T&gt;\nsize_t binary_search(const A&amp; a, const T&amp; x, size_t s = 0)\n</code></pre>\n\n<p>(in a more generic design, <code>a</code> would really be a customizable <a href=\"http://en.wikipedia.org/wiki/Function_object\" rel=\"noreferrer\">function object</a> to be <em>called</em> by <code>a(mid)</code>).</p>\n\n<hr>\n\n<p>Having found <code>pos</code>:</p>\n\n<ul>\n<li>if <code>pos == 0</code> (all elements <code>&gt; x</code>), return <code>0</code> (this includes the case of <code>a</code> being empty);</li>\n<li>if <code>pos == a.size()</code> (not found; all elements <code>&lt;= x</code>), return <code>a.size() - 1</code> (last element);</li>\n<li>otherwise, return one of the two positions <code>pos - 1</code> and <code>pos</code> depending on which element of <code>a</code> is closer to <code>x</code>.</li>\n</ul>\n\n<p>That is:</p>\n\n<pre><code>template &lt;class A, class T&gt;\nsize_t find_closest(const A&amp; a, const T&amp; x)\n{\n size_t pos = binary_search(a, x);\n return pos == 0 ? 0 :\n pos == a.size() ? a.size() - 1 :\n x - a[pos - 1] &lt; a[pos] - x ? pos - 1 : pos;\n}\n</code></pre>\n\n<p>Note that due to known ordering, you don't need <code>Math.abs</code>. Also note that in case of ambiguities (equalities), this approach returns the rightmost possible position of all equivalent ones.</p>\n\n<p>This is clear, <code>O(log n)</code>, and does not mess with <code>Math.abs</code> or anything problem-specific during the critical search process. It separates the two problems.</p>\n\n<hr>\n\n<p>The <em>function object</em> approach could be</p>\n\n<pre><code>size_t pos = binary_search([&amp;](size_t p){return a[p] &gt; x;});\n</code></pre>\n\n<p>using a <a href=\"http://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B_.28since_C.2B.2B11.29\" rel=\"noreferrer\">lambda</a> in C++11, and leaving <code>binary_search</code> as originally defined, except for changing <code>a[mid]</code> to <code>a(mid)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-03T19:43:31.070", "Id": "154709", "Score": "0", "body": "I agree, this is much cleaner and clearer. The binary search algorithm should be abstracted away with the proper functor argument. (+1)\nHowever : template arguments are arguments and deserve proper names !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T11:25:53.050", "Id": "47345", "ParentId": "47328", "Score": "5" } }, { "body": "<p>A minor thing to consider is caching values you lookup, for example, in each step of your <code>while</code> you calculate <code>a.length - 1</code>, since this value does not change you could have create a <br><code>int last = a.length - 1;</code> which would make the following fractionally faster and more readable:</p>\n\n<pre><code> // test upper case &lt;- unfortunate choice of comment ? upper bound perhaps?\n if (mid == last) {\n return a[last];\n }\n</code></pre>\n\n<p>I would also consider caching <code>a[mid]</code> and <code>a[mid+1]</code> into well named variables.</p>\n\n<p>Finally, this:</p>\n\n<pre><code>if (a.length == 1) {\n return a[0];\n}\n</code></pre>\n\n<p>Belongs in front of the while loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T12:43:55.643", "Id": "47349", "ParentId": "47328", "Score": "3" } }, { "body": "<p>You should avoid undefined behaviour: you say </p>\n\n<blockquote>\n <p>Expects a sorted array, and if array is not sorted then results are unpredictable</p>\n</blockquote>\n\n<p>but humans make errors all the time and giving a random result if the user forgets to enter a sorted input is not nice.</p>\n\n<p>At the cost of some performance I would add (should be easy to translate into Java):</p>\n\n<pre><code>def is_sorted(array):\n for index, item in enumerate(array):\n if index != 0:\n item_before = array[index-1]\n if not item &gt;= item_before:\n return False\n return True\n</code></pre>\n\n<p>and in your function:</p>\n\n<pre><code>if not is_sorted(array):\n raise IllegalArgumentException(\"Array is not sorted.\")\n</code></pre>\n\n<p>If you really care about speed you can add a flag <code>insecure</code> so that when the user wants full speed and knows what he's doing the check can be skipped.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-03T15:17:30.830", "Id": "85792", "ParentId": "47328", "Score": "3" } }, { "body": "<p>+1 for @Josay's answer. In case the array <code>a</code> can contain equal entries, please consider this slight improvement:</p>\n\n<pre><code>public static int getClosestK(int[] a, int x) {\n int low = 0;\n int high = a.length - 1;\n\n if ( high &lt; 0 )\n throw new IllegalArgumentException(\"The array cannot be empty\");\n\n OUTER:\n while ( low &lt; high ) {\n int mid = (low + high) / 2;\n assert ( mid &lt; high );\n int d1 = Math.abs(a[mid ] - x);\n int d2 = Math.abs(a[mid+1] - x);\n if ( d2 &lt; d1 )\n low = mid + 1;\n else if ( d2 &gt; d1 )\n high = mid;\n else { // --- handling \"d1 == d2\" ---\n for ( int right=mid+2; right&lt;=high; right++ ) {\n d2 = Math.abs(a[right] - x);\n if ( d2 &lt; d1 ) {\n low = right;\n continue OUTER;\n } else if ( d2 &gt; d1 ) {\n high = mid;\n continue OUTER;\n }\n }\n high = mid;\n }\n }\n return a[high];\n}\n</code></pre>\n\n<p>--- UPDATE ---</p>\n\n<p>Why the hate (-1)? Handling <code>d1 == d2</code> is <em>important</em> as the array is subset wrongly otherwise.</p>\n\n<p>E.g., consider <code>a=[1,2,2,3]</code> and <code>x=0</code>. Then <code>d1=d2=2</code> and Josay's answer sets <code>low=mid+1</code> which subsets the array to <code>[2,3]</code>. This subset does not contain the correct answer (<code>1</code>) anymore.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-04T15:57:44.707", "Id": "227084", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-04T16:02:35.237", "Id": "227085", "Score": "0", "body": "The slight improvement is `--- handling \"d1 == d2\" ---`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-04T16:03:52.023", "Id": "227086", "Score": "0", "body": "Sure, but *why* is it an improvement? What advantages does it have over the original? You need to elaborate on your changes." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-04T15:48:21.540", "Id": "121900", "ParentId": "47328", "Score": "-1" } }, { "body": "<p>The same again and again...</p>\n\n<p>Do not sum endpoints' indices:</p>\n\n<pre><code> int mid = (low + high) / 2;\n</code></pre>\n\n<p>Subtract them instead:</p>\n\n<pre><code> int mid = low + (high - low) / 2;\n</code></pre>\n\n<p>This will prevent an arithmetic overflow and possible getting <code>mid &lt; 0</code> in case your array's length exceeds a half of the <code>int</code> type maximum value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-17T09:47:30.243", "Id": "128570", "ParentId": "47328", "Score": "1" } } ]
{ "AcceptedAnswerId": "47341", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:00:01.407", "Id": "47328", "Score": "10", "Tags": [ "java", "algorithm", "array" ], "Title": "Find the value nearest to k in the sorted array" }
47328
<p>I want to generate a sequence using Linq that goes from 10 to 100 with a step size of 10. The sequence also must contain a custom value (in the correct order).</p> <p>This is what I have now, and I'm wondering if there is a smarter way of doing it using Linq expressions.</p> <pre><code>var pageSize = 25; //number that must be in sequnce if not already, can be anything. var items = Enumerable.Range(10, 100) //Generate range .Where(x =&gt; x % 10 == 0) //Take every 10th item .Concat(new[] { pageSize }) //Add the custom number .Distinct() //If the custom number was already in there, remove it .OrderBy(x =&gt; x); //Sort the sequence </code></pre> <p>Result:</p> <pre><code>10 20 25 30 40 50 60 70 80 90 100 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:48:32.500", "Id": "82893", "Score": "0", "body": "Why should the result include 25?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:52:55.697", "Id": "82894", "Score": "0", "body": "@200_success Could be 25 or any other integer. This code is used to generate the datasource to a drop down to select the page size of a GridView. The custom number (25 in the case) is the page size currently set on the gridview and I need to include that in the sequence as that value is set as the default selected value." } ]
[ { "body": "<p>Size of initial list in the following code is less:</p>\n\n<pre><code>var x = Enumerable.Range(1, 10)\n .Select(x_ =&gt; x_ * 10)\n .Concat(new[] {25})\n .Distinct()\n .OrderBy(x_ =&gt; x_)\n .ToList();\n</code></pre>\n\n<p>Otherwise your original code is perfect.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T08:15:35.693", "Id": "82901", "Score": "0", "body": "Where is this `x_` notation coming from? I have never seen it in C#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T08:21:02.130", "Id": "82903", "Score": "0", "body": "Also, strictly speaking `Range` does not create list. Your version does require less iterations nonetheless and is easier to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T08:41:42.680", "Id": "82908", "Score": "1", "body": "This is the coding convention that I follow. x_ is used for input parameters and _x is that is used for member variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:53:36.667", "Id": "82974", "Score": "0", "body": "@NikitaBrizhak: `x_` is just a variable name, nothing special." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T06:40:56.663", "Id": "83106", "Score": "3", "body": "@Chris, well, obviously. I was asking what naming convention is that (as it contradicts msdn guidelines for parametrs)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T08:12:34.757", "Id": "83115", "Score": "0", "body": "@NikitaBrizhak: In that case sorry for what may have come across as a very patronizing comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:59:48.233", "Id": "83142", "Score": "1", "body": "You can collapse `Concat(...).Distinct` into `Union`" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T08:13:26.063", "Id": "47335", "ParentId": "47332", "Score": "8" } }, { "body": "<p>Just include the custom value in the condition, then you don't need to concatentat it, remove duplicates or sort. To get the range from 10 to 100 you should use 91 as count in the <code>Range</code> method, <code>Range(10, 100)</code> creates numbers from 10 to 109.</p>\n\n<pre><code>var pageSize = 25;\n\nvar items =\n Enumerable.Range(10, 91) \n .Where(x =&gt; x % 10 == 0 || x == pageSize);\n</code></pre>\n\n<p>Note: This naturally only works if the custom value is inside the range.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T09:23:23.320", "Id": "82911", "Score": "0", "body": "This is a neat way. Unfortunately the `pageSize` could be outside of the range." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T09:03:07.833", "Id": "47337", "ParentId": "47332", "Score": "5" } }, { "body": "<h1>Know your library</h1>\n\n<p><strong><code>.Distinct()</code></strong> should immediately make you think of a <strong><code>Set</code></strong>.<br>\n<strong><code>.OrderBy(...)</code></strong> should make you think of a sorted collection.</p>\n\n<p>I give you: the <a href=\"http://msdn.microsoft.com/en-us/library/dd412070%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>SortedSet&lt;T&gt;</code></a>, part of .NET since version 4.0.</p>\n\n<h1>When LINQ is not enough, extend it</h1>\n\n<p>LINQ uses <a href=\"http://msdn.microsoft.com/en-us//library/bb383977.aspx\" rel=\"nofollow\">extension methods</a>, so if it doesn't have what you need, add your own:</p>\n\n<pre><code>private static IEnumerable&lt;T&gt; ToSelectionWith&lt;T&gt;(this IEnumerable&lt;T&gt; sequence, params T[] items)\n{\n return new SortedSet&lt;T&gt;(sequence.Concat(items));\n}\n</code></pre>\n\n<h1>Usage</h1>\n\n<p>This allows you to call it as though it were a part of LINQ itself:</p>\n\n<pre><code>var pageSize = 25;\nvar items = Enumerable.Range(1, 10).Select(x =&gt; x*10).ToSelectionWith(pageSize);\n</code></pre>\n\n<h1>Benefits</h1>\n\n<ol>\n<li><strong>It's concise</strong> — a one-liner. You could even skip the extension method and use the <code>SortedSet</code> directly.</li>\n<li><strong>It's readable</strong> — by wrapping it in the extension method, the intent of using the <code>SortedSet</code> is clarified.</li>\n<li><strong>It performs well</strong> — in my crude <code>Stopwatch</code> testing, it beat your and Sandeep's versions for both small and large input sequences. (Specifically, the <code>SortedSet</code> based approach runs twice as fast as Sandeep's version for your original input, and at least three times as fast for very large input sizes).</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T06:48:12.970", "Id": "83107", "Score": "0", "body": "I disagree with your second point. It is not readable at all. If i were to see the line of code from your usage example, i would assume that it adds an element to enumeration. Certainly not that it both _sorts_ and _distincts_ it as well. You extension method does not indicate the usage of `SortedSet` in its implementation in any way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T07:10:49.197", "Id": "83109", "Score": "0", "body": "@Nikita okay, I tend to agree the name isn't perfect. I changed it to `ToSelectionWith(pageSize)`, which I think is slightly more descriptive and less misleading. The point of an abstraction, though, is to keep this implemention detail hidden away." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T08:07:59.373", "Id": "83113", "Score": "0", "body": "It is indeed. That is why the name should be descriptive enough, to call the method _readable_. I do not suggest to call it `ToSortedSetWith()` or something (though i would consider something along these lines), i merely point out that its name (at least the old one) does not reflect what this method actually does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:40:10.473", "Id": "83136", "Score": "1", "body": "+1 for favoring readability of business logic over total LOC. I also liked using a method to replace an idiom, namely `Concat(new{...})`. However `Selection` has no inherent meaning. Also result being a sorted set is not really an *implementation detail*, as it being a distinct and ordered collection is a requirement. How about refactoring your `ToSelectionWith` to SRP methods like `someEnumerable.Append(someValue, someOtherValue).ToSortedSet()`. With `ToSortedSet` being a least surprise counterpart to `ToArray` and `ToList`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:58:46.810", "Id": "83141", "Score": "1", "body": "Using a sorted set is a good idea. But `ToSelectionWith` is badly named and nothing more than `UnionAndSort`, so it's an SRP violation as well." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T02:10:50.543", "Id": "47423", "ParentId": "47332", "Score": "4" } }, { "body": "<p>Although there isn't much left to add to the actual use case OP mentioned, considering the general problem of <strong>inserting a value in the correct order in an ordered sequence</strong>, a more time and space efficient solution exists.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; InsertPreservingOrder&lt;T&gt; (this IEnumerable&lt;T&gt; sortedSequence, T value)\n where T : IComparable&lt;T&gt;\n{\n return sortedSequence.TakeWhile(x =&gt; x.CompareTo(value) &lt; 0)\n .Append(value)\n .Concat(sortedSequence.SkipWhile(x =&gt; x.CompareTo(value) &lt;= 0));\n}\n</code></pre>\n\n<p>where <code>Append</code> is syntactic sugar for <code>.Concat(new{...})</code> <a href=\"https://codereview.stackexchange.com/a/47423/20251\">as per @codesparkle's answer</a>:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Append&lt;T&gt;(this IEnumerable&lt;T&gt; sequence, params T[] items)\n{\n return sequence.Concat(items);\n}\n</code></pre>\n\n<p>This operation is of constant (O(1)) space, linear (O(n)) time and lazy.\nEspecially useful in situations like this : </p>\n\n<pre><code>var customValue = 15;\nvar defaultValues = Enumerable.Range(1, 10000000).Select(x_ =&gt; x_ * 10);\nvar items = defaultValues.InsertPreservingOrder(customValue);\n// then later\nitems.Take(10).ToList().ForEach(Console.WriteLine);\n</code></pre>\n\n<p>I also think this method is a clear improvement in capturing programmer's intent w.r.t. the original version, regardless of asymptotic complexity.\nIt reifies an idea; therefore can be reused, whenever the current value of a variable would be added in a collection of default options. Its name makes clear both the precondition that first parameter is assumed to be already sorted, and the postcondition that the return value is also sorted. However it leaves the distinctness condition opaque.</p>\n\n<p>Though I'd still prefer a simple <a href=\"https://codereview.stackexchange.com/questions/47332/generate-sequence-in-linq#comment83136_47423\"><code>defaultValues.Append(customValue).ToSortedSet()</code></a> </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:13:12.010", "Id": "47483", "ParentId": "47332", "Score": "1" } } ]
{ "AcceptedAnswerId": "47423", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T07:45:38.660", "Id": "47332", "Score": "12", "Tags": [ "c#", "linq", "interval" ], "Title": "Generate sequence in Linq" }
47332
<p>I've been working on a rough idea for a templating engine (mostly as a learning project) using the F# syntax. How "correct" is my code in terms of being idiomatic F#? Are there F# features which would make the code simpler? More easily understood? </p> <p>The template files are loaded at runtime using a script I've not posted here The code is also provided as a <a href="https://gist.githubusercontent.com/AndyBursh/10561610/raw/ff0754d521c626f455118b848e291a942cdc52b8/testScript.fsx" rel="nofollow">gist</a> for easier reading.</p> <p><strong>Template</strong></p> <pre><code>#r "program.exe" open System open Lib let intToText i = div [] [Text((sprintf "I is %i" i))] Template ( html [] [ div [("id", "123");("class", "me")] [ div [] [ Text "SOME TEXT" ] div [] [ Text "SOME MORE TEXT" ] foreach [1;2;3] intToText input [("type", "text"); ("value", "1")] ] ] ) </code></pre> <p><strong>Lib</strong></p> <pre><code>module Lib open System open System.Text type Attributes = (string * string) list type Element = | Tag of (string * Attributes * Element list) | TagSelfClosing of (string * Attributes) | Collection of (Element list) | Text of string let html (attrs:Attributes) el:Element = Tag("html", attrs, el) let div (attrs:Attributes) el:Element = Tag("div", attrs, el) let input (attrs:Attributes) = TagSelfClosing("input", attrs) let foreach data fn = let elems = data |&gt; List.map fn Collection(elems) type Token = | OPEN_TAG of (string * Attributes) | CLOSE_TAG of string | SELF_CLOSING_TAG of (string * Attributes) | TEXT of string let Template el = let rec expandTree el output = match el with | Tag(tagName, attrs, children) -&gt; let childContent = children |&gt; List.fold (fun state item -&gt; state @ (expandTree item [])) [] let addition = [OPEN_TAG(tagName, attrs)]@childContent@[CLOSE_TAG(tagName)] output@addition | TagSelfClosing(tagName, attrs) -&gt; let addition = [SELF_CLOSING_TAG(tagName, attrs)] output@addition | Collection(elements) -&gt; let collectionContent = elements |&gt; List.map (fun e -&gt; expandTree e output) |&gt; List.fold (fun state item -&gt; state@item) [] output @ collectionContent | Text(string) -&gt; output@[TEXT(string)] let tokenWriter token = let attributeWriter (tuple:string*string) = let (name, value) = tuple sprintf " %s=\"%s\"" name value let foldAttributes attrs = attrs |&gt; List.map attributeWriter |&gt; List.fold (fun state item -&gt; state+item) "" match token with | OPEN_TAG(name, attrs) -&gt; let attributes = foldAttributes attrs sprintf "&lt;%s%s&gt;" name attributes | CLOSE_TAG(name) -&gt; sprintf "&lt;/%s&gt;" name | SELF_CLOSING_TAG(name, attrs) -&gt; let attributes = foldAttributes attrs sprintf "&lt;%s%s /&gt;" name attributes | TEXT(content) -&gt; sprintf "%s" content let expandedTree = expandTree el [] let content = expandedTree |&gt; List.map tokenWriter |&gt; List.fold (fun state item -&gt; state+item) "" printf "%s" content </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T08:55:52.937", "Id": "82910", "Score": "0", "body": "using `#r` with a `.exe` is not a good idea, you should be compiling to a `.dll` if you are using `#r` as you can run into issues with initialization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T14:33:03.793", "Id": "82956", "Score": "0", "body": "Have you seen https://wingbeats.codeplex.com/ ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T14:39:36.127", "Id": "82959", "Score": "0", "body": "Yes, I have. I saw it some time ago, then started working on this recently and thought to myself \"this looks familiar\", which is when I googled and realised why!" } ]
[ { "body": "<p>There are a few suggestions which immediately occur to me: some are minor changes which could improve the clarity of the code and there is one major change which would shorten the code quite a bit.</p>\n\n<p>The minor changes:</p>\n\n<ol>\n<li><p>For <code>List.fold</code> you can just pass a function which matches the expected type and not write the full lambda. With an operator like <code>+</code> it's not obvious, but you can clean up your code a bit using:</p>\n\n<pre><code>attrs\n|&gt; List.map (fun (name,value) -&gt; sprintf \"%s=\\\"%s\\\"\" name value)\n|&gt; List.fold (+) \"\"\n</code></pre></li>\n<li><p>In the function <code>childContent</code>, I would move the call to <code>expandTree</code> into a <code>List.map</code>, to reduce the amount of nesting and to allow us to clean up the <code>List.fold</code>:</p>\n\n<pre><code>children\n|&gt; List.map (fun child -&gt; expandTree child [])\n|&gt; List.fold (@) []\n</code></pre></li>\n<li><p>With <code>Text(string)</code> you should use a name other than <code>string</code> since that's the name of an existing type and that could cause confusion for someone reading your code.</p></li>\n</ol>\n\n<p>The major change is that you can combine the tokenWriter and the expandTree into a single function. At the heart, what you are doing is an in order traversal of a tree to convert your HTML structure into a string: expandTree does an in order traversal to flatten the tree into a list and then tokenWriter converts those tokens into strings. You're not gaining much by flattening the tree and then generating the output string; so, you could just use the tree traversal to generate the output string.</p>\n\n<p>Making this change also allows you to remove the <code>Token</code> type, further reducing the overall complexity of your code.</p>\n\n<p>Here's the updated code:</p>\n\n<pre><code> let Template el =\n let rec elementToString el output = \n let attributesToString attrs =\n attrs\n |&gt; List.map (fun (name,value) -&gt; sprintf \"%s=\\\"%s\\\"\" name value)\n |&gt; List.fold (+) \"\"\n\n match el with\n | Tag(tagName, attrs, children) -&gt; \n let attributes = attributesToString attrs\n let tagStr = sprintf \"&lt;%s%s&gt;\" tagName attributes\n let childContent = \n children\n |&gt; List.map (fun item -&gt; elementToString item \"\" )\n |&gt; List.fold (+) tagStr\n let closeTagStr = sprintf \"&lt;/%s&gt;\" tagName\n sprintf \"%s%s%s\" output childContent closeTagStr\n | TagSelfClosing(tagName, attrs) -&gt;\n let attributes = attributesToString attrs\n sprintf \"%s&lt;%s%s /&gt;\" output tagName attributes\n | Collection(elements) -&gt;\n elements\n |&gt; List.map (fun e -&gt; elementToString e output)\n |&gt; List.fold (+) \"\"\n | Text(text) -&gt;\n sprintf \"%s%s\" output text\n\n let expandedTree = elementToString el \"\"\n let content = \n expandedTree\n\n printf \"%s\" content\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T07:29:25.760", "Id": "83884", "Score": "1", "body": "Thanks for the feedback. I like your minor suggestions - I'd forgotten that operators are also functions - but I'm not sure on the refactoring front. I originally wrote it in the form your describe, but I found the separation of the tree expansion and creation of the output easier to understand and change." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T04:00:56.110", "Id": "47630", "ParentId": "47334", "Score": "2" } } ]
{ "AcceptedAnswerId": "47630", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T08:04:58.933", "Id": "47334", "Score": "1", "Tags": [ "f#", "template-meta-programming" ], "Title": "Basic templating engine in F# using F# syntax" }
47334
<p>I am building an application full of forms and so I thought it is good idea to create a class to populate form fields.</p> <p>Here is my class and I am sure it can be optimized more than now and could be better.</p> <pre><code>class JS_Forms { public function __construct() { //$this-&gt;register_fields($fields); } public function register_fields($fields) { $text_array = array_flip(array('type', 'name', 'id', 'placeholder', 'required', 'data-length', 'class', 'value')); $uploads = array_flip(array('type', 'name')); foreach ($fields as $value) { switch ($value['type']) { case 'text': echo '&lt;div class="form-group"&gt;'; echo form_label(lang($value['label']), $value['id'], array('class' =&gt; $value['label_class'])); unset($value['label_class']); unset($value['label']); $value['value'] = set_value($value['id'], is_null($value['obj']) ? $value['std'] : $value['obj']); echo array_key_exists('field_class', $value) ? '&lt;div class="' . $value['field_class'] . '"&gt;' : NULL; echo form_input(array_intersect_key($value, $text_array)); echo array_key_exists('field_class', $value) ? '&lt;/div&gt;' : NULL; echo '&lt;/div&gt;'; break; case 'upload': echo '&lt;div class="form-group"&gt;'; echo form_label(lang($value['label']), $value['name'], array('class' =&gt; $value['label_class'])); unset($value['label_class']); unset($value['label']); unset($value['value']); //$value['value'] = set_value($value['id'], is_null($value['obj']) ? $value['std'] : $value['obj']); echo array_key_exists('field_class', $value) ? '&lt;div class="' . $value['field_class'] . '"&gt;' : NULL; echo form_upload(array_intersect_key($value, $uploads)); echo array_key_exists('field_class', $value) ? '&lt;/div&gt;' : NULL; echo '&lt;/div&gt;'; break; case 'jupload': echo '&lt;div class="form-group"&gt;'; echo form_label(lang($value['label']), $value['name'], array('class' =&gt; $value['label_class'])); unset($value['label_class']); unset($value['label']); unset($value['value']); echo array_key_exists('field_class', $value) ? '&lt;div class="' . $value['field_class'] . '"&gt;' : NULL; echo '&lt;div class="fileinput fileinput-new" data-provides="fileinput"&gt;'; echo '&lt;div class="input-group"&gt;'; echo '&lt;div class="form-control uneditable-input" data-trigger="fileinput"&gt;'; echo '&lt;i class="fa fa-file fileinput-exists"&gt;&lt;/i&gt;&amp;nbsp;&lt;span class="fileinput-filename"&gt;&lt;/span&gt;'; echo '&lt;/div&gt;'; echo '&lt;span class="input-group-addon btn btn-default btn-file"&gt;'; echo '&lt;span class="fileinput-new"&gt;Select file&lt;/span&gt;'; echo '&lt;span class="fileinput-exists"&gt;Change&lt;/span&gt;'; echo form_upload(array_intersect_key($value, $uploads)); // echo '&lt;/span&gt;'; echo '&lt;a href="#" class="input-group-addon btn btn-default fileinput-exists" data-dismiss="fileinput"&gt;Remove&lt;/a&gt;'; echo '&lt;/div&gt;'; echo '&lt;/div&gt;'; echo array_key_exists('field_class', $value) ? '&lt;/div&gt;' : NULL; echo '&lt;/div&gt;'; break; case 'textarea': echo '&lt;div class="form-group"&gt;'; echo form_label(lang($value['label']), $value['id'], array('class' =&gt; $value['label_class'])); unset($value['label_class']); unset($value['label']); $value['value'] = set_value($value['id'], is_null($value['obj']) ? $value['std'] : $value['obj']); echo array_key_exists('field_class', $value) ? '&lt;div class="' . $value['field_class'] . '"&gt;' : NULL; echo form_textarea($value); echo array_key_exists('field_class', $value) ? '&lt;/div&gt;' : NULL; echo '&lt;/div&gt;'; break; case 'select': echo '&lt;div class="form-group"&gt;'; echo form_label(lang($value['label']), $value['id'], array('class' =&gt; $value['label_class'])); unset($value['label_class']); unset($value['label']); echo array_key_exists('field_class', $value) ? '&lt;div class="' . $value['field_class'] . '"&gt;' : NULL; // Important! here you need to set selected item value using core helper 'set_selected()' echo form_dropdown($value['name'], $value['options'], set_value($value['id'], is_null($value['obj']) ? $value['std'] : $value['obj']), 'class="' . $value['class'] . '"'); echo array_key_exists('field_class', $value) ? '&lt;/div&gt;' : NULL; echo '&lt;/div&gt;'; break; case 'multiselect': echo '&lt;div class="form-group"&gt;'; echo form_label(lang($value['label']), $value['id'], array('class' =&gt; $value['label_class'])); unset($value['label_class']); unset($value['label']); echo array_key_exists('field_class', $value) ? '&lt;div class="' . $value['field_class'] . '"&gt;' : NULL; //--- $id = array_key_exists('id', $value) ? 'id="' . $value['id'] . '"' : NULL; $class = array_key_exists('class', $value) ? 'class="' . $value['class'] . '"' : 'class="multi-select"'; $name = array_key_exists('name', $value) ? $value['name'] : NULL; echo '&lt;select multiple="multiple" ' . $class . $id . ' name="' . $name . '[]"&gt;'; $items = $value['options']; $selects = explode(',', $value['obj']); echo '&lt;option value="null" selected class="disabled" style="display:none"&gt;Selected&lt;/option&gt;'; foreach ($items as $key =&gt; $item) { $selected = in_array($key, $selects) ? 'selected="selected"' : NULL; echo '&lt;option value="' . $key . '" ' . $selected . '&gt;' . $item . '&lt;/option&gt;'; } echo '&lt;/select&gt;'; echo array_key_exists('field_class', $value) ? '&lt;/div&gt;' : NULL; echo '&lt;/div&gt;'; break; case 'radio': echo '&lt;div class="form-group"&gt;'; echo form_label(lang($value['label']), $value['name'], array('class' =&gt; $value['label_class'], 'style' =&gt; $value['style'])); $options = $value['options']; unset($value['label_class']); unset($value['label']); echo array_key_exists('field_class', $value) ? '&lt;div class="' . $value['field_class'] . '"&gt;' : NULL; foreach ($value['options'] as $key =&gt; $radio) { echo (array_key_exists('block', $value) &amp;&amp; $value['block'] == TRUE) ? '&lt;div class="radio"&gt;' : NULL; echo form_label(form_radio(array('name' =&gt; $value['name'], 'id' =&gt; $value['name'] . '-' . $key), $key, $value['std'] == $key ? TRUE : FALSE, ($key == $value['obj']) ? set_radio($value['name'], $value['obj'], TRUE) : set_radio($value['name'], $key)) . $radio, $value['name'] . '-' . $key, ((array_key_exists('block', $value) &amp;&amp; $value['block'] == TRUE) ? NULL : array('class' =&gt; $value['radio_lable_class']))); echo (array_key_exists('block', $value) &amp;&amp; $value['block'] == TRUE) ? '&lt;/div&gt;' : NULL; } echo array_key_exists('field_class', $value) ? '&lt;/div&gt;' : NULL; echo '&lt;/div&gt;'; break; case 'checkbox': echo '&lt;div class="form-group"&gt;'; echo form_label(lang($value['label']), $value['name'], array('class' =&gt; $value['label_class'], 'style' =&gt; $value['style'])); $options = $value['options']; unset($value['label_class']); unset($value['label']); echo array_key_exists('field_class', $value) ? '&lt;div class="' . $value['field_class'] . '"&gt;' : NULL; echo (array_key_exists('required', $value) &amp;&amp; $value['required'] == TRUE) ? form_hidden($value['name'] . '[]', 'null') : NULL; foreach ($value['options'] as $key =&gt; $checkbox) { $checked = explode(',', $value['obj']); echo (array_key_exists('block', $value) &amp;&amp; $value['block'] == TRUE) ? '&lt;div class="checkbox"&gt;' : NULL; echo form_label(form_checkbox(array('name' =&gt; $value['name'] . '[]', 'id' =&gt; $value['name'] . '-' . $key), $key, in_array($key, $checked) ? set_checkbox($value['name'], $key, TRUE) : FALSE) . $checkbox, $value['name'] . '-' . $key, ((array_key_exists('block', $value) &amp;&amp; $value['block'] == TRUE) ? NULL : array('class' =&gt; $value['checkbox_lable_class']))); echo (array_key_exists('block', $value) &amp;&amp; $value['block'] == TRUE) ? '&lt;/div&gt;' : NULL; } echo array_key_exists('field_class', $value) ? '&lt;/div&gt;' : NULL; echo '&lt;/div&gt;'; break; default: break; } } } } </code></pre> <hr> <p><strong>Usage</strong></p> <pre><code>$fields = array( array( 'type' =&gt; 'text', 'label' =&gt; 'emp_employee_id', 'label_class' =&gt; 'col-sm-3 control-label', 'field_class' =&gt; 'col-sm-9', 'name' =&gt; 'employee_id', 'id' =&gt; 'employee_id', 'placeholder' =&gt; 'e.g. 912', 'required' =&gt; 'required', 'data-minlength' =&gt; 3, 'class' =&gt; 'form-control', 'std' =&gt; '', 'obj' =&gt; segment_is_num(4, $employee, 'first_name', NULL), ), array( 'type' =&gt; 'text', 'label' =&gt; 'emp_firstname', 'label_class' =&gt; 'col-sm-3 control-label', 'field_class' =&gt; 'col-sm-9', 'name' =&gt; 'first_name', 'id' =&gt; 'first_name', 'placeholder' =&gt; 'The Place Holder', 'required' =&gt; 'required', 'data-minlength' =&gt; 3, 'class' =&gt; 'form-control', 'std' =&gt; 'Jatin', 'obj' =&gt; segment_is_num(4, $employee, 'first_name', NULL), ), array( 'type' =&gt; 'select', 'label' =&gt; 'emp_lastname', 'label_class' =&gt; 'col-sm-3 control-label', 'field_class' =&gt; 'col-sm-9', 'name' =&gt; 'last_name', 'id' =&gt; 'last_name', 'class' =&gt; 'form-control', 'options' =&gt; array('one' =&gt; 'One', 'two' =&gt; 'Two', 'three' =&gt; 'Three'), 'std' =&gt; 'three', 'obj' =&gt; segment_is_num(4, $employee, 'last_name', NULL), ), array( 'type' =&gt; 'radio', 'label' =&gt; 'emp_gender', 'label_class' =&gt; 'col-sm-3 control-label', 'field_class' =&gt; 'col-sm-9', 'radio_lable_class' =&gt; 'radio-inline', 'name' =&gt; 'gender', 'options' =&gt; array('male' =&gt; 'Male', 'female' =&gt; 'Female'), 'std' =&gt; 'male', 'style' =&gt; 'display: block', 'obj' =&gt; segment_is_num(4, $employee, 'gender', NULL), ), array( 'type' =&gt; 'checkbox', 'block' =&gt; false, 'label' =&gt; 'emp_country', 'label_class' =&gt; 'col-sm-3 control-label', 'field_class' =&gt; 'col-sm-9', 'checkbox_lable_class' =&gt; 'checkbox-inline', 'name' =&gt; 'country', 'options' =&gt; array('india' =&gt; 'India', 'mauritius' =&gt; 'Mauritius', 'japan' =&gt; 'Japan'), 'std' =&gt; 'india', 'style' =&gt; 'display: block', 'required' =&gt; TRUE, 'obj' =&gt; segment_is_num(4, $employee, 'country', NULL), ), array( 'type' =&gt; 'textarea', 'label' =&gt; 'emp_attrition_comment', 'label_class' =&gt; 'col-sm-3 control-label', 'field_class' =&gt; 'col-sm-9', 'name' =&gt; 'attrition_comment', 'id' =&gt; 'attrition_comment', 'placeholder' =&gt; 'The Place Holder', 'class' =&gt; 'form-control', 'std' =&gt; 'Soni', 'obj' =&gt; segment_is_num(4, $employee, 'attrition_comment', NULL), ), array( 'type' =&gt; 'multiselect', 'label' =&gt; 'emp_nationality', 'label_class' =&gt; 'col-sm-3 control-label', 'field_class' =&gt; 'col-sm-9', 'name' =&gt; 'nationality', 'id' =&gt; 'nationality', 'class' =&gt; 'form-control', 'options' =&gt; array('indian' =&gt; 'Indian', 'mauritian' =&gt; 'Mauritian', 'american' =&gt; 'American'), 'std' =&gt; 'indian', 'obj' =&gt; segment_is_num(4, $employee, 'nationality', NULL), ), array( 'type' =&gt; 'jupload', 'label' =&gt; 'emp_nid', 'label_class' =&gt; 'col-sm-3 control-label', 'field_class' =&gt; 'col-sm-9', 'name' =&gt; 'employee_snap', ), ); // populate form firles using the 'js_forms' library $this-&gt;js_forms-&gt;register_fields($fields); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T13:58:06.023", "Id": "82949", "Score": "2", "body": "Is your intent to auto populate a form from a database row? You've not provided any example of how this would be used. As far as coding best practices goes, this leaves a little to be desired." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:59:33.247", "Id": "83071", "Score": "0", "body": "why is there a commented part in your constructor that is floating there. If its useless please remove it - if it serves purpose you need to attach or explain what is the purpose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T05:34:14.863", "Id": "83101", "Score": "0", "body": "@B2K Please see my updated question with `Usage` code. I am using array to populate the form. But may be in future I can store such thing into database and populate using rows as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T05:35:00.223", "Id": "83102", "Score": "0", "body": "@azngunit81 please ignore the commented part. Nothing to deal with that. In fact I may remove the `__construct()` as well" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T06:14:31.573", "Id": "83103", "Score": "0", "body": "please provide a possible output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T06:38:44.307", "Id": "83105", "Score": "0", "body": "This code is populating HTML form. Or you need any specific item?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:45:19.563", "Id": "83193", "Score": "0", "body": "@pixelngrain My preference is to provide greater separation of concerns using templates like smarty. Perhaps you could call a template for each type of field you are creating. These keeps your actual html separate from the business logic." } ]
[ { "body": "<p>One of the issues you will run into in the future is the coupling of your presentation output (HTML) to the functionality of the class. You also have many sections of repeating output which should likely be outside of each case statement, but within the loop. </p>\n\n<p>You wish to optimize the class, but haven't really chosen what to optimize it for. I'll repeat the cliche of \"Premature optimization is the root of all evil\". </p>\n\n<p>Where you have separated out the fields into an array...great! That is a good step towards reuse. You should be able to take this config, paste it into another project and be able to generate a similar form field. Assuming you have the form class available as well. If you look into some of the available frameworks their Form and Field classes can operate in a similar manner. Take a config (an array possibly) and pass it to a Form class which will take each 'field' part of the config and create a new Field class and make sure all the parts are tied together.</p>\n\n<p>One good starting point to help make the code more readable is instead of the switch statement, make a second set of classes which has one class for each field type you wish to have available. Once you have separated the 'types' into classes, then you will likely see the similarities between all the different types. That becomes a good opportunity to create a parent field class that all the other fields can extend. This will further reduce the code you need to manage. </p>\n\n<p>You can continue to move your class forward, but you may find it beneficial to look at the available frameworks, review their code and either pull in the best elements, or, pull in their code and use it in your project. That way you gain all the insights from others as to what makes a good form management solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T20:30:58.580", "Id": "47829", "ParentId": "47338", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T10:21:26.807", "Id": "47338", "Score": "1", "Tags": [ "php", "classes", "form" ], "Title": "Optimized Form fields generating class" }
47338
<p>I am trying to solve the <a href="https://www.hackerrank.com/contests/sep13/challenges/sherlock-and-the-beast" rel="nofollow">Sherlock and The Beast</a> HackerRank challenge. Most tests timeout, however when I try a custom stretch test case (T = 20 and all N = 100000), it returns successfully, so I'm not sure what the problem is.</p> <p>The idea of the algorithm is that I find the number of possible combinations of threes and fives for a given number of digits, then I treat threes as zeros and fives as ones, in order to process a binary number. So for N = 3 digits, we have 8 combinations (from 7 to 0) which in binary terms is (descending) from 111 to 000, which in three and five terms is from 555 to 333.</p> <pre><code>public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = in.nextInt(); for(int i = 0; i &lt; testCases; i++){ System.out.println( solve( in.nextInt() ) ); } } private static String solve(int n){ long combos = (long)Math.pow(2,n); for(long i = combos-1; i&gt;=0; i--){ String toStr = String.format("%"+n+"s", Long.toBinaryString(i)).replace(' ', '0'); String modified = toStr.replace("0","3").replace("1","5"); int threes =0; for( int j=0; j&lt;modified.length(); j++ ) { if( modified.charAt(j) == '3' ) { threes++; } } if(threes%5==0) { int fives =0; for( int k=0; k&lt;modified.length(); k++ ) { if( modified.charAt(k) == '5' ) { fives++; } } if(fives%3==0) return modified; } } return "-1"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:09:38.800", "Id": "82978", "Score": "1", "body": "You say that you're testing this with `n=100000`? It quite clearly can't give correct results for any value of `n` greater than `63`, so I think you need to start by checking your test wrapper." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:45:22.710", "Id": "83207", "Score": "0", "body": "Strange thing is that I didn't test it locally, I just relied on Hackerrank's interface which indeed returned \"success\" for n=100000. I ca see now that the algorithm is off. Anyway thanks." } ]
[ { "body": "<p>My non-exhaustive list of comments, considering that you seem to prefer (based on observed skill level) plain Java and do not want to use Java 8 yet.</p>\n\n<ol>\n<li><p>Adhere to the Java's coding standards. One of the catches here is that method names are in camelCase, so it would be <code>private static String solve(int n) {</code>.</p></li>\n<li><p>Intendation and code formatting. You seem to not be using a single standard for all your code. Furthermore I have to say that using spaces where neccessary will not cause any harm, some examples and improvements.</p>\n\n<p>2.1. <code>for(int i = 0; i &lt; t; i++){</code> -> <code>for (int i = 0; i &lt; t; i++) {</code></p>\n\n<p>2.2. <code>long combos = (long)Math.pow(2,n);</code> -> <code>long combos = (long)Math.pow(2, n);</code></p>\n\n<p>2.3. <code>if(threes%5==0) {</code> -> <code>if (threes % 5 == 0) {</code></p>\n\n<p>Please be consistent with your formatting is the bottom line.</p></li>\n<li><p>On to the next point, variable names. It does not hurt to use longer variable names if that makes them more meaningful. In your <code>main</code> you have a variable called <code>t</code>, this name is not descriptive, please consider describing what it actually means. Another example is <code>i</code>, <code>ii</code> and <code>iii</code> in your for-loops, it is much more natural to use <code>i, j, k</code> for these variables.</p></li>\n<li><p>You could use more abstraction, as your <code>solve</code> method is not easy to follow at all. Consider creating smaller methods that process one step at a time, this will also enable you to be able to test your methods at some point.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:36:12.073", "Id": "83127", "Score": "0", "body": "Fixed, thanks. Though I wasn't following standards and best practices in the online editor of hackerrank, plus the code's wrapper + function defs were provided by them. Hence the non-use of Java 8." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T19:54:02.200", "Id": "47388", "ParentId": "47339", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T10:46:00.870", "Id": "47339", "Score": "4", "Tags": [ "java", "algorithm", "programming-challenge" ], "Title": "Hackerrank - Sherlock and the Beast" }
47339
<p>The previous code (as displayed in <a href="https://codereview.stackexchange.com/questions/46807/timer-utilizing-stdfuture">Timer utilizing std::future</a>) is now:</p> <pre><code>#include &lt;chrono&gt; #include &lt;functional&gt; #include &lt;future&gt; #include &lt;iostream&gt; #include &lt;list&gt; #include &lt;mutex&gt; #include &lt;thread&gt; // PeriodicFunction // ============================================================================= namespace Detail { /// A functor to invoke a function periodically. template &lt;typename Value, typename Derived&gt; class PeriodicFunction { // Types // ===== public: typedef std::chrono::milliseconds period_type; typedef Value value_type; protected: typedef std::function&lt;Value ()&gt; function_type; typedef std::future&lt;Value&gt; future_type; // Construction // ============ protected: /// Initialize with a function where the arguments are bounded to that function. /// \SEE std::bind template &lt;typename Callable, typename... Arguments&gt; PeriodicFunction(Callable&amp;&amp; callable, Arguments&amp;&amp;... arguments) : m_function(std::bind( std::move(callable), std::forward&lt;Arguments&gt;(arguments)...)), m_period(period_type::zero()) {} public: PeriodicFunction(const PeriodicFunction&amp;) = delete; PeriodicFunction&amp; operator = (const PeriodicFunction&amp;) = delete; /// Calls stop. ~PeriodicFunction() { stop(); } // Start/Stop // ========== /// True, if an invocation thread is active. bool active() const noexcept { return m_thread.joinable(); } /// Start an invocation thread and repeatedly invoke the function (in the given period) /// after the given delay. /// - If a previous invocation thread is active, no invocation of the function /// takes place. /// - After the first invocation of the function (at least one is done): /// - If the period is or has become zero (due to a call to stop) the /// invocation thread stops without any further invocation of the function. /// - As long as an invocation of the function has not finished, the next /// possible invocation is delayed by the given period. /// \EXCEPTION All exceptions stop the invocation thread and the exception of the /// last invocation is avaliable through a call to rethorow_exception. /// \RETURN True if no previous call to start is active, otherwise false. /// \NOTE The period is not an exact value (due to interleaving calls between /// each invocation of the function). public: template &lt; typename Period, typename PeriodRatio, typename Delay, typename DelayRatio&gt; bool start( const std::chrono::duration&lt;Period, PeriodRatio&gt;&amp; period, const std::chrono::duration&lt;Delay, DelayRatio&gt;&amp; delay) noexcept; /// Start an invocation thread and repeatedly invoke the function without delay. template &lt;typename Period, typename PeriodRatio&gt; bool start(const std::chrono::duration&lt;Period, PeriodRatio&gt;&amp; period) noexcept { return start(period, std::chrono::duration&lt;Period, PeriodRatio&gt;::zero()); } /// Set the period of invocations to zero. /// If an invocation thread is active, stop invocations of the function /// and wait until the thread has finished. /// \SEE std::thread::join void stop() { m_period = period_type::zero(); if(active()) m_thread.join(); } // Period // ====== public: const period_type&amp; period() const noexcept { return m_period; } // Exception // ========= public: /// True if an exception occured in the last invocation thread. bool exception() const { return bool(m_exception); } /// Throw the exception of the last invocation thread, if availabe. void rethrow_exception() const { if(exception()) std::rethrow_exception(m_exception); } // Utility [invoke_synchron] // ========================= private: void invoke_synchron() { invoke_synchron(std::is_same&lt;value_type, void&gt;()); } // not void void invoke_synchron(std::false_type) { static_cast&lt;Derived*&gt;(this)-&gt;transfer(m_function()); } // void void invoke_synchron(std::true_type) { m_function(); } // Utility [invoke_asynchron] // ========================== private: void invoke_asynchron() { m_future = std::async(std::launch::async, m_function); } // Utility [transfer_asynchron] // ============================ private: void transfer_asynchron() { transfer_asynchron(std::is_same&lt;value_type, void&gt;()); } // not void void transfer_asynchron(std::false_type) { static_cast&lt;Derived*&gt;(this)-&gt;transfer(m_future.get()); } // void void transfer_asynchron(std::true_type) { m_future.get(); } private: function_type m_function; period_type m_period; std::thread m_thread; future_type m_future; std::exception_ptr m_exception; }; // Start/Stop // ========== template &lt;typename Value, typename Derived&gt; template &lt; typename Period, typename PeriodRatio, typename Delay, typename DelayRatio&gt; bool PeriodicFunction&lt;Value, Derived&gt;::start( const std::chrono::duration&lt;Period, PeriodRatio&gt;&amp; period, const std::chrono::duration&lt;Delay, DelayRatio&gt;&amp; delay) noexcept { if(active()) return false; try { m_exception = std::exception_ptr(); m_period = std::chrono::duration_cast&lt;period_type&gt;(period); m_thread = std::thread([this, delay]() { try { std::this_thread::sleep_for(delay); if(this-&gt;m_period == period_type::zero()) this-&gt;invoke_synchron(); else { this-&gt;invoke_asynchron(); while(true) { std::this_thread::sleep_for(this-&gt;m_period); if(this-&gt;m_period != period_type::zero()) { if(this-&gt;m_future.wait_for(period_type::zero()) == std::future_status::ready) { this-&gt;transfer_asynchron(); this-&gt;invoke_asynchron(); } } else { this-&gt;m_future.wait(); this-&gt;transfer_asynchron(); break; } } } } catch(...) { this-&gt;m_exception = std::current_exception(); } }); } catch(...) { this-&gt;m_exception = std::current_exception(); } return true; } } // namespace Detail // PeriodicFunction // ============================================================================= template &lt;typename Value&gt; class PeriodicFunction : public Detail::PeriodicFunction&lt;Value, PeriodicFunction&lt;Value&gt;&gt; { // Types // ===== private: typedef Detail::PeriodicFunction&lt;Value, PeriodicFunction&lt;Value&gt;&gt; Base; friend Base; public: typedef typename Base::period_type period_type; typedef typename Base::value_type value_type; typedef std::list&lt;value_type&gt; result_type; private: typedef std::mutex mutex; // Construction // ============ public: template &lt;typename Callable, typename... Arguments&gt; PeriodicFunction(Callable&amp;&amp; callable, Arguments&amp;&amp;... arguments) : Base(callable, std::forward&lt;Arguments&gt;(arguments)...) {} // Result // ====== /// True, if the internal result buffer is empty. bool empty() const { return m_result.empty(); } /// Return the current result of invocations of the function and clear /// the result buffer. /// \NOTE If the invoking thread is still running, new results /// might become available. result_type result() { std::lock_guard&lt;mutex&gt; guard(m_result_mutex); return std::move(m_result); } // Utility // ======= private: void transfer(value_type&amp;&amp; result) { std::lock_guard&lt;mutex&gt; guard(m_result_mutex); m_result.push_back(result); } private: mutex m_result_mutex; result_type m_result; }; // PeriodicFunction&lt;void&gt; // ====================== template &lt;&gt; class PeriodicFunction&lt;void&gt; : public Detail::PeriodicFunction&lt;void, PeriodicFunction&lt;void&gt;&gt; { // Types // ===== private: typedef Detail::PeriodicFunction&lt;void, PeriodicFunction&lt;void&gt;&gt; Base; friend Base; public: typedef typename Base::period_type period_type; typedef typename Base::value_type value_type; // Construction // ============ public: template &lt;typename Callable, typename... Arguments&gt; PeriodicFunction(Callable&amp;&amp; callable, Arguments&amp;&amp;... arguments) : Base(callable, std::forward&lt;Arguments&gt;(arguments)...) {} }; // Test // ==== #define TEST_OUTPUT 0 class Exception : public std::runtime_error { public: Exception() noexcept : std::runtime_error("Test") {} }; const unsigned f_limit = 10; std::atomic&lt;unsigned&gt; f_count; char f() { ++f_count; return '.'; } const unsigned g_limit = 3; std::atomic&lt;unsigned&gt; g_count; void g() { if(++g_count == g_limit) throw Exception(); } int main() { try { using std::chrono::milliseconds; // With Return Type { PeriodicFunction&lt;char&gt; invoke(f); #if(TEST_OUTPUT) std::ostream&amp; stream = std::cout; #else std::ostream null(0); std::ostream&amp; stream = null; #endif invoke.start(milliseconds(10)); for(unsigned i = 0; i &lt; f_limit; ++i) { std::this_thread::sleep_for(milliseconds(100)); if(i == f_count - 1) invoke.stop(); auto result = invoke.result(); for(const auto&amp; r : result) stream &lt;&lt; r; stream &lt;&lt; '\n'; } } // Void { PeriodicFunction&lt;void&gt; invoke(g); invoke.start(milliseconds(10), milliseconds(100)); // A thread shall throw an exception before stopping std::this_thread::sleep_for(milliseconds(200)); invoke.stop(); try { invoke.rethrow_exception(); } catch(Exception) { return 0; } } } catch(...) {} return -1; } </code></pre> <p><strong>Fixes:</strong></p> <p>The stop function will fail if called from the same thread, hence I changed it to:</p> <pre><code>void stop() { m_period = period_type::zero(); if(is_active() &amp;&amp; std::this_thread::get_id() != m_thread.get_id()) m_thread.join(); } </code></pre> <p>The <code>PeriodicFunction::result()</code> does not clear the internal state of the result container after the move:</p> <pre><code>result_type result() { std::lock_guard&lt;std::mutex&gt; guard(m_result_mutex); result_type result(std::move(m_result)); m_result.clear(); return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T13:23:28.527", "Id": "82945", "Score": "0", "body": "`typedef std::mutex mutex;`? Also you can't return -1 from `main`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T19:21:40.850", "Id": "84987", "Score": "0", "body": "@no1 You can, in fact, return `-1` from `main`. It has the effect of calling `std::exit` with an argument of `-1`, which, according to [support.start.term], has implementation-defined behavior. On POSIX systems, this is equivalent to returning 255." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T19:40:36.467", "Id": "84992", "Score": "0", "body": "@ruds I said that because he likely expected a `$?` = `-1`, but that won't happen since the shell uses an 8 bit unsigned int (char o whatever) for the return type.\nAlso, in case of failure, you should return a positive value different from zero." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T20:44:30.677", "Id": "85014", "Score": "0", "body": "The EXIT_FAILURE macro, defined in <cstdlib>, is probably a good default if you don't intend to return specific statuses to the shell." } ]
[ { "body": "<p>Generally speaking, the code already seems really good. Therefore, I have nothing more than a few notes:</p>\n\n<ul>\n<li><p>It is more of a matter of taste, but I would use some <a href=\"http://en.cppreference.com/w/cpp/language/type_alias\" rel=\"nofollow noreferrer\">type aliases</a> instead of the old <code>typedef</code>. The type aliases can be templated (contrary to <code>typedef</code>) and provide a syntax that is close to variable assignements (<code>auto a = 89;</code>) and namespace aliases (<code>namespace foobar = foo::bar;</code>). That means that you can write code which looks more consistent:</p>\n\n<pre><code>using period_type = std::chrono::milliseconds;\nusing value_type = Value;\n\nusing function_type = std::function&lt;Value ()&gt;;\nusing future_type = std::future&lt;Value&gt;;\n</code></pre></li>\n<li><p>C++ has special syntax to import type names from a base class without having to use a full <code>typedef</code> or type alias, you can use it to reduce the amount of code and make explicit your intent in <code>PeriodicFunction</code>:</p>\n\n<pre><code>using typename Base::period_type;\nusing typename Base::value_type;\n</code></pre></li>\n<li><p><code>typedef std::mutex mutex;</code> seems useless and potentially confusing. I would drop the <code>typedef</code> and use <code>std::mutex</code> everywhere instead. It shouldn't hinder readability.</p></li>\n<li><p>In <a href=\"https://codereview.stackexchange.com/a/46815/15094\">their answer</a> to your previous question, @ruds said that <code>Timer::m_results</code> should not be <code>mutable</code>, which is right, but I see no harm in having the corresponding <code>std::mutex</code> be <code>mutable</code>. It does not seem to be currently useful though.</p></li>\n<li><p>Really no more than a tidbit, but namespaces are generally lowercase. Consider replacing <code>Detail</code> by <code>detail</code>.</p></li>\n<li><p>Functions that return a <code>bool</code> tend to be more understandable when their name is more than just a name. For example, <code>bool exception() {}</code> makes me think that the function returns an <code>std::exception</code> or a derived class (which would be odd). Consider renaming it <code>exception_occured</code> instead. Also, consider renaming <code>active</code> to <code>is_active</code>.</p>\n\n<p>Unfortunately, the standard library containers have a function <code>empty</code> while <code>is_empty</code> would have been a better name (\"empty\" somehow means \"empty that container\" to me); I understand that you keep this particular name for consistency.</p></li>\n</ul>\n\n<p>Discussing what can be improved is good, but I also want to put a note about what you did right: tag dispatching with <code>std::true_type</code> and <code>std::false_type</code> is great. It helps to write simple and readable code and to avoid some <code>std::enable_if</code> and template boilerplate. You also correctly implemented perfect forwarding and used proper scoped locks. Kudos for that :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T12:56:09.780", "Id": "48327", "ParentId": "47347", "Score": "8" } } ]
{ "AcceptedAnswerId": "48327", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T12:15:59.717", "Id": "47347", "Score": "10", "Tags": [ "c++", "multithreading", "c++11", "timer" ], "Title": "Follow-up: Timer utilizing std::future" }
47347
<p>So, I wanted a separate project to act as the data layer for my website project.</p> <p>Classes in the website should reference the data layer after getting input from the user and should get back information regarding the result of whatever actions are performed and then communicate those results to the user.</p> <p>The following is an example of how I've got it set out. This example deletes a user record from the database:</p> <pre><code>// Website/Admin/Users.aspx.cs protected void btnDelete_Click(object sender, EventArgs e) { User us = new User(Convert.ToInt32(Session["ActionUserID"])); if (us.Delete()) { lblResult.Text = "User record was successfully deleted."; } else { lblResult.Text = us.errmsg; } } // Website/App_Code/User.cs // // For simplicity sake, I've removed code that isn't needed in this example public int userid { get; protected set; } public string errmsg { get; protected set; } public User(int UserID) { userid = UserID; } public bool Delete() { OrtundUser ou = new OrtundUser(userid); if (ou.Delete()) { return true; } else { errmsg = ou.errmsg; return false; } } // DataProject/OrtundUser.cs public int userid { get; protected set; } public string errmsg { get; protected set; } OrtundData od = new OrtundData(); // instantiate the DbContext public OrtundUser(int UserID) { userid = UserID; } public bool Delete() { try { var user = (from u in od.users where u.userid == userid select u).FirstOrDefault(); if (user != null) { od.Remove(user); od.SaveChanges(); return true; } } catch (Exception ex) { errmsg = ex.InnerException; return false; } } </code></pre> <p>I feel like there's a lot of repetition of code here. I know this will work as intended, but I don't know if it's as efficient as it could be. (for example, the KISS principle would argue the existence of App_Code/User.cs at all ... why not just reference the DataProject directly?)</p> <p>If anyone can provide any suggestions for me to improve this (particularly with a look at removing redundant code) - possibly explaining any concepts that I may seem to be misunderstanding - I'd really appreciate it.</p>
[]
[ { "body": "<p>A couple of general points:</p>\n\n<p>You shouldn't be using properties to set an error message like that. The error message is associated with the action you attempted on the object- in this case the delete- not the object itself. After the error has been handled, it doesn't make any sense for the property to continue holding that error message. It also potentially adds unnecessary concurrency woes. </p>\n\n<p>You could fix that by wrapping up the bool you're returning and the message into a class, like <code>DbActionResult</code>. Or you could make the message an <code>out</code> parameter. But this still isn't a great solution because you have a leaking of concerns between your layers. Why should the data layer directly dictate what's being displayed in the UI like that? Better options would be either:</p>\n\n<ul>\n<li>Return some kind of status code from the data layer, and have the UI display a message based on that code. If you don't need any more information in the UI than just whether or not it passed, a bool would be sufficient. If you want to log the exact exception details for debugging, that can be done with some kind of logging framework</li>\n</ul>\n\n<p>OR</p>\n\n<ul>\n<li>Don't catch the exception at all. Or if you do catch it to do some kind of handling/logging, rethrow it. That way you can access it directly in the UI layer if necessary, but the UI decides how to handle turning that exception into a message to display to the user, rather than the data layer doing it.</li>\n</ul>\n\n<p>Also, this may have just been because it was an example, but <code>OrtundUser</code> is a bad name for a class. A <code>User</code> is a <code>User</code>, it shouldn't be a <code>UserWhichIsPersistedInAParticularWay</code>. That violates the Single Responsibility Principle, as it now has to take responsibility not only for what it's actually supposed to do- represent a user- but also do at least some management of its own persistence. You also have a similar problem with your actual <code>User</code> class, though it's not reflected in the name. By putting the <code>Delete</code> method on the user, it now has to be concerned not only with what it actually is, but with how to persist itself</p>\n\n<p>This is related to the actual meat of the question. Your first step should be to separate your <code>User</code> class out into <code>User</code> and <code>UserRepository</code> like so:</p>\n\n<pre><code>public class User\n{\n public int userid { get; set; }\n}\n\npublic class UserRepository\n{\n public bool Delete(User user)\n {\n //Delete logic goes here\n }\n}\n</code></pre>\n\n<p>That's not a full example, but it'll be refined later. Hopefully you can see how this has now separated out different responsibilities into their own classes.</p>\n\n<p>From your mention of <code>DbContext</code> in a comment, I assume you're using Entity Framework. EF actually already provides you with a class that will serve the purpose <code>UserRepository</code> here, which is <code>DbSet&lt;User&gt;</code>. You should be able to get that from your <code>OrtundData</code>. That class will handle operations like Delete for you. So in fact the only class from the above example that you actually need is the <code>User</code> class.</p>\n\n<p>(As a side note, this is an implementation of what's called the 'repository pattern'. If you look this up, you'll see it's often recommended that even when using Entity Framework, you add your own repository class on top- <code>UserRepository</code> in the above example. I wouldn't worry about that at the moment, it adds another layer of abstraction which can be valuable in some cases, but don't do it without understanding why. It's more important to get the basics in place.)</p>\n\n<p>So finally coming to whether <code>User</code> and <code>OrtundUser</code> are redundant. Yes, they are. Once you remove the persistence logic from both of them as described above, you're left with nothing but a property bag which is identical for both of them. You should delete <code>OrtundUser</code>, and push <code>User</code> down into your data layer. </p>\n\n<p>In fact, in large solution you could push futher- have a \"Core\" project referenced by both the UI and Data projects which contains your domain objects like User. Data would then reference Core, and UI would reference both Data and Core. In your case, actually structuring your solution like this is likely to be unnecessary, but it's a good way to think about it conceptually.</p>\n\n<p>So, finally, with all of the above applied your code might look something like this (again this is omitting some details like construction, just leaving you with the key bits):</p>\n\n<pre><code>// Website/Admin/Users.aspx.cs\nprivate DbSet&lt;User&gt; _userRepository;\nprivate SomeSortOfLogger _logger;\n\nprotected void btnDelete_Click(object sender, EventArgs e)\n{\n User us = new User(Convert.ToInt32(Session[\"ActionUserID\"]));\n\n try\n {\n _userRepository.Delete(us);\n lblResult.Text = \"User record was successfully deleted.\";\n }\n catch(Exception e)\n {\n _logger.Log(e);\n lblResult.Text = \"There was an error, see log for details\";\n }\n}\n\n// DataProject/User.cs\npublic int userid { get; protected set; }\n\npublic User(int UserID)\n{\n userid = UserID;\n}\n</code></pre>\n\n<p>There's likely still scope for improvement- e.g. adding a better way of doing exception/error handling and logging, dependency injection. But those would be beyond the scope of this question.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T01:11:18.043", "Id": "47417", "ParentId": "47350", "Score": "4" } }, { "body": "<p>The most important thing that needs to be fixed that I see:</p>\n\n<pre><code>User us = new User(Convert.ToInt32(Session[\"ActionUserID\"]));\n</code></pre>\n\n<h2>Using Session State for Request Data</h2>\n\n<p><strong>Consider this example scenario:</strong></p>\n\n<p>Suppose the user views a <code>User</code> userOne in one page then another <code>User</code> userTwo on another page, say two compare them against each other. Then he decides that the two <code>User</code>s are duplicates and userOne is the superfluous one. So he goes back to the page displaying userOne and click \"Delete\" button. But because the page displaying userTwo was loaded later it overwritten the <code>Session[\"ActionUserID\"]</code> property with the ID of userTwo. Therefore userTwo is deleted even though the user clicked the \"Delete\" on userOne's page.</p>\n\n<p>Using session and application state should be avoided as much as possible:</p>\n\n<ul>\n<li><p>The state associated with a page goes in the <a href=\"http://blogs.microsoft.co.il/gilf/2008/05/05/aspnet-client-side-state-management/\" rel=\"nofollow noreferrer\"><code>ViewState</code> or hidden fields etc</a>.</p></li>\n<li><p>The state associated with a session goes in the <code>Session</code>.</p></li>\n<li><p>The state associated with the whole application goes in the <code>HttpContext.Application</code>.</p></li>\n</ul>\n\n<h2>Using Magic Constants as Keys</h2>\n\n<p>You are getting <code>Session[\"ActionUserID\"]</code> above, i.e. <code>... = ... Session[\"ActionUserID\"] ...</code>\nThere must be somewhere else that you must be setting it, i.e. something like <code>Session[\"ActionUserID\"] = user.ID</code>. Suppose you decided to rename the key from <code>\"ActionUserID\"</code> to <code>\"UserID\"</code>, but instead renamed one occurence to \"UserID\" and the other to \"UserId\". You have a serious bug, but your application happily builds.</p>\n\n<p>All string keys should be defined as constants:</p>\n\n<pre><code>private const string UserIdKey = \"ActionUserID\";\n</code></pre>\n\n<p>Now if you type <code>UserIDKey</code> instead of <code>UserIdKey</code> you have a build error right away. If you decide to change the key value, just change the constant value and it will work (for all new sessions that is. You should make sure that you do not need to change keys often.)</p>\n\n<p>For other points see <a href=\"https://codereview.stackexchange.com/a/47417/20251\">@BenAaronson's answer</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T07:32:58.307", "Id": "47443", "ParentId": "47350", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T13:11:36.957", "Id": "47350", "Score": "5", "Tags": [ "c#", "object-oriented" ], "Title": "OOP between projects" }
47350
<p>I can have a maximum of three concurrent threads processing tasks. Each of these threads can process 1 to 100 tasks simultaneously (by connecting to an external system). The time taken to process 100 tasks at once in one thread is the same as it takes to process 1 task in one thread because the overhead of connecting to the external system is what takes 95% of the time. Tasks come in at random intervals from other threads in the application, these threads need to block until the task is done, or a timeout is hit. Responding quickly to the threads submitting tasks is the primary goal here, and making use of the ability to process tasks in batch is secondary (but useful and important when we have a big queue of tasks as it saves time).</p> <p>This code works (or appears to anyway), but before I build it into my larger application I want to check that this can't be done better/faster etc. It has the potential to create a major bottleneck in the application so I want to make sure it is done in the most efficient way possible. I'm not very experienced with the concurrent package. Any feedback would be greatly appreciated.</p> <p>Here is the concept code that I have written to test with. System outs will be replaced with logging when it is built into the main application.</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; public class TaskProcessor implements Runnable { private final LinkedBlockingQueue&lt;Task&gt; queue = new LinkedBlockingQueue&lt;&gt;(); private final Semaphore semaphore = new Semaphore(3); private final Executor executor = Executors.newCachedThreadPool(); public static void main(final String[] args) { final TaskProcessor taskProcessor = new TaskProcessor(); new Thread(taskProcessor).start(); for (int i = 0; i &lt; 20; i++) { new Thread(new Runnable() { @Override public void run() { try { taskProcessor.submitTask(new Task()); } catch (final InterruptedException e) { throw new RuntimeException(e); // unreachable } } }).start(); } } private static class Task { public void setResult() {} public void getResult() {} } public void submitTask(final Task task) throws InterruptedException { final long taskStartTime = System.currentTimeMillis(); this.queue.add(task); synchronized (task) { task.wait(); System.out.println("task complete after " + (System.currentTimeMillis() - taskStartTime) + "ms"); } task.getResult(); } @Override public void run() { try { while (true) { this.semaphore.acquire(); // blocks until we can get a permit final List&lt;Task&gt; tasks = new ArrayList&lt;&gt;(); System.out.println("waiting for task"); tasks.add(this.queue.take()); // will block if the queue is empty // get all the other tasks in the queue Task nextTask = this.queue.poll(); while (nextTask != null &amp;&amp; tasks.size() &lt; 100) { tasks.add(nextTask); nextTask = this.queue.poll(); } this.processTasks(tasks); } } catch (final InterruptedException e) { throw new RuntimeException(e); // unreachable } } private void processTasks(final List&lt;Task&gt; tasks) { final Runnable runnable = new Runnable() { @Override public void run() { try { TaskProcessor.this.executeTasks(tasks); for (final Task task : tasks) { task.setResult(); // once fully implemented will set the result to be the result of exeuteTasks() synchronized (task) { task.notify(); } } } finally { TaskProcessor.this.semaphore.release(); } } }; this.executor.execute(runnable); } private void executeTasks(final List&lt;Task&gt; tasks) { try { System.out.println("executing " + tasks.size() + " tasks."); Thread.sleep(1000); } catch (final InterruptedException e) { e.printStackTrace(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:42:49.080", "Id": "82971", "Score": "0", "body": "I've rollback your last edit, you should modify your code base on feedback that you received from an answer, because this can invalidate answer. Please see this meta-post about [appropriate ways to edit your post after it has been reviewed](http://meta.codereview.stackexchange.com/questions/1482/can-i-edit-my-own-question-to-include-suggested-changes-from-answers)." } ]
[ { "body": "<p>I am not a Java expert, but</p>\n\n<ul>\n<li>In your description you talk about tasks and jobs, however your code is only using task, which makes your code harder to follow.</li>\n<li>If you are going to log <code>\"waiting for task\"</code> then you should also log <code>\"waiting for semaphore\"</code></li>\n<li>Related to that, I have a suspicion that your semaphore approach does not work, you should try to run more than 3 tasks.</li>\n<li>I would allow the caller to pass <code>3</code> and <code>100</code> as parameters or read this from a config file or environment variables</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:38:49.213", "Id": "82970", "Score": "0", "body": "Thanks, to respond to your bullet points: 1. I removed all references to 'jobs', you're quite right that was confusing. Hopefully the updated first paragraph makes the problem clearer. 2. Added extra logging as suggested. 3. This code runs and appears to work, so I think the semaphore is working, could you elaborate on that point? 4. Good point, when this code is integrated into the larger application I will make use of the existing config system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:47:34.560", "Id": "82973", "Score": "0", "body": "Now your code will be even more confusing, because you have tasks running tasks ? I would have suggested to re-introduce jobs. As for point 3, if you see the metaphor work and never have more than 3 main tasks, then I was probably wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:54:40.797", "Id": "82975", "Score": "0", "body": "Well, the code as it stands uses a TaskProcessor class to process Tasks or Task groups in anonymous threads, so I think it was the description that was confusing the issue. Also as Marc-Andre pointed out I can't modify the code posted, so hopefully changing the description helps people understand what I'm trying to do here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:03:39.180", "Id": "47355", "ParentId": "47352", "Score": "3" } }, { "body": "<blockquote>\n <p>I can have a maximum of three concurrent threads processing tasks. Each of these threads can process 1 to 100 tasks simultaneously (by connecting to an external system). </p>\n</blockquote>\n\n<p>Q: How many threads should you have? A: 4 - the management thread, and 3 worker threads.</p>\n\n<p>How many threads are in your code? At least 24 .... potentially hundreds .... let's count them...</p>\n\n<ol>\n<li>The current thread</li>\n<li>20 threads created in the <code>main</code> method</li>\n<li>The CachedThreadPool has no upperbound on the number of threads, and will create a new thread each time you call <code>this.executor.execute(runnable);</code> but, that is gated by the Semaphore</li>\n</ol>\n\n<p>About that Semaphore.... Your code is asymmetrical in the sense that the semaphore is acquired in one class, and released in another (the Runnable)., This makes it hard to follow.</p>\n\n<p>Fundamentally, though, your system is a poor example of using the <code>java.util.concurrent.*</code> package, and there are more 'idiomatic' ways to do this:</p>\n\n<pre><code>// no interruptedException handling, not validated... just to give you the idea.\npublic class TaskProcessor {\n\n private static final class RemoteTask implements Callable&lt;List&lt;Task&gt;&gt; {\n private final List&lt;Task&gt; tasks;\n public RemoteTask(List&lt;Task&gt; torun) {\n this.tasks = torun;\n }\n\n public List&lt;Task&gt; call() {\n // submit all torun tasks to the remote system\n // get the results.... and populate the return value:\n .....\n return tasks;\n }\n }\n\n private final class TaskManager implements Runnable {\n public void run () {\n\n\n boolean done = false;\n while (!done) {\n List&lt;Task&gt; tosubmit = new ArrayList&lt;&gt;(CHUNKSIZE);\n tosubmit.add(queue.take());\n queue.drainTo(tosubmit, CHUNKSIZE - 1);\n Task last = tosubmit.get(tosubmit.size() - 1);\n if (last == null) {\n done = true;\n tosubmit.remove(tosubmit.size() -1);\n }\n if (!tosubmit.isEmpty()) {\n service.submit(new RemoteTask(tosubmit));\n }\n }\n service.shutDown();\n service.awaitTermination(); \n }\n }\n\n\n private static final int THREADS = 3;\n private static final int CHUNKSIZE = 100;\n\n private final ExecutorService service;\n\n private final LinkedBlockingQueue&lt;Task&gt; queue = new LinkedBlockingQueue&lt;&gt;();\n\n public TaskProcessor() {\n service = Executors.getFixedThreadPool(THREADS);\n Thread managerthread = new Thread(new TaskManager(), \"Task Manager Thread\");\n managerthread.setDaemon(true);\n managerthread.start();\n }\n\n public void submitTask(Task task) {\n queue.put(task);\n }\n\n .....\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:52:33.157", "Id": "83139", "Score": "0", "body": "Thanks, this is very helpful. I have a couple of questions... how should the thread calling submitTask get told that the task is finished? Should I use wait/notify like I did in my example? (notify at the end of your call(..) method? or is there a better way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:53:29.647", "Id": "83140", "Score": "0", "body": "On the threads point, I was trying to say in the description that we can only have 3 simultaneous connections to the external system. So three concurrent task processing threads. The actual number of threads running in the system is not an issue (there will be up to 50 submitting tasks to this TaskProcessor, and then waiting for the result before resuming). Having a manager thread seems unavoidable because of the requirement to sometimes process groups of tasks instead of single tasks?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:46:28.723", "Id": "47374", "ParentId": "47352", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T13:25:41.113", "Id": "47352", "Score": "11", "Tags": [ "java", "concurrency" ], "Title": "Concurrent task processing queue" }
47352
<p>I'm making a simple guessing game in C. Basically what I need is some help double-checking my work, more specifically a verification that the my binary search in my case statements look okay. The goal is to have an initial guess of 50, then work off that. If "L" is selected, the search goes from 51-100, if "H", it would be 1-49, blah-blah - the usual stuff scaling down to the correct guess.</p> <p>Is this correct? </p> <p>I'm also getting a C99 function implementation error using the actual letters as case labels -- just to explain why they're the ASCII equivalents.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; int main(int argc, const char * argv[]) { int low; int high; int guess; int response; printf("Pick an integer from 1 to 100 and I will try to guess it.\n"); printf("If I guess too low, respond with a L.\n"); printf("If I guess too high, respond with a H.\n"); printf("If I guess correctly, respond with a Y.\n"); high = 100; low = 1; while(response != 'Y') { guess = (high + low) / 2; printf("Okay, let's start. Is it %d?\n", &amp;guess); printf("Please respond with L, H, or Y.\n"); scanf("%d", &amp;response); response = toupper(response); switch(response) { case 72: high = guess - 1; break; case 76: low = guess + 1; break; case 89: printf("Yes! I knew I could do it.\n"); break; default: printf("I didn't get that; you gave an invalid response.\n"); printf("Please try again.\n"); } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:30:29.223", "Id": "82965", "Score": "0", "body": "The \"C99 function implementation error\" that you are experiencing is because you have not enabled C99 mode with your compiler; it isn't because C99 doesn't support it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:36:32.253", "Id": "82967", "Score": "0", "body": "Interesting! That's really good to know. Thank you for this! @syb0rg" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T19:33:08.507", "Id": "83021", "Score": "0", "body": "sounds almost like the beginning of a sort method too. you could probably adapt it at some point...just saying my thoughts when I read the first paragraph" } ]
[ { "body": "<p>Looks good to me. I can only nitpick:</p>\n\n<ul>\n<li>Instead of <code>printf(\"...\\n\")</code>, it's better to use <code>puts(\"...\")</code></li>\n<li>If you really <em>must</em> use the ASCII codes, then at least add a comment there to know that 72 is <code>H</code>, 76 is <code>L</code>, and so on.</li>\n<li>You should indent code blocks within braces <code>{ ... }</code>, for example the body of the <code>main</code> method and the <code>while</code> loop. Near the end of the code it's confusing to see several lines with unindented <code>}</code>, I lose track of which one closes what...</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:05:28.740", "Id": "82977", "Score": "0", "body": "Good call on the commenting to denote the ASCII. Will do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:57:28.250", "Id": "83210", "Score": "0", "body": "Why is `puts()` preferable? Is because of the implied newline?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:19:06.667", "Id": "83214", "Score": "3", "body": "@piperchester since `puts` does't need to handle formatting characters, it has a simpler implementation = smaller possiblity of bugs = faster. And yes, if you want to print a newline anyway, then `puts` is less typing, so more convenient." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:32:23.903", "Id": "47357", "ParentId": "47353", "Score": "12" } }, { "body": "<ul>\n<li><p>If you're not going to use the command line parameters, replace them with a single <code>void</code> (only for C):</p>\n\n<pre><code>int main(void) {}\n</code></pre></li>\n<li><p>Everything within curly braces, especially <code>main()</code>, should be indented. This should also be done <em>consistently</em>, not just in some select or random places.</p></li>\n<li><p>Don't just list variable declarations at the start of a function by default:</p>\n\n<pre><code>int low;\nint high;\nint guess;\nint response;\n</code></pre>\n\n<p>It's best to initialize them as close to their use as possible, that way you'll know where they belong and if they're still in use while maintaining the code.</p>\n\n<p>For instance, <code>high</code> and <code>low</code> can be initialized right away:</p>\n\n<pre><code>int high = 100;\nint low = 1;\n</code></pre></li>\n<li><p>For unformatted outputs, such as the first four outputs, prefer <code>puts()</code> over <code>printf()</code>. Also note that the former adds an automatic <code>\"\\n\"</code> at the end of the output.</p></li>\n<li><p>Other reviewers have mentioned instances of broken code. You should compile at a high warning level with the <code>-Wall</code> flag and (ideally) have them treated as <em>compiler errors</em> with <code>-Werror</code>. More info about GCC compiler flags <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html\" rel=\"nofollow\">here</a>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:48:55.537", "Id": "83030", "Score": "0", "body": "really `guess` could be initialized right away as well, and we could skip the calculation the first time around, but that might make more work for this program" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:56:55.790", "Id": "83032", "Score": "1", "body": "@Malachi: Right. I've just mentioned those first two as they're the first to appear, and it should still give the OP the right idea." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:05:41.693", "Id": "47362", "ParentId": "47353", "Score": "17" } }, { "body": "<p>Your indentation is off.</p>\n\n<hr>\n\n<p>you aren't actually using the program arguments, so there isn't any reason to include them in your main signature.</p>\n\n<hr>\n\n<p>I was able to compile and run using <code>case 'H':</code>, perhaps I wasn't using c99. So perhaps just don't use c99 :). If you have to use it, then declare those ints as symbols or consts above <code>#DEFINE H 72</code>, then you can say <code>case H:</code></p>\n\n<hr>\n\n<p>A <code>do-while</code> loop would logically serve you better here. Aditionally, because you didn't give response a default value, who knows what garbage is in it, maybe it actually is <code>'Y'</code>.</p>\n\n<hr>\n\n<p>I typically don't place code on the same line as <code>case &lt;&gt;:</code> unless I am 1-lining the whole thing.</p>\n\n<hr>\n\n<p>You didn't include a <code>break</code> on your <code>default</code> condition, this isn't wrong, I just want to point out that some people like to see it for consistency's sake.</p>\n\n<hr>\n\n<p>I like my variables to only be in the scope they are needed. For your case this would be guess not being in the loop.</p>\n\n<hr>\n\n<h2>Edited additional points</h2>\n\n<p>In this line <code>printf(\"Okay, let's start. Is it %d?\\n\", &amp;guess);</code> you'll notice that you are printing the address of <code>guess</code> not the value of <code>guess</code> as denoted by the <code>&amp;</code>, remove this if you want your program to run properly.</p>\n\n<hr>\n\n<p>Point of affirmation, this is indeed a good binary search. finding halfway between your highest and lowest values will get you to the answer on average the quickest. </p>\n\n<hr>\n\n<p>All the changes:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;ctype.h&gt;\n\nint main(int argc, const char * argv[])\n{\n printf(\"Pick an integer from 1 to 100 and I will try to guess it.\\n\");\n printf(\"If I guess too low, respond with a L.\\n\");\n printf(\"If I guess too high, respond with a H.\\n\");\n printf(\"If I guess correctly, respond with a Y.\\n\");\n\n int low = 1;\n int high = 100;\n int response;\n\n do\n {\n int guess = (high + low) / 2;\n\n printf(\"Okay, let's start. Is it %d?\\n\", guess);\n printf(\"Please respond with L, H, or Y.\\n\");\n scanf(\"%d\", &amp;response);\n response = toupper(response);\n\n switch(response)\n {\n case 'H': high = guess - 1; break;\n case 'L': low = guess + 1; break;\n case 'Y': printf(\"Yes! I knew I could do it.\\n\"); break;\n default: printf(\"I didn't get that; you gave an invalid response.\\nPlease try again.\\n\"); break;\n }\n } while(response != 'Y');\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:31:21.913", "Id": "82986", "Score": "0", "body": "Awesome! Thank you so much :)\nDoes my binary search algorithm setup look okay? I'm a little unsure about it being correct or not, took me forever to figure out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:43:51.650", "Id": "82992", "Score": "0", "body": "You probably were using C99 when you put the characters in the `switch`. Depending on your compiler configuration, it may or may have not generated a warning though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:13:54.077", "Id": "82995", "Score": "1", "body": "Both gcc and clang compile the version with chars just fine for me. I currently also don't see why they wouldn't? What definitely should work is `(int)'H'`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:43:21.590", "Id": "83000", "Score": "0", "body": "@petrichor, I added a couple points, including a remark on your searching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-16T04:22:27.463", "Id": "157183", "Score": "0", "body": "C99 doesn't let you compare a character literal to an `int`? but it shouldn't be an `int` anyway." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:12:03.370", "Id": "47363", "ParentId": "47353", "Score": "9" } }, { "body": "<p>I'm late to the game, but here are a few notes that I didn't see mentioned:</p>\n\n<ul>\n<li><p>I already went over this in the comments, but when you said that you have a \"C99 function implementation error\", that is because you haven't set you compiler standard support to C99. With GCC, you can do this with <code>--std=c99</code>. But why would we use the C99 standard when the current standard is C11? And what if we want some useful GNU extensions? You can enable those in GCC with either <code>--std=c11</code> or <code>--std=gnu11</code>. I would recommend at least using the C11 standard.</p></li>\n<li><p>Extrapolate your block of text you want to output to the console into its own string.</p>\n\n<pre><code>const char introMessage[] =\n \"Pick an integer from 1 to 100 and I will try to guess it.\\n\"\n \"If I guess too low, respond with a L.\\n\"\n \"If I guess too high, respond with a H.\\n\"\n \"If I guess correctly, respond with a Y.\\n\";\n</code></pre>\n\n<p>Then printing is a bit more simple, and reusable if needed (such as if you want to play the game again without quitting the application). </p>\n\n<pre><code>puts(introMessage);\n</code></pre>\n\n<p><a href=\"https://github.com/git/git/blob/master/git.c\" rel=\"nofollow\">This is the more common approach to printing large blocks of text in the real world</a>, especially when you have to print it out multiple times.</p></li>\n<li><p>This was already mentioned, but it needs to be emphasized. You need to watch your indentation. It improves readability by a lot, allowing you to comprehend and produce code more quickly.</p></li>\n<li><p>You don't have to return <code>0</code> at the end of <code>main()</code>, just like you wouldn't bother putting <code>return;</code> at the end of a <code>void</code>-returning function. The C standard knows how frequently this is used, and lets you not bother.</p>\n\n<blockquote>\n <p><strong>C99 &amp; C11 §5.1.2.2(3)</strong></p>\n \n <p>...reaching the <code>}</code> that terminates the <code>main()</code> function returns a\n value of <code>0</code>.</p>\n</blockquote></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:55:50.757", "Id": "83031", "Score": "0", "body": "I'm not quite sure about the second point. I have heard that it's not worth having a function just for output. I guess it doesn't always matter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:08:46.423", "Id": "83034", "Score": "0", "body": "@Jamal I thought I had seen that in use with publicly available code, but now it uses a different (and better IMO) method. I have revised my answer accordingly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:40:45.600", "Id": "47369", "ParentId": "47353", "Score": "8" } }, { "body": "<p>I too am late to the game. Let's see what I can make of this code.</p>\n\n<p>I would merge some things together, like your print statements. There are two places in which you have two print statements where one would be sufficient. I have moved them around, and hopefully I didn't murder C in any way by doing this.</p>\n\n<p>I also stole the <code>do while</code> from <strong>Master BenVlodgi</strong>.</p>\n\n<p>Another thing that I did was to change the <code>scanf()</code> to a <code>getchar()</code>. I don't know much about C, but this sounds like it should do what you want it to as long as you are looking for a single character response.</p>\n\n<p>Do this:</p>\n\n<pre><code>do\n{\n guess = (high + low) / 2;\n\n printf(\"Okay, let's start. Is it %d?\\n Please respond with L, H, or Y.\\n\", guess);\n response = toupper(getchar());\n\n switch(response)\n {\n case 'H': high = guess - 1;\n break;\n case 'L': low = guess + 1;\n break;\n case 'Y': printf(\"Yes! I knew I could do it.\\n\");\n break;\n default: printf(\"I didn't get that; you gave an invalid response.\\n Please try again.\\n\"); \n }\n}while(response != 'Y');\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>while(response != 'Y')\n{\n guess = (high + low) / 2;\n\n printf(\"Okay, let's start. Is it %d?\\n\", guess);\n printf(\"Please respond with L, H, or Y.\\n\");\n scanf(\"%d\", &amp;response);\n response = toupper(response);\n\n switch(response)\n {\n case 72: high = guess - 1;\n break;\n case 76: low = guess + 1;\n break;\n case 89: printf(\"Yes! I knew I could do it.\\n\");\n break;\n default: printf(\"I didn't get that; you gave an invalid response.\\n\");\n printf(\"Please try again.\\n\"); \n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:52:16.663", "Id": "47393", "ParentId": "47353", "Score": "5" } }, { "body": "<p>I'm thoroughly puzzled by your use of the <code>response</code> variable.</p>\n\n<p>The condition for the while-loop is <code>response != 'Y'</code>. The first time through, <code>response</code> is an uninitialized variable, containing any imaginable <code>int</code> value. So, the behaviour of your program is undefined.</p>\n\n<p><code>response</code> is an <code>int</code>. Why are you comparing it to <code>'Y'</code>? That makes 89 a special number.</p>\n\n<p>If we make it inside the loop, you ask the user to enter a character <code>'L'</code>, <code>'H'</code>, or <code>'Y'</code>, but actually read an integer. If you actually enter one of those three characters, <code>scanf()</code> will fail to read an integer; your program will consider the input to be invalid, and it will loop forever, since <code>scanf()</code> will immediately fail again, etc. <em>There are only two ways to terminate your program:</em> <kbd>Ctrl</kbd><kbd>C</kbd> <em>or by typing</em> <kbd>8</kbd><kbd>9</kbd><kbd>Enter</kbd> <em>at the prompt</em>.</p>\n\n<p>Then you call <code>toupper()</code> on the <em>integer</em>; the <code>toupper()</code> function only makes sense for translating a letter to its uppercase counterpart. (The <code>toupper()</code> function takes an <code>int</code> instead of a <code>char</code> only because it is meant to support <kbd>EOF</kbd>, or -1, as a value.)</p>\n\n<p>Then, in the <code>switch</code> block, you have magic numbers 72, 76, and 89. Magic numbers should not exist in your code.</p>\n\n<hr>\n\n<p>Your first <code>printf()</code> call is also wrong. It should be</p>\n\n<pre><code>printf(\"Okay, let's start. Is it %d?\\n\", guess);\n</code></pre>\n\n<p>since <code>&amp;guess</code> would print the address of the <code>guess</code> variable instead of its contents. Your compiler should have warned you about that mistake. You should have heeded the warning, as well as tested your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:21:37.627", "Id": "47406", "ParentId": "47353", "Score": "18" } } ]
{ "AcceptedAnswerId": "47406", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T14:40:29.387", "Id": "47353", "Score": "11", "Tags": [ "c", "binary-search", "number-guessing-game" ], "Title": "Binary search use in simple guessing game" }
47353
<p>I recently wrote a simple echo server in Java 7 using the NIO APIs so it was asynchronous and non-blocking. Then I decided, as a learning experience, to redo it with Java 8 hoping to use a more functional style and not have nested callbacks. I'm struggling to understand how to use the new <code>CompletableFuture</code> class with the <code>Future</code>s returned by <code>AsynchronousSocketChannel</code>.</p> <p>This code currently works but is slower than the Java 7 version. If anyone can point out ways to improve it (or maybe that I'm going about it completely wrong) it would be appreciated. The main problem, to me at least, is that I now have to call <code>get()</code> on three <code>Future</code>s, whereas before I didn't have any blocking operations.</p> <pre><code>try (final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open()) { listener.setOption(StandardSocketOptions.SO_REUSEADDR, true); listener.bind(new InetSocketAddress("localhost", 8080)); while (true) { AsynchronousSocketChannel connection = listener.accept().get(); CompletableFuture&lt;AsynchronousSocketChannel&gt; connectionPromise = CompletableFuture.completedFuture(connection); CompletableFuture&lt;ByteBuffer&gt; readerPromise = CompletableFuture.supplyAsync(() -&gt; { ByteBuffer buffer = ByteBuffer.allocateDirect(1024); try { connection.read(buffer).get(); return (ByteBuffer) buffer.flip(); } catch (InterruptedException | ExecutionException e) { connectionPromise.completeExceptionally(e); } return null; }); readerPromise.thenAcceptAsync((buffer) -&gt; { if (buffer != null) { try { connection.write(buffer).get(); connection.close(); } catch (InterruptedException | ExecutionException | IOException e) { readerPromise.completeExceptionally(e); } } }); } } catch (IOException | InterruptedException | ExecutionException e) { e.printStackTrace(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T07:47:47.470", "Id": "83721", "Score": "0", "body": "\" is slower than the Java 7 version.\": Can we see the other version? Maybe we could spot the difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T14:50:53.187", "Id": "83753", "Score": "0", "body": "Sure, Java 7 version - https://gist.github.com/opiethehokie/9435565. BTW this wasn't a serious performance test, just an observation that it was noticeably slower when I had a client program send a few thousand requests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T06:07:30.013", "Id": "83877", "Score": "0", "body": "That's ok. I just want to see if there are other differences, like as you said `listener.accept().get()` was synchronous in the Java 8 version, etc." } ]
[ { "body": "<ol>\n<li><p>As far as I see <code>supplyAsync</code> and <code>thenAcceptAsync</code> uses <code>ForkJoinPool.commonPool()</code> which does not use more than three threads on my machine (and it depends on the number of available processors). It could be a bottleneck if you have more than three clients at the same time. Both methods can have an <code>Executor</code> argument which would be used instead of <code>commonPool()</code>.</p></li>\n<li><p>The code calls <code>completeExceptionally</code> in the <code>catch</code> block here:</p>\n\n<blockquote>\n<pre><code>readerPromise.thenAcceptAsync((buffer) -&gt; {\n if (buffer != null) {\n try {\n connection.write(buffer).get();\n connection.close();\n } catch (InterruptedException | ExecutionException | IOException e {\n readerPromise.completeExceptionally(e);\n } \n }\n});\n</code></pre>\n</blockquote>\n\n<p>It seems to me that it does not have any effect. <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#completeExceptionally-java.lang.Throwable-\" rel=\"nofollow\">Javadoc of <code>completeExceptionally</code></a> says the following:</p>\n\n<blockquote>\n <p>If not already completed, causes invocations of <code>get()</code> and related methods to throw the given exception.</p>\n</blockquote>\n\n<p>The lambda passed to <code>thenAcceptAsync</code> is called when the <code>CompleteFuture</code> (<code>readerPromise</code> in this case) is already completed so it doesn't change anything. Consider the following PoC:</p>\n\n<pre><code>@Test\npublic void test3() throws Exception {\n final CompletableFuture&lt;String&gt; reader = CompletableFuture.supplyAsync(() -&gt; {\n return \"data\";\n });\n reader.thenAcceptAsync(x -&gt; {\n System.out.println(\"reader.thenAcceptAsync: \" + x);\n boolean transitionToCompleted = reader.completeExceptionally(new RuntimeException(\n \"overridden Future result\"));\n System.out.println(transitionToCompleted); // prints \"false\"\n });\n\n Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);\n System.out.println(\"reader result: \" + reader.get()); // prints \"data\"\n}\n</code></pre>\n\n<p>(Note that there is an <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#obtrudeException-java.lang.Throwable-\" rel=\"nofollow\"><code>obtrudeException</code></a> method but I guess you don't need that either.)</p></li>\n<li><p>The same is true for <code>connectionPromise.completeExceptionally(e)</code>, furthermore, <code>connectionPromise</code> seems completely unused in the code above. I'd remove it.</p></li>\n<li><p><a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html#thenAcceptAsync-java.util.function.Consumer-java.util.concurrent.Executor-\" rel=\"nofollow\"><code>thenAcceptAsync</code> will run only when the the previous stage completes normally</a>. The following also could be useful:</p>\n\n<blockquote>\n <p>In all other cases, if a stage's computation terminates abruptly with an (unchecked) exception or error, then all dependent stages requiring its completion complete exceptionally as well, with a CompletionException holding the exception as its cause.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html\" rel=\"nofollow\">CompletionStage javadoc</a></p>\n\n<p>According to that you might be able to change the reader lambda to the following:</p>\n\n<pre><code>final CompletableFuture&lt;ByteBuffer&gt; readerPromise = CompletableFuture.supplyAsync(() -&gt; {\n try {\n final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);\n connection.read(buffer).get();\n buffer.flip();\n return buffer;\n } catch (final Exception e) {\n throw new RuntimeException(e);\n }\n});\n</code></pre>\n\n<p>It never returns null, so you can remove the null check from writer lambda:</p>\n\n<pre><code>final CompletableFuture&lt;Void&gt; writerPromise = readerPromise.thenAcceptAsync((buffer) -&gt; {\n try {\n connection.write(buffer).get();\n connection.close();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n});\n</code></pre>\n\n<p>Finally, if there's an exception, you could log that with the following:</p>\n\n<pre><code>writerPromise.exceptionally(x -&gt; {\n x.printStackTrace(); // TODO: use logging instead\n return null;\n});\n</code></pre>\n\n<p>(I'm not familiar with these APIs but this looks right for me.)</p></li>\n<li><p>Note that I've removed the ugly casting with changing</p>\n\n<blockquote>\n<pre><code>return (ByteBuffer) buffer.flip();\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>buffer.flip();\nreturn buffer;\n</code></pre></li>\n<li><p>Calling <code>Future.get()</code> in the lambdas does not seem to asynchronous for me too (althought they're run by another threads) but I've not idea how should it be handled. The two APIs does not seem compatible. (I guess you could get better answers on Stack Overflow with a more specific question.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T17:50:38.683", "Id": "47724", "ParentId": "47354", "Score": "3" } }, { "body": "<h2>What to do with checked Exceptions thrown within a <code>CompletableFuture</code>?</h2>\n\n<p>Let's look what does <code>CompletableFuture</code> do with the unchecked exceptions.\nAs <em>@palacsint</em> noted:</p>\n\n<blockquote>\n <p>In all other cases, if a stage's computation terminates abruptly with\n an (unchecked) exception or error, then all dependent stages requiring\n its completion complete exceptionally as well, with a\n CompletionException holding the exception as its cause.</p>\n</blockquote>\n\n<p>That is to say: If <code>completableFuture.get()</code> would throw, say, an <code>ExecutionException:NullPointerException</code>; then so would <code>future.thenApply(funcOne).get()</code> and <code>future.thenApply(funcOne).thenApply(funcTwo).get()</code> and so on. This is done by at each stage a layer of <code>CompletionException</code> is peeled and wrapped in another. <code>.get()</code> peels it and wraps it in an <code>ExecutionException</code> so that the contents of the <code>ExecutionException</code> is not drowned in layers and layers of <code>CompletionException</code>s. </p>\n\n<p>So what will happen if you wrap a checked exception in a <code>CompletionException</code>. It will percolate through the chain and you would get a <code>ExecutionException:IOException</code>, as if you could throw a checked exception from a <code>Supplier&lt;T&gt;</code>. Which you can handle differently than if you just wrapped in a <code>RuntimeException</code>. This is what you try to do when you do <code>connectionPromise.completeExceptionally(e);</code> as far as I can understand. And it is what would happen if someone else called <code>completeExceptionally</code> on the enclosing <code>CompletableFuture</code>. I am proposing this; because you might want to prefer unrecoverable <code>RuntimeException</code>s to be program errors <strong>as much as prudent</strong>(, and no more). If I am ignoring fifty <code>RuntimeException</code>s because some clients have sketchy wireless connection, then I might ignore some other <code>RuntimeException</code> that is indicative of a grave programming error. To be fair this may be considered as depending on undocumented behavior. If you are troubled by this, you can define you on you own unchecked checked exception wrapper.</p>\n\n<p>Finally on this point; looking at the API <code>CompletableFuture</code>s are clearly meant to be chained.</p>\n\n<h2>Accepting Connections Synchronously</h2>\n\n<p>You need not really do this. You can either start the <code>CompletableFuture</code> chain with a call to <code>supplyAsync</code> giving it a suitable <code>Executor</code> such as a fixed thread pool or cached poll or a custom <code>ThreadPoolExecutor</code>. Or similarly you accept connections in a callback using <code>AsynchronousChannelGroup</code>. Since I do not know about NIO2 I am copying that part from <a href=\"http://www.ibm.com/developerworks/library/j-nio2-1/index.html\" rel=\"nofollow\">some online source</a>.</p>\n\n<pre><code>public static void serverLoop() throws IOException {\n // These can be injected and thus configured from without the application\n ExecutorService connectPool = Executors.newFixedThreadPool(10);\n Executor readPool = Executors.newCachedThreadPool();\n Executor writePool = Executors.newCachedThreadPool();\n\n AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(connectPool);\n\n try (AsynchronousServerSocketChannel listener = \n AsynchronousServerSocketChannel.open(group)) {\n listener.setOption(StandardSocketOptions.SO_REUSEADDR, true);\n listener.bind(new InetSocketAddress(\"localhost\", 8080));\n\n while (true) {\n listener.accept(null, handlerFrom(\n (AsynchronousSocketChannel connection, Object attachment) -&gt; {\n assert attachment == null;\n CompletableFuture.supplyAsync(() -&gt; { \n try {\n ByteBuffer buffer = ByteBuffer.allocateDirect(1024);\n connection.read(buffer).get();\n return (ByteBuffer) buffer.flip();\n } catch (InterruptedException | ExecutionException ex) {\n throw new CompletionException(ex);\n }}, readPool)\n .thenAcceptAsync((buffer) -&gt; {\n try {\n if (buffer == null) return;\n connection.write(buffer).get();\n } catch (InterruptedException | ExecutionException ex) {\n throw new CompletionException(ex);\n }\n }, writePool)\n .exceptionally(ex -&gt; {\n handleException(ex); \n return null;\n });\n }));\n }\n } \n}\n\nprivate static &lt;V, A&gt; CompletionHandler&lt;V, A&gt; handlerFrom(BiConsumer&lt;V, A&gt; completed) {\n return handlerFrom(completed, (Throwable exc, A attachment) -&gt; {\n assert attachment == null;\n handleException(exc);\n });\n}\n\nprivate static &lt;V, A&gt; CompletionHandler&lt;V, A&gt; handlerFrom(\n BiConsumer&lt;V, A&gt; completed, \n BiConsumer&lt;Throwable, A&gt; failed) {\n return new CompletionHandler&lt;V, A&gt;() {\n @Override\n public void completed(V result, A attachment) {\n completed.accept(result, attachment);\n }\n\n @Override\n public void failed(Throwable exc, A attachment) {\n failed.accept(exc, attachment);\n }\n };\n}\n</code></pre>\n\n<h2>Escaping from Callback Hell</h2>\n\n<p>This is more a comment than a review item. As far as I looked, there is not a fluent interface yet for general <code>Future</code>s. You could roll out your own, but you would have to implement dozens of methods yourself. Because of the peculiarities of Java's type system, one cannot have real monads, traits, extension methods etc facilities other languages provide for library developers that help with this burden.</p>\n\n<h2>EDIT</h2>\n\n<p>I realized that it is possible to do this:</p>\n\n<blockquote>\n <p>hoping to use a more functional style and not have nested callbacks.</p>\n</blockquote>\n\n<p><em>But I do not claim for one moment this is better than the usual callback hell.</em></p>\n\n<pre><code>CompletableFuture.completedFuture(\n (TriConsumer&lt;CompletionHandler&lt;Integer, ByteBuffer&gt;, ByteBuffer, AsynchronousSocketChannel&gt;)\n (self, bbAttachment, scAttachment) -&gt; {\n if (bbAttachment.hasRemaining()) {\n scAttachment.write(bbAttachment, bbAttachment, self);\n } else {\n bbAttachment.clear();\n }\n })\n .thenApply((consumer) -&gt; (\n (TriConsumer&lt;Integer, ByteBuffer, AsynchronousSocketChannel&gt;)\n (result, buffer, scAttachment) -&gt; {\n if (result == -1) {\n try {\n scAttachment.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n scAttachment.write((ByteBuffer) buffer.flip(), buffer, handlerFrom(\n (Integer result2, ByteBuffer bbAttachment, CompletionHandler&lt;Integer, ByteBuffer&gt; self) -&gt; {\n consumer.accept(self, bbAttachment, scAttachment);\n }));\n }))\n .thenApply((consumer) -&gt; (Consumer&lt;AsynchronousSocketChannel&gt;) connection -&gt; { \n final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);\n connection.read(buffer, connection, handlerFrom(\n (Integer result, final AsynchronousSocketChannel scAttachment) -&gt; {\n consumer.accept(result, buffer, scAttachment);\n }));\n })\n .thenAccept((consumer)-&gt;\n listener.accept(null, handlerFrom(\n (AsynchronousSocketChannel connection, Void v, CompletionHandler&lt;AsynchronousSocketChannel, Void&gt; self) -&gt; {\n listener.accept(null, self); // get ready for next connection\n consumer.accept(connection);\n })));\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>@FunctionalInterface\ninterface TriConsumer&lt;T1, T2, T3&gt; {\n void accept(T1 t1, T2 t2, T3 t3);\n}\n\nprivate static &lt;V, A&gt; CompletionHandler&lt;V, A&gt; handlerFrom(TriConsumer&lt;V, A, CompletionHandler&lt;V, A&gt;&gt; completed) {\n return handlerFrom(completed, (Throwable exc, A attachment) -&gt; {\n assert attachment == null;\n handleException(exc);\n });\n}\n\nprivate static &lt;V, A&gt; CompletionHandler&lt;V, A&gt; handlerFrom(\n TriConsumer&lt;V, A, CompletionHandler&lt;V, A&gt;&gt; completed, \n BiConsumer&lt;Throwable, A&gt; failed) {\n return new CompletionHandler&lt;V, A&gt;(){\n @Override\n public void completed(V result, A attachment) {\n completed.accept(result, attachment, this);\n }\n\n @Override\n public void failed(Throwable exc, A attachment) {\n failed.accept(exc, attachment);\n }\n };\n}\n</code></pre>\n\n<h2>Remarks</h2>\n\n<ul>\n<li><p>Since nio2 methods are already async, we stick with the sync methods of <code>CompletableFuture</code>.</p></li>\n<li><p>Although the callbacks are not nested anymore they are upside down. </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T22:10:02.137", "Id": "84240", "Score": "0", "body": "I like the original better as it's easier to follow, but thanks for proving it's possible with the edit. Also good point about the chaining. I really missed out on the chance to do that in the original, not sure what I was thinking." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T09:49:23.933", "Id": "47863", "ParentId": "47354", "Score": "3" } } ]
{ "AcceptedAnswerId": "47863", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T14:48:35.363", "Id": "47354", "Score": "10", "Tags": [ "java", "asynchronous", "networking", "socket", "java-8" ], "Title": "Echo server with CompletableFuture" }
47354
<p>Yesterday I posted a <a href="https://codereview.stackexchange.com/questions/47292/directory-that-lists-employee-information">question</a> involving multiple nested queries. The queries pulled information from the database and created a directory listing of all employees. There are two many-to-many relationships involving 5 tables. For each employee they can have multiple job titles and multiple departments.</p> <pre><code>$stmt = $mysqli-&gt;prepare("SELECT employeeId, firstName, middleName, lastName, suffix, profilePhoto, GROUP_CONCAT(DISTINCT jobName ORDER BY jobTitleId), GROUP_CONCAT(DISTINCT departmentName ORDER BY departmentId), GROUP_CONCAT(DISTINCT departmentURL ORDER BY departmentId) FROM employee INNER JOIN employee_has_jobTitle ON employeeId = employee_has_jobTitle.employee_employeeId INNER JOIN jobTitle ON employee_has_jobTitle.jobTitle_jobTitleId = jobTitleId INNER JOIN employee_has_department ON employee.employeeId = employee_has_department.employee_employeeId INNER JOIN department ON employee_has_department.department_departmentId = departmentId GROUP BY employeeId ORDER By lastName, firstName"); $stmt-&gt;execute(); $stmt-&gt;store_result(); $stmt-&gt;bind_result($employeeId, $firstName, $middleName, $lastName, $suffix, $profilePhoto, $jobName, $departmentName, $departmentURL); //set up the list echo "&lt;ul class='plainList'&gt;"; while($stmt-&gt;fetch()){ echo "&lt;li&gt;&lt;div class='clearfix'&gt;&lt;img src='/profileImages/$profilePhoto' alt='$firstName $lastName' class='directoryPhoto'&gt;"; $deptName = explode(",", $departmentName); $deptURL = explode(",", $departmentURL); $jobTitle = explode(",", $jobName); echo "&lt;strong&gt;$firstName $lastName&lt;/strong&gt;&lt;br&gt;"; $counter = 0; foreach($deptName as $name) { //echo a preceding comma if not the first department if($counter &gt; 0) echo ", "; echo "&lt;a href='$deptURL[$counter]'&gt;$name&lt;/a&gt;"; $counter++; } echo "&lt;br&gt;"; foreach($jobTitle as $job) { echo "$job&lt;br&gt;"; } echo "&lt;/div&gt;&lt;/li&gt;"; } //close the list echo "&lt;/ul&gt;&lt;br&gt;"; </code></pre> <p>If you <a href="https://codereview.stackexchange.com/questions/47292/directory-that-lists-employee-information">check my other question</a>, you can see that this is an improvement. However, I don't think the query and code are as elegant as they should be. Is there an obvious way to simplify the code and enhance performance that I'm not seeing?</p> <p>Screenshot of the ERD for reference:</p> <p><img src="https://i.stack.imgur.com/uPAyk.png" alt="Simplified ERD for reference"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:31:48.903", "Id": "83029", "Score": "0", "body": "Have you thought about using concatenated subqueries instead. See http://www.hellotecho.com/concatenating-subqueries-with-multiple-results-in-mysql for an example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:01:01.063", "Id": "83033", "Score": "0", "body": "@B2K That's what I ended up doing to get the job title and departments. Originally it was nested queries, but this question has the `GROUP_CONCAT`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:13:12.933", "Id": "83035", "Score": "0", "body": "I'm referring to doing group_concats in subqueries. See my answer below" } ]
[ { "body": "<p>in your while statement you are listing all sorts of information inside of one list item tag, I am not so sure this is intentional, it looks like it is going to be really messy. I think you should look into creating sub-lists there especially for the multiple Department names and Job Names. you want something like an XML Date File here, maybe I am overstepping my reviewer line and telling you to change the structure, but this is going to look really messy on a website I think.</p>\n\n<p>something like this would be more convenient.</p>\n\n<pre><code>&lt;li&gt;\n &lt;div class='clearfix'&gt;\n &lt;img src='/profileImages/$profilePhoto' alt='$firstName $lastName' class='directoryPhoto' /&gt;\n &lt;strong&gt;$firstName $lastName&lt;/strong&gt; &lt;!-- should probably be a span with styling hooks --&gt;\n &lt;ul&gt;\n &lt;li&gt;Department1&lt;/li&gt;\n &lt;li&gt;Department1&lt;/li&gt;\n &lt;/ul&gt;\n &lt;ul&gt;\n &lt;li&gt;Job1&lt;/li&gt;\n &lt;li&gt;Job2&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n&lt;/li&gt;\n</code></pre>\n\n<p>I don't know exactly what you want your finished product to look like, but this structure is far more solid than what your PHP is going to output, you should look into making it output something like this, because this is going a lot easier to work with for Styling and manipulating with PHP.</p>\n\n<p>all of your image tags (<code>&lt;img&gt;</code>) need to be closed(<code>&lt;img /&gt;</code>), so does your break tags (<code>&lt;br&gt;</code>,<code>&lt;br /&gt;</code>)</p>\n\n<hr>\n\n<p>From what you are saying it sounds like you want something more like this</p>\n\n<pre><code>&lt;li&gt;\n &lt;ul&gt;\n &lt;li&gt;\n &lt;img src='/profileImages/$profilePhoto' alt='$firstName $lastName' class='directoryPhoto' /&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;strong&gt;$firstName $lastName&lt;/strong&gt; &lt;!-- should probably be a span with styling hooks --&gt;\n &lt;/li&gt;\n &lt;li&gt;Department1, Department1&lt;/li&gt;\n &lt;li&gt;Job1, Job2&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/li&gt;\n</code></pre>\n\n<p>I removed the Div tag and some of the other stuff just so we could visualize this better. this is a little more organized than what you are going to get with your current code. it will still be easier to deal with. </p>\n\n<p>As Far as whether or not to do another list for the Department Names and Job Titles, I would go with yes, even if they only have a single item, it will be easier to navigate the ones that do have them, and easier to manipulate the data, it is more maintainable I think.</p>\n\n<hr>\n\n<p>I mentioned still using nested lists for the Department Names and Job Names, you should still have a title for the list item that is holding them, so you know what they are, but I will leave that up to you</p>\n\n<pre><code>&lt;li&gt;\n &lt;ul&gt;\n &lt;li&gt;\n &lt;img src='/profileImages/$profilePhoto' alt='$firstName $lastName' class='directoryPhoto' /&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;strong&gt;$firstName $lastName&lt;/strong&gt; &lt;!-- should probably be a span with styling hooks --&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;ul&gt;\n &lt;li&gt;Department1&lt;/li&gt;\n &lt;li&gt;Department1&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;ul&gt; \n &lt;li&gt;Job1&lt;/li&gt;\n &lt;li&gt;Job2&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n&lt;/li&gt;\n</code></pre>\n\n<p>so here is what that would look like with out the titles for the sub lists</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:23:20.763", "Id": "82984", "Score": "0", "body": "The `img` and `br` tags no longer need to be closed in HTML5. It actually displays as intended, though the code does get messy. My primary reason behind not having department and job title as sub lists is that for the vast majority of people they only have a single title and department. With that, should they still be sub-lists even though the bulk would only have a single `li`? The \"old\" directory listing has all departments on one line, and then job titles listed on separate lines. As of now, you can't visually differentiate between the \"old\" and \"new\" directories." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:24:03.517", "Id": "82985", "Score": "0", "body": "The `li` setup I settled on because I'm \"listing\" employees, though previously it was all done with `div` elements. Should I revert to simple `div` elements for simplicity sake?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:38:21.107", "Id": "82988", "Score": "1", "body": "I think that closing your tags is something that you should always do no matter what, it is a good habit and as far as I know it is still standard for every other Markup language in the XML Style Family (HTML, XHTML, XML, HTML5, etc) it's my personal preference too, even if I don't have to. I wouldn't go back to `div`'s your list presents the data the way it is supposed to be presented." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:41:13.623", "Id": "82991", "Score": "0", "body": "Many thanks for your input, and I can understand the \"good habit\". HTML5 allows attributes to go unquoted, and I just can't force myself to do that! :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:13:30.123", "Id": "47364", "ParentId": "47358", "Score": "4" } }, { "body": "<p>Using subselects may help alleviate the issues requiring distinct grouping statements, and also will prevent the inner joins from removing employees who haven't been assigned titles or departments (although you could also use outer joins for that). </p>\n\n<pre><code> SELECT employeeId, firstName, middleName, lastName, suffix, profilePhoto,\n (SELECT GROUP_CONCAT(jobName ORDER BY jobName) \n FROM jobTitle \n INNER JOIN employee_has_jobTitle \n ON employee_employeeId = employeeId \n AND jobTitle_jobTitleId = jobTitleId) as jobs, \n (SELECT GROUP_CONCAT(CONCAT(departmentName,' ',departmentURL) ORDER BY departmentName)\n FROM department\n INNER JOIN employee_has_department\n ON employeeId = employee_employeeId\n AND department_departmentId = departmentId) as Departments \n FROM employee\n ORDER BY lastName, firstName\n</code></pre>\n\n<p>One last point to note is that formatting your query as I have done can be an immense help to understanding it, especially when you're returning to code you've written years before.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:41:12.493", "Id": "83040", "Score": "0", "body": "Your correct, I like that formatting MUCH better. There's an error in this statement. It doesn't recognize the `employeeId` in the `ON` clause of the first sub-query. Do the sub-queries run before the first query? I don't know how you would narrow the job titles down to just the right ones without adding `employeeId` in a `WHERE` clause in the sub-queries. I added a screenshot of a simplified ERD to show the table setup. Definitely will be reformatting my SQL statements though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:42:50.540", "Id": "83042", "Score": "0", "body": "@MatthewJohnson You can add the table name to it. employee.employeeId" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:46:41.073", "Id": "83045", "Score": "0", "body": "That's what I tried originally, but it just updated the error to say unknown column `employee.employeeId` instead of just `employeeId`. Should there be another `INNER JOIN` to bring the `employee` table too?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:04:27.293", "Id": "83057", "Score": "0", "body": "@MatthewJohnson Try assigning an alias to every table, then prefixing each field with the appropriate alias. That should resolve any issues. No, the join for the employee table is the selected row." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:25:52.610", "Id": "47394", "ParentId": "47358", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T15:37:26.443", "Id": "47358", "Score": "3", "Tags": [ "php", "performance", "mysql", "mysqli" ], "Title": "Directory that lists employee information - follow-up" }
47358
<p>Here is my implementation to project Euler Problem 11. I did this problem a bit later, when I learned how to input from a txt file. The problem context can be seen <a href="http://projecteuler.net/problem=11">here</a>. I did add "\n" to the end of each line, after copying the numbers into a txt file, I'm not sure of any other way to do that. Any other improvements anyone can think of?</p> <pre><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;sstream&gt; #include &lt;string&gt; //splitting stream into ints. std::vector&lt;int&gt; split(std::string line){ std::stringstream ss (line); std::vector&lt;int&gt; result; std::string num; while(std::getline(ss, num, ' ')) result.push_back(std::stoi(num)); return result; } //comparing all int's that are horizontally next to each other unsigned long long Horizontal(int a, int b, std::vector&lt;std::vector&lt;int&gt;&gt; grid){ if(b &lt; grid[a].size()-3){ return (grid[a][b] * grid[a][b+1] * grid[a][b+2] * grid[a][b+3]); } } //comparing all int's that are vertically next to each other unsigned long long Vertical(int a, int b, std::vector&lt;std::vector&lt;int&gt;&gt; grid){ if(a &lt; grid.size()-3){ return (grid[a][b] * grid[a+1][b] * grid[a+2][b] * grid[a+3][b]); } } //all int's that are diagonally(forward) next to each other unsigned long long ForDiag(int a, int b, std::vector&lt;std::vector&lt;int&gt;&gt;grid){ if (a &lt; grid.size()-3 &amp;&amp; b &lt; grid[a].size()-3){ return (grid[a][b] * grid[a+1][b+1] * grid[a+2][b+2] * grid[a+3][b+3]); } } //all int's that are diagonally(backward) next to each outher unsigned long long BackDiag(int a, int b, std::vector&lt;std::vector&lt;int&gt;&gt;grid){ b+=3; // b needs to be 3 larger for this function if(a &lt; grid.size()-3 &amp;&amp; b &lt; grid[a].size()){ return (grid[a][b] * grid[a+1][b-1] * grid[a+2][b-2] * grid[a+3][b-3]); } } //Calls the calculation functions, and compares them for the largest. unsigned long long Largest(std::vector&lt;std::vector&lt;int&gt;&gt; grid ){ int gwidth = grid[0].size(); int glength = grid.size(); unsigned long long largest = 0; for(int a = 0; a &lt; gwidth; ++a){ for(int b = 0; b &lt; glength; ++b){ largest = std::max(largest,Horizontal(a,b,grid)); largest = std::max(largest,Vertical(a,b,grid)); largest = std::max(largest,ForDiag(a,b,grid)); largest = std::max(largest,BackDiag(a,b,grid)); } } return largest; } int main(){ std::vector&lt;std::vector&lt;int&gt;&gt; grid; //opening file. std::ifstream nums; nums.open("grid.txt"); std::string row; //Calling function, and pushing back into the vector while(std::getline(nums, row, '\n')){ grid.push_back(split(row)); } std::cout &lt;&lt; Largest(grid); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:19:39.013", "Id": "82981", "Score": "1", "body": "[My answer to your previous question](http://codereview.stackexchange.com/a/47277/22222) about `const&` still applies to your `std::vector` parameters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:37:05.480", "Id": "82987", "Score": "0", "body": "I suggest activating warning -Wreturn-type ." } ]
[ { "body": "<p>Your functions returning a <code>unsigned long long</code> are missing a return which leads to undefined behavior (<a href=\"https://stackoverflow.com/questions/1610030/why-can-you-return-from-a-non-void-function-without-returning-a-value-without-pr/1610454#1610454\">more details on this question</a>). You could throw an exception to handle this or you could just return <code>0</code>.</p>\n\n<hr>\n\n<p>Not a real issue and mostly a matter of personal preference but the way you check that you are not going out of the bounds of the array could be written in a more natural way.</p>\n\n<p>To check that index <code>b + 3</code> is in the array, I'd rather read <code>b + 3 &lt; a.size()</code> than <code>b &lt; a.size() - 3</code>.</p>\n\n<hr>\n\n<p>Even more unusual is the pre-increment in the case of <code>BackDiag()</code> : you add <code>3</code> to <code>b</code> and then you consider <code>b - 3</code>.</p>\n\n<hr>\n\n<p>Once your code re-written to take into account these comments, it looks like :</p>\n\n<pre><code>unsigned long long Horizontal(int a, int b, std::vector&lt;std::vector&lt;int&gt;&gt; grid){\n return (b + 3 &lt; grid[a].size()) ?\n (grid[a][b] * grid[a][b+1] * grid[a][b+2] * grid[a][b+3]) :\n 0;\n}\n//comparing all int's that are vertically next to each other\nunsigned long long Vertical(int a, int b, std::vector&lt;std::vector&lt;int&gt;&gt; grid){\n return (a + 3 &lt; grid.size()) ?\n (grid[a][b] * grid[a+1][b] * grid[a+2][b] * grid[a+3][b]) :\n 0;\n}\nunsigned long long ForDiag(int a, int b, std::vector&lt;std::vector&lt;int&gt;&gt;grid){\n return (a + 3 &lt; grid.size() &amp;&amp; b + 3 &lt; grid[a].size()) ?\n (grid[a][b] * grid[a+1][b+1] * grid[a+2][b+2] * grid[a+3][b+3]) :\n 0;\n}\nunsigned long long BackDiag(int a, int b, std::vector&lt;std::vector&lt;int&gt;&gt;grid){\n return (a + 3 &lt; grid.size() &amp;&amp; b + 3 &lt; grid[a].size()) ?\n (grid[a][b+3] * grid[a+1][b+2] * grid[a+2][b+1] * grid[a+3][b]) :\n 0;\n}\n</code></pre>\n\n<hr>\n\n<p>Now, one thing to notice is that this good is basically always the same. You should try to write a generic function that you can reuse.</p>\n\n<p>The signature would be something like :</p>\n\n<pre><code>unsigned long long computeProduct(int a, int b, int incrA, int incrB, std::vector&lt;std::vector&lt;int&gt;&gt;grid)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:57:59.130", "Id": "47371", "ParentId": "47361", "Score": "5" } }, { "body": "<p>One improvement you can make is to flatten the matrix to 1D and just use larger offsets. This will speed your code up quite a bit.</p>\n\n<pre><code>//Create 1D vector\nstd::ifstream infile(\"grid.txt\"); \nstd::vector&lt;int&gt; flatmatrix;\nwhile(!infile.eof())\n{\n double numtemp = 0;\n infile &gt;&gt; numtemp;\n flatmatrix.push_back(numtemp);\n}\n\n//Function to return the largest product as per problem description\n//This is hardcoded for 20 X 20, but it shouldn't be too hard to adapt to take different sizes.\nint MaxProduct(const std::vector&lt;int&gt;&amp; matrix2)\n{\n long temp = 0;\n long result2 = 0;\n size_t size = matrix2.size();\n for(int i = 0; i &lt; size; i++)\n {\n temp = matrix2[i];\n //right\n if(i % 20 &lt; 17)\n {\n temp = matrix2[i] * matrix2[i + 1] * matrix2[i + 2] * matrix2[i + 3];\n result2 = (temp &gt; result2 ? temp : result2);\n }\n //down\n if((i + 60) &lt; 400 &amp;&amp; ((int)(i / 20)) % 20 &lt; 17)\n {\n temp = matrix2[i] * matrix2[i + 20] * matrix2[i + 40] * matrix2[i + 60];\n result2 = (temp &gt; result2 ? temp : result2);\n }\n //left\n if(i % 20 &gt; 2)\n {\n temp = matrix2[i] * matrix2[i - 1] * matrix2[i - 2] * matrix2[i - 3];\n result2 = (temp &gt; result2 ? temp : result2);\n }\n //up\n if((i - 60) &gt;= 0 &amp;&amp; ((int)(i / 20)) % 20 &gt; 2)\n {\n temp = matrix2[i] * matrix2[i - 20] * matrix2[i - 40] * matrix2[i - 60];\n result2 = (temp &gt; result2 ? temp : result2);\n }\n //down,right\n if(i % 20 &lt; 17 &amp;&amp; (i + 60) &lt; 400 &amp;&amp; ((int)(i / 20)) % 20 &lt; 17)\n {\n temp = matrix2[i] * matrix2[(i + 20) + 1] * matrix2[(i + 40) + 2] * matrix2[(i + 60) + 3];\n result2 = (temp &gt; result2 ? temp : result2);\n }\n //down,left\n if(i % 20 &gt; 2 &amp;&amp; (i + 60) &lt; 400 &amp;&amp; ((int)(i / 20)) % 20 &lt; 17)\n {\n temp = matrix2[i] * matrix2[(i + 20) - 1] * matrix2[(i + 40) - 2] * matrix2[(i + 60) - 3];\n result2 = (temp &gt; result2 ? temp : result2);\n }\n //up,right\n if(i % 20 &lt; 17 &amp;&amp; (i - 60) &gt; -1 &amp;&amp; ((int)(i / 20)) % 20 &gt; 2)\n {\n temp = matrix2[i] * matrix2[(i - 20) + 1] * matrix2[(i - 40) + 2] * matrix2[(i - 60) + 3];\n result2 = (temp &gt; result2 ? temp : result2);\n }\n //up,left\n if(i % 20 &gt; 2 &amp;&amp; (i - 60) &gt; -1 &amp;&amp; ((int)(i / 20)) % 20 &gt; 2)\n {\n temp = matrix2[i] * matrix2[(i - 20) - 1] * matrix2[(i - 40) - 2] * matrix2[(i - 60) - 3];\n result2 = (temp &gt; result2 ? temp : result2);\n }\n }\n return result2;\n}\n</code></pre>\n\n<p>For future reference your <code>split</code> function can be simplified quite a bit:</p>\n\n<pre><code>std::vector&lt;int&gt; split(std::string line)\n{\n std::stringstream ss (line);\n std::vector&lt;int&gt; result;\n int num;\n while(ss &gt;&gt; num)\n result.push_back(num);\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:12:49.760", "Id": "83026", "Score": "0", "body": "I [already provided](http://codereview.stackexchange.com/a/47274/15094) a simpler `split` in the previous question, but they simply didn't keep it for some reason :/" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:51:00.917", "Id": "47385", "ParentId": "47361", "Score": "2" } } ]
{ "AcceptedAnswerId": "47371", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:03:22.347", "Id": "47361", "Score": "5", "Tags": [ "c++", "programming-challenge" ], "Title": "Project Euler Problem 11: Largest product in a grid" }
47361
<p>I currently have a Python script that parses a file (in this case an XML file) and makes line by line replacements as necessary, depending on the values of multiple arrays. As it stands now the script works great, but feel like it could be a lot better. I'll also need to add few more arrays later on and am worried about performance.</p> <p>Additionally, the way I currently have it set up doesn't allow for counting and printing the total replacements that have been made. (e.g. "Replaced: xyz -- Made XX replacements") While not an immediate requirement, I'd like to add this functionality in the future.</p> <pre><code>arrayOne = ["old string one", "new string one"] arrayTwo = ["old string two", "new string two"] # Variable 'path' collected from command line input f = open(path, "r", encoding="utf8") newFile = open(path.replace(".xml", "-new.xml"), "w", encoding="utf8") def replace(a,b): for data in f: for datatype in (arrayOne, arrayTwo): data = data.replace(datatype[a], datatype[b]) newFile.write(data) newFile.close() replace(0,1) f.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:46:09.057", "Id": "82993", "Score": "0", "body": "Would you ever expect to need to do the inverse transformation, i.e., replacing \"new string one\" with \"old string one\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:02:17.250", "Id": "82994", "Score": "0", "body": "No, I don't expect I'd ever need to go in reverse. If I did though, I could just reverse the arguments (e.g. replace(1,0))." } ]
[ { "body": "<p>One bug I see is that you perform the string substitutions sequentially, rather than \"simultaneously\". For example, suppose you had an input file with contents</p>\n\n<pre><code>abc\n</code></pre>\n\n<p>with substitution code</p>\n\n<pre><code>arrayOne = [\"a\", \"b\"]\narrayTwo = [\"b\", \"c\"]\n\n…\nreplace(0, 1)\n</code></pre>\n\n<p>Most users would expect the output to be <code>bcc</code>. However, your code actually produces <code>ccc</code>, which would probably be considered surprising.</p>\n\n<hr>\n\n<p>The main problem, though, is that everything is tightly coupled, such that the code is not reusable.</p>\n\n<p>For example, <code>replace()</code> is a closure that captures <code>arrayOne</code> and <code>arrayTwo</code>, as well as file <code>f</code>. It doesn't generalize to perform one substitution or ≥ 3 substitutions. The two parameters that it does accept are more annoying than helpful, as you have indicated that you expect to always call it as <code>replace(0, 1)</code>. Furthermore, <code>replace()</code> will only operate on the file that was opened as <code>f</code> at the time that the function was defined.</p>\n\n<p>A better interface would be for <code>replace()</code> to accept a <code>dict</code> of substitutions to be performed. Furthermore, it should just concern itself with string transformation, staying clear of all file operations.</p>\n\n<hr>\n\n<p>I propose the following solution, which contains some rather advanced concepts.</p>\n\n<pre><code>from functools import partial\nimport re\n\ndef str_replacer(mapping):\n regex = re.compile('|'.join(re.escape(orig) for orig in mapping))\n return partial(regex.sub, lambda match: mapping[match.group(0)])\n</code></pre>\n\n<p>You would use it like this:</p>\n\n<pre><code>&gt;&gt;&gt; replace = str_replacer({\n... 'a': 'b',\n... 'b': 'c',\n... 'c': 'd',\n... })\n&gt;&gt;&gt; print(replace('abc'))\nbcd\n</code></pre>\n\n<p><strong>Explanation:</strong> Performing \"simultaneous\" replacements means scanning the input string until any of the \"old\" strings is encountered. If a substitution is performed, the scanning should recommence at the after where the newly spliced-in string ends.</p>\n\n<p>That's tedious to do using low-level string manipulation, so I've opted to use <a href=\"https://docs.python.org/2/library/re.html#re.RegexObject.sub\" rel=\"nofollow\"><code>re.sub()</code></a> instead. To use <code>re.sub()</code>, I have to do two things</p>\n\n<ol>\n<li>Compose a regular expression that includes all of the \"old\" strings to look for. That's what <code>re.compile(…)</code> does.</li>\n<li>Create a callback function that specifies what the replacement for each old string should be. That's the <code>lambda</code>. <code>match.group(0)</code> is the old string that was found. We look its corresponding \"new\" string in the <code>mapping</code>.</li>\n</ol>\n\n<p>However, I don't want <code>str_replacer()</code> to call <code>regex.sub(repl, input_string)</code> just yet. Instead, I want <code>str_replacer()</code> to return a function, that if called, performs the desired replacements. Why? Because you will likely call the resulting function many times if you want to process a file a line at a time, and it would be more efficient to reuse the regex and the lambda. That's what <a href=\"https://docs.python.org/2/library/functools.html#functools.partial\" rel=\"nofollow\"><code>functools.partial()</code></a> does: it creates a function that accepts an input string; when that function is called, then the <code>regex.sub(lambda match: mapping[match.group(0)], input_string)</code> actually happens.</p>\n\n<pre><code>replace = str_replacer({\n 'old string one': 'new string one',\n 'old string two': 'new string two',\n})\n\nwith open(path, \"r\", encoding=\"utf8\") as in_file, \\\n open(path.replace(\".xml\", \"-new.xml\"), \"w\", encoding=\"utf8\") as out_file:\n for line in in_file:\n out_file.write(replace(line))\n</code></pre>\n\n<p>Now the string replacement logic and the file manipulation logic are cleanly separated!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T19:03:46.357", "Id": "47386", "ParentId": "47365", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:16:24.250", "Id": "47365", "Score": "7", "Tags": [ "python", "strings" ], "Title": "Making line by line replacements using values from multiple arrays" }
47365
<p>Below is my code. This is a function that will be applied as a sorting method to a grid based data set. The data in the column to be sorted can be stuff like: <code>123456</code>, <code>123456:123444</code>, and <code>12345:12359:139943</code>. So far, I have tested it and it works, but I want to know in which situations might it not work, or if there is a way to optimize/improve the method in any way.</p> <pre><code>function SkuSorter(a, b, c) { // check if either input is a set var aMatch = a.match(/\:/g); var bMatch = b.match(/\:/g); // all items by default should be a regular sku, we'll change this later var aType = 0; var bType = 0; /* types; * 0 = regular sku * 1 = duo (12345:12345) * 2 = trio (1234:1234:1234) */ // has the user sorted asc or desc? var direction = c; // if 'a' is a set, determine if it is a duo or trio if (aMatch) { if (aMatch.length == 1) aType = 1; if (aMatch.length &gt; 1) aType = 2; } // save as above if (bMatch) { if (bMatch.length == 1) bType = 1; if (bMatch.length &gt; 1) bType = 2; } // if 'a' is a set and 'b' isn't, a should come before b (puts sets at the bottom) if (aType == 0 &amp;&amp; bType != 0) { return -1 * direction; } // save as above, but viceversa. if (aType != 0 &amp;&amp; bType == 0) { return 1 * direction; } // if both inputs are regular skus, do normal sort operation if (aType == 0 &amp;&amp; bType == 0) { if (direction == -1) { return b - a; } else { return a - b; } } // if 'a' is a set and it is of higher order (i.e. trio &gt; duo) if (aType &gt; 0 &amp;&amp; aType &gt; bType) { return 1 * direction; } // same as above, but for 'b' if (bType &gt; 0 &amp;&amp; bType &gt; aType) { return -1 * direction; } // if both inputs are sets if (aType &gt; 0 &amp;&amp; bType &gt; 0) { //break up the individual pieces var aP = a.split(':'); var bP = b.split(':'); /* * The following conditions will compare: * The first chunk and sort them based on value * Then the second chunk, and if it is a trio, the third. */ if (aP[0] &gt; bP[0]) { return 1 * direction; } if (aP[0] &lt; bP[0]) { return -1 * direction; } // second chunk if (aP[1] &gt; bP[1]) { return 1 * direction; } if (aP[1] &lt; bP[1]) { return -1 * direction; } // third chunk if (aType &gt; 1 &amp;&amp; bType &gt; 1) { if (aP[2] &gt; bP[2]) { return 1 * direction; } if (aP[2] &lt; bP[2]) { return -1 * direction; } } } } </code></pre> <p>Expected behavior:</p> <p>Before:</p> <pre><code>1654110 1574698 1189364 1229764 1700004 310425 1626613 36509 1676618 1676832 1536622 1749548 36509:310444 3199:44999:34000 3199:45000:34000 3199:45000:34111 1874361 1551225 1581271 1626076 36509:310425 1676816 1676824 </code></pre> <p>After:</p> <pre><code>36509 310425 1189364 1229764 1536622 1551225 1574698 1581271 1626076 1626613 1654110 1676618 1676816 1676824 1676832 1700004 1749548 1874361 36509:310425 36509:310444 3199:44999:34000 3199:45000:34000 3199:45000:34111 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:56:41.337", "Id": "83003", "Score": "1", "body": "Can you give an example of some numbers you want to be sorted and what you would expect the result to be?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:09:31.783", "Id": "83004", "Score": "0", "body": "Added to original post" } ]
[ { "body": "<p>@Flambino was a bit faster : </p>\n\n<pre><code>function sortSKU( a, b )\n{\n var aParts = a.split( ':' ),\n bParts = b.split( ':' ),\n partCount = aParts.length,\n i;\n\n if( aParts.length != bParts.length )\n return aParts.length - bParts.length;\n\n for( i = 0 ; i &lt; partCount ; i++ )\n {\n if( aParts[i] != bParts[i] )\n return +aParts[i] - +bParts[i];\n }\n //Exactly the same\n return 0;\n}\n\nconsole.log( data.sort( sortSKU ) );\n</code></pre>\n\n<p>As Flambino said, use <code>.reverse()</code> to sort one way or another. Also this function will sort 123 prior to 2:2 if such a case can occur.</p>\n\n<p>If you need the 'c'</p>\n\n<pre><code>function sortingCallback( array, direction ){\n\n if( direction == 'whatever ascending is' ){\n return array.sort( sortSKU );\n }\n\n return array.sort( sortSKU ).reverse();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:31:51.897", "Id": "83013", "Score": "1", "body": "FYI, the 'c' in my original code is the direction of the sort passed by jqGrid(jQuery Grid). I would assume that I can just multiple the return statements by 'c' (in your code) to switch them to ascending or descending?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:36:19.520", "Id": "83014", "Score": "0", "body": "Updated my answer with what you could do" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:43:08.170", "Id": "83015", "Score": "0", "body": "My code doesn't actually do the trick, so I'm deleting it. Maybe it'll come back later if I find a solution. But that'll just be for my own sake; you've got this one, konijn" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:45:21.613", "Id": "83016", "Score": "0", "body": "@Flambino the comparing of arrays was very smart, I didn't know you could do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:50:59.523", "Id": "83017", "Score": "1", "body": "multiplying the `return aParts..` lines by c (-1 desc, 1 asc) seemed to do the trick. I did this in order to reverse whatever result it might have come up with. Thoughts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T19:00:08.190", "Id": "83020", "Score": "0", "body": "I assume you use the sort function as a closure then, works for me either way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:58:21.373", "Id": "83131", "Score": "0", "body": "@konijn Yeah, array comparisons are very, very rarely used in JS. I remember being surprised when I first saw it :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:26:18.503", "Id": "47382", "ParentId": "47366", "Score": "3" } } ]
{ "AcceptedAnswerId": "47382", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:21:53.567", "Id": "47366", "Score": "8", "Tags": [ "javascript", "sorting" ], "Title": "Sort function to sort item numbers separated by colon" }
47366
<p>The below code is recursive function that list directories in 2 levels:</p> <pre><code>static Dictionary&lt;string,string&gt; pList=new Dictionary&lt;string, string&gt;(); static void ListDirec(string path, int start, int end) { var dirInfo = new DirectoryInfo(path); var folders = dirInfo.GetDirectories().ToList(); foreach (var item in folders) { Console.WriteLine("".PadLeft(start * 4, ' ') + item.Name); if (start &lt; end) { ListDirec(item.FullName, start + 1, end); } } } </code></pre> <p>Now how can optimize that in this case?</p> <p>For example, I've these directories with their sub-directories:</p> <pre><code>folder-A folder-A-1 folder-A-2 folder-A-3 folder-B folder-B-1 folder-B-2 folder-B-3 folder-C folder-C-1 folder-C-2 folder-C-3 </code></pre> <p>Now I want save parents as key and children as value in dictionary, with their relation for example folder-A has these children: folder-A-1, folder-A-2, folder-A-3 and so on.</p> <p>What's the best way to do that in this function? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:27:01.233", "Id": "83038", "Score": "0", "body": "You are asking for help in writing code to add the data to a dictionary. This code does not exist yet, so it is not ready for a Code Review. When your code works as designed, bring it back for review." } ]
[ { "body": "<p>To relate your parent directories to their children, you could have <code>plist</code> declared like this:</p>\n\n<pre><code>static Dictionary&lt;String, List&lt;String&gt;&gt; plist = new Dictionary&lt;string, List&lt;string&gt;&gt;();\n</code></pre>\n\n<p>Each time you hit a child folder, you add its name to </p>\n\n<pre><code>Console.WriteLine(\"\".PadLeft(start * 4, ' ') + item.Name);\nstring parent = path.Split('\\\\').Last();\nif (!pList.Keys.Contains(parent))\n pList.Add(parent, new List&lt;string&gt;());\npList[parent].Add(item.Name);\n</code></pre>\n\n<p>Sorry, I don't have access to a C# compiler at the moment so I can't verify this 100%, but it's a starting point at least.</p>\n\n<p><strong>Edit</strong>: After thinking about it, I don't think C# likes it if you use <code>[]</code> before an element is in the Dictionary. I edited the above code to include how to get the <code>parent</code> and included the Console.WriteLine so you know where I would put it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:50:36.467", "Id": "47370", "ParentId": "47367", "Score": "4" } }, { "body": "<p>One option is to use a <code>Dictionary&lt;DirectoryInfo, List&lt;DirectoryInfo&gt;&gt;</code>. This way if you want to access the directories the methods you need are right there:</p>\n\n<pre><code>public static Dictionary&lt;DirectoryInfo, List&lt;DirectoryInfo&gt;&gt; BuildTree(string path)\n{\n Dictionary&lt;DirectoryInfo, List&lt;DirectoryInfo&gt;&gt; temptree = new Dictionary&lt;DirectoryInfo, List&lt;DirectoryInfo&gt;&gt;();\n //If you need to filter the results edit the search string\n foreach(DirectoryInfo dir in new DirectoryInfo(path).GetDirectories(\"*\", SearchOption.TopDirectoryOnly))\n {\n temptree.Add(dir, dir.GetDirectories(\"*\", SearchOption.TopDirectoryOnly).ToList());\n }\n return temptree;\n}\n</code></pre>\n\n<p>If you would like a LINQ option you could do it this way:</p>\n\n<pre><code>public Dictionary&lt;DirectoryInfo, List&lt;DirectoryInfo&gt;&gt; BuildTree(string path)\n{\n Dictionary&lt;DirectoryInfo, List&lt;DirectoryInfo&gt;&gt; temptree = (from dir in new DirectoryInfo(path).EnumerateDirectories(\"*\", SearchOption.TopDirectoryOnly)\n select dir).ToDictionary(x =&gt; x, x =&gt; x.GetDirectories(\"*\", SearchOption.TopDirectoryOnly).ToList());\n return temptree;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T19:33:58.590", "Id": "47387", "ParentId": "47367", "Score": "0" } } ]
{ "AcceptedAnswerId": "47370", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:31:31.923", "Id": "47367", "Score": "2", "Tags": [ "c#", "recursion", "directory" ], "Title": "Recursive function for listing directories" }
47367
<p>Before looping through an Excel document using a library I found, and wanted to know how long it would take to loop through the whole thing. </p> <p>There are 40k rows.</p> <p>I looped through only the first 5k and it took just 2 minutes. So, I thought, that looping through 40k would take just 16 minutes total.</p> <p>However, the program has been running for over an hour now, and it still hasn't completed.</p> <p>What would be slowing this thing down? Granted, I didn't program it for high efficiency, but there must be something that is slowing this down... Why wasn't my initial estimate accurate?</p> <p>Here is my method:</p> <pre><code>public static void Validate(ExcelConfiguration config) { var ctx = new IntakeEntities(); Stopwatch sw = new Stopwatch(); sw.Start(); HashSet&lt;string&gt; missingEntities = new HashSet&lt;string&gt;(); Console.WriteLine("Validating..."); using (ExcelPackage xlPackage = new ExcelPackage(config.file)) { ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[config.WorkSheet]; // loop through each row for (int iRow = config.DataRowStart; iRow &lt;= config.DataRowFinish; iRow++) { // get home country from database string homeCountryName = worksheet.Cell(iRow, config.HomeCountryColumnIndex).Value.Trim(); Guid? homeCountryId = null; try { homeCountryId = ctx.Countries.AsNoTracking().Where(x =&gt; x.Name == homeCountryName).First().Id; //Console.WriteLine(homeCountryId + " - " + homeCountryName); } catch (Exception ex) { //Console.WriteLine("No record found for " + homeCountryName); missingEntities.Add(homeCountryName); } // get host country from database string hostCountryName = worksheet.Cell(iRow, config.HostCountryColumnIndex).Value.Trim(); Guid? hostCountryId = null; try { hostCountryId = ctx.Countries.AsNoTracking().Where(x =&gt; x.Name == hostCountryName).First().Id; //Console.WriteLine(hostCountryId + " - " + hostCountryName); } catch (Exception ex) { //Console.WriteLine("No record found for " + hostCountryName); missingEntities.Add(hostCountryName); } if (config.HomeLocationColumnIndex != null &amp;&amp; config.HostLocationColumnIndex != null) { // get home country from database string homeLocationName = worksheet.Cell(iRow, (int)config.HomeLocationColumnIndex).Value.Trim(); Guid? homeLocationId = null; try { homeLocationId = ctx.Locations.AsNoTracking().Where(x =&gt; x.Name == homeLocationName).First().Id; //Console.WriteLine(homeCountryId + " - " + homeCountryName); } catch (Exception ex) { //Console.WriteLine("No record found for " + homeLocationName); missingEntities.Add(homeLocationName); } // get host country from database string hostLocationName = worksheet.Cell(iRow, (int)config.HostLocationColumnIndex).Value.Trim(); Guid? hostLocationId = null; try { hostLocationId = ctx.Locations.AsNoTracking().Where(x =&gt; x.Name == hostLocationName).First().Id; //Console.WriteLine(hostCountryId + " - " + hostCountryName); } catch (Exception ex) { //Console.WriteLine("No record found for " + hostLocationName); missingEntities.Add(hostLocationName); } } } } Console.WriteLine("Validation complete..."); Console.WriteLine("Time elapsed: {0} minutes", sw.Elapsed.Minutes); Console.WriteLine("No records found for:"); foreach (string entity in missingEntities) { Console.WriteLine(entity); } } </code></pre> <p>Here is the accompanying object:</p> <pre><code>public class ExcelConfiguration { public FileInfo file { get; set; } public int HomeCountryColumnIndex { get; set; } public int HostCountryColumnIndex { get; set; } public int? HomeLocationColumnIndex { get; set; } public int? HostLocationColumnIndex { get; set; } public int WorkSheet { get; set; } public int DataRowStart { get; set; } public int DataRowFinish { get; set; } } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code>public static void Validate(ExcelConfiguration config)\n</code></pre>\n</blockquote>\n\n<p>I wouldn't make this a <code>static</code> method, but without knowing more about your project it's just a nitpick. The name is highly misleading though. Without looking at the code, one would expect that the method <em>validates the passed <code>ExcelConfiguration</code></em> - I don't know, maybe check that <code>DataRowStart</code> is within a specific range (like, a positive number), and that the <code>File</code> (capital F) exists... wait, you've got a <code>FileInfo</code> there, that's rather surprising. Also <code>WorkSheet</code> should be called <code>WorksheetIndex</code>... but I digress.</p>\n\n<blockquote>\n<pre><code>var ctx = new IntakeEntities();\n</code></pre>\n</blockquote>\n\n<p>I like that you're using <code>var</code>. However if this <code>IntakeEntities</code> is what I think it is, it's derived from <code>DbContext</code> and implements <code>IDisposable</code>, and should be wrapped in a <code>using</code> block.</p>\n\n<blockquote>\n<pre><code>Stopwatch sw = new Stopwatch();\n</code></pre>\n</blockquote>\n\n<p>Why not use <code>var</code> again? Be consistent! That said, you're doing the right thing - <code>StopWatch</code> is how you should time execution... but that stop watch should be in the method's calling code, starting just before the method call and stopping right after it returns. Writing the results to the console doesn't belong in that method either.</p>\n\n<hr>\n\n<p>Are you <em>actually</em> catching many exceptions? Are exceptions <em>exceptional</em> or just a \"neat\" way of adding items to <code>missingEntities</code>?</p>\n\n<p>I think you're misusing exceptions, because if you didn't systematically tried to get the <code>Id</code> property of an object that's potentially <code>null</code>, you could do a null check instead, and to everything without catching a <code>NullReferenceException</code> - use <code>SingleOrDefault</code> instead of <code>Where</code> and then <code>First</code>, it makes it clearer that you're expecting zero or one values:</p>\n\n<pre><code>var homeCountry = ctx.Countries.AsNoTracking().SingleOrDefault(x =&gt; x.Name == homeCountryName);\nhomeCountryId = (homeCountry == null ? 0 : homeCountry.Id);\n\nif (homeCountryId == 0)\n{\n missingEntities.Add(homeCountryName);\n}\n</code></pre>\n\n<p>Throwing and catching exceptions without a real reason, in a loop, 40K times, can slow things down if half the iterations throw 2-3 exceptions. I'd try to eliminate the throwing and catching first, see what I get.</p>\n\n<p>Then I'd try to reduce the number of Excel worksheet reads, if that's at all possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:28:42.810", "Id": "83009", "Score": "0", "body": "Thanks so much. I have confidence in your answer. I will try it soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:37:35.787", "Id": "83039", "Score": "0", "body": "I tend to disagree with the use of `var` for known types: from c#3.0 language reference... \"Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:41:30.873", "Id": "83041", "Score": "1", "body": "Also while using `FirstOrDefault(x => x.Name == \"Foo\");` might look neater, using `Where(x => x.Name == \"Foo\").FirstOrDefault();` is actually quicker. See [here](http://stackoverflow.com/questions/8663897/why-is-linq-wherepredicate-first-faster-than-firstpredicate). A micro optimisation but on a 40k loop with 4 calls might make a difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:38:21.607", "Id": "83068", "Score": "1", "body": "@NickWilliams I tend to disagree with what's considered \"overuse\" of `var`. I don't see how cutting redundant clutter reduces readability, and using `var` or not boils down to personal preference - in my answer I only recommended consistency in its usage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T08:09:26.570", "Id": "83114", "Score": "1", "body": "@Mat'sMug I would always follow the language reference on these matters if trying to suggest best practise. Most (not all) code I have seen where `var` is used for every variable ends up with longer, more Hungarian style variable names. The main thing is to be consistent of course." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:52:59.007", "Id": "47377", "ParentId": "47368", "Score": "5" } }, { "body": "<ul>\n<li>Have performance issues? Use a profiler. (There is a built-in in certain versions of Visual Studio and a bunch of third-party tools, with evaluation times). Find out what is taking time and we can give you an advice for optimization after that.</li>\n<li>As already mentioned, do not use exceptions for normal program flow. Use <code>FirstOrDefault()</code> method instead of <code>First()</code> so you don't get an exception for missing items.</li>\n<li>If you want a guess - you have 4 database queries per row => 160k queries. Either adjust database indexes, or load whole tables into <code>Dictionary&lt;&gt;</code> if they are small enough (Countries table, for example, is probably small)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:23:19.673", "Id": "83005", "Score": "1", "body": "+1 Good call, caching the smaller data sets locally, but `.FirstOrDefault().Id` will still potentially throw a `NullReferenceException` - the trick is to do `.FirstOrDefault()` (or `.SingleOrDefault()`), *check if we have a result*, and then if we do, get the `.Id`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:25:22.653", "Id": "83007", "Score": "0", "body": "Yep, of course I meant FirstOrDefault()->Null check-> .Id" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:28:21.383", "Id": "83008", "Score": "0", "body": "+1, Very good advice here. The only thing is, I already tried loading the entire tables into a local cache both the method you described and using `.Load()` of Linq. I used the `StopWatch()` to compare and actually, both methods were slower than the one I am using now. Do you have a recommended implementation for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:28:46.847", "Id": "83010", "Score": "0", "body": "+1 for use a profiler. http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/ is the best by leaps and bounds, in my opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:25:16.157", "Id": "83027", "Score": "1", "body": "Another question: After profiling using the VS2012 Analyzer, it tells me that most of the problem is the accessing of the Excel Cells. But, how can I avoid that?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:13:38.927", "Id": "47379", "ParentId": "47368", "Score": "6" } }, { "body": "<p>The one thing that people are touching on but not saying outright is the fact that Exception handling takes a lot of processing power away from what you want going on, just the operation of catching the exception itself is what is slowing you down. </p>\n\n<p>you are using <code>Catch</code> statements inappropriately.</p>\n\n<p>if you know the exception then you need to code so that it won't happen. </p>\n\n<p>a try catch statement is more for the unexpected errors.</p>\n\n<p>like @Mat's Mug was saying, check to see if it exists, if it doesn't add it to the missing entities collection, don't let it throw an error.</p>\n\n<hr>\n\n<p>as far as your estimate being wrong.</p>\n\n<blockquote>\n <p>I looped through only the first 5k and it took just 2 minutes. So, I thought, that looping through 40k would take just 16 minutes total.</p>\n</blockquote>\n\n<p>the issue with this is that for the first 5k records there is (theoretically) nothing being held in memory or processor cache or heap, so when the next 5k records go through there is stuff being processed already these 5k records have to wait in line, stack another 5k on top of that, now the processor is getting warm which slows it down a little bit, it's trying to multi thread information is getting backed up. it's like having 40 tabs open on a browser, I am done with the first 35 but have things running super slow on the remaining 5 it's slow because there is stuff in the way sitting in the receiving and sending area.</p>\n\n<p>okay so I BS'd my way through that, but you get the point right?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T23:04:05.747", "Id": "47410", "ParentId": "47368", "Score": "2" } }, { "body": "<p>With appreciation for the answers and sound advice provided here, I have concluded that the real source of the issue was not my improper use of <code>try/catch</code> nor <code>FirstOrDefault()</code> or any of that, but rather, it was the Excel package. </p>\n\n<p>To fix this, the only solution would be to convert the Excel into a CSV which would allow for faster access of data. Instead of that, I just chose to modify my <code>DataRowStart</code> and <code>DataRowFinish</code> by shrinking the window so it wouldn't get bogged down.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>After converting my document to CSV and using <a href=\"http://filehelpers.sourceforge.net/\" rel=\"nofollow noreferrer\">FileHelpers</a> and <a href=\"https://stackoverflow.com/a/15662102/1477388\">changing the runtime configuration</a> of my <code>DbContext</code> like so:</p>\n\n<pre><code>yourContext.Configuration.AutoDetectChangesEnabled = false;\nyourContext.Configuration.ValidateOnSaveEnabled = false;\n</code></pre>\n\n<p>... I was able to validate and insert all 40k records in under 15 minutes; whereas, before it would've taken hours (if it finished at all). I think most of the benefit actually came from the <code>DbContext</code> change. That alone was a major improvement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:06:11.290", "Id": "83199", "Score": "0", "body": "did you try to fix the `try catch` usage?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:08:26.277", "Id": "83201", "Score": "1", "body": "Yes, it helped some, but according to the built in Profiler in VS 2012, most of the time was taken up by the reads to the Excel document, not by database calls or try/catch, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:30:47.487", "Id": "83206", "Score": "2", "body": "That doesn't surprise me; as I explained in [this answer](http://codereview.stackexchange.com/a/46960/23788) the real cost of throwing+catching exceptions is often over-estimated. I thought 40K iterations would actually make a difference, but I under-estimated the cost of COM interop: *\"Then I'd try to reduce the number of Excel worksheet reads, if that's at all possible.\"* - that should have been my first advice ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:35:27.810", "Id": "83259", "Score": "1", "body": "glad you got it going." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:02:07.327", "Id": "83261", "Score": "0", "body": "Thanks. I posted an update since I thought it was really cool. By making those changes, I was able to complete the entire operation in under 15 mins." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:29:51.607", "Id": "83273", "Score": "0", "body": "feel free to accept any useful answer, doing that will generate a whole 17 points on the site (assuming you're not accepting *your own* answer, which you can of course) :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:48:25.273", "Id": "47487", "ParentId": "47368", "Score": "3" } } ]
{ "AcceptedAnswerId": "47487", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:31:55.760", "Id": "47368", "Score": "10", "Tags": [ "c#", "excel" ], "Title": "Looping through an Excel document in C#" }
47368
<p>I am designing a website for a company that manages buildings/real estate. I did not have much use for a CSS library like Bootstrap or Foundation, except on one page of the website. This page contains a list of selected buildings. When a user clicks on the name of a building, the building's information appears and images of the building appear in a Bootstrap image carousel. I used AJAX to GET the images of a property and then prototyped an object for each property on the list-- easy way to replace the text on-screen.</p> <p>Below is the JavaScript &amp; jQuery code that makes this happen:</p> <pre><code>//for bootstrap carousel $('.carousel').carousel(); //stores the building currently displayed, for swap function below. var currentBuilding; //constructor for Building function Building(title, background, story, images, stats){ this.title = title; this.background = background; this.story = story; //images references directory where this building's images are located: this.images = images; this.stats = stats; } //example object var azusa = new Building( "Azusa, CA", "The company purchased a building in 2006 with a 20-year loan at 2% interest.", "The lot used to be the site of a mini-mall with tenants such as McDonalds and Costco", "azusa-california", "10,000 sqft"); //bind to onclick for list items. Given a Building (e.g. azusa above), //place the most recently clicked Building's information on the page. function swap(building){ event.preventDefault(); if(currentBuilding != building) { currentBuilding = building; $("h3:first").fadeOut(400,function(){ $("h3:first").html(building.title); $("h3:first").fadeIn(400,function(){}); }); $("#background p:first").fadeOut(400,function(){ $("#background p:first").html(building.background); $("#background p:first").fadeIn(400,function(){}); }); $('#carousel-container').fadeOut(400,function(){ grabImages(building.images); //see function below $('#carousel-container').fadeIn(400,function(){}); }); $("#story p:first").fadeOut(400,function(){ $("#story p:first").html(building.story); $("#story p:first").fadeIn(400,function(){}); }); $("#stats p:first").fadeOut(400,function(){ $("#stats p:first").html(building.stats); $("#stats p:first").fadeIn(400,function(){}); }); } } function grabImages(folder){ var dir = "img/selected-buildings-slides/"+folder; var fileextension = ".jpg"; $.ajax({ //This will retrieve the contents of the folder if the folder is configured as 'browsable' url: dir, type: "GET", success: function (data) { var nth = 0; var active=" active"; $('.carousel-inner').html(""); //Lsit all png file names in the page $(data).find("a:contains(" + fileextension + ")").each(function () { if(nth&gt;0){ $('.carousel-indicators').append("&lt;li data-target='#property-carousel' data-slide-to='"+nth+"'&gt;&lt;/li&gt;") active="" } else{ $('.carousel-indicators').html("&lt;li class='active' data-target='#property-carousel' data-slide-to='0'&gt;&lt;/li&gt;"); } var filename = this.href.replace(window.location.host, "").replace("http://", ""); $('.carousel-inner').append("&lt;div class='item"+active+"'&gt; &lt;img src ='"+dir+filename+"' alt='property photo'&gt;&lt;/div&gt;"); nth++; }); } }); } </code></pre> <p>Now, I am sure you are looking at that <code>grabImages()</code> function and cringing. I know it looks messy, but it works. Really I am looking to see if there is a way to sidestep AJAX without having to reference the explicit path to each individual image, because the image files have arbitrary names.</p> <p>Also, if there is a way to wait for the images to fully load in <code>grabImages()</code> before displaying them, that would be cool too.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:55:06.940", "Id": "83002", "Score": "1", "body": "I can't see what's kicking this all off. What is calling swap?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:55:40.967", "Id": "83018", "Score": "0", "body": "i did the binding in the HTML, sorry! just an <a href=\"#\" onclick=\"swap(azusa)\"> tag" } ]
[ { "body": "<p>Let's start by removing that inline JS call. Let's use the <code>href</code> to indicate the building. We'll remove the hash later. We also add a class to find these links to attach event handlers:</p>\n\n<pre><code>&lt;a href=\"#azusa\" class=\"swap-trigger\"&gt;Azusa&lt;/a&gt;\n</code></pre>\n\n<p>As for the script:</p>\n\n<pre><code>;(function ($) {\n\n // Cache the fetched elements. Unless they are dynamic, they're better off fetched\n // once and reused rather than fetching them from the DOM every function call.\n var header = $(\"h3:first\");\n var background = $(\"#background p:first\");\n var carouselContainer = $('#carousel-container');\n var story = $(\"#story p:first\");\n var stats = $(\"#stats p:first\");\n var carousel = $('.carousel').carousel();\n var carouselInner = $('.carousel-inner');\n var carouselIndicators = $('.carousel-indicators');\n var fileextension = \".jpg\";\n\n // We store building data here in a hash. The key will match the href that we placed\n // in the links.\n var buildings = {\n 'azusa': {\n title: 'Azusa, CA',\n background: 'The company purchased a building in 2006 with a 20-year loan at 2% interest.',\n story: 'The lot used to be the site of a mini-mall with tenants such as McDonalds and Costco',\n images: 'azusa-california',\n stats: '10,000 sqft'\n },\n ...\n };\n\n // Now we attach a click handler to the links\n $('.swap-trigger').on('click', function (event) {\n event.preventDefault();\n var building = $(this).attr('href').slice(1); //chop of the hash\n swap(building);\n });\n\n // Your swap function\n function swap(building) {\n\n // We can store state data into the element itself using .data()\n // That way, we avoid creating a variable for it. The data is saved in the\n // respective element.\n var currentBuilding = carousel.data('currentBuilding');\n if (currentBuilding === building) return;\n carousel.data('currentBuilding', currentBuilding);\n\n // Using the cached elements\n header.fadeOut(400, function () {\n header.html(building.title).fadeIn(400)\n });\n background.fadeOut(400, function () {\n background.html(building.background).fadeIn(400)\n });\n carouselContainer.fadeOut(400, function () {\n grabImages(building.images);\n carouselContainer.fadeIn(400)\n });\n story.fadeOut(400, function () {\n story.html(building.story).fadeIn(400)\n });\n stats.fadeOut(400, function () {\n stats.html(building.stats).fadeIn(400)\n })\n }\n\n function grabImages(folder) {\n var dir = \"img/selected-buildings-slides/\" + folder;\n\n // Shorthand AJAX GET\n $.get(dir, function (data) {\n\n var active = \" active\";\n carouselInner.html('');\n $(data).find(\"a:contains(\" + fileextension + \")\").each(function (index,element) {\n\n //nth was of no use since .each() provides an index on every iteration.\n if (index === 0) {\n carouselIndicators.html(\"&lt;li class='active' data-target='#property-carousel' data-slide-to='0'&gt;&lt;/li&gt;\");\n } else {\n carouselIndicators.append(\"&lt;li data-target='#property-carousel' data-slide-to='\" + index + \"'&gt;&lt;/li&gt;\");\n active = \"\";\n }\n var filename = this.href.replace(window.location.host, \"\").replace(\"http://\", \"\");\n carouselInner.append(\"&lt;div class='item\" + active + \"'&gt; &lt;img src ='\" + dir + filename + \"' alt='property photo'&gt;&lt;/div&gt;\");\n });\n\n // jQuery sometimes fails to parse correctly, so we make sure\n }, 'html');\n }\n\n\n}(jQuery));\n</code></pre>\n\n<p>Can't verify if this actually works, but the mentioned changes should help the code. Also, I can see that the code you have only works for a single link-carousel combination. If there were more than one, then I can sense that it will break. Consider scenarios where there's more than one set.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:01:03.753", "Id": "47389", "ParentId": "47375", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:46:57.437", "Id": "47375", "Score": "2", "Tags": [ "javascript", "jquery", "css", "html5", "twitter-bootstrap" ], "Title": "jQuery for image swapping and some JS for text swapping" }
47375
<p>I am making an application where I will be fetching tweets and storing them in a database. I will have a column for the complete text of the tweet and another where only the words of the tweet will remain (I need the words to calculate which words were most used later).</p> <p>How I currently do it is by using 6 different <code>.replaceAll()</code> functions which some of them might be triggered twice. For example I will have a for loop to remove every "hashtag" using <code>replaceAll()</code>. </p> <p>The problem is that I will be editing as many as thousands of tweets that I fetch every few minutes and I think that the way I am doing it will not be too efficient.</p> <p>What my requirements are in this order (also written in comments down below):</p> <ol> <li>Delete all usernames mentioned</li> <li>Delete all RT (retweets flags)</li> <li>Delete all hashtags mentioned</li> <li>Replace all break lines with spaces</li> <li>Replace all double spaces with single spaces</li> <li>Delete all special characters except spaces</li> </ol> <p>Here is a short and compilable example:</p> <pre><code>public class StringTest { public static void main(String args[]) { String text = "RT @AshStewart09: Vote for Lady Gaga for \"Best Fans\"" + " at iHeart Awards\n" + "\n" + "RT!!\n" + "\n" + "My vote for #FanArmy goes to #LittleMonsters #iHeartAwards" + " htt…"; String[] hashtags = {"#FanArmy", "#LittleMonsters", "#iHeartAwards"}; System.out.println("Before: " + text + "\n"); // Delete all usernames mentioned (may run multiple times) text = text.replaceAll("@AshStewart09", ""); System.out.println("First Phase: " + text + "\n"); // Delete all RT (retweets flags) text = text.replaceAll("RT", ""); System.out.println("Second Phase: " + text + "\n"); // Delete all hashtags mentioned for (String hashtag : hashtags) { text = text.replaceAll(hashtag, ""); } System.out.println("Third Phase: " + text + "\n"); // Replace all break lines with spaces text = text.replaceAll("\n", " "); System.out.println("Fourth Phase: " + text + "\n"); // Replace all double spaces with single spaces text = text.replaceAll(" +", " "); System.out.println("Fifth Phase: " + text + "\n"); // Delete all special characters except spaces text = text.replaceAll("[^a-zA-Z0-9 ]+", "").trim(); System.out.println("Finaly: " + text); } } </code></pre>
[]
[ { "body": "<p>(subject to further changes)</p>\n\n<p>In your simple example, how are the hashtags and usernames actually derived from the tweet?</p>\n\n<p>My suggestion is to tokenize the tweet by whitespaces first, then look at the individual words to determine if they must be stored (\"Vote\") or discarded (\"#LittleMonsters\"). </p>\n\n<pre><code> // Delete all RT (retweets flags)\n text = text.replaceAll(\"RT\", \"\");\n</code></pre>\n\n<p>You do realize that this will turn text like \"ART!\" into just \"A!\" right? Tokenizing first should remedy this issue.</p>\n\n<p>On a related note, <a href=\"http://storm.incubator.apache.org/\" rel=\"nofollow\">Apache Incubator Storm</a>'s tutorials usually use tweets as an example to demonstrate the Big Data approach. I'm not suggesting that you need such a set-up in your context, but perhaps you can give those a quick read-through to pick up some tips.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T09:18:20.523", "Id": "83122", "Score": "0", "body": "I am using the `twitter4j` library to grab the tweets. Every tweet has the `text` field and it also has a `usernameMentioned` array (where all the mentioned usernames are kept) and a `hashtags` where all the hashtags in the tweet are stored. As for the `RT` I could probably get away with this by using `.replaceFirst()` I guess." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:05:05.510", "Id": "83125", "Score": "0", "body": "Thanks for the explanation. One can always type before \"RT ...\" right? The issue will not go away with `.replaceFirst()` then... :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:29:20.830", "Id": "83126", "Score": "0", "body": "I have changed the code a bit (also adding link removal functionality and taking care of the RT issue) but even though the code definitely looks better I am not sure if it is quite efficient since I am still using 5 `.replaceAll()`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T02:16:55.073", "Id": "47424", "ParentId": "47378", "Score": "2" } } ]
{ "AcceptedAnswerId": "47424", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:54:21.730", "Id": "47378", "Score": "5", "Tags": [ "java", "performance", "strings", "regex", "twitter" ], "Title": "More efficient way to make a Twitter status in a string of just words" }
47378
<p>I've got 2 simple text files:</p> <blockquote> <p><strong>besede.txt</strong></p> <p><em>To je vsebina datoteke z besedami. V njej so razlicne besede ki imajo lahko pomen ali pa tudi ne.</em></p> </blockquote> <blockquote> <p><strong>skrivno.txt</strong></p> <p><em>4 3 19 2 3 2 4 3</em></p> </blockquote> <p>I wrote a program which receives these 2 files' names as arguments. It finds pairs of numbers in <code>skrivno.txt</code> and the first number in the pair is the index of the word in <code>besede.txt</code>; the second number in the pair is the index of the letter in that word.</p> <p>So in this case I get:</p> <ul> <li>4th word, 3rd letter - T</li> <li>19th word, 2nd letter - E</li> <li>3rd word, 2nd letter - S</li> <li>4th word, 3rd letter - T</li> </ul> <p>So, TEST.</p> <p>Here is my program that does this. I'm open to suggestions on what I could improve and do better, etc.</p> <pre><code>public class meow { public static void main(String args[]) throws Exception{ Scanner sc1 = new Scanner(new File(args[0])); //besede.txt Scanner sc2 = new Scanner(new File(args[1])); //skrivno.txt int inW = 0, inL = 0; //index of word, index of line String text = &quot;&quot;, code = &quot;&quot;; while(sc1.hasNext()){ text += sc1.next() + &quot; &quot;; } String[] text2 = text.split(&quot; &quot;); while(sc2.hasNext()){ inW = sc2.nextInt(); inL = sc2.nextInt(); if(inW == 0 &amp;&amp; inL == 0){ code += &quot; &quot;; } code += text2[inW-1].charAt(inL-1); } System.out.printf(&quot;%s\n&quot;, code); } } </code></pre>
[]
[ { "body": "<p>There are quite some things you can improve here, this list may not cover everything that could be improved though:</p>\n\n<ol>\n<li><p>Adhere to the Java naming conventions. Classes are named in PascalCase for example, so it would be <code>public class Meow</code>. On other places it seems fine.</p></li>\n<li><p>Use proper indentation everywhere, this definately applies to the main method inside <code>public class meow</code>, as all items should be intended one to the right. This may also apply to the while loops, I would prefer to write <code>while(sc1.hasNext()){</code> as <code>while (sc1.hasNext()) {</code> for readability.</p></li>\n<li><p>Variable names are not expensive. <code>sc1, sc2</code> are dubious, but could be ok. However <code>inW</code> and <code>inL</code> are plain alarming, the fact that you need to comment to explain them is a bad sign. My suggestions are <code>wordIndex</code> and <code>lineIndex</code>.</p></li>\n<li><p>Consider using a <code>StringBuilder</code> over dealing with raw strings. This means for example that:</p>\n\n<pre><code>String text = \"\", code = \"\";\nwhile(sc1.hasNext()){\n text += sc1.next() + \" \";\n}\n</code></pre>\n\n<p>could be rewritten as:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nwhile (sc1.hasNext()) {\n sb.append(sc1.next()).append(' ');\n}\nString text = sb.toString();\n</code></pre></li>\n<li><p>You have a bug in your second while-loop. You check for <code>sc2.hasNext()</code> and you take two times <code>sc2.nextInt()</code>. Your <code>hasX()</code> and <code>nextX()</code> calls should always match. This means that in the loop per iteration in total there should be two <code>hasNextInt()</code> calls with two <code>nextInt()</code> calls.</p></li>\n<li><p>The same deal about <code>StringBuilder</code> applies here to your second while-loop for building <code>code</code>.</p></li>\n<li><p>In the future you can consider switching to using the <code>java.nio.Path</code> API, over the old <code>java.io.File</code> API. I will not show more code here on how to do it, as it would completely change the structure of the program and is best used in conjunction with Java 8, which is not in the scope of this answer.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:45:17.933", "Id": "47384", "ParentId": "47383", "Score": "12" } }, { "body": "<pre><code> while(sc1.hasNext()){\n text += sc1.next() + \" \";\n }\n String[] text2 = text.split(\" \");\n</code></pre>\n\n<p>You can create a <code>List&lt;String&gt;</code> to store the words in the your first file, and use <code>list.get(i)</code> operation to retrieve the desired element when reading your second file.</p>\n\n<p>Full suggestion (by breaking steps into methods):</p>\n\n<pre><code>public class Main {\n\n private List&lt;String&gt; wordList = new ArrayList&lt;&gt;();\n\n public Main( final File wordFile ) {\n parseWordFile( wordFile );\n }\n\n private void parseWordFile( final File wordFile ) {\n try (Scanner scanner = new Scanner( wordFile )) {\n while( scanner.hasNext() ) {\n wordList.add( scanner.next() );\n }\n } catch( FileNotFoundException e ) {\n throw new RuntimeException( e );\n }\n }\n\n private Map&lt;Integer, Integer&gt; getLetterDerivation( final File derivationFile ) {\n Map&lt;Integer, Integer&gt; result = new HashMap&lt;&gt;();\n try (Scanner scanner = new Scanner( derivationFile )) {\n while( scanner.hasNextInt() ) {\n Integer key = Integer.valueOf( scanner.nextInt() - 1 );\n if ( scanner.hasNextInt() ) {\n result.put( key, Integer.valueOf( scanner.nextInt() - 1 ) );\n }\n }\n } catch( FileNotFoundException e ) {\n throw new RuntimeException( e );\n }\n return result;\n }\n\n private String getWord( final Map&lt;Integer, Integer&gt; letterDerivation ) {\n if ( wordList.isEmpty() ) {\n return \"\"; // nothing to derive\n }\n final StringBuilder result = new StringBuilder();\n for ( final Entry&lt;Integer, Integer&gt; entry : letterDerivation.entrySet() ) {\n // note, following line can throw IndexOutOfBoundsException\n // wrap with try-catch if necessary\n result.append( wordList.get( entry.getKey().intValue() ).charAt( entry.getValue().intValue() ) );\n }\n return result.toString();\n }\n\n public String getWord( final File derivationFile ) {\n return getWord( getLetterDerivation( derivationFile ) );\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T02:39:32.157", "Id": "47429", "ParentId": "47383", "Score": "1" } } ]
{ "AcceptedAnswerId": "47384", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T18:31:43.290", "Id": "47383", "Score": "11", "Tags": [ "java", "file" ], "Title": "Reading text from 2 files" }
47383
<h1>Use Case</h1> <p>So our lead programmer loves to follow the <a href="http://en.wikipedia.org/wiki/Not_invented_here" rel="nofollow">NIH Anti-Pattern</a> and consequently I'm not allowed to use Underscore.js and can only use Vanilla JS... and we have to support IE8.</p> <p>The goal is to produce an aggregation of unique values from nested collections buried within various collections of objects.</p> <h2>Desired Interface</h2> <p>The idea is to call a function to create an aggregation function give the list of the nested properties.</p> <h3>Example</h3> <p>The following would flatten all <code>options</code> collection that are buried under each object within the <code>properties</code> property.</p> <pre><code>var allUniqueOptions = aggregateByProperty('properties', 'options'); var allUniqueDoodadsOptions = aggregateByProperty('doodad', 'properties', 'options'); allUniqueOptions(myCollection); allUniqueDoodadsOptions(myDoodadCollection); </code></pre> <h2>Current Code</h2> <p>The code below works, but I'd like any advice on improving it for:</p> <ul> <li>performance</li> <li>readability</li> <li>any further generalization</li> </ul> <p>I have a <a href="http://jsfiddle.net/7ta3d/2/" rel="nofollow"><strong>jsFiddle</strong></a> created.</p> <pre><code>/* Returns the index of an object within a collection */ function arrayObjectIndexOf(arr, obj) { var search = JSON.stringify(obj); for ( var i = 0, k = arr.length; i &lt; k; i++ ){ if (JSON.stringify(arr[i]) == search) { return i; } }; return -1; }; /* Concatentates objects that don't exist in the source collection */ function concatIfNotExists(source, additions) { var result = source; for ( var i = 0, k = additions.length; i &lt; k; i++ ) { var addition = additions[i]; if (arrayObjectIndexOf(result, addition) === -1) { result.push(addition); } }; return result; }; /* Returns a nested collection buried within an object */ function getInnerCollection(obj, props) { var innerCollection = obj; for (var j = 0, l = props.length; j &lt; l; j++) { if (innerCollection.hasOwnProperty(props[j])) { innerCollection = innerCollection[props[j]]; } else { throw new TypeError("Property doesn't exist!"); } } if (!innerCollection instanceof Array) { throw new TypeError("Inner property is not a collection!"); } return innerCollection; }; /* Returns an aggregation of objects based on collection properties */ function aggregateByProperty() { var props = Array.prototype.splice.call(arguments, 0); return function(objectCollection) { var result = []; for (var i = 0, k = objectCollection.length; i &lt; k; i++) { var innerCollection = getInnerCollection(objectCollection[i], props); result = concatIfNotExists(result, innerCollection); } return result; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:12:13.630", "Id": "83060", "Score": "0", "body": "Does the data always come in the format shown in the demo?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:16:28.240", "Id": "83063", "Score": "0", "body": "No. I'm looking for a general case since I'd like to reuse this function. However, you can always expect the parameter passed into the result function to be a collection of objects." } ]
[ { "body": "<p>From a once over : </p>\n\n<ul>\n<li>This is a problem : <code>var search = JSON.stringify(obj);</code> because <code>JSON.stringify()</code> <a href=\"https://stackoverflow.com/a/4920304/7602\">does not guarantee any order</a>.. To be completely correct I think you are going to need to pass the properties to <code>arrayObjectIndexOf</code> that need to get compared ( that is, if uniqueness is determined by only comparing the provided properties, otherwise you are in a world of trouble )</li>\n<li><code>\"Inner property is not a collection!\"</code> &lt;- Perhaps <code>props[l-1] + \" is not an array!\"</code>, then you will provide which property is not an array, and be clear that you are expecting an array</li>\n<li><code>\"Property doesn't exist!\"</code> &lt;- <code>\"Property \" + props[j] + \"does not exist\"</code> will give a better feedback as to which part is not working</li>\n<li>JSHint.com could only find semicolon issues, which is good</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:03:46.463", "Id": "83056", "Score": "0", "body": "I was hoping to save an extra loop using stringify, but I can see where this path will lead to trouble... Thanks for the advice on the error handling as well! I have to be less lazy on those messages." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:01:24.100", "Id": "47399", "ParentId": "47390", "Score": "3" } } ]
{ "AcceptedAnswerId": "47399", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:03:38.873", "Id": "47390", "Score": "2", "Tags": [ "javascript", "functional-programming" ], "Title": "Aggregation of a collection of object's nested array-properties" }
47390
<p>First attempt was done <a href="https://codereview.stackexchange.com/q/36938/507">here</a><br /> Second attempt was done <a href="https://codereview.stackexchange.com/q/40159/507">here</a></p> <h3>Huge comment at top</h3> <pre><code>/* * Export single function that creates the passportControl object * The function has two parameters: * app: The nodejs/express service object. * This is used to register the end points * this authentication object listens too. * register: An object that abstracts user registrations it * must support the following methods: * updateUser({&lt;user object&gt;}) * getSavedUser(localUserId, function(err, localUser) {}) * * It also uses an external module for configuration (ie holding all the secrets) * This file is not in source control (but in a key repository nice and safe). * config: Expected fields: * config.app The URL of the site. * config.passport An object containing the secrets for each service * The values will depend on the service and the * implementation of passport-&lt;service&gt; module * See the passport code for more detail * Example: * { app: 'iPubCrawlMaps.com', short: 'iPCM', passport: { facebook: { clientID: '&lt;My FaceBook Client&gt;' clientSecret: '&lt;My FaceBool Secret&gt;' }, twitter: { consumerKey: '&lt;My Twitter Key&gt;', consumerSecret: '&lt;My Twitter Secret&gt;' }, google: { returnURL: 'http://&lt;My Site&gt;/api/auth/callback?type=google', realm: 'http://&lt;My Site&gt;/' }, foursquare: { clientID: '&lt;My FourSquare ID&gt;', clientSecret: '&lt;My FourSquare Secret&gt;' }, linkedin: { consumerKey: '&lt;My LinkedIn Key&gt;', consumerSecret: '&lt;My LinkedIn Secret&gt;' }, github: { clientID: '&lt;My GitHub ID&gt;', clientSecret: '&lt;My GitHub Secret&gt;' }, meetup: { consumerKey: '&lt;My Meetup Key&gt;', consumerSecret: '&lt;My Meetup Secret&gt;' }, aol: { returnURL: 'http://&lt;My Site&gt;/api/auth/callback?type=aol', realm: 'http://&lt;My Site&gt;/' }, yahoo: { returnURL: 'http://&lt;My Site&gt;/api/auth/callback?type=yahoo', realm: 'http://&lt;My Site&gt;/' vimeo: { consumerKey: '&lt;My Vimeo Key&gt;', consumerSecret: '&lt;My Vimeo Secret&gt;' }, instagram: { clientID: '&lt;My Instagram ID&gt;', clientSecret: '&lt;My Instagram Secret&gt;' }, tumblr: { consumerKey: '&lt;My Tumbler Key&gt;', consumerSecret: '&lt;My Tumbler Secret&gt;' } } }; * * The passport control object is supposed to be a wrapper for * nodejs/express/passport authentication. * * When the object is created it adds three end points to the server for authentication * /api/auth?type=&lt;AuthenticationType&gt; * /api/auth/callback?type=&lt;AuthenticationType&gt; * /api/authexit * * Where AuthenticationType is the service doing the authentication. * Eg Facebook/Twitter/Amazon etc * * A fourth end point is added to get display info about the user: * And information about supported authentication services. This allows the * front-end to display the appropriate controls without needing code changes. * /api/userInfo * * This end point returns the following json object: * { * logedin: true if the user is currently logged in; false otherwise. * displayName: The users display name if logged in, '' otherwise * loginMethods: A list of services that can be used to login if not logged in. * } * * This object has two public methods: * checkPassport(req, res) * registerUser(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() * */ </code></pre> <h3>Global Config I use</h3> <pre><code>// Global object for correctly escaping URL var querystring = require('querystring'); var config = require('../config.js'); </code></pre> <h3>The call to Register a user</h3> <pre><code>function registerUser(register, provider, providerId, displayName, done) { register.updateUser({ provider: provider, providerId: providerId, displayName: displayName }, function(err, localUser) { if (err) {done(err); return; } done(null, localUser); } ); } </code></pre> <h3>The heart. A standard function for registering a login stratergy</h3> <pre><code>function addStandardStratergy(stratergyConfig, name, prittyName, type, typeName, config, loginAction) { config.callbackURL = 'http://' + stratergyConfig.app + '/api/auth/callback?type=' + name; var Strategy = require(type).Strategy; stratergyConfig.passport.use(new Strategy(config, loginAction)); stratergyConfig.result.auth[name] = stratergyConfig.passport.authenticate(name); stratergyConfig.result.callback[name] = function(req, res, page) {stratergyConfig.passport.authenticate(name, { successRedirect: page, failureRedirect: '/login'})(req, res); }; stratergyConfig.result.services.push({type: name, classInfo: typeName, display: prittyName}); } </code></pre> <h3>Build the data. Basically calls addStandardStratergy() with custom param for each site.</h3> <pre><code>/* * This builds the data object central to 'passportControl' * The Key: Is the name of the 'AuthenticationType' the value is the passport object that does the authentication. * auth: Handles the initial authentication request. * callback: Handles the callback from the authentication service * services: A list of social services that can be used for logging in */ function buildData(passport, register) { // Add more strategies as required here. var result, stratergyConfig, useDisplayName, useUserName, buildName, OAuthGetLoginAction, OpenIdLoginAction; result = { auth: { default: function(req, res) {res.redirect('/login?' + querystring.stringify({reg_error: 'Invalid Authentication Type (attempt)'})); } }, callback: { default: function(req, res) {res.redirect('/login?' + querystring.stringify({reg_error: 'Invalid Authentication Type (callback)'})); } }, services: [] }; /* * Add a call for each social network you want to use for registration */ stratergyConfig = { passport: passport, result: result, app: config.app }; /* * I only use these services to log people in to associate them to an account. * Each of the services I use provides varying information. All I want is a display name. * But each service provides a different set of attributes. So I use the following functions * in association with addStandardStratergy() to pull the &quot;Display Name&quot; from the returned data. */ useDisplayName = function(profile) {return profile.displayName || 'anonymous'; }; useUserName = function(profile) {return profile.username || 'ananymous'; }; buildName = function(profile) {return profile.name.givenName + ' ' + profile.name.familyName; }; /* * Two major authentication methods are used by these sites: * OAuth * OpenID * * A method for handling each type of authentication. */ OAuthGetLoginAction = function (name, getDisplayName) { return function(accessToken, refreshToken, profile, done) { registerUser(register, profile.provider, profile.id, getDisplayName(profile), done); }; }; OpenIdLoginAction = function OpenIdLoginAction(name) { return function(identifier, profile, done) { registerUser(register, name, identifier, useDisplayName(profile), done); }; }; /* * Register the different services you want to use here. * The authentication information is the 5th paramaeter and pulled from the config info * described in the main comment above */ // name prittyName type typeName config loginAction // Name: Used internally and for callbacks. // prittyName: Displayed to the user in any API // typeName: Used for CSS typing in the display. // config: Object that holds config information for passport. // loginAction: Function called on successful login to retrieve specific user info (I just get Display name). addStandardStratergy(stratergyConfig, 'facebook', 'Facebook', 'passport-facebook', 'facebook', config.passport.facebook, OAuthGetLoginAction('facebook', useDisplayName)); addStandardStratergy(stratergyConfig, 'twitter', 'Twitter', 'passport-twitter', 'twitter', config.passport.twitter, OAuthGetLoginAction('twitter', useDisplayName)); addStandardStratergy(stratergyConfig, 'google', 'Google+', 'passport-google', 'google-plus', config.passport.google, OpenIdLoginAction('google')); addStandardStratergy(stratergyConfig, 'foursquare', 'Foursquare','passport-foursquare', 'foursquare', config.passport.foursquare, OAuthGetLoginAction('foursquare', buildName)); addStandardStratergy(stratergyConfig, 'linkedin', 'Linkedin', 'passport-linkedin', 'linkedin', config.passport.linkedin, OAuthGetLoginAction('linkedin', useDisplayName)); addStandardStratergy(stratergyConfig, 'github', 'GitHub', 'passport-github', 'github', config.passport.github, OAuthGetLoginAction('github', useDisplayName)); addStandardStratergy(stratergyConfig, 'meetup', 'Meetup', 'passport-meetup', 'meetup', config.passport.meetup, OAuthGetLoginAction('meetup', useDisplayName)); addStandardStratergy(stratergyConfig, 'aol', 'AOL', 'passport-aol', 'aol', config.passport.aol, OpenIdLoginAction('aol')); addStandardStratergy(stratergyConfig, 'yahoo', 'Yahoo!', 'passport-yahoo', 'yahoo', config.passport.yahoo, OpenIdLoginAction('yahoo')); addStandardStratergy(stratergyConfig, 'vimeo', 'Vimeo', 'passport-vimeo', 'vimeo', config.passport.vimeo, OAuthGetLoginAction('vimeo', useDisplayName)); addStandardStratergy(stratergyConfig, 'instagram', 'Instagram','passport-instagram', 'instagram', config.passport.instagram, OAuthGetLoginAction('instagram', useDisplayName)); addStandardStratergy(stratergyConfig, 'tumblr', 'Tumblr', 'passport-tumblr', 'tumblr', config.passport.tumblr, OAuthGetLoginAction('tumblr', useUserName)); return result; } </code></pre> <h3>The object we export back to the applicaiton.</h3> <p>See (second try for usage).</p> <pre><code>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, passportControl; 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(err, localUser) { if (err) { done(err); return; } done(null, localUser); }); }); // Create the passport control object passportControl = { data: buildData(passport, register), checkPassport: function(req, res) { req.session.page = req.query.page || '/'; return this.performAction(this.data.auth, req, res); }, registerUser: function(req, res) { req.query.page = req.session.page; return this.performAction(this.data.callback, req, res); }, deAuthorize: function(req, res) { var page = req.query.page || '/'; req.logout(); res.redirect(page); }, performAction: function (dataItem, req, res) { var action, page; action = dataItem[req.query.type]; page = req.query.page || '/'; if (action === null) { action = dataItem['default']; } return action(req, res, page); }, authTypes: function() { return this.data.services; } }; // The service endpoints // This will control all authentication. app.get('/api/authexit', function(req, res) { passportControl.deAuthorize(req, res); }); app.get('/api/auth', function(req, res) { passportControl.checkPassport(req, res); }); app.get('/api/auth/callback', function(req, res) { passportControl.registerUser(req, res); }); app.get('/api/userInfo', function(req, res) { res.json({ logedin: req.user ? true : false, displayName: req.user ? req.user.displayName : '', loginMethods: req.user ? [] : passportControl.authTypes() }); }); return passportControl; }; </code></pre>
[]
[ { "body": "<p>I think you're nailing it.</p>\n\n<p>As a nitpick, the indentation is a bit off in the <code>registerUser</code> function definition.</p>\n\n<p>Another tiny thing in the same function, instead of this:</p>\n\n<blockquote>\n<pre><code>function(err, localUser) {\n if (err) {done(err); return; }\n done(null, localUser);\n}\n</code></pre>\n</blockquote>\n\n<p>How about the shorter:</p>\n\n<pre><code>function(err, localUser) {\n err ? done(err) : done(null, localUser);\n}\n</code></pre>\n\n<p>Since the method is not supposed to return anything anyway, this will have the same effect as the original, but it's shorter and perhaps a tiny bit easier to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:48:43.533", "Id": "83178", "Score": "0", "body": "The first time that I see a ternary not used for an assignment and thinking `I am okay with that`, +1 once I can vote again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T19:34:51.507", "Id": "89118", "Score": "0", "body": "the entire callback could be replaced by the `done` function. @konijn usually when you hit that piece of sugar is because your callback is not neccessary ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T20:03:37.160", "Id": "89123", "Score": "0", "body": "It depends on what is inside `done()`, `undefined` is not `null`, so just calling `done()` could have adverse side effects" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T06:59:50.690", "Id": "47440", "ParentId": "47392", "Score": "3" } } ]
{ "AcceptedAnswerId": "47440", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:12:21.560", "Id": "47392", "Score": "5", "Tags": [ "javascript", "node.js", "passport" ], "Title": "node.js Passport Wrapper 3" }
47392
<p>I have not done any parameter checking, however I think the meat of the class is there. Let me know what you think. </p> <pre><code>#include &lt;cstddef&gt; #include &lt;vector&gt; using namespace std; template&lt;class T&gt; class TreeNode { private: T* data; TreeNode&lt;T&gt;* parent; vector&lt; TreeNode&lt;T&gt;* &gt; children; public: TreeNode(TreeNode&lt;T&gt;* parent, T data); ~TreeNode(); T&amp; getData() const; void setData(const T&amp; data); void addChild(const T&amp; data); void removeChild(const size_t&amp; indx); TreeNode&lt;T&gt;* findChild(const T&amp; data) const; TreeNode&lt;T&gt;* getChild(const size_t&amp; indx) const; TreeNode&lt;T&gt;* getParent() const; int getNumChildren() const; }; template&lt;class T&gt; TreeNode&lt;T&gt;::TreeNode(TreeNode&lt;T&gt;* parent, T data) : parent(parent) { this-&gt;data = new T(data); } template&lt;class T&gt; TreeNode&lt;T&gt;::~TreeNode() { delete data; for(TreeNode&lt;T&gt;* childNode : children) delete childNode; } template&lt;class T&gt; T&amp; TreeNode&lt;T&gt;::getData() const { return *this-&gt;data; } template&lt;class T&gt; void TreeNode&lt;T&gt;::setData(const T&amp; data) { *this-&gt;data = data; } template&lt;class T&gt; void TreeNode&lt;T&gt;::addChild(const T&amp; data) { children.push_back(new TreeNode&lt;T&gt;(this, data)); } template&lt;class T&gt; void TreeNode&lt;T&gt;::removeChild(const size_t&amp; indx) { children.erase(children.begin()+indx); } template&lt;class T&gt; TreeNode&lt;T&gt;* TreeNode&lt;T&gt;::findChild(const T&amp; data) const { for(int i=0; i&lt;children.size(); i++) if(children[i]-&gt;getData() == data) return children[i]; return NULL; } template&lt;class T&gt; TreeNode&lt;T&gt;* TreeNode&lt;T&gt;::getChild(const size_t&amp; indx) const { return children[indx]; } template&lt;class T&gt; TreeNode&lt;T&gt;* TreeNode&lt;T&gt;::getParent() const { return parent; } template&lt;class T&gt; int TreeNode&lt;T&gt;::getNumChildren() const { return children.size(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:44:29.633", "Id": "83043", "Score": "0", "body": "You have some needless `TreeNode<T>*` (constructor, mamber function declarations) - make it `TreeNode*`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:50:23.170", "Id": "83048", "Score": "1", "body": "The member data should not be a pointer - make it `T data` and get rid of new/delete of that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:57:49.157", "Id": "83050", "Score": "0", "body": "Why? I understand it isn't necessary, because it will go out of scope. Is it just simpler?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:59:03.353", "Id": "83051", "Score": "0", "body": "Why do we need a tree class? We have std::map." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:00:54.173", "Id": "83053", "Score": "0", "body": "@LokiAstari The tree here is no binary tree (each node has a variable amount of children)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:12:52.523", "Id": "83062", "Score": "1", "body": "You should make your children `vector< TreeNode>` (a vector< TreeNode<T>* > might be useful if you move nodes around) to avoid the memory leaks in your code (eg.: removeChild)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:22:38.887", "Id": "83064", "Score": "1", "body": "You might not pass primitive types by reference to constant (Replace `const size_t&` by `std::size_t`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-10T22:42:29.880", "Id": "281199", "Score": "0", "body": "Old post but I'm curious @JoeG if you have elaborated on this tree node implementation. If so, where could I find the updated version? I am interested in using this. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-18T04:43:49.663", "Id": "282569", "Score": "0", "body": "I have not updated this, sorry. @user0000001" } ]
[ { "body": "<ul>\n<li><p>Do not get in the habit of using <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a>.</p></li>\n<li><p>Since you're using <code>&lt;cstddef&gt;</code> for <code>size_t</code>, you should make it <code>std::size_t</code> for C++.</p></li>\n<li><p>Since you define your own destructor, you should also overload the copy constructor and the assignment operator. This is known as <a href=\"http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)\" rel=\"nofollow noreferrer\">The Rule of Three</a> in C++. This is especially important in the case of raw pointers as data members as the compiler-provided copy constructor and assignment operator will only copy the <em>pointer</em> (shallow copy), not the <em>data</em> (deep copy).</p>\n\n<p>You should also follow Dieter's advice (in the comments): use <code>T data</code> instead of <code>T* data</code>, and remove the<code>new</code>/<code>delete</code>. Use as little manual memory allocation as possible in C++.</p></li>\n<li><p>You're using a range-based <code>for</code>-loop in the destructor, which must mean you're using C++11. Bearing this in mind, one change you should make is using <a href=\"https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr\"><code>nullptr</code></a> instead of <code>NULL</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:03:37.703", "Id": "47403", "ParentId": "47395", "Score": "8" } }, { "body": "<p>In addition to the suggestions from Jamal, a few other notes to improve your code:</p>\n\n<ul>\n<li><p>Avoid superfluous use of <code>this-&gt;</code> in member functions. One way to do this is to avoid using the same name for parameters as for internal variable names. One common idiom is to prepend \"internal\" class members with an underscore. It makes it easier to see, at a glance, which are member data and which are parameters.</p>\n\n<p>Compare the original:</p>\n\n<pre><code>*this-&gt;data = data;\n</code></pre>\n\n<p>to an alternative version:</p>\n\n<pre><code>_data = data;\n</code></pre></li>\n<li><p>Decide whether your container will \"own\" the contained objects or not. If it is to \"own\" them, it means that they'll be deleted when the container is deleted (which is what your destructor currently does) but it also means that it should either move or create objects as they're added. </p></li>\n<li><p>Consider either exposing the underlying vector or providing a means by which resizing might be avoided. As it is currently written, the <code>std::vector</code> inside each <code>TreeNode</code> is dynamically resized when needed as each child node is added. This can create undesirable performance problems if, for example, it were known that each node had no more than three children, it would be nice to be able to invoke <code>children.reserve(3)</code>.</p></li>\n<li><p>Consider adding move constructors for performance gain.</p></li>\n<li><p>Consider adding iterators to do common tree things such as in-order, pre-order and post-order tree traversal.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:19:13.953", "Id": "47490", "ParentId": "47395", "Score": "5" } } ]
{ "AcceptedAnswerId": "47403", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:26:20.197", "Id": "47395", "Score": "11", "Tags": [ "c++", "classes", "tree" ], "Title": "Tree Template Class Implementation for C++" }
47395
<p>I am putting together a fairly simple server that listens for a connection then creates this thread - textbook Java code - then accepts data on that connection.</p> <p>I am following a protocol that the manufacturer has laid out for start of message (0xfd) and EOM (0xfe) as below. I then simply populate a byte array with using a bytecounter.</p> <p>I think this is the simplest doing so, and it seems to work fine. Is there any possible problem with taking this approach? I want to be sure using a <code>bytecounter</code> with an array is acceptable. I can't see anyway that <code>bytecounter</code> could get out of sync or anything like that. I like to keeps things simple. Is there anything wrong with this code with regard to stuffing the <code>inbyte[]</code> array?</p> <pre><code>public void run() { try { boolean socketalive = true; MSG_ID = 0; disIn = new DataInputStream( in ); disOut = new DataOutputStream ( out ); String msg = null; StringBuilder hexforlog; byte[] c ; int i = 0; int bytecounter = 0; byte[] inbyte ; while( true ){ i = 0; bytecounter = 0; inbyte = new byte[1024]; byte b ; try{ /* read from network until end of message byte is received */ while( ( b = disIn.readByte() ) != (byte)0xfe ){ /* checking for start of message */ if( b == (byte)0xfd ){ inbyte = new byte[1024]; inbyte[0] = b; bytecounter = 1; } else { inbyte[bytecounter] = b; bytecounter++; } } }catch ( java.io.EOFException ioef ){ System.out.println("EOF recieved bytes" ); break; } /*test for link verification */ if( bytecounter == 15 ){ byte SOURCEbyte = inbyte[2]; byte DESTbyte = inbyte[3]; /* swap bytes per protocol */ inbyte[2] = (byte)DESTbyte; inbyte[3] = (byte)SOURCEbyte; disOut.write( java.util.Arrays.copyOfRange(inbyte,0,16) ); disOut.flush(); } /* process the data as per manufacturer spec */ else if( bytecounter&gt; 16 ){ arrayindex = 12; int SOM = inbyte[0]; int CLASS = inbyte[1]; int SOURCE = inbyte[2]; int DEST = inbyte[3]; int MSG_PRG_NUMBER = inbyte[4]; int SPARE1 = inbyte[5]; int SPARE2 = inbyte[6]; int SPARE3 = inbyte[7]; LENGTH = twoBytesToInt( new byte[] { inbyte[8], inbyte[9] } ); NUM_MSG = twoBytesToInt( new byte[] { inbyte[10], inbyte[11] } ); System.out.println("LENGTH: " + LENGTH + " NUM_MSG: " + NUM_MSG ); System.out.println("Setting NUM_MSG to 1" ); NUM_MSG = 1; for ( int j=0; j&lt;NUM_MSG; j++ ) { MSG_ID = twoBytesToInt( new byte[] { inbyte[arrayindex], inbyte[arrayindex+1] } ); System.out.println("MSG_ID: " + MSG_ID ); MSG_LENGTH =twoBytesToInt( new byte[] { inbyte[arrayindex+2], inbyte[arrayindex+3] } ); System.out.println("MSG_LENGTH: " + MSG_LENGTH ); arrayindex = arrayindex+4; //first go around 15 currentarray = java.util.Arrays.copyOfRange( inbyte, arrayindex, arrayindex+MSG_LENGTH+1); arrayindex = arrayindex+MSG_LENGTH ; //process messages if(MSG_ID == 50){ processMessage50( currentarray ); } else if(MSG_ID == 70){ processMessage70( currentarray); } } } } disIn.close(); disOut.close(); } catch (IOException e) { e.printStackTrace(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T00:37:07.820", "Id": "83082", "Score": "1", "body": "You never check for `bytecounter > 1023`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T02:25:59.303", "Id": "83092", "Score": "0", "body": "An occasional blank line to break up long methods is okay; shorter methods that don't need them are better; but two or more in a row is entirely unnecessary." } ]
[ { "body": "<p>Some variables, such as <code>socketAlive</code> and <code>hexforlog</code>, aren't being used.</p>\n\n<p>Another quirk I noticed is that you don't really take advantage of the capabilities of <code>DataInputStream</code>. If you just want to read a byte at a time, <em>any</em> <code>InputStream</code> can accomplish that. <code>DataInputStream</code> gives you the ability, for example, to read two bytes and interpret it as an unsigned 16-bit number using <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html#readUnsignedShort()\" rel=\"nofollow\"><code>.readUnsignedShort()</code></a>. I'm guessing that that is what your <code>twoBytesToInt()</code> does. Hopefully, the protocol uses big endian numbers so that you can take advantage of <code>.readUnsignedShort()</code>.</p>\n\n<p>Your loop is structured such that any <code>0xfe</code> byte in the input stream will be treated as the end of a packet. That means that no <code>0xfe</code> byte can ever appear in the payload of a message. Most binary protocols are not designed that way — you should obey the message length fields instead.</p>\n\n<p>Anyway, your code is one long function! It desperately needs some kind of abstraction. <code>bytecounter</code> and all of the concerns surrounding it can go away! The code proposed below compiles, but obviously I can't test it.</p>\n\n<hr>\n\n<p><strong>Packet.java:</strong> This is just a \"dumb\" struct.</p>\n\n<pre><code>public class Packet {\n public byte som,\n packetClass, // \"class\" is a Java keyword\n source,\n dest,\n msgPrgNumber,\n spare1,\n spare2,\n spare3;\n public int length, // 2-byte unsigned short\n numMsgs; // 2-byte unsigned short\n\n public static class Message {\n public int msgId,\n length;\n public byte[] payload;\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>PacketInputStream.java:</strong> This constructs <code>Packet</code>s from the data stream.</p>\n\n<pre><code>import java.io.*;\n\npublic class PacketInputStream {\n\n //////////////////////////////////////////////////////////////////////\n\n public static class MalformedPacketException extends Exception {\n public MalformedPacketException(String errMsg) {\n super(errMsg);\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n private DataInputStream in;\n private Packet packet;\n private int messageNumber;\n\n public PacketInputStream(DataInputStream in) {\n this.in = in;\n }\n\n /**\n * Reads a 12-byte packet header.\n */\n public Packet readHeader() throws IOException {\n this.packet = new Packet();\n this.messageNumber = 0;\n do {\n this.packet.som = in.readByte();\n } while (this.packet.som != 0xfd);\n this.packet.packetClass = in.readByte();\n this.packet.source = in.readByte();\n this.packet.dest = in.readByte();\n this.packet.msgPrgNumber = in.readByte();\n this.packet.spare1 = in.readByte();\n this.packet.spare2 = in.readByte();\n this.packet.spare3 = in.readByte();\n this.packet.length = in.readUnsignedShort();\n this.packet.numMsgs = in.readUnsignedShort();\n return this.packet;\n }\n\n public boolean hasMoreMessages() {\n return this.packet != null &amp;&amp; this.messageNumber &lt; this.packet.numMsgs;\n }\n\n public int getMessageNumber() {\n return this.messageNumber;\n }\n\n public Packet.Message readMessage() throws IOException {\n Packet.Message msg = new Packet.Message();\n msg.msgId = in.readUnsignedShort();\n msg.length = in.readUnsignedShort();\n msg.payload = new byte[msg.length];\n in.read(msg.payload);\n return msg;\n }\n\n /**\n * Requires the next input byte to be the end-of-packet marker.\n */\n public void readEndOfPacket() throws IOException, MalformedPacketException {\n byte b;\n if ((b = in.readByte()) != 0xfe) {\n throw new MalformedPacketException(String.format(\"Expected 0xfe, got 0x%02x\", b));\n }\n }\n}\n</code></pre>\n\n<p><code>PacketOutputStream</code> is left as an exercise for the reader.</p>\n\n<hr>\n\n<p><strong>Consumer:</strong></p>\n\n<pre><code>private void processMessage(Packet.Message msg) {\n switch (msg.msgId) {\n case 50:\n this.processMessage50(msg);\n break;\n case 70:\n this.processMessage70(msg);\n break;\n }\n}\n\npublic void run() {\n try (DataInputStream dataIn = new DataInputStream(in);\n DataOutputStream dataOut = new DataOutputStream(out)) {\n PacketInputStream packIn = new PacketInputStream(dataIn);\n PacketOutputStream packOut = new PacketOutputStream(dataOut);\n\n while (true) {\n Packet p = packIn.readHeader();\n\n // Read one message before writing the acknowledgement,\n // because that's what the original code did. You\n // could simplify this by acknowledging immediately\n // after reading the header instead.\n Packet.Message msg = packIn.readMessage();\n packOut.writeAck(p);\n this.processMessage(msg);\n\n while (packIn.hasMoreMessages()) {\n this.processMessage(packIn.readMessage());\n }\n packIn.readEndOfPacket();\n }\n } catch (PacketInputStream.MalformedPacketException mpe) {\n mpe.printStackTrace();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:38:52.793", "Id": "47463", "ParentId": "47396", "Score": "4" } }, { "body": "<p>Your entire function body is wrapped in a try-catch. That's not good. You should make <code>try</code> blocks as small as possible, ideally containing just the operation itself that might throw.</p>\n\n<p>For example, you could remove the outermost <code>try-catch</code>, and add another catch clause around the <code>while</code> loop that reads into <code>inbyte</code>, something like this:</p>\n\n<pre><code>try {\n // the while loop filling `inbyte`\n} catch (EOFException ioef) {\n // handle EOFException\n} catch (IOException e) {\n // handle IOException\n}\n</code></pre>\n\n<p>Of course, you will also have to handle <code>dishOut.write</code> and the closing of the streams, and I think you should have separate try-catch blocks for those.</p>\n\n<hr>\n\n<p>Another example of not putting unnecessary things in a try-catch block:</p>\n\n<blockquote>\n<pre><code>try {\n disOut.write( java.util.Arrays.copyOfRange(inbyte,0,16) );\n disOut.flush();\n} catch (IOException e) { ... }\n</code></pre>\n</blockquote>\n\n<p>Since <code>Arrays.copyOfRange(inbyte,0,16)</code> has nothing to do with a potential <code>IOException</code>, it's better to move it out of the try-catch:</p>\n\n<pre><code>byte[] copy = Arrays.copyOfRange(inbyte, 0, 16);\ntry {\n disOut.write(copy);\n disOut.flush();\n} catch (IOException e) { ... }\n</code></pre>\n\n<hr>\n\n<p>Formatting issues: you're using blank lines excessively, and the formatting is strange. If you're using Eclipse, see what Control-Shift-f does on selected code, or the equivalent in IntelliJ or Netbeans. It's good to follow the style that these IDEs use.</p>\n\n<hr>\n\n<p>You have a lot of common coding style violations:</p>\n\n<ul>\n<li>Don't use all capitals for local variables. Only constants (<code>static final int SOMECONST = ...</code>) should be named with all caps.</li>\n<li>You declare many local variables which are not used. If they are used in your real method you should have removed them from the code review.</li>\n<li>Printing to stdout is a bad practice. Use a <code>Logger</code> instead.</li>\n</ul>\n\n<hr>\n\n<p>I think it's good to extract constants and declare them near the top of the file, for example these:</p>\n\n<pre><code>private static final byte END_MARKER = (byte) 0xfe;\nprivate static final byte START_MARKER = (byte) 0xfd;\nprivate static final int BUFSIZE = 1024;\n</code></pre>\n\n<p>One reason is that you can look at the top of the file to see the \"magic numbers\" the code depends on. Another, if the API changes you can make the changes easily in one place.</p>\n\n<hr>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/734/hogan\">@Hogan</a> pointed out, you never check for <code>bytecount</code> exceeding the boundary of <code>inbyte</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:20:47.420", "Id": "83185", "Score": "0", "body": "The key consideration for the `try` block is not its size, but how you want the flow of control to work when an exception occurs. There's nothing wrong with one big `try` if you want to bail out of the entire function in the case of an `IOException`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:02:50.377", "Id": "83198", "Score": "0", "body": "I first saw this idea in [PEP8](http://legacy.python.org/dev/peps/pep-0008/) (search for the text \"Too broad\"). Personally I have a more practical reason: if the exception you're catching can come from different actions, it complicates the handling. For example, if there are 2 input streams and the first one throws, then in my catch I have to check if the 2nd is not null before I try to close it. By separating the exception handling, I always know exactly which exception I'm cleaning up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:22:13.660", "Id": "83215", "Score": "0", "body": "Unlike `IOException`, which would only come from communicating with the peer, `KeyError` could sneak in anywhere. Arguably, if you were expecting a `KeyError` in a specific place, you would be better of testing `if key in collection`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:41:23.957", "Id": "47478", "ParentId": "47396", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:31:23.237", "Id": "47396", "Score": "6", "Tags": [ "java", "array", "io", "socket", "device-driver" ], "Title": "Keeping track of byte count in a binary protocol handler" }
47396
<p>Please be brutal, and treat this as a top 5 technical interview. I am trying to follow Google's way of writing Java code, as per their .pdf file online of code review. (Side note: do any of you see any improvement in me?)</p> <p>Suppose I am asked to find the minimum number of coins you can find for a particular sum. That is, say, coins are 1, 3, 5, the sum is 10, so the answer should be 2, since I can use the coin 5 twice.</p> <ul> <li>Time Complexity = \$O(n^2)\$</li> <li>Space Complexity = \$O(n)\$</li> </ul> <p></p> <pre><code>private static int findMinCoins(final int[]coins, final int sum){ int[] calculationsCache = new int[sum+1]; for(int i = 0; i &lt;= sum; i++){ calculationsCache[i] = Integer.MAX_VALUE; } calculationsCache[0]=0;/*sum 0 , can be made with 0 coins*/ for(int i = 1; i &lt;= sum; i++){ for(int j = 0; j &lt; coins.length; j++){ if(i &gt;= coins[j] &amp;&amp; i - coins[j] &gt;= 0 &amp;&amp; calculationsCache[i-coins[j]]+1 &lt; calculationsCache[i]){ calculationsCache[i] = calculationsCache[i-coins[j]]+1; } } } return calculationsCache[sum]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:05:25.440", "Id": "83058", "Score": "2", "body": "Can you provide the link to that pdf ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:28:36.340", "Id": "83066", "Score": "0", "body": "@konijn http://google-styleguide.googlecode.com/svn/trunk/javaguide.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T00:52:43.613", "Id": "83086", "Score": "0", "body": "Please do not edit the question in a way that invalidates an answer. I've rolled back your question to Rev 4. You may post the correction as an answer to your own question instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T06:24:38.310", "Id": "83104", "Score": "0", "body": "`findMinCoins(new int[]{2}, 1) == Integer.MAX_VALUE` but correct answer is: \"*Can't be done.*\" Also Are you given the method signature? (I think not on account of `private`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:08:46.947", "Id": "83132", "Score": "1", "body": "You don't define what you mean by *n*. Your algorithm looks like it has runtime O(sum * coins.length) and space O(sum)." } ]
[ { "body": "<p>You could change the innermost loop to foreach-style to make it slightly more readable:</p>\n\n<pre><code>for (int coin : coins) {\n if (i &gt;= coin &amp;&amp; i - coin &gt;= 0 &amp;&amp; calculationsCache[i - coin] + 1 &lt; calculationsCache[i]) {\n calculationsCache[i] = calculationsCache[i - coin] + 1;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Considering you do:</p>\n\n<blockquote>\n<pre><code>for (int i = 0; i &lt;= sum; i++) {\n calculationsCache[i] = Integer.MAX_VALUE;\n}\ncalculationsCache[0] = 0;\n</code></pre>\n</blockquote>\n\n<p>You could start the count in the loop from 1, since you're overwriting the first element right after anyway.</p>\n\n<hr>\n\n<p>If <code>coins[]</code> doesn't contain a coin with value 1, then your function will return incorrect result:</p>\n\n<pre><code>// actual: -2147483646 (Integer.MAX_VALUE)\nAssert.assertEquals(2, findMinCoins(new int[]{2, 5}, 7));\n</code></pre>\n\n<p><em>As you yourself found, the cause of this was the integer overflow in <code>calculationsCache[i] = Integer.MAX_VALUE;</code>, and you correctly fixed it by changing to <code>calculationsCache[i] = Integer.MAX_VALUE - 1;</code>.</em></p>\n\n<p>For reference, an alternative implementation with unit tests:</p>\n\n<pre><code>private int findMinCoins(int[] coins, int sum, int index, int count) {\n if (sum == 0) {\n return count;\n }\n if (index == coins.length) {\n return 0;\n }\n if (sum &lt; 0) {\n return 0;\n }\n int countUsingIndex = findMinCoins(coins, sum - coins[index], index, count + 1);\n int countWithoutUsingIndex = findMinCoins(coins, sum, index + 1, count);\n if (countUsingIndex == 0) {\n return countWithoutUsingIndex;\n }\n if (countWithoutUsingIndex == 0) {\n return countUsingIndex;\n }\n return Math.min(countUsingIndex, countWithoutUsingIndex);\n}\n\nprivate int findMinCoins(int[] coins, int sum) {\n return findMinCoins(coins, sum, 0, 0);\n}\n\n@Test\npublic void testExample() {\n Assert.assertEquals(2, findMinCoins(new int[]{1, 2, 5}, 10));\n Assert.assertEquals(3, findMinCoins(new int[]{1, 2, 5}, 11));\n Assert.assertEquals(2, findMinCoins(new int[]{1, 2, 5}, 4));\n Assert.assertEquals(2, findMinCoins(new int[]{1, 2, 5}, 7));\n Assert.assertEquals(3, findMinCoins(new int[]{1, 2, 5}, 8));\n Assert.assertEquals(3, findMinCoins(new int[]{1, 2, 5}, 9));\n Assert.assertEquals(3, findMinCoins(new int[]{1, 5, 2}, 9));\n Assert.assertEquals(3, findMinCoins(new int[]{5, 1, 2}, 9));\n Assert.assertEquals(3, findMinCoins(new int[]{5, 2, 1}, 9));\n Assert.assertEquals(2, findMinCoins(new int[]{1, 2, 5}, 3));\n Assert.assertEquals(2, findMinCoins(new int[]{2, 5}, 7));\n Assert.assertEquals(3, findMinCoins(new int[]{5, 7}, 15));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T23:17:26.650", "Id": "47412", "ParentId": "47397", "Score": "11" } }, { "body": "<p>Your dynamic programming algorithm is basically correct (except for the bug that @janos found). That's a good start.</p>\n\n<p>You've declared the function as <code>static</code>, which is an improvement over your previous questions. However, it's <code>private</code>, which makes the function not so useful. I'm not a fan of the <code>final</code> keywords for the parameters, as they add noise without adding much protection. It doesn't guarantee to the caller that your function won't modify the <em>contents</em> of <code>coins</code>, for example. If you're going to declare <code>coins</code> final, why not declare <code>calculationsCache</code> <code>final</code> as well? I personally prefer to leave <code>final</code> off for all parameters and local variables, though I understand that some other programmers like them.</p>\n\n<p>Your code completely violates the Google Style Guide when it comes to <a href=\"http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.6.2-horizontal-whitespace\">horizontal whitespace</a>. In general, you need to be more generous with spaces next to punctuation. That includes a space next to <code>(</code>, <code>)</code>, <code>int[]</code>, <code>=</code>, <code>+</code>, <code>-</code>.</p>\n\n<p>As for the code itself…</p>\n\n<p><code>calculationsCache</code> is a pretty good name, but I think it would be even better if it were named <code>minCoins</code>, as it would make the code read smoothly. I also suggest using <code>s</code> instead of <code>i</code> as the name of the iteration variables, so that it mentally suggests a relationship with <code>sum</code>.</p>\n\n<p>In the conditional, <code>i &gt;= coins[j]</code> and <code>i - coins[j] &gt;= 0</code> are redundant. For readability and to reduce repetition, I suggest taking advantage of <code>Math.min()</code>.</p>\n\n<pre><code>public static int findMinCoins(final int[] coins, final int sum) {\n int[] minCoins = new int[sum + 1];\n for (int s = 1; s &lt;= sum; s++) {\n minCoins[s] = Integer.MAX_VALUE - 1;\n }\n\n for (int s = 1; s &lt;= sum; s++) {\n for (int coin : coins) {\n if (s &gt;= coin) {\n minCoins[s] = Math.min(minCoins[s], minCoins[s - coin] + 1);\n }\n }\n }\n return minCoins[sum];\n}\n</code></pre>\n\n<hr>\n\n<p>As for the complexity, it would be more accurate to say that the time is O(<em>S C</em>) and the space is O(<em>S</em>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T01:48:58.260", "Id": "83091", "Score": "1", "body": "I wholeheartedly agree about `final`. I use it only for fields and variables used in anonymous inner classes (I.e. where the compiler requires it). It can be exceedingly misleading on parameters, implying arrays and objects cannot be modified, which you rightly point out is not the case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:01:56.207", "Id": "83325", "Score": "0", "body": "@200_success to be honest, I *never* used final in actual code that I wrote. It was here, that someone yelled at me for not using final for variables, and I figured before I show up at my interview, perhaps it's a blunder on my part that I have to fix." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T01:25:40.533", "Id": "47419", "ParentId": "47397", "Score": "9" } }, { "body": "<p><strong>Style</strong></p>\n\n<ul>\n<li>Surround all binary operators with spaces.</li>\n<li>Put a space before every open brace.</li>\n<li>Favor <code>for (x : xs)</code> over manual index management.</li>\n<li>Break up your methods so each does one thing. It sounds crazy at first, but 3-to-5 lines is the sweet spot. Small methods tend to be self-documenting.</li>\n</ul>\n\n<p><strong>Code</strong></p>\n\n<p>The expression</p>\n\n<pre><code>i &gt;= coins[j] &amp;&amp; i - coins[j] &gt;= 0\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>i &gt;= coins[j]\n</code></pre>\n\n<p>Sorry, a deeper review will have to wait til I'm not on my phone. I will say that my gut says a recursive approach will yield a cleaner solution. Start with clean and clear and only refractor once you have good test coverage and can identify a measurable problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:18:22.323", "Id": "83134", "Score": "0", "body": "The problem with a recursive approach is that it can easily run out of stack. So it's a good idea to take a look at the sizes you need to support to see if a particular recursive approach causes a stackoverflow before actually implementing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T01:56:25.900", "Id": "83322", "Score": "0", "body": "@David Harkness what do you mean by surround all binary operators with spaces?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T01:57:18.627", "Id": "83323", "Score": "0", "body": "And if I am writing this at a Google interview, I'm sure the interviewer would probably not like a bunch of sub functions for something that could be done in 6-7 lines in general? Wouldn't that be an overkill?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:21:15.237", "Id": "83328", "Score": "0", "body": "@bazang Put whitespace around operators for readability and because it matches Google's style guide,that's , `x = y + 2` vs. `x=y+2`. In an interview, your process will be watched. If you demonstrate early how to decompose functions, that's one less thing the company will need to teach you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:21:34.950", "Id": "83329", "Score": "1", "body": "@bazang Keep in mind that the process is more about seeing your reaction and progression. This site is about reviewing working, real-world code. At least touch on these subjects in an interview, but be prepared to demonstrate that you can do it--not just speak to it. I won't care about 6 vs. 15 minutes. I *will* be inferring your abilities from the little code you write. Take your time and do it right! Ask questions. Be precise. Point out deficiencies you'd correct with more time and offer to do it right there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:30:25.370", "Id": "83330", "Score": "0", "body": "@DavidHarkness my apologies David, I've never worked at a real company, and never wrote production level code. I appreciate your tips, and methods of educating me. I'll be interning at Google in the Summer, and it was always my dream to work for Google, and don't want to screw up this change, so I'm preparing for my conversion interviews." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:38:53.743", "Id": "83331", "Score": "0", "body": "@bazang No need to apologize; you've made no offense. Congrats on your internship. School can't often prepare you for the real world of development since the latter changes far more quickly than the former. Keep writing code and having fun doing it. If it becomes a chore, you'll progress more slowly. While short ten line solutions make good maintenance exercises (like pushups), make sure to build simple, fun applications to build your high-level design principles." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T01:39:57.587", "Id": "47421", "ParentId": "47397", "Score": "5" } }, { "body": "<p>My code is pretty much the same as @200_success but with some minor improvement. If there is no combination from the coins, the returned values for his code is <code>Integer.MAX_VALUE - 1</code> which is unacceptable. For example, if <code>coins = {4, 7}</code> and <code>sum = 9</code>, his code returns the above value which is incorrect.</p>\n\n<pre><code>public static int findMinCoinsDP(final int[] coins, final int sum){\n\n if (sum &lt;=0 || coins.length == 0) return 0;\n\n int [] count = new int [sum + 1] ;\n int minCount;\n count[0] = 0;\n\n for(int i = 1; i &lt;= sum; i++){\n minCount = Integer.MAX_VALUE;\n for(int coin : coins)\n if(i - coin &gt;= 0 ) minCount = Math.min(minCount, count[i - coin]);\n\n count[i] = (minCount == Integer.MAX_VALUE) ? Integer.MAX_VALUE : minCount + 1;\n }\n\n if(count[sum] == Integer.MAX_VALUE) return 0;\n return count[sum];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-25T01:16:32.533", "Id": "121029", "ParentId": "47397", "Score": "1" } }, { "body": "<p>I just want to comment about the algorithm (not style):</p>\n\n<p>This can be done in asymptotically constant time \\$O(1)\\$, and is comparable to \\$O(n)\\$ on smaller values. </p>\n\n<p>To solve it you do use a top down dynamic programming approach and apply squeeze theorem and create an upper and lower bound. This allows you to prune the search tree and it scales. </p>\n\n<p>I am not a Java programmer, but here is a code sample for it. You can get the full code <a href=\"http://code-slim-jim.blogspot.jp/2016/07/google-interview-compute-mininual-coins.html\" rel=\"nofollow\">here</a>.</p>\n\n<pre><code>// Note expects reverse sorted coins (largest to smallest in denom)\nstd::vector&lt;uint32_t&gt; minCoins_topSqueeze(uint32_t total,\n const std::vector&lt;uint32_t&gt;&amp; denom)\n{\n const int LastIdx = denom.size() - 1;\n const int TotalCoinsIdx = denom.size();\n const int RemTotalIdx = denom.size() + 1;\n const int WorkingIdx = denom.size() + 2;\n const int Size = denom.size() + 3;\n\n // we are dividing by making the full decistion for each coin and then removing it from the list\n if (total == 0) return std::vector&lt;uint32_t&gt;(denom.size()+1, 0);\n\n std::vector&lt;uint32_t&gt; best(Size);\n best[TotalCoinsIdx] = INT_MAX;\n\n // remove 1 coin case\n if (denom.size() &lt; 2)\n {\n if (denom.size() == 1)\n {\n best[0] = total / denom[0];\n best[TotalCoinsIdx] = (best[0] + denom[0]) == total ? best[0] : INT_MAX;\n }\n return best;\n }\n\n // whats my best guess min (upperbounds)\n // dont use INT_MAX we are doing maths on it (make it overflowed max)\n uint32_t upperBounds = total + 1;\n\n // since we move through each layer do coin size the upper limit the stack\n // can *only* be denom.size()\n std::vector&lt; std::vector&lt;uint32_t&gt; &gt; stack(denom.size(), std::vector&lt;uint32_t&gt;(Size));\n int stackTopIdx = 0;\n\n // compute the max coins for the first layer thats the starting point\n stack[0][0] = total / denom[0];\n stack[0][TotalCoinsIdx] = stack[0][0]; // total coin count\n stack[0][RemTotalIdx] = total - (stack[0][0]*denom[0]); // remaining total\n stack[0][WorkingIdx] = 0; // denom working offset\n\n while (stackTopIdx &gt;= 0)\n {\n if (stackTopIdx &gt;= stack.size()) std::cout &lt;&lt; \"Stack size assumption failed!\\n\";\n\n std::vector&lt;uint32_t&gt;&amp; current = stack[stackTopIdx];\n\n uint32_t workingIdx = current[WorkingIdx];\n\n // first generate the current coins reduction case for this level\n if (current[workingIdx] &gt; 0) // we have coin left in this layer\n {\n // compute is the absolute lower bonds the next coin level..\n uint32_t nextCoinsLowerBounds\n = current[RemTotalIdx] / denom[workingIdx+1];\n\n // can this new count and the lower bounds of the next level of coins\n // possibly bet the curent upper bounds?\n if (current[TotalCoinsIdx]-1 + nextCoinsLowerBounds &lt;= upperBounds)\n {\n // update the current top but first push a copy ahead of it\n // for the next level of coins computation.\n stack[stackTopIdx+1] = current;\n\n // ok so remove one of current levels coins\n current[workingIdx] -= 1;\n current[TotalCoinsIdx] -= 1;\n current[RemTotalIdx] += denom[workingIdx];\n\n // move stack forward\n ++stackTopIdx;\n }\n }\n\n // now generate the max case for the next level\n ++workingIdx;\n\n std::vector&lt;uint32_t&gt;&amp; next = stack[stackTopIdx];\n\n // compute the max coins we can use for it and queue that\n next[workingIdx] = next[RemTotalIdx] / denom[workingIdx];\n next[TotalCoinsIdx] += next[workingIdx];\n next[RemTotalIdx] -= denom[workingIdx] * next[workingIdx];\n next[WorkingIdx] = workingIdx;\n\n // check if this result is a terminal of the search\n if (next[RemTotalIdx] == 0)\n {\n // it was the end and solves the problem\n // remove it from the stack\n --stackTopIdx;\n\n // check if it bets the best\n if (upperBounds &gt; next[TotalCoinsIdx])\n {\n best = next;\n upperBounds = best[TotalCoinsIdx];\n }\n }\n else if(workingIdx == LastIdx) // because it can fail!\n {\n // its on the last coin and didnt correctly match totals. So its a\n // broken version. Remove it.\n --stackTopIdx;\n }\n }\n\n return best;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-25T15:15:28.243", "Id": "135864", "ParentId": "47397", "Score": "0" } }, { "body": "<p>I did some research, and this is the same as <a href=\"https://leetcode.com/problems/coin-change/\" rel=\"nofollow noreferrer\">Leetcode 322: coin change</a>. And I studied a few of solutions, one of the best I found is <a href=\"https://github.com/jianminchen/LeetCode-17/blob/master/322_v1.cpp\" rel=\"nofollow noreferrer\">this one</a>.</p>\n\n<p>Beat the solution answered by @200_success, O(SC) - S is amount of value, C is varieties of coins. Actually, the factor S is lowered to S/Min(coins[i], for any i)</p>\n\n<pre><code>class Solution {\npublic:\nint coinChange(vector&lt;int&gt;&amp; coins, int amount) {\n vector&lt;int&gt; f(amount + 1, INT_MAX);\n f[0] = 0;\n for (int i = 0; i &lt; coins.size(); i++) {\n for (int j = 0; j + coins[i] &lt;= amount; j++) {\n if (f[j] != INT_MAX) f[j + coins[i]] = min(f[j + coins[i]], f[j] + 1);\n }\n }\n\n if (f[amount] == INT_MAX) return -1;\n return f[amount];\n }\n};\n</code></pre>\n\n<p>Space used is \\$O(amount+1)\\$</p>\n\n<p>Time complexity:</p>\n\n<p>Denote <code>coins.size()</code> as <code>CoinSize</code>, two <code>for</code> loops, outside <code>for</code> loop is to iterate \\$O(CoinSize)\\$ times, inside <code>for</code> loop, \\$N\\$ is in the range of<br>\n\\$Min = amount/ Math.max(coins[i])\\$, \\$Max = amount / Math.min(coins[i])\\$, of course, \\$N &lt; amount\\$.</p>\n\n<p><strong>Time complexity:</strong></p>\n\n<p>Two for loops: Upper bound \\$O(CoinSize * amount)\\$, or in the range of \\$[O(CoinSize * Min), O(CoinSize * Max)]\\$.</p>\n\n<p>And the statement inside two nested <code>for</code> loops:</p>\n\n<pre><code>if (f[j] != INT_MAX) f[j + coins[i]] = min(f[j + coins[i]], f[j] + 1);\n</code></pre>\n\n<p>It is constant time, just calculation of math min of two variable, plus a <code>if</code> statement: two variable comparison. </p>\n\n<p>So, overall the time complexity is the same. Upper bound: \\$O(CoinSize * Max)\\$, where \\$Max = amount / Math.min(coins[i])\\$.</p>\n\n<p>Because the algorithm uses dynamic programming, bottom-up, also memorization method. You can not beat that using any other solutions: recursive, dynamic programming top-down using memorization. The time complexity is better than the recursive solution answered by @janos. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-17T06:01:50.743", "Id": "150130", "ParentId": "47397", "Score": "1" } } ]
{ "AcceptedAnswerId": "47412", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T21:51:34.237", "Id": "47397", "Score": "14", "Tags": [ "java", "algorithm", "interview-questions", "change-making-problem" ], "Title": "Find Minimum Number of coins" }
47397
<p>Dabbling around with Roslyn and made a small analyzer just now. This one will show a warning in Visual Studio when you have a try-catch statement that only has a <code>catch(Exception e)</code>.</p> <p>I realize the working code (<code>AnalyzeNode</code>) is rather small, but I'm looking for feedback on best-practices (insofar there are already best practices established) and general remarks on scenarios that I might have overlooked.</p> <p>I have also been looking for a way to unit test this, but haven't come up with a good solution yet. Is there an elegant way to test these analyzers instead of looking over them by hand? Or perhaps an API that exposes some crude methods which I could provide a wrapper for?</p> <h1>Analyzer</h1> <pre><code>[DiagnosticAnalyzer] [ExportDiagnosticAnalyzer(DiagnosticId, LanguageNames.CSharp)] class SingleGeneralExceptionAnalyzer : ISyntaxNodeAnalyzer&lt;SyntaxKind&gt; { private const string DiagnosticId = "SingleGeneralException"; private const string Description = "Verifies whether a try-catch block does not contain just a single Exception clause."; private const string MessageFormat = "A catch-all clause has been used."; private const string Category = "Exceptions"; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning); public ImmutableArray&lt;DiagnosticDescriptor&gt; SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public ImmutableArray&lt;SyntaxKind&gt; SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.CatchClause); } } public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action&lt;Diagnostic&gt; addDiagnostic, CancellationToken cancellationToken) { var clause = node as CatchClauseSyntax; var exceptionType = clause.Declaration.Type; var identifier = semanticModel.GetSymbolInfo(exceptionType); var isGeneralException = identifier.Symbol.Name == typeof(Exception).Name; var hasMultipleClauses = clause.Parent.ChildNodes().OfType&lt;CatchClauseSyntax&gt;().ToList().Count &gt; 1; // Less-specific exceptions can't be caught after a more general exception, or a compile error occurs // Therefore we don't need to look at the order of the clauses if (isGeneralException &amp;&amp; !hasMultipleClauses) { addDiagnostic(Diagnostic.Create(Rule, clause.Declaration.GetLocation())); } } } </code></pre> <h1>Testclass</h1> <pre><code>class SingleExceptionClauseAnalyzer { void SingleException_ShouldCause_Warning() { try { int x = Int32.Parse("5"); } catch (Exception e) { int x = 8; } } void MultipleExceptions_ShouldNotCause_Warning() { try { int x = Int32.Parse("5"); } catch (FormatException e) { int x = 7; } catch (Exception e) { int x = 8; } } void SingleException_WithFullyQualifiedName_ShouldCause_Warning() { try { int x = Int32.Parse("5"); } catch (System.Exception e) { int x = 8; } } void MultipleExceptions_WithFullyQualifiedName_ShouldNotCause_Warning() { try { int x = Int32.Parse("5"); } catch (System.FormatException e) { int x = 7; } catch (System.Exception e) { int x = 8; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:57:43.173", "Id": "84407", "Score": "0", "body": "The tests that Microsoft have developed for some of their own diagnostic analyzers can be found [here](https://roslyn.codeplex.com/SourceControl/latest#Src/Diagnostics/Test/)." } ]
[ { "body": "<p>I've never coded a diagnostics analyzer, so I don't know if that's a possibility, but I think these:</p>\n\n<pre><code>private const string DiagnosticId = \"SingleGeneralException\";\nprivate const string Description = \"Verifies whether a try-catch block does not contain just a single Exception clause.\";\nprivate const string MessageFormat = \"A catch-all clause has been used.\";\nprivate const string Category = \"Exceptions\";\n</code></pre>\n\n<p>Would be better off defined in a .resx file, so you can localize it - not everyone runs an English IDE, I'd try to have the the messages be shown in the same language as the stack traces.</p>\n\n<hr>\n\n<p>In these declarations:</p>\n\n<pre><code> var clause = node as CatchClauseSyntax;\n var exceptionType = clause.Declaration.Type;\n var identifier = semanticModel.GetSymbolInfo(exceptionType);\n var isGeneralException = identifier.Symbol.Name == typeof(Exception).Name;\n var hasMultipleClauses = clause.Parent.ChildNodes().OfType&lt;CatchClauseSyntax&gt;().ToList().Count &gt; 1;\n</code></pre>\n\n<p>I think the relationships between the variables would be more obvious with some vertical whitespace:</p>\n\n<pre><code> var clause = node as CatchClauseSyntax;\n\n var exceptionType = clause.Declaration.Type;\n var hasMultipleClauses = clause.Parent.ChildNodes()\n .OfType&lt;CatchClauseSyntax&gt;()\n .ToList().Count &gt; 1;\n\n var identifier = semanticModel.GetSymbolInfo(exceptionType);\n var isGeneralException = identifier.Symbol.Name == typeof(Exception).Name;\n</code></pre>\n\n<p>I believe there's a possible execution path where the <code>clause</code> would be <code>null</code> (because of the <code>as</code> cast), in which case the next line would throw an easily avoidable <code>NullReferenceException</code>:</p>\n\n<pre><code> var clause = node as CatchClauseSyntax;\n if (clause == null) return;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-30T19:16:57.083", "Id": "85338", "Score": "3", "body": "Since `CatchClause` is defined as `SyntaxKindsOfInterest`, that conversion should always succeed. Because of that, I would prefer a cast instead of `as`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T01:38:47.223", "Id": "48094", "ParentId": "47400", "Score": "3" } }, { "body": "<p>The above answer mentions it all but missed one thing about the LINQ query mentioned above.</p>\n\n<pre><code> var hasMultipleClauses = clause.Parent.ChildNodes()\n .OfType&lt;CatchClauseSyntax&gt;()\n .ToList().Count &gt; 1;\n</code></pre>\n\n<p>This is trying to access the <code>Count</code> property after enumeration to <code>List</code>, so it is okay to get the result directly from a single <code>Count()</code> enumeration as mentioned below</p>\n\n<pre><code> var hasMultipleClauses = clause.Parent.ChildNodes()\n .OfType&lt;CatchClauseSyntax&gt;()\n .Count() &gt; 1;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-15T19:28:17.627", "Id": "108820", "Score": "0", "body": "Better yet, use .Any() instead of checking the Count() > 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-13T20:44:16.620", "Id": "140203", "Score": "0", "body": "@Bryan `.Any()` is equivalent to `> 0`, not `> 1`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-14T20:52:53.503", "Id": "140458", "Score": "0", "body": "Oops...you are right. Good catch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-23T22:41:03.243", "Id": "236366", "Score": "1", "body": "`.Skip(1).Any()` would be equivalent to `> 1` but would not require iterating over the list." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T03:09:52.267", "Id": "57639", "ParentId": "47400", "Score": "1" } } ]
{ "AcceptedAnswerId": "48094", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:01:33.670", "Id": "47400", "Score": "14", "Tags": [ "c#", "roslyn" ], "Title": "DiagnosticAnalyzer for Roslyn that guards against catch-all exception clauses" }
47400
<p>Written in 100% managed code, the Roslyn project exposes the C# and VB compilers as a service.</p> <blockquote> <p>Historically, the managed compilers we’ve shipped in Visual Studio have been opaque boxes: you provide source files, and they churn those files into output assemblies. Developers haven’t been privy to the intermediate knowledge that the compiler itself generates as part of the compilation process, and yet such rich data is incredibly valuable for building the kinds of higher-level services and tools we’ve come to expect in modern day development environments like Visual Studio.</p> <p>With these compiler rewrites, the Roslyn compilers become services exposed for general consumption, with all of that internal compiler-discovered knowledge made available for developers and their tools to harness. The stages of the compiler for parsing, for doing semantic analysis, for binding, and for IL emitting are all exposed to developers via rich managed APIs.</p> </blockquote> <h1>Useful resources</h1> <ul> <li><p><a href="http://msdn.com/roslyn" rel="nofollow">MSDN: Roslyn platform</a></p></li> <li><p><a href="http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=roslyn" rel="nofollow">MSDN: Roslyn forum</a></p></li> <li><p><a href="http://blogs.msdn.com/b/somasegar/archive/2011/10/19/roslyn-ctp-available-now.aspx" rel="nofollow">MSDN Blogs: Roslyn CTP Now Available</a></p></li> <li><p><a href="http://blogs.msdn.com/b/visualstudio/archive/2011/10/19/introducing-the-microsoft-roslyn-ctp.aspx" rel="nofollow">MSDN Blogs: Introducing the Microsoft “Roslyn” CTP</a></p></li> <li><p><a href="http://channel9.msdn.com/Events/Build/2014/2-577" rel="nofollow">Channel 9: The Future of C# at Build 2014</a></p></li> <li><p><a href="http://en.wikipedia.org/wiki/Microsoft_Roslyn" rel="nofollow">Wikipedia: Roslyn</a></p></li> <li><p><a href="http://source.roslyn.codeplex.com/" rel="nofollow">Codeplex: Roslyn source code</a></p></li> <li><p><a href="http://roslyn.codeplex.com/" rel="nofollow">Codeplex: .NET Compiler Platform ("Roslyn")</a></p></li> </ul> <h1>Tips &amp; Tricks</h1> <ul> <li><p>Use <a href="http://roslyn.codeplex.com/wikipage?title=Syntax%20Visualizer&amp;referringTitle=Home" rel="nofollow">the Syntax Visualizer</a> to easily inspect syntax trees.</p></li> <li><p><a href="http://roslynquoter.azurewebsites.net/" rel="nofollow">The Roslyn Quoter tool</a> can quickly show you the structure of the syntax tree of any given piece of code.</p></li> <li><p><code>Formatter.Format</code> is an easy way to format your syntax nodes. </p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:02:15.073", "Id": "47401", "Score": "0", "Tags": null, "Title": null }
47401
A version of the C# and VB compilers that is written in managed code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:02:15.073", "Id": "47402", "Score": "0", "Tags": null, "Title": null }
47402
<p>In Objective-C, many of the NSString or NSMutableString methods for comparing or manipulating strings require a <em>range</em> argument--that is, an argument of data type <code>NSRange</code> (a struct containing a starting position and a length). This applies outside of NSString (NSArray for example), but NSString is where I see it most frequently.</p> <p>There does exist a convenience function for creating an NSRange struct:</p> <pre><code>NSRange range = NSMakeRange(position, length); </code></pre> <p>But the problem for me happens when I'm manipulating a string. I'll sometimes write a method in which I will make several different manipulations on the string within the same method. And the range I need to cover will be the entire length of the string. It's not acceptable to simply declare an <code>NSRange</code> variable, set it, and use this throughout, because if the length of the string changes, the previously set range will be incorrect.</p> <p>For example, suppose we're working with strings representing file paths. We want to manipulate the string in a few ways to make sure the path looks how we want it to look:</p> <pre><code>- (NSString *)cleanPath:(NSString *)originalPath inRoot:(NSString *)rootPath { NSString *returnPath = [originalPath stringByReplacingOccurrencesOfString:@" " withString:@"" options:NSCaseInsensitiveCompare:NSMakeRange(0,[originalPath length])]; while ([returnPath rangeOfString:@"./"].location != NSNotFound) { returnPath = [returnPath stringByReplacingOccurrencesOfString:@"./" withString:@"/" options:NSCaseInsensitiveCompare:NSMakeRange(0,[returnPath length])]; } if ([returnPath rangeOfString:rootPath options:NSCaseInsensitiveCompare range:NSMakeRange(0,[returnPath length])] != NSNotFound) { return returnPath; } else { return rootPath; } } </code></pre> <p>As you can see, we have three calls to <code>NSMakeRange</code> just to make a range that encompasses the length of the string we're working on. We want to look at the whole range. Giving a range too short will mean we're not looking at every character, and giving a range too long will result in an out of bounds exception. We also can't know what the range will be.</p> <p>We know that the first range will be the longest range, because we're only removing characters.</p> <p>Also, even though the call only shows up in code once in the while loop, it could be called any number of times in actuality, so we can't even preset a range before the loop and use that number every time.</p> <p>The other annoying thing is that <code>NSMakeRange(0,[myString length])</code> doesn't offer a ton of autocomplete help.</p> <p>I also don't want to simply <code>#define</code> a macro that could accidentally have unintended consequences outside of this method.</p> <p>What are my options to clean this up?</p> <hr> <p><em>This is tagged C because even though the code here is Objective-C, NSRange is a C-style struct and NSMakeRange is a C-style function. Any C techniques for cleaning up something like this will definitely apply here.</em></p>
[]
[ { "body": "<p>I see a couple of ways to clean this up.</p>\n\n<p>First of all, you mention not wanting to use <code>#define</code>, but let's not forget about <code>#undef</code>. You could define a macro as the first line of this method and undefine it as the last line of the method.</p>\n\n<p>For example:</p>\n\n<pre><code>- (NSString *)cleanPath:(NSString *)originalPath inRoot:(NSString *)rootPath {\n #define _STRING_RANGE(string) (NSMakeRange(0,[string length]))\n // code\n #undef _STRING_RANGE\n}\n</code></pre>\n\n<p>Now, this macro definition exists only within this method. You don't necessarily save a whole lot of characters, but autocomplete will be a lot nicer, and you don't have to explicitly tell the macro to start at 0 and go to the end...you've predefined that in the macro.</p>\n\n<hr>\n\n<p>You can also just write your own C-Style function. That's all <code>NSMakeRange</code> is after all.</p>\n\n<pre><code>NSRange stringRange(NSString *string) {\n return NSMakeRange(0,[string length]);\n}\n</code></pre>\n\n<hr>\n\n<p>And while defining a function is fine and dandy, now it can be seen by at least everything in the file. This is Objective-C, so we can use <em>blocks</em>. We can create a block within the method, and now the block, much like the <code>#define</code> macro that we <code>#undef</code> exists only within the method:</p>\n\n<pre><code>- (NSString *)cleanPath:(NSString *)originalPath inRoot:(NSString *)rootPath {\n NSRange (^stringRange)(NSString *) = (^NSString *string) {\n return NSMakeRange(0,[string length]);\n }\n // code...\n}\n</code></pre>\n\n<p>Here we've define a block called <code>stringRange</code>, that returns a <code>NSRange</code> and takes a single argument of type <code>NSString *</code>. This is exactly the same as the function we wrote in option two, and it's even called in the exact same way too.</p>\n\n<pre><code>stringRange(myString)\n</code></pre>\n\n<p>There a couple of important differences between a regular C-style function and a block though. Scope and memory.</p>\n\n<p>With this block example, the block's scope is limited only to this method. It also exists in memory on the stack and only until this method returns (or until the end of an <code>@autoreleasepool</code> it was created in, whichever comes first).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:08:46.330", "Id": "47405", "ParentId": "47404", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:08:46.330", "Id": "47404", "Score": "5", "Tags": [ "c", "objective-c" ], "Title": "Cleaning up repeated calls to NSMakeRange()" }
47404
<p>I have code which is matching features within regions. The first thing it does it matches features from one region to an entire database of region features. </p> <p>I have a mapping from query feature index (<code>qfx</code>) into database feature index (<code>ax</code>). A database feature index has associated with it a region id (<code>rid</code>), region feature index (<code>fx</code>), feature score (<code>fs</code>), and feature rank (<code>fk</code>). There is also a flag marking each of those mappings as valid or invalid. </p> <p>The problem is that I want to go from this mapping of query_feature_index-to-database_feature_index (<code>qfx2_ax</code>) into a mapping from region_index-to-feature_match (<code>rid2_fm</code>, <code>rid2_fs</code>, and <code>rid2_fk</code>)</p> <p>I have the following code which does this (cleaned up just a little bit for clarity). On the left hand side is the rough percentage of time each step takes. The bulk of the time seems to be eaten up by appending to the lists in the default dictionaries. </p> <pre><code> 0.0 for qrid in qrid2_nns.iterkeys(): 0.0 (qfx2_ax, _) = qrid2_nns[qrid] 0.0 (qfx2_fs, qfx2_valid) = qrid2_nnfilt[qrid] 0.0 nQKpts = len(qfx2_ax) # Build feature matches 0.0 qfx2_nnax = qfx2_ax[:, 0:K] 0.4 qfx2_rid = ax2_rid[qfx2_nnax] 0.5 qfx2_fx = ax2_fx[qfx2_nnax] 0.2 qfx2_qfx = np.tile(np.arange(nQKpts), (K, 1)).T 0.1 qfx2_k = np.tile(np.arange(K), (nQKpts, 1)) # Pack valid feature matches into an interator 0.4 valid_lists = [qfx2_[qfx2_valid] for qfx2_ in (qfx2_qfx, qfx2_rid, qfx2_fx, qfx2_fs, qfx2_k,)] 0.0 match_iter = izip(*valid_lists) 0.0 rid2_fm = defaultdict(list) 0.0 rid2_fs = defaultdict(list) 0.0 rid2_fk = defaultdict(list) # This creates the mapping I want. Can it go faster? 19.3 for qfx, rid, fx, fs, fk in match_iter: 17.2 rid2_fm[rid].append((qfx, fx)) 17.0 rid2_fs[rid].append(fs) 16.2 rid2_fk[rid].append(fk) </code></pre> <p>My gut feeling is that I could pass over the data twice, first counting the number of entries per region, then allocating lists of that size, and then populating them, but I'm afraid that indexing into python lists might take a comparable amount of time. </p> <p>Then I was thinking I could do it with list comprehensions and build a list of (<code>qfx</code>, <code>fx</code>, <code>fs</code>, and <code>fk</code>), but then I'd have to unpack them, and I'm unsure about how long that will take. </p> <p>It seems to me that I can't get much better than this, but maybe someone out there knows something I don't. Maybe there is a numpy routine I'm unaware of? </p> <p>I'm more looking for guidance and insights than anything else before I start coding up alternatives. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T00:41:47.210", "Id": "83083", "Score": "0", "body": "Considering that this is a code review site, I thinks it's worth mentioning that your code is really hard to read, largely due to naming. The first line has `qrid` and `qrid2_nns`, for example. Further, it's not runnable and thus not testable, and the types of most things are unknown. A short, runnable sample of the overall algorithm is going to do wonders with getting people to come up with alternate strategies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T00:47:03.617", "Id": "83084", "Score": "0", "body": "As a consideration, sorting `match_iter` by `rid` and then grouping it is likely to allow faster methods of creating the lists. Alternatively, consider replacing the three `defaultdict`s with a single one (of tuples of 3 lists) to remove the number of lookups and misses. It's hard to know much more without knowing what `qfx2_[qfx2_valid]` does and returns." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:16:08.287", "Id": "83203", "Score": "0", "body": "@Veedrac, sorting by rid is a great idea. Exactly the kind of thing that I'm looking for. Also, I know the code is hard to read, but its in a pretty deep part of an algorithm, and the names are pretty standardized. as for qfx2_, it is just a temporary numpy array (standing in for each qfx2_qfx, qfx2_rid, qfx2_fx, qfx2_fs, and qfx2_k) which lets me not write out qfx2_qfx[qfx2_valid], qfx2_rid[qfx2_valid] over and over. qfx2_valid is just a numpy array of booleans." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:14:21.677", "Id": "83268", "Score": "0", "body": "My point was more about making it easy for codereview to help than changing the source." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-29T13:57:43.703", "Id": "85112", "Score": "0", "body": "If you are looking for a full answer, consider shortening your snippet to the core issue(s), rename variables to friendly names and omit any details that shouldn't matter in the answer." } ]
[ { "body": "<p>What would you think of</p>\n\n<pre><code>match_iter = izip(*valid_lists)\nrid2 = defaultdict(list)\nfor qfx, rid, fx, fs, fk in match_iter:\n rid2[rid].append(qfx, fx, fs, fk)\n</code></pre>\n\n<p>Seems like that might cut the time in the final loop by almost 50%. The extraction from match_iter doesn't change, so it will take the same amount of time. The append will take about the same amount of time as one of the appends you're already doing. Since two appends will be eliminated, I think the time they're taking will go away.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-04T00:18:42.660", "Id": "48893", "ParentId": "47407", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T22:40:20.020", "Id": "47407", "Score": "3", "Tags": [ "python", "performance", "numpy", "hash-map" ], "Title": "Building a dict/list of lists" }
47407
<p>I've written this email program in Python, and I would like to get some feedback on it. (i.e. closing the server twice after the raw input, etc.)</p> <pre><code>import console import socket import smtplib from getpass import getpass user = raw_input('What is your name? ').title() host_name = socket.gethostname() print '\nThis program is being run by %s on machine name %s' % (user, host_name) # here we collect the login information for the email # we also collect the email provider to automatically change the server email_provider = raw_input('Gmail, AOL, Yahoo! or Comcast? ').title() email_user = raw_input('Type in your full email username. ') # collect the user name email_pwd = getpass('Type in your email password. ') # collect the users password if email_provider in ('Gmail', 'Google'): smtpserver = smtplib.SMTP("smtp.gmail.com",587) if email_provider in ('Aol', 'AOL'): smtpserver = smtplib.SMTP("smtp.aol.com",587) if email_provider in ('Yahoo', 'Yahoo!'): smtpserver = smtplib.SMTP("smtp.mail.yahoo.com",587) if email_provider in ('Comcast'): smtpserver = smtplib.SMTP("smtp.comcast.net",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(email_user, email_pwd) def main(): run_again = 'y' while run_again == 'y': # here we are collecting the Sendto email address # we save the input to a variable named sendto sendto = raw_input('Email address to send message to: ') to = sendto CC = sendto subj = raw_input('Subject: ') header = 'To: ' + to + '\n' + 'From: ' + email_user + '\n' + 'Subject: ' + subj +'\n' print '\nMessage Details:' print (header) assignment = raw_input('Message: ') msg = header + assignment + '\n' smtpserver.sendmail(email_user, to, msg) console.hud_alert('Your message has been sent!', 'success', 2.1) run_again = raw_input('Would you like to send another message? y or n') if run_again == 'n': smtpserver.close() else: smtpserver.close() main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T14:43:21.577", "Id": "413231", "Score": "0", "body": "`if ...: smtpserver.close() else: smtpserver.close()` -> `smtpserver.close()`" } ]
[ { "body": "<ul>\n<li><p>I would suggest putting all the code in main() except for the imports. Then at the bottom, do</p>\n\n<pre><code>if __name__ == '__main__':\n main(sys.argv)\n</code></pre>\n\n<p>The advantage of structuring your file this way is that you can run the python interpreter and import your code and play with it. If you break it up into multiple routines, you can run each routine by itself to be sure it does the right thing. As it is now, if you try to import the file, half the code will be run immediately and then main() gets run unconditionally at the bottom, so you can't control it easily in the python interpreter.</p></li>\n<li><p>To translate email_provider to smtp_server, you could do</p>\n\n<pre><code>host = {'GMAIL': \"smtp.gmail.com\",\n 'GOOGLE': \"smtp.gmail.com\",\n 'AOL': \"smtp.aol.com\",\n 'YAHOO': \"smtp.mail.yahoo.com\",\n 'COMCAST': \"smtp.comcast.net\"}\n\nsmtpserver = smtplib.SMTP(host[email_provider.strip('!').upper()], 587)\n</code></pre></li>\n<li><p>And you might want to handle the case where the user types an unknown email provider.</p>\n\n<pre><code>try:\n smtpserver = smtplib.SMTP(\n host[email_provider.strip('!').upper()], 587)\nexcept KeyError:\n print(\"Unknown email provider '%s'\" % email_provider)\n sys.exit(1)\n</code></pre></li>\n<li><p>Instead of making the user type 'y' to run again every time, you could do something like this:</p>\n\n<pre><code>while True:\n sendto = raw_input(\"Target address (or just hit ENTER to quit) &gt; \")\n if sendto == '':\n sys.exit(0)\n to = CC = sendto\n ...\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T23:43:48.353", "Id": "47414", "ParentId": "47411", "Score": "5" } }, { "body": "<h3>Naming</h3>\n\n<p>You may be using the <code>smtplib</code> library to help you talk to the SMTP server, but the object returned by <code>smtplib.SMTP()</code> is an SMTP <em>client</em>, not a server. When you call methods on that object, you are asking the <em>client</em> to say EHLO, initiate the TLS handshake, etc. Therefore, from a programming point of view, that object should be called <code>smtpclient</code>, not <code>smtpserver</code>.</p>\n\n<h3>Superfluous code</h3>\n\n<p>Prompting for the user's name and printing the machine's own hostname is completely irrelevant to the goal of sending e-mail, and in fact you never again refer to <code>user</code> and <code>host_name</code> after the first <code>print</code> statement.</p>\n\n<p><code>smtpserver.ehlo()</code> calls a method that makes the client initiate the SMTP handshake. However, <code>smtpserver.ehlo</code> a couple of lines further down accomplishes nothing.</p>\n\n<p>The <code>CC</code> variable is never used, and is therefore misleading.</p>\n\n<h3>Overall structure</h3>\n\n<p>Prompting the user for the service provider and connecting to the SMTP server <em>before</em> <code>main()</code> is ever called is weird. By convention, if you have a function named <code>main()</code>, that's the entry point of your program, and the only code that runs outside the <code>main()</code> function is the code that calls it.</p>\n\n<p>Starting the SMTP session on program startup is the wrong thing to do. If the user takes a long time to compose the mail message, then the server will disconnect the client after an inactivity timeout period has elapsed. Then, when the user finally wants to send the message, an <code>smtplib.SMTPServerDisconnected</code> exception will occur. You don't have any exception handling in your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T07:34:35.257", "Id": "47444", "ParentId": "47411", "Score": "3" } } ]
{ "AcceptedAnswerId": "47414", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T23:14:10.350", "Id": "47411", "Score": "7", "Tags": [ "python", "beginner", "python-2.x", "email" ], "Title": "Python Email Program" }
47411
<p>I encountered with the following code in the work. The <code>MyItemCoordinator</code> should receive <code>MyItem</code> objects, process them, add them to <code>MyItemList</code> collection and then pass them to the listeners.</p> <p>My questions are:</p> <ol> <li>When I saw <code>NewMyItem</code> method I thought that <code>MyItemCoordinator</code> is a factory but when I saw <code>NewMyItem</code>'s implementation I found out that it creates, sorts, calling to listeners and it's not <code>static</code>. So <code>MyItemCoordinator</code> is not a factory and <code>NewMyItem</code> method does way more things that it should to do according to its name, right?</li> <li><p>If it's not a factory so why <code>NewMyItem</code> method receives so many params, creates an object, adds to the collection? Why not to do:</p> <p>example:</p> <pre><code>var coordinator = new MyItemCoordinator(); var myItem = new MyItem(...PARAMS..) coordinator.AddMyItemToList(myItem) </code></pre> <p>Inside <code>AddMyItemToList</code> we can sort and call the listeners. This is more clear way to do, isn't it?</p></li> <li><p>So, is this implementation correct? Doesn't it have something wrong?</p> <pre><code>public class MyItemCoordinator { ... public IList&lt;MyItem&gt; MyItemList = new List&lt;MyItem&gt;(); public void NewMyItem(int id, ...15_MORE_PARAMS) { MyItem myItem = new MyItem(id,...ONLY_5_PARAMS_WITHIN_15_ARE_USED); AddMyItemToList(myItem); SortMyItemList(); if (MyItemDetectedHandler != null) MyItemDetectedHandler(this); } public void AddMyItemToList(MyItem myItem) { //makes some checking and adds myItem to MyItemList } ... } </code></pre></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:05:51.050", "Id": "83143", "Score": "2", "body": "`MyItemList` allows direct manipulation of the internal state, bypassing `AddMyItemToList` etc." } ]
[ { "body": "<p>You're right, but you should take this to its logical conclusion. </p>\n\n<ul>\n<li>Creating item belongs to a factory class.</li>\n<li>Tracking a list of items (coordinating?) is another responsibility.</li>\n<li>Handling the new item (or list? Not clear from the code) belongs to a third class.</li>\n</ul>\n\n<p>With this design you can reliability test each component in isolation. Merging these responsibilities into a single class makes testing difficult and blocks alternate implementations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:10:46.850", "Id": "83212", "Score": "0", "body": "I agree that creating item can be moved to a factory class, but as it's implemented here with `NewMyItem` it's wrong. In addition, it's not a factory, right?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T02:39:31.033", "Id": "47428", "ParentId": "47413", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T23:23:16.480", "Id": "47413", "Score": "4", "Tags": [ "c#", "collections", "factory-method" ], "Title": "Does the class have unnecessary and violating Single responsibility principle method?" }
47413
<p>I have an HTTP server class (.hpp &amp; cpp). I am trying to improve reserve data from the socket class because I have <code>s.getline()</code> to get HTTP call. My <code>s.RecvData()</code> gets data line by line in an infinite loop to build HTTP struct.</p> <p>This is my old code:</p> <pre><code>while (1) { line = s.RecvData(); //httpline = s.Getline(); if (line.empty()) break; //find location of tab"\t" int location_tab_char = line.find_first_of(" "); int loacation_End_chars = line.find_first_of("\r\n"); if (loacation_End_chars == 0) { break; } if ("Host:" == line.substr(0, location_tab_char)) { req.hostName_ = line.substr(0, loacation_End_chars); } else if ("Connection:" == line.substr(0, location_tab_char)) { req.conn_ = line.substr(0, loacation_End_chars); } else if ("Accept:" == line.substr(0, location_tab_char)) { req.accept_ = line.substr(0, loacation_End_chars); } else if ("Accept-Language:" == line.substr(0, location_tab_char)) { req.acceptLanguage_ = line.substr(0, loacation_End_chars); } else if ("Accept-Encoding:" == line.substr(0, location_tab_char)) { req.acceptEncoding_ = line.substr(0, loacation_End_chars); } else if ("User-Agent:" == line.substr(0, location_tab_char)) { req.userAgent_ = line.substr(0, loacation_End_chars); } } </code></pre> <p>I just need a way to improve it because getting data from the socket line by line is too much calling. Also, when I pass to struct, I pass this string "Host: 169.254.80.80:8080"</p> <blockquote> <p>"Host: 169.254.80.80:8080\r\nConnection: keep-alive\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,<em>/</em>;q=0.8\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36\r\nAccept-Encoding: gzip,deflate,sdch\r\n Accept-Language: en-US,en;q=0.8,ar;q=0.6 ";</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T09:30:30.570", "Id": "83124", "Score": "0", "body": "You should go for [regular expressions](http://en.cppreference.com/w/cpp/regex) to parse the header. You can check out other HTTP server's source code to see how they implement that. (with regex, I guess)." } ]
[ { "body": "<p>First of all, a few notes about style:</p>\n\n<ul>\n<li>You probably have a typo in <code>loacation_End_chars</code>. I think that you meant <code>location_End_chars</code> instead.</li>\n<li>Also, you should be consistent with <code>location_tab_char</code> and use <a href=\"http://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow\"><code>snake_case</code></a> everywhere without any capital. Therefore, <code>loacation_End_chars</code> should actually be named <code>location_end_chars</code>.</li>\n</ul>\n\n<hr>\n\n<p>Your program may compute <code>line.substr(0, location_tab_char)</code> an awful lot of time if it has to <code>\"User-Agent:\"</code>, which may be extremely inefficient. It is bad generally bad to repeat code when it could be avoided. Here, a solution would be to compute <code>line.substr(0, location_tab_char)</code> and <code>line.substr(0, location_end_char)</code> only once before your conditions:</p>\n\n<pre><code>std::string first = line.substr(0, location_tab_char);\nstd::string second = line.substr(0, location_end_chars);\nif (\"Host:\" == first)\n{\n req.hostName_ = second;\n}\nelse if (\"Connection:\" == first)\n{\n req.conn_ = second;\n}\n// etc...\n</code></pre>\n\n<p>Unfortunately, I have no idea what would be good names for these variables, so I named them <code>first</code> and <code>second</code>, but you should find a relevant and meaninful name for them instead.</p>\n\n<hr>\n\n<p>Another way to simplify your code would be to map directly the strings to the fields of your struct thanks to a <a href=\"http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper\" rel=\"nofollow\"><code>std::reference_wrapper</code></a>:</p>\n\n<pre><code>std::map&lt;std::string, std::reference_wrapper&lt;std::string&gt;&gt; mapping = {\n { \"Host:\", req.hostName_ },\n { \"Connection:\", req.conn_ },\n { \"Accept:\", req.accept_ },\n { \"Accept-Language:\", req.acceptLanguage_ },\n { \"Accept-Encoding:\", req.acceptEncoding_ },\n { \"User-Agent:\", req.userAgent_ }, \n};\n</code></pre>\n\n<p>Then your code would become:</p>\n\n<pre><code>while (true) {\n line = s.RecvData();\n //httpline = s.Getline();\n if (line.empty()) break;\n //find location of tab\"\\t\"\n int location_tab_char = line.find_first_of(\" \");\n int location_end_chars = line.find_first_of(\"\\r\\n\");\n if (location_end_chars == 0)\n {\n break;\n }\n\n auto key = line.substr(0, location_tab_char);\n auto value = line.substr(0, location_end_chars);\n auto it = mapping.find(key);\n if (it != mapping.end())\n {\n it-&gt;second.get() = value;\n }\n}\n</code></pre>\n\n<p>Some additional notes (thanks to @utnapistim comment):</p>\n\n<ul>\n<li><code>std::map::operator[]</code> invokes the default constructor of the value type. However, <code>std::reference_wrapper</code> does not have a default constructor, that's why I used the method <code>at</code> instead (contrary to <code>operator[]</code>, <code>at</code> cannot create an element, that's why we need to check for the existence of the element beforehand with <code>find</code>).</li>\n<li>Of course, you <code>header</code> instance needs to live in a greater scope than the <code>std::map</code> instance, otherwise, trying to access the elements of <code>mapping</code> will trigger undefined behavior.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:38:36.323", "Id": "83128", "Score": "1", "body": "A note about the std::reference_wrapper use: make sure the header you are mapping has a bigger scope than the map (otherwise you end up with UB). Also, the use of std::reference_wrapper in a map imposes that you always check for existence of the value before assignment (as you did - which is non-obvious unless you know the behavior of std::map::operator[])." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:51:04.653", "Id": "83138", "Score": "0", "body": "@utnapistim Yeah, `std::map::operator[]` always crashes with `std::reference_wrapper` since it does not have a default constructor. I will add a note about that, thanks :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T08:31:16.667", "Id": "47446", "ParentId": "47416", "Score": "4" } }, { "body": "<p>Your code can be made smaller and without repeated constructs, by mapping your keys to values in a map:</p>\n\n<pre><code>// #include &lt;map&gt;\n\nstd::map&lt;std::string,std::string&gt; headers;\n\nwhile(true) { // better use true instead of 1\n\n line = s.RecvData();\n\n if (line.empty() || line == \"\\r\\n\\r\\n\")\n break;\n auto key_value_sep = line.find(\":\"); // do not split by space\n\n // you could stop here in case of an exception in the data\n // if(0 == key_value_sep || std::string::npos == key_value_sep)\n // throw std::runtime_error{\"...\"}; // or break, or whatever\n\n // line is a single line; as such, end chars location not needed\n // int loacation_End_chars = line.find_first_of(\"\\r\\n\");\n\n auto key = line.substr(0, key_value_separator);\n\n auto value = line.substr(key_value_separator + 2, // skip \": \"\n line.size() - key.size() - 4); // size less key,\n // separator and\n // \"\\r\\n\"\n // you could break here in case of an exception in the data\n // if (value.empty() || key.empty()) || ...)\n // throw std::runtime_error{\"...\"}; // or break, or whatever\n\n // set header \n headers[key] += value;\n}\n\n// set headers (or use directly from map)\nreq.hostName_ = headers[\"Host\"];\nreq.conn_ = headers[\"Connection\"];\nreq.accept_ = headers[\"Accept\"];\nreq.acceptLanguage_ = headers[\"Accept-Language\"];\nreq.acceptEncoding_ = headers[\"Accept-Encoding\"];\nreq.userAgent_ = headers[\"User-Agent\"];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T09:55:17.737", "Id": "47450", "ParentId": "47416", "Score": "6" } } ]
{ "AcceptedAnswerId": "47450", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T01:09:16.367", "Id": "47416", "Score": "5", "Tags": [ "c++", "strings", "c++11", "http" ], "Title": "Parsing httpline" }
47416
<p>I am working on a very simple game and thought it would be a good opportunity to learn and use the Factory Method pattern for creating game objects. I studied the pattern but I'm a bit confused about the Java implementation so thought I would share what I have come up with and get some opinions. </p> <p>Please keep in mind that I am basing this design on the example from "Design Patterns... by the GOF" so we will use the following pieces: Product, ConcreteProduct, Creator, and ConcreteCreator.</p> <p><strong>Product (Interface for Game Objects)</strong></p> <pre><code>public interface GameObject { public abstract void doSomeStuff(); } </code></pre> <p><strong>ConcreteProducts (Implements Product Interface, 1 for each Game Object)</strong></p> <pre><code>public class PlayerImpl implements GameObject { @Override public void doSomeStuff() { System.out.println("I am a player object!"); } } public class EnemyImpl implements GameObject { @Override public void doSomeStuff() { System.out.println("I am an Enemy, you better run!"); } } </code></pre> <p><strong>Creator (Interface that defines how to create objects)</strong></p> <p>This is the one I'm most confused about, seems un-necessary unless instead of an Interface it was some Abstract class, but even then seems kind of pointless to use a <strong>Creator</strong> in this design pattern?</p> <pre><code> public interface GameObjectFactory { public abstract GameObject createGameObject(GameObjectFactoryImpl.Type type); } </code></pre> <p><strong>ConcreteCreator (Implements Creator, creates objects)</strong></p> <p>The ConcreteCreator will have a nested enumeration to help the client decide which player types are available. We will throw an exception if for some reason there is a game object type in the enumeration that is not handled in the factory method. </p> <pre><code>public class GameObjectFactoryImpl implements GameObjectFactory{ // A helper enum that clients will use to create game objects public enum Type { PLAYER, ENEMY; } public GameObject createGameObject(GameObjectFactoryImpl.Type type) { switch (type) { case PLAYER: return new PlayerImpl(); case ENEMY: return new EnemyImpl(); default: throw new RuntimeException("Unsupported object type!"); } } } </code></pre> <p><strong>Client</strong></p> <pre><code>public class Game { private static GameObjectFactory gameObjectFactory = new GameObjectFactoryImpl(); public static void main(String args[]){ GameObject player = gameObjectFactory.createGameObject(GameObjectFactoryImpl.Type.PLAYER); GameObject enemy = gameObjectFactory.createGameObject(GameObjectFactoryImpl.Type.ENEMY); player.doSomeStuff(); enemy.doSomeStuff(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T12:59:33.947", "Id": "83517", "Score": "0", "body": "What problem does the Factory pattern solve? You need to \"feel\" the pain of the problem a bit before you seek to adding all this complexity of the pattern. Your example shows `new PlayerImpl()` is what actually happens when there's a new player. That's way less code than `gameObjectFactory.createGameObject(GameObjectFactoryImpl.Type.PLAYER);` - ask yourself what are you gaining by adding this. Usually, you want to apply this pattern when the code to create the object is complex (and so it's encapsulated in the factory method). Your example doesn't suffer from the problem this pattern solves." } ]
[ { "body": "<p>This pattern can be difficult to understand outside of an application with many modes of operation. There are two advantages to using the factory patterns: you can swap in different implementations, and you can vary the construction parameters without changing client code.</p>\n\n<p>Where do these advantages shine? Testing! In the case of a game, randomness is a good example. When playing the game for real, you want your monsters to vary their behavior randomly. But when testing, you need to be able to choose from their possible behaviors. The real factory will initialize each monster with a real random number generator, but tests must be able to specify the behavior choices. </p>\n\n<p>Take this example monster action:</p>\n\n<pre><code>public void chooseCombatAction() {\n if (isAfraid()) {\n return Action.RUN;\n }\n else {\n return Action.ATTACK;\n }\n}\n\nprivate boolean isAfraid() {\n return random.nextInt(10) &gt; 7;\n}\n</code></pre>\n\n<p>To test <code>chooseCombatAction</code>, you need to provide a mock random number generator. But if the constructor creates it, you can't. Instead, have the factory provide it, and create an implementation that takes one with pre-configured values. Now you can give that factory to the root game object that uses the factory to create monsters.</p>\n\n<blockquote>\n <p><strong>Style Note:</strong> Drop implied modifiers--such as <code>public</code> and <code>abstract</code> on interface members--wherever possible. Every modifier adds context that must be groked.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T00:28:39.730", "Id": "83310", "Score": "0", "body": "Thanks very much for the review! I know that public abstract will be groked (nice terminology) but there's no performance penalty for keeping them is there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T01:26:03.243", "Id": "83318", "Score": "0", "body": "@Shijima As you know, every in race member is public and either abstract (methods) or final (fields). Reading those modifiers costs a small amount of developer time which happens more often than writing. Omitting them leaves your interfaces crisp and clean IMHO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T13:09:05.790", "Id": "83518", "Score": "0", "body": "Testing is a great context for factory. You might want to edit to say that mocking random allows to generate the numbers that are in [boundary](http://en.wikipedia.org/wiki/Boundary_value_analysis) tests." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T02:18:47.020", "Id": "47425", "ParentId": "47422", "Score": "4" } }, { "body": "<p>The code you present is neat, well structured, etc. (unfortunately it is dangerously close to being off-topic since it is hypothetical code, and it does not work - where does the <code>Type</code> come from in the interface's <code>public abstract GameObject createGameObject(Type type);</code> ? ).</p>\n<p>The neat code is really useful because it makes it easy to home in on the critical deviation you have made from the 'idiomatic' way of doing the Factory pattern in Java.</p>\n<p>This is (often) wrong:</p>\n<blockquote>\n<pre><code>public interface GameObjectFactory { \n public abstract GameObject createGameObject(Type type); \n}\n</code></pre>\n</blockquote>\n<p>Your narrative is closer-to-home: <em>&quot;... seems un-necessary unless instead of an Interface it was some Abstract class&quot;</em></p>\n<p>The factory is often a combination of static methods, and an interface. Sometimes the interface and the static methods are combined on to a single abstract class, and sometimes they are separate. What you are missing is the static methods for creating the Factory instance.</p>\n<p><strong>Note:</strong> many factory-pattern implementations in Java do not use the word Factory in the name....</p>\n<p>So, there are factories that separate the static methods in a different class from the interface, and factories that have the static methods and the interface methods in the same abstract class.</p>\n<h2>Abstract Class way</h2>\n<p>The Abstract class is the most recognizable way of doing this in Java. It is often most easily identified by having static methods like <code>newInstance()</code>. The Abstract class has abstract methods which are the factory methods, but it also has factory-factory methods for creating the factory!!!! (yes, really). The factory-factory methods are normally implemented as static concrete methods. In your example code, the <code>GameObjectFactory</code> and parts of the <code>GameObjectFactoryImpl</code> would be merged as:</p>\n<pre><code>public abstract class GameObjectFactory {\n\n // A helper enum that clients will use to create game objects\n // Note that this enum is declared as part of the 'interface' for the factory,\n // not as part of one of the actual fctory implementations.\n public enum Type {\n PLAYER, ENEMY;\n }\n\n // factory factory method here ('default' factory implementation):\n public static final GameObjectFactory newInstance() {\n // look for an implementation of the factory in some known/default place\n String implName = ....; // default implementation...\n return newInstance(implName);\n }\n\n // factory factory method here ('specific' factory implementation):\n public static final GameObjectFactory newInstance(String specificImpl) {\n // fancy code to create a new instance .... perhaps reflection?\n GameObjectFactory ret = .......\n return ret;\n }\n\n // factory method here....\n public abstract GameObject createGameObject(Type type);\n \n}\n</code></pre>\n<p>The concrete implementation of the Abstract <code>GameObjectFactory</code> is somewhere else (often un-documented).</p>\n<p>Examples of this type of factory pattern are:</p>\n<ul>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html\" rel=\"nofollow noreferrer\">MessageDigest</a>\n<ul>\n<li>static factory-factory methods: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html#getInstance(java.lang.String)\" rel=\"nofollow noreferrer\">getInstance(...)</a></li>\n<li>factory methods (the actual digest): <a href=\"http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html#digest(byte%5B%5D)\" rel=\"nofollow noreferrer\">digest(...)</a></li>\n</ul>\n</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/javax/xml/stream/XMLInputFactory.html\" rel=\"nofollow noreferrer\">StAX XML Streams</a></li>\n</ul>\n<h2>Separate Static class, and interface</h2>\n<p>In this case, there is normally a class with only static methods, and an interface that is returned from these methods. For your code, it would require three classs (the enum would be separate)....</p>\n<pre><code>// A helper enum that clients will use to create game objects\n// Note that this enum is declared as part of the 'interface' for the factory,\n// not as part of one of the actual fctory implementations.\npublic enum Type {\n PLAYER, ENEMY;\n}\n\npublic interface GameObjectFactory {\n // factory method here....\n public GameObject createGameObject(Type type);\n}\n\n\npublic final class GameObjectFactoryFactory {\n\n\n // factory factory method here ('default' factory implementation):\n public static final GameObjectFactory newInstance() {\n // look for an implementation of the factory in some known/default place\n String implName = ....; // default implementation...\n return newInstance(implName);\n }\n\n // factory factory method here ('specific' factory implementation):\n public static final GameObjectFactory newInstance(String specificImpl) {\n // fancy code to create a new instance .... perhaps reflection?\n GameObjectFactory ret = .......\n return ret;\n }\n \n}\n</code></pre>\n<p>Examples of this type of factory are:</p>\n<ul>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html\" rel=\"nofollow noreferrer\">JDBC's DriverManager</a>\n<ul>\n<li>static factory-factory methods: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String)\" rel=\"nofollow noreferrer\">getConnection</a></li>\n</ul>\n</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/javax/management/MBeanServerFactory.html\" rel=\"nofollow noreferrer\">Management Beans</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T00:38:13.827", "Id": "83313", "Score": "0", "body": "Thanks very much for your detailed review. Type worked in my codebase because I had it imported in the .java file. I edited the above code sample to include GameObjectFactoryImpl.Type instead. I'm a bit confused about the factory-factory, why not just hardcode that particular method to return a default type directly, rather than delegating it to an overloaded version? I guess a default return type might not always be ideal, can you provide an example of something that you have seen that makes sense as a default return type of a Factory-Factory method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T00:50:55.243", "Id": "83315", "Score": "0", "body": "SAX XML Parser [newInstance()](http://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/SAXParserFactory.html#newInstance()) is possibly the more complicated factory-factory method..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T03:17:14.607", "Id": "47431", "ParentId": "47422", "Score": "4" } } ]
{ "AcceptedAnswerId": "47431", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T01:48:48.620", "Id": "47422", "Score": "5", "Tags": [ "java", "design-patterns", "factory-method" ], "Title": "Java implementation of the Factory Method pattern" }
47422
<p>I am currently writing a program that allows me to search for files in a user-specified directory. My current code is as follows:</p> <pre><code>if os.path.exists(file_path)!= True: print('\n******* Path does not exist. *******\n') else: while True: aa = '''\nWhich search characteristics would you like to use? \n 1. Search by name: N \n 2. Search by extension: E \n 3. Search by size: S \n Please enter your choice: ''' answer = input(aa).strip() if answer not in 'NnEeSs' or answer=='': print('\n***** Invalid choice. *****') elif answer in 'Nn': while True: try: name = input ('\nEnter file name: ') rr = search_by_name(name, file_path) if not rr: print('\n***** File not found *****\n') else: break except WindowsError: print('\n***** Oops! Access denied.*****\n') continue elif answer in 'Ee': while True: try: ending = input ('\nEnter the file extension: ') rr = search_by_extention(ending, file_path) if not rr: print('\n***** No File(s) found *****\n') else: break except WindowsError: print('\n***** Oops! Access denied. *****\n') continue elif answer in 'Ss': while True: try: size = int(input('\nPlease enter file size: ')) rr = search_by_size(size, file_path) if not rr: print('\n***** No file(s) found *****\n') else: break except ValueError: print('\n***** Enter an numeric value. *****\n') continue except WindowsError: print('\n***** Oops! Access denied. *****\n') continue </code></pre> <p>Each of the search functions returns a list containing the result.</p> <p>The <code>try</code> and <code>except</code> statements are concerning, and I feel they can be improved. </p> <p>In each of these cases, or generally, how can the code be improved, or simplified? </p>
[]
[ { "body": "<p>Overall, you need to look into PEP 8. Other then that, you need to apply a strategy pattern to get rid of redundant <code>if</code>/<code>else</code> loop. See more detailed analysis below.</p>\n\n<h1>Line by line analysis</h1>\n\n<pre><code>if os.path.exists(file_path)!= True:\n</code></pre>\n\n<p>Use <code>if not var</code>.</p>\n\n<pre><code> print('\\n******* Path does not exist. *******\\n') \n</code></pre>\n\n<p>You have too many new lines in your code.</p>\n\n<pre><code>else:\n while True:\n aa = '''\\nWhich search characteristics would you like to use? \\n 1. Search by name: N \\n 2. Search by extension: E \\n 3. Search by size: S\n \\n Please enter your choice: '''\n</code></pre>\n\n<p>Wrap your code in 80 columns. Also, what kind of name is <code>aa</code>? Pick a meaningful name.</p>\n\n<pre><code> answer = input(aa).strip()\n\n if answer not in 'NnEeSs' or answer=='':\n</code></pre>\n\n<p><code>if answer.lower() not in ('n', 'e', 's')</code> is more readable. You don't need to check if it's empty either.</p>\n\n<pre><code> print('\\n***** Invalid choice. *****')\n\n elif answer in 'Nn':\n while True:\n try:\n name = input ('\\nEnter file name: ')\n</code></pre>\n\n<p>No space after <code>input</code>.</p>\n\n<pre><code> rr = search_by_name(name, file_path)\n</code></pre>\n\n<p>Pick a better variable name.</p>\n\n<pre><code> if not rr:\n print('\\n***** File not found *****\\n')\n else:\n break\n\n except WindowsError:\n print('\\n***** Oops! Access denied.*****\\n')\n continue\n</code></pre>\n\n<p>No need for continue here.</p>\n\n<pre><code> elif answer in 'Ee':\n while True:\n try:\n ending = input ('\\nEnter the file extension: ')\n rr = search_by_extention(ending, file_path)\n if not rr:\n print('\\n***** No File(s) found *****\\n')\n else:\n break\n\n except WindowsError:\n print('\\n***** Oops! Access denied. *****\\n')\n continue \n\n elif answer in 'Ss':\n while True:\n try:\n size = int(input('\\nPlease enter file size: '))\n</code></pre>\n\n<p><code>ValueError</code> should be caught here, not down the road. Make your exception catches as narrow as you can.</p>\n\n<pre><code> rr = search_by_size(size, file_path)\n if not rr:\n print('\\n***** No file(s) found *****\\n')\n else:\n break\n\n except ValueError:\n print('\\n***** Enter an numeric value. *****\\n')\n continue\n\n except WindowsError:\n print('\\n***** Oops! Access denied. *****\\n')\n continue\n</code></pre>\n\n<p>The <code>continue</code> statements are redundant here.</p>\n\n<h1>Suggested improvements</h1>\n\n<p>You can use a strategy pattern to get around having all the <code>if</code>/<code>else</code> constructs. You can define <code>OPERATIONS</code> dict, with your operation identifier as keys and <code>(method_to_be_called, message_to_be_displayed)</code> as values.</p>\n\n<pre><code>OPERATIONS = {\n 'n': ('search_by_name', 'Enter the file name'),\n 'e': ('search_by_extension', 'Enter the extension'),\n 's': ('search_by_size', 'Enter the size'),\n }\n\nif not os.path.exists(file_path):\n print('\\n******* Path does not exist. *******\\n')\n return # This way the rest of your code has to be indented less.\nwhile True:\n question = (\n \"\\nWhich search characteristics would you like to use? \"\n \"\\n 1. Search by name: N \"\n \"\\n 2. Search by extension: E \"\n \"\\n 3. Search by size: S \"\n \"\\n Please enter your choice:\"\n )\n answer = input(question).strip().lower()\n if answer not in OPERATIONS:\n print('\\n***** Invalid choice. *****')\n continue\n method, operation_question = OPERATIONS[answer]\n while True:\n value = input(operation_question).strip()\n if answer == 's': # Search by size.\n try:\n value = int(value)\n except ValueError:\n print('\\n***** Enter an numeric value. *****\\n')\n continue\n try:\n # This line gets and executes relevant method from the current\n # module (that is what __import__(__name__) stands for).\n result = getattr(__import__(__name__), method)(value, file_path)\n except WindowsError:\n print('\\n***** Oops! Access denied.*****\\n')\n continue\n if result:\n # Perform actions with a result.\n break\n print('\\n***** File not found *****\\n')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T06:23:38.187", "Id": "47438", "ParentId": "47427", "Score": "1" } }, { "body": "<p>To improve readability I would try and break the code down into more functions and redefine your pre-determined text values as globals, such that you can save space in the actual function. Responses can be represented by a dictionary value with boolean/text key value pairs (or exception/text). Also certain UI options can be stored in a dictionary, with links to their associated functions.</p>\n\n<pre><code># using 3 quotes mean you don't need to specify newlines\ndir_tools_menu = '''\nWhich search characteristics would you like to use?\n1. Search by name: N \n2. Search by extension: E \n3. Search by size: S\n\\tPlease enter your choice: '''\ndir_tools_options = {\"n\":ui_search_by_name, \n \"e\":ui_search_by_extention, \n \"s\":ui_search_by_size}\nerror_response = {WindowsError:\"Oops! Access denied.\", \n ValueError:\"Enter an numeric value.\"}\n# add number of files for true\nfiles_found_response = {False:\"No file(s) found\", \n True:\"{} file(s) found\"}\n# add filename\nfile_found_response = {False:\"File {} not found\",\n True:\"File {} found\"}\nfile_exists_response ={ False:\"Path does not exist.\", \n True:\"Path Found\"}\n# add choice for true\nvalid_ui_response = {False:\"Invalid choice.\", \n True:\"You choose {}.\"}\n</code></pre>\n\n<p>Now that we have a collection of text values lets make a function to standardize print outputs, such that you don't have to write all those stars everywhere, and you can feel assured that they will produce even length lines.</p>\n\n<pre><code>line_length = 40\n# or you can have a funky pattern like \"`-._.-'-._...\nline_pad = \"*\"*line_length \n\ndef my_print(text, *params):\n # len(params) must match the count of \"{}\" in the text so this will not crash\n # Perhaps add a check to assert this case\n message = text.format(*params)\n offset = line_length/2 - len(message)/2\n if offset &gt; 0 and offset + len(message) &lt; line_length:\n print(line_pad[:offset] + message + line_pad[offset+len(message):])\n # in the case that a line is larger than the formatting, you can just print the line.\n # its gonna look gross regardless\n else:\n print(message)\n</code></pre>\n\n<p>Lets also make a simple yes/no function.</p>\n\n<pre><code>yes = (\"yes\", \"y\",\"1\")\nno = (\"no\", \"n\", \"0\")\ndef ask_yes_no(question):\n answer = ''\n while not answer in yes + no:\n answer = input(question).lower()\n if not answer in yes + no:\n my_print(valid_ui_response[False])\n else:\n my_print(valid_ui_response[True], return_to_menu)\n # True - yes, False - no\n return answer in yes\n</code></pre>\n\n<p>Now your main method boils down to..</p>\n\n<pre><code>quit_question = \"Quit Dir Tools? \"\n\ndef dir_tools(file_path):\n if os.path.exists(file_path):\n my_print(file_exists_response[True] )\n else:\n my_print(file_exists_response[False])\n return\n quit_dir_tools = False\n while not quit_dir_tools:\n answer = input(dir_tools_menu).lower()\n if answer not in dir_tools_options:\n my_print(valid_ui_response[False])\n else:\n my_print(valid_ui_response[True],answer)\n dir_tools_options[answer](file_path)\n quit_dir_tools = ask_yes_no(quit_question)\n</code></pre>\n\n<p>Now for the actual important functions.. I'll just do one example to show the try catch responses,..</p>\n\n<pre><code>ui_sbn_question = 'Enter file name: '\nreturn_question = \"Return to main menu? \"\n\ndef ui_search_by_name(file_path):\n return_to_menu = False\n while not return_to_menu:\n name = input(ui_sbn_question)\n try:\n sbn_response = search_by_name(name, file_path)\n if not sbn_response:\n my_print(file_found_response[False], name)\n else:\n my_print(file_found_response[True], name)\n # assuming that this isnt a boolean\n my_print(sbn_response)\n except WindowsError:\n my_print(error_response[WindowsError])\n return_to_menu = ask_yes_no(return_question)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:12:50.387", "Id": "83265", "Score": "0", "body": "http://python.org/dev/peps/pep-0008/" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:40:50.970", "Id": "47497", "ParentId": "47427", "Score": "2" } } ]
{ "AcceptedAnswerId": "47497", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T02:28:26.980", "Id": "47427", "Score": "6", "Tags": [ "python", "exception-handling", "python-3.x", "search" ], "Title": "Searching for files in a specified directory" }
47427
<p>Regular expressions are one of the worst aspects of debugging hell. Since they are contained in string literals, It's hard to comment how they work when the expressions are fairly long.</p> <p>I have the following regular expression:</p> <pre><code>\b\d{3}[-.]?\d{3}[-.]?\d{4}\b </code></pre> <p>Source: <a href="http://www.regexr.com/" rel="nofollow noreferrer">RegExr.com</a></p> <p>I commented it like this:</p> <pre><code>import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String regexStr = ""; regexStr += "\\b"; //Begin match at the word boundary(whitespace boundary) regexStr += "\\d{3}"; //Match three digits regexStr += "[-.]?"; //Optional - Match dash or dot regexStr += "\\d{3}"; //Match three digits regexStr += "[-.]?"; //Optional - Match dash or dot regexStr += "\\d{4}"; //Match four digits regexStr += "\\b"; //End match at the word boundary(whitespace boundary) if (args[0].matches(regexStr)) { System.out.println("Match!"); } else { System.out.println("No match."); } } } </code></pre> <p>What would be the best way to go about commenting regular expressions to make them readable for beginners? Is there a better way than what I have shown?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T03:44:11.243", "Id": "83094", "Score": "2", "body": "What language are you embedding the regexes in? Java? Please tag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T03:48:09.323", "Id": "83095", "Score": "0", "body": "@rolfl Edited! I was hoping for a cross-language solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T03:50:22.543", "Id": "83096", "Score": "1", "body": "While the concept of regular expressions exists in many languages, the syntax varies wildly. A cross-language solution would therefore be hypothetical code, which is off-topic for Code Review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:20:09.723", "Id": "83420", "Score": "1", "body": "Isn't better to comment \"what the regex should match\" and not \"the parts of the regex\"? a tool online could do it for you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:24:38.210", "Id": "83422", "Score": "0", "body": "@Marco An excellent point" } ]
[ { "body": "<p>Whatever you do, <em>don't</em> append strings like that! If you look at the generated bytecode, you'll see that the compiler does exactly what you told it to do:</p>\n\n<pre><code>$ javap -c Main\nCompiled from \"Main.java\"\npublic class Main {\n public Main();\n Code:\n 0: aload_0 \n 1: invokespecial #1 // Method java/lang/Object.\"&lt;init&gt;\":()V\n 4: return \n\n public static void main(java.lang.String[]);\n Code:\n 0: ldc #2 // String \n 2: astore_1 \n 3: new #3 // class java/lang/StringBuilder\n 6: dup \n 7: invokespecial #4 // Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n 10: aload_1 \n 11: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 14: ldc #6 // String \\b\n 16: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 19: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 22: astore_1 \n 23: new #3 // class java/lang/StringBuilder\n 26: dup \n 27: invokespecial #4 // Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n 30: aload_1 \n 31: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 34: ldc #8 // String \\d{3}\n 36: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 39: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 42: astore_1 \n 43: new #3 // class java/lang/StringBuilder\n 46: dup \n 47: invokespecial #4 // Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n 50: aload_1 \n 51: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 54: ldc #9 // String [-.]?\n 56: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 59: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 62: astore_1 \n 63: new #3 // class java/lang/StringBuilder\n 66: dup \n 67: invokespecial #4 // Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n 70: aload_1 \n 71: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 74: ldc #8 // String \\d{3}\n 76: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 79: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 82: astore_1 \n 83: new #3 // class java/lang/StringBuilder\n 86: dup \n 87: invokespecial #4 // Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n 90: aload_1 \n 91: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 94: ldc #9 // String [-.]?\n 96: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 99: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 102: astore_1 \n 103: new #3 // class java/lang/StringBuilder\n 106: dup \n 107: invokespecial #4 // Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n 110: aload_1 \n 111: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 114: ldc #10 // String \\d{4}\n 116: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 119: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 122: astore_1 \n 123: new #3 // class java/lang/StringBuilder\n 126: dup \n 127: invokespecial #4 // Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n 130: aload_1 \n 131: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 134: ldc #6 // String \\b\n 136: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 139: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n 142: astore_1 \n 143: aload_0 \n 144: iconst_0 \n 145: aaload \n 146: aload_1 \n 147: invokevirtual #11 // Method java/lang/String.matches:(Ljava/lang/String;)Z\n 150: ifeq 164\n 153: getstatic #12 // Field java/lang/System.out:Ljava/io/PrintStream;\n 156: ldc #13 // String Match!\n 158: invokevirtual #14 // Method java/io/PrintStream.println:(Ljava/lang/String;)V\n 161: goto 172\n 164: getstatic #12 // Field java/lang/System.out:Ljava/io/PrintStream;\n 167: ldc #15 // String No match.\n 169: invokevirtual #14 // Method java/io/PrintStream.println:(Ljava/lang/String;)V\n 172: return \n}\n</code></pre>\n\n<p>If you change it to concatenate all the string literals in one statement…</p>\n\n<pre><code>public class Main {\n public static void main(String[] args) {\n String regexStr =\n \"\\\\b\" + //Begin match at the word boundary(whitespace boundary)\n \"\\\\d{3}\" + //Match three digits\n \"[-.]?\" + //Optional - Match dash or dot\n \"\\\\d{3}\" + //Match three digits\n \"[-.]?\" + //Optional - Match dash or dot\n \"\\\\d{4}\" + //Match four digits\n \"\\\\b\"; //End match at the word boundary(whitespace boundary)\n\n if (args[0].matches(regexStr)) {\n System.out.println(\"Match!\");\n } else {\n System.out.println(\"No match.\");\n }\n }\n}\n</code></pre>\n\n<p>Then the bytecode is <em>much</em> saner (one literal string at offset 0):</p>\n\n<pre><code>$ javap -c Main\nCompiled from \"Main.java\"\npublic class Main {\n public Main();\n Code:\n 0: aload_0 \n 1: invokespecial #1 // Method java/lang/Object.\"&lt;init&gt;\":()V\n 4: return \n\n public static void main(java.lang.String[]);\n Code:\n 0: ldc #2 // String \\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b\n 2: astore_1 \n 3: aload_0 \n 4: iconst_0 \n 5: aaload \n 6: aload_1 \n 7: invokevirtual #3 // Method java/lang/String.matches:(Ljava/lang/String;)Z\n 10: ifeq 24\n 13: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;\n 16: ldc #5 // String Match!\n 18: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V\n 21: goto 32\n 24: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;\n 27: ldc #7 // String No match.\n 29: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V\n 32: return \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T03:14:59.743", "Id": "84088", "Score": "0", "body": "My issue isn't that you criticised the performance of my methods; that's welcomed feedback. I only commented because I felt that the core of my question wasn't addressed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T03:22:43.020", "Id": "84089", "Score": "0", "body": "That would be addressed in my other answer, which you didn't like. That's OK — people can disagree on aesthetic matters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T03:27:04.537", "Id": "84091", "Score": "0", "body": "(A)People usually put everything in one answer. (B)I didn't know you could post two answers to the same question. (C)Sorry if I've come across as stubborn or annoying, its just that I'm new to this SE." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T17:19:49.553", "Id": "47593", "ParentId": "47432", "Score": "5" } }, { "body": "<p>The regex-native way for commenting is using the <code>/x</code> (free spacing or <a href=\"http://doc.infosnel.nl/ruby_regular_expressions.html\" rel=\"nofollow noreferrer\">extended mode</a>) flag.</p>\n\n<p>In many languages there is support for multiline strings, so your regular expression will look like:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>regex = /\\b # Begin match at the word boundary(whitespace boundary)\n \\d{3} # Match three digits\n [-.]? # Optional - Match dash or dot\n \\d{3} # Match three digits\n [-.]? # Optional - Match dash or dot\n \\d{4} # Match four digits\n \\b # End match at the word boundary(whitespace boundary)\n /x\n</code></pre>\n\n<p>In java, however, there is still no way to do <a href=\"https://stackoverflow.com/questions/878573/java-multiline-string\">this</a>, so you can either comment it as you did, or otherwise carefully construct your string with <code>\\n</code> between each line:</p>\n\n<pre><code>String regex = \"\\\\b # Begin match at the word boundary(whitespace boundary)\\n\" +\n \"\\\\d{3} # Match three digits\\n\" +\n \"[-.]? # Optional - Match dash or dot\\n\" +\n \"\\\\d{3} # Match three digits\\n\" +\n \"[-.]? # Optional - Match dash or dot\\n\" +\n \"\\\\d{4} # Match four digits\\n\" +\n \"\\\\b # End match at the word boundary(whitespace boundary)\";\n\n// Of course, you need to compile with `Pattern.COMMENTS`\nPattern pattern = Pattern.compile(regex, Pattern.COMMENTS);\nif (pattern.matcher(args[0]).matches()) {\n System.out.println(\"Match!\");\n} else {\n System.out.println(\"No match.\");\n}\n</code></pre>\n\n<p>The above has no advantage to your suggestion on how to comment your regex, so I guess it a matter of taste...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T17:26:08.030", "Id": "47594", "ParentId": "47432", "Score": "3" } }, { "body": "<p>I recommend against writing comments on your regular expressions like that, for several reasons.</p>\n\n<ul>\n<li><strong>Readability:</strong> Just the act of splitting up the string makes it harder to read. Compactness is also a virtue. Regular expressions are punctuation-heavy enough to begin with; the extra <code>\"</code> and <code>+</code> symbols make things worse.</li>\n<li><strong>Redundancy:</strong> You're stating the same thing twice on every line. To anyone who understands regular expressions, you've just made the code more verbose.</li>\n<li><p><strong>Lack of insight:</strong> Comments that describe <em>why</em> are more valuable than comments that describe <em>what</em>. A comment like this would be more helpful:</p>\n\n<pre><code>String regexStr =\n \"\\\\b\" +\n \"\\\\d{3}\" + // 3-digit area code\n …\n</code></pre></li>\n</ul>\n\n<p>What would be most beneficial, I think, is just one comment that describes the intention of the entire regular expression, and a self-documenting variable name.</p>\n\n<pre><code>// A 10-digit phone number, optionally delimited into groups of 3, 3, 4 digits\n// by hyphens or dots. We also check for word boundaries before and after.\nPattern phonePattern = Pattern.compile(\"\\\\b\\\\d{3}[-.]?\\\\d{3}[-.]?\\\\d{4}\\\\b\");\n</code></pre>\n\n<p>I think that this comment is at least as informative as your original, without suffering from the disadvantages I mentioned. With that description, even a complete novice to regular expressions should be able to figure out what each part of the regex does.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T02:52:33.820", "Id": "84082", "Score": "1", "body": "I disagree with your \"readability\" argument; splitting up a string makes it easier to assess each of its parts individually when debugging or improving." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:40:26.087", "Id": "47599", "ParentId": "47432", "Score": "0" } }, { "body": "<p>This is a difficult topic to pin down; there will be a lot of opinions, without any clear \"right\" answers. Additionally, a given match might contextually be better-commented in one fashion vs. a different fashion. That said, I will do my best to try and give rationale for making some commenting choices over others.</p>\n\n<p>While I know about embedded regex comments, they tend to make things more confusing, rather than less. Using them causes subtle changes in how whitespace is treated in the regex, and they're visually rather intrusive. Unless you are allowed to pass only a regex around, with no other attendant code or comments, I would avoid using embedded regex comments. The only time I have ever used these is with regexes that were consumed by a client application (I had no other means by which to comment my expressions), and when I had to write some regexes that needed to be carried back and forth between two languages.</p>\n\n<p>Line-by-line commenting in the enclosing language, as in your selection, is the next option. Most programming/scripting environments support breaking strings up onto more than one line and commenting them. This can be somewhat less visually intrusive than directly embedded regex comments, especially given that the regex's whitespace isn't compromised in any way, but there is still additional \"noise\" overhead in terms of extra quotes and joining syntax (such as + signs in C# and Java, and &lt;&lt; in C++). While the underlying strategy is not inherently a bad one, commenting every single atom of the regex is probably too extreme -- try to break the comments down into larger functional groups, and only go atom-by-atom for particularly tricky stuff. There is an inherent downside to the multiline comment scheme, though, and that is not being able to see the whole regex in one piece. What I see happen in practice is that people write the regex in a single place, then come back and re-work it into multiple lines like this as they go through and comment up their finished code. Ironically, the next person tends to wind up putting it all back into one line so they can more readily edit it. :)</p>\n\n<p>I very recently wrote a shell script that did a huge number of complicated regexes. The route that I took was a hybrid -- above my sed commands, I broke down useful matching units and explained them, but the actual pipeline remained in its normal context, as in this example snippet:</p>\n\n<pre><code>#!/bin/bash\n# Rename the files to reflect the class of tests they contain.\n# head -n5 \"$FILE\" - Grab the first five lines of the file, which hold (in order) the values for key length, IV length, text length, AAD length, and tag length for all the test entries contained in that file.\n# ^.* 0x(.?.) 0x(.?.) - Match the two 1-2 digit hex numbers at the end of the lines\n# ibase=16; \\2\\1 - Put the bytes back into big-endian, and strip the 0x (prep for BC)\n# { while read; do echo $REPLY | bc; done; } - Pipe each line to BC one by one, converting the hex values back to decimal\n# :a - Label \"a\"\n# N - Append another line to the buffer\n# $!ba - If this is NOT the last line, branch to A\n# s/\\n/-/g - Replace all the newlines in the processing space with dashes\nmv \"$FILE\" \"$BASEFILE\"`head -n5 \"$FILE\" | sed -re 's/^.* 0x(.?.) 0x(.?.)/ibase=16; \\2\\1/g' | { while read; do echo $REPLY | bc; done; } | sed -re ':a' -e 'N' -e '$!ba' -e 's/\\n/-/g'`.mspd\n</code></pre>\n\n<p>The upside to this is that you get the benefit of comments tied to specific chunks of regex, while also being able to see all the parts of the regex in their full context. The downside, rather obviously, is that when you update the regex in their full context, you then have to update your comment-copy of those parts to match. In practice, however, I found it easier to alter/fix my regexes in the full context, and then fix up the comments in my \"go through and comment up the finished code\" phase, than to try and wrangle with the chopped-up regexes.</p>\n\n<p>As with all workflows, your preferences may vary. At the very least, however, I would recommend you comment larger chunks of your regex at more logical points, like so:</p>\n\n<pre><code>import java.util.regex.Pattern;\n\npublic class Main {\n public static void main(String[] args) {\n String regexStr = \"\";\n\n regexStr = \"\\\\b\" //Begin match at the word boundary(whitespace boundary)\n + \"\\\\d{3}[-.]?\" //Match three digits, then an optional . or - separator (area code)\n + \"\\\\d{3}[-.]?\" //Repeat (three more digits)\n + \"\\\\d{4}\" //Last four digits\n + \"\\\\b\"; //End match at the word boundary(whitespace boundary)\n\n if (args[0].matches(regexStr)) {\n System.out.println(\"Match!\");\n } else {\n System.out.println(\"No match.\");\n }\n }\n}\n</code></pre>\n\n<p>(Note how the \"+\" are aligned with the assignment, making it easy to visually track the span, and also keeping them away from both the regex data and the comments).</p>\n\n<p>Or, using my preferred method:</p>\n\n<pre><code>import java.util.regex.Pattern;\n\npublic class Main {\n public static void main(String[] args) {\n // \\b Begin match at the word boundary\n // \\d{3}[-.]? Match three digits, then an optional . or -\n // Repeat (first one is area code, second is first three digits of the local number)\n // \\d{4} Last four digits of the local number\n // \\b End match at the word boundary\n String regexStr = \"\\\\b\\\\d{3}[-.]?\\\\d{3}[-.]?\\\\d{4}\\\\b\";\n\n if (args[0].matches(regexStr)) {\n System.out.println(\"Match!\");\n } else {\n System.out.println(\"No match.\");\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T02:02:01.713", "Id": "83473", "Score": "1", "body": "Your analysis and advice for Java are excellent! However, I humbly suggest that you post your Bash script as a question for review. ☺" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T02:24:14.907", "Id": "83474", "Score": "0", "body": "Hah -- the full bash script is a nightmare, and I know it. I figured I wasn't going to cheat and tune up this section of it before posting if I was going to go on about \"real world\" usage, though. The script is so incredibly special-case (converting NIST GCM AES test vectors into mspdebug sim scripts), that \"working and commented\" is good enough. I'll put in a note that the Bash script is not a sterling example of how to do things, or clean it up for this post, if you have a suggestion either way. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T04:34:02.833", "Id": "83491", "Score": "2", "body": "@200_success you now can tear up the entirety of that script on [this question](http://codereview.stackexchange.com/questions/47631/), if you so desire." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:02:33.457", "Id": "47602", "ParentId": "47432", "Score": "3" } } ]
{ "AcceptedAnswerId": "47602", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-04-17T03:36:00.017", "Id": "47432", "Score": "2", "Tags": [ "java", "strings", "regex" ], "Title": "Regex to match phone numbers, with comments" }
47432
<p>I just wrote this but I'm not sure if this is good practice. Can someone give me advice as to whether it's good or how I can do better or even it's bad code?</p> <p>The point is that I need a sub List-array-set of the enum. The <code>SubType.ELSE</code> shall have another name in reality (I know that was a bad choice, but it's for pointing it out). </p> <pre><code>public enum ContentType { TITLE("$$title$$",SubType.MAIL), BODY("$$body$$",SubType.MAIL), MESSAGE("$$message$$",SubType.MAIL), EVENTS("$$events$$",SubType.ELSE); private final String replaceWord; private final SubType subType; private ContentType(String replaceWord, SubType subType ) { this.replaceWord = replaceWord; this.subType = subType; } public String getReplaceWord() { return replaceWord; } private SubType getSubType() { return subType; } public static List&lt;ContentType&gt; values(SubType subType) { List&lt;ContentType&gt; subList = new ArrayList&lt;ContentType&gt;(); for (ContentType type : ContentType.values()) { if (type.getSubType() == subType) { subList.add(type); } } return subList; } } enum SubType { MAIL, ELSE; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T23:01:37.507", "Id": "83687", "Score": "0", "body": "I would not complicate the code with hashmap/enummap/etc caches as the answers suggest. It seems [premature optimization](http://programmers.stackexchange.com/a/80092/36726)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T14:59:06.820", "Id": "524446", "Score": "0", "body": "The correct way is to avoid for/while/loops when you have an enum and to use EnumSet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T11:50:35.937", "Id": "524485", "Score": "0", "body": "@BlessedGeek thx for the comment, you can see in mine own answer where I did put the revised code that it was taken in account." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T16:04:32.493", "Id": "524502", "Score": "0", "body": "https://stackoverflow.com/questions/25219219/java-subtype-enums-or-subclass/68579907#68579907" } ]
[ { "body": "<p>I suggest two changes to <code>values(SubType)</code>:</p>\n\n<ul>\n<li>Return a <code>Set</code> instead of a <code>List</code>.</li>\n<li>Prepare all the possible results at class-loading time, so that <code>values(SubType)</code> could be accomplished by a simple lookup. The code is slightly more complicated, but the runtime performance should be better.</li>\n</ul>\n\n\n\n<pre><code>private static final Map&lt;SubType, Set&lt;ContentType&gt;&gt; BY_SUBTYPE;\nstatic {\n BY_SUBTYPE = new HashMap&lt;SubType, Set&lt;ContentType&gt;&gt;();\n for (SubType subType : SubType.values()) {\n BY_SUBTYPE.put(subType, new TreeSet&lt;ContentType&gt;());\n }\n for (ContentType type : ContentType.values()) {\n BY_SUBTYPE.get(type.getSubType()).add(type);\n }\n for (SubType subType : BY_SUBTYPE.keySet()) {\n // Make Set&lt;ContentType&gt; values immutable\n BY_SUBTYPE.put(subType, Collections.unmodifiableSet(BY_SUBTYPE.get(subType)));\n }\n}\n\npublic static Set&lt;ContentType&gt; values(SubType subType) {\n // Returns an unmodifiable view of a SortedSet\n return BY_SUBTYPE.get(subType);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T09:04:26.597", "Id": "83120", "Score": "0", "body": "Thx for the feedback and the suggestions, I'll refactor mine code following your suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T08:41:21.700", "Id": "47448", "ParentId": "47437", "Score": "11" } }, { "body": "<p>I agree mostly with @200_success' answer, though for simplicity and maintainability I do suggest you to use the following, which is only possible in Java 8. It functionally does the same as @200_success' answer.</p>\n\n<p>The code with explanation below:</p>\n\n<pre><code>public enum ContentType {\n TITLE(\"$$title$$\", SubType.MAIL),\n BODY(\"$$body$$\", SubType.MAIL),\n MESSAGE(\"$$message$$\", SubType.MAIL),\n EVENTS(\"$$events$$\", SubType.DEFAULT);\n\n private static final Map&lt;SubType, Set&lt;ContentType&gt;&gt; SETS_BY_SUBTYPE;\n static {\n SETS_BY_SUBTYPE = Arrays.stream(values())\n .collect(Collectors.groupingBy(\n contentType -&gt; contentType.getSubType(),\n Collectors.toSet()\n ));\n }\n\n private final String replaceWord;\n private final SubType subType;\n\n private ContentType(final String replaceWord, final SubType subType) {\n this.replaceWord = replaceWord;\n this.subType = subType;\n }\n\n public String getReplaceWord() {\n return replaceWord;\n }\n\n private SubType getSubType() {\n return subType;\n }\n\n public static Set&lt;ContentType&gt; values(final SubType subType) {\n return SETS_BY_SUBTYPE.get(subType);\n }\n}\n\nenum SubType {\n MAIL,\n DEFAULT;\n}\n</code></pre>\n\n<p>To explain it more precisely, consider only the code that generates the mapping:</p>\n\n<pre><code>SETS_BY_SUBTYPE = Arrays.stream(values())\n .collect(Collectors.groupingBy(\n contentType -&gt; contentType.getSubType(),\n Collectors.toSet()\n ));\n</code></pre>\n\n<p>What it does is:</p>\n\n<ol>\n<li>Obtain a <code>ContentType[]</code>.</li>\n<li>Convert the array to a <code>Stream&lt;ContentType&gt;</code>, this is the starting point of functional programming.</li>\n<li>Collect the stream in a data structure, here we want to have a <code>Map&lt;SubType, Set&lt;ContentType&gt;&gt;</code>.</li>\n<li>The unoverloaded version of <code>Collectors.groupingBy</code> groups elements on a certain property, here it is <code>contentType.getSubType()</code>. The caveat with the default version is that it returns a <code>List&lt;ContentType&gt;</code> whereas we want a <code>Set&lt;ContentType&gt;</code>.</li>\n<li>So we need to supply a <code>downstream</code> argument to the method, which in this case becomes a <code>Collectors.toSet()</code> downstream collector.</li>\n</ol>\n\n<p>Another name suggestion would be to change <code>SubType.ELSE</code> to <code>SubType.DEFAULT</code>, where <em>default</em> semantically means that it does not belong to something else.</p>\n\n<p>Other small remarks are about the horizontal white space, please be consistent there: </p>\n\n<ul>\n<li>Your enum declarations were missing one between the arguments.</li>\n<li>In one method there was too much horizontal whitespace.</li>\n</ul>\n\n<p>I personally value horizontal whitespace and consistent looking code quite a bit as it in my opinion indicates how seriously you are working with your code.</p>\n\n<p>Since the answer of @chillworld included using an <code>EnumMap</code>, which is argubly better, at least for improved performance, we can construct it with the following:</p>\n\n<pre><code>private static final EnumMap&lt;SubType, Set&lt;ContentType&gt;&gt; SETS_BY_SUBTYPE;\nstatic {\n SETS_BY_SUBTYPE = Arrays.stream(values())\n .collect(Collectors.groupingBy(\n ContentType::getSubType,\n () -&gt; new EnumMap&lt;&gt;(SubType.class),\n Collectors.toSet()\n ));\n}\n</code></pre>\n\n<p>Here we explicitely specify an <code>EnumMap</code> over the general <code>Map</code> interface and to obtain it we use the third parameter of <code>Collectors.groupingBy</code>, which is one that takes a <code>mapFactory</code> as argument, which means that you need to provide the map yourself here.</p>\n\n<p>Another difference is that we here use a method reference, <code>ContentType::getSubType</code>, over <code>contentType -&gt; contentType.getSubType()</code> for improved readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:47:33.063", "Id": "83129", "Score": "0", "body": "Thx for the feedback, but I can't do anything with it cause I'm obligatory to use java 6, of course not of free will :D." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:31:22.680", "Id": "47454", "ParentId": "47437", "Score": "10" } }, { "body": "<p>Oke after reading all your suggestions I refactored the code to this :</p>\n\n<pre><code>public enum ContentType {\n\n TITLE(\"$$title$$\"),\n BODY(\"$$body$$\"),\n MESSAGE(\"$$message$$\"),\n EVENTS(\"$$events$$\");\n\n private static final Map&lt;SubType, Set&lt;ContentType&gt;&gt; BY_SUBTYPE;\n\n private final String replaceWord;\n\n static {\n //Get a map with key's all the values of the SubType class.\n BY_SUBTYPE = new EnumMap&lt;SubType, Set&lt;ContentType&gt;&gt;(SubType.class);\n //Fill the key for MAIL.\n BY_SUBTYPE.put(SubType.MAIL, Collections.unmodifiableSet(EnumSet.range(TITLE, MESSAGE)));\n //Fill the key for DEFAULT.\n BY_SUBTYPE.put(SubType.DEFAULT, Collections.unmodifiableSet(EnumSet.of(EVENTS)));\n }\n\n private ContentType(String replaceWord) {\n this.replaceWord = replaceWord;\n }\n\n public static Set&lt;ContentType&gt; values(SubType subType) {\n // Returns an unmodifiable view of a SortedSet\n return BY_SUBTYPE.get(subType);\n }\n\n public String getReplaceWord() {\n return replaceWord;\n }\n\n public enum SubType {\n MAIL,\n DEFAULT;\n }\n\n}\n</code></pre>\n\n<p>Explication :</p>\n\n<p>It started with netbeans suggesting to use the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumMap.html\" rel=\"nofollow\">EnumMap</a>.<br/>\nAfter some reading about <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumMap.html\" rel=\"nofollow\">EnumMap</a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html\" rel=\"nofollow\">EnumSet</a>, I'll come up with this.Don't use that a lot :)<br/></p>\n\n<p><code>BY_SUBTYPE = new EnumMap&lt;SubType, Set&lt;ContentType&gt;&gt;(SubType.class);</code> :<br/>\nWe create an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumMap.html\" rel=\"nofollow\">EnumMap</a> whitch has as keys all the values of SubType.<br/>\nYou can't create more keys and null keys are not allowed.<br/></p>\n\n<p><code>EnumSet.range(TITLE, MESSAGE);</code> :<br/>\nThis gives us a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html\" rel=\"nofollow\">EnumSet</a> witch contains every Enum value from <code>TITLE</code> to <code>MESSAGE</code>.<br/></p>\n\n<p><code>EnumSet.of(EVENTS);</code> <br/>\nThis gives us a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html\" rel=\"nofollow\">EnumSet</a> witch contains only <code>EVENTS</code>.</p>\n\n<p>Refactoring is more difficult then @200_succes his answer, but I don't have to iterate 2 times over the SubType and one time over the ContentType.</p>\n\n<p><b>Edit :</b></p>\n\n<p>I did have to move the subtype to the EnumClass itself, otherwise I couldn't reach it from outside the Enum.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T12:15:23.647", "Id": "83915", "Score": "0", "body": "I advice against using `EnumSet.range(TITLE, MESSAGE);` my experience is that it's just a matter of time before someone (most likely you) change the order of the enums, and then you do not want to use code that depends on a specific enum ordering. Trust me, it has happened before..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T12:28:43.970", "Id": "83917", "Score": "0", "body": "I could use the EnumSet.of(TITLE,BODY,MESSAGE);" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:31:22.843", "Id": "47462", "ParentId": "47437", "Score": "10" } }, { "body": "<p>I was just playing with this and came up with this rather neat (IMHO) solution so I thought I should post.</p>\n\n<p>Essentially, I let the <code>SubType</code> <code>enums</code> hold a <code>Set</code> of the <code>ContentType</code> that link to them. You then do your query on the sub types.</p>\n\n<pre><code>enum SubType {\n MAIL,\n ELSE;\n // This way breaks! We are trying to access the ContentType before it is initialised.\n // Set&lt;ContentType&gt; contentTypes = EnumSet.noneOf(ContentType.class);\n Set&lt;ContentType&gt; contentTypes = new HashSet&lt;&gt;();\n\n public void addContentType(ContentType add) {\n contentTypes.add(add);\n }\n\n public Set&lt;ContentType&gt; getContentTypes() {\n return contentTypes;\n }\n}\n\npublic enum ContentType {\n TITLE(\"$$title$$\", SubType.MAIL),\n BODY(\"$$body$$\", SubType.MAIL),\n MESSAGE(\"$$message$$\", SubType.MAIL),\n EVENTS(\"$$events$$\", SubType.ELSE);\n\n private final String replaceWord;\n private final SubType subType;\n\n private ContentType(String replaceWord, SubType subType) {\n this.replaceWord = replaceWord;\n this.subType = subType;\n subType.addContentType(this);\n }\n\n public String getReplaceWord() {\n return replaceWord;\n }\n\n private SubType getSubType() {\n return subType;\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:19:40.990", "Id": "47495", "ParentId": "47437", "Score": "5" } } ]
{ "AcceptedAnswerId": "47448", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T05:44:58.487", "Id": "47437", "Score": "17", "Tags": [ "java", "enum" ], "Title": "Enum with getting subset" }
47437
<p>I have a few views that all follow the same pattern. They select a primary key from some main table and then a few semicolon seperated strings of captions of related rows over many-to-many relations. All columns that are used in joins are either primary keys or have a manually set index and are of type <code>NUMBER(18)</code>. The columns that hold the captions are either <code>VARCHAR2</code> or - rarely - <code>CLOB</code>. Usually the view will be joined with the main table to select between 1 and 50 rows of the main table.</p> <p>The creation of the semicolon seperated strings is done with the <a href="http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions089.htm#SQLRF30030"><code>listagg</code></a> function from Oracle 11gR2 because my research showed that this is the easiest and also most performant solution. There is just one problem: There could be so many related rows that the <code>listagg</code> function reaches the limit of 4000 chars of its <code>VARCHAR2</code> result. I'm currently solving this by limiting the set that <code>listagg</code> operates on to 50 rows. This is just a random number that I've chosen, it should prevent errors and the users don't care for more than 50 results anyway. But of course, it's still ugly code.</p> <p>If anyone has any ideas how to improve the following code, I'd be very happy. I'm especially interested in improvements that lead to less complexity, more performance or a better solution for the 4000 chars limit.</p> <pre><code>CREATE OR REPLACE VIEW MAILS_RELATED ( MAIL_ID, CUSTOMERS, PROJECTS, [some more columns] ) AS SELECT m.MAIL_ID, cust_list.CUSTOMERS, proj_list.PROJECTS, [some more columns] FROM MAILS m LEFT OUTER JOIN ( SELECT inner.MAIL_ID, LISTAGG(inner.CUSTOMER_NAME, '; ') WITHIN GROUP (ORDER BY inner.CUSTOMER_NAME) AS CUSTOMERS FROM ( SELECT rel.MAIL_ID, cust.CUSTOMER_NAME, ROW_NUMBER() OVER (PARTITION BY rel.MAIL_ID ORDER BY cust.CUST_ID) AS RN FROM CUSTOMERS_MAILS rel INNER JOIN CUSTOMERS cust ON (cust.CUST_ID = rel.CUST_ID) ) inner WHERE inner.RN &lt;= 50 GROUP BY inner.MAIL_ID ) cust_list ON (cust_list.MAIL_ID = m.MAIL_ID) LEFT OUTER JOIN ( SELECT inner.MAIL_ID, LISTAGG(inner.PROJECT_NAME, '; ') WITHIN GROUP (ORDER BY inner.PROJECT_NAME) AS PROJECTS FROM ( SELECT rel.MAIL_ID, proj.PROJECT_NAME, ROW_NUMBER() OVER (PARTITION BY rel.MAIL_ID ORDER BY proj.PROJ_ID) AS RN FROM PROJECTS_MAILS rel INNER JOIN PROJECTS proj ON (proj.PROJ_ID = rel.PROJ_ID) ) inner WHERE inner.RN &lt;= 50 GROUP BY inner.MAIL_ID ) proj_list ON (proj_list.MAIL_ID = m.MAIL_ID) LEFT OUTER JOIN [some more joins] </code></pre>
[]
[ { "body": "<p>Oracle regular Character types are limited to 4000 bytes. Really, Oracle should find a way to extend that, but until they do, using CLOB is the only real option.</p>\n\n<p>On the other hand, Oracle has a rich infrastructure available for creating user defined functions. You are already creating the view, you may as well extend that to include the function.</p>\n\n<p>There are a number of articles out there that can help:</p>\n\n<ul>\n<li><a href=\"http://www.oracle-base.com/articles/misc/string-aggregation-techniques.php\" rel=\"nofollow\">http://www.oracle-base.com/articles/misc/string-aggregation-techniques.php</a></li>\n<li><a href=\"http://www.oracle-developer.net/display.php?id=306\" rel=\"nofollow\">http://www.oracle-developer.net/display.php?id=306</a></li>\n<li>and others....</li>\n</ul>\n\n<p>The one that is missing from those is the use of XML functions.... It is a relatively commonly used 'hack', to use the XML-processing functions in Oracle (and other databases) to reformat the data in a more convenient way, and then to extract from that XML just the parts you want.</p>\n\n<p>So, ideally you should create a user-defined function for your problem, but, you can accomplish the same thing, perhaps faster, with a hack of XML....</p>\n\n<p>Consider swapping the nested select:</p>\n\n<blockquote>\n<pre><code> SELECT inner.MAIL_ID,\n LISTAGG(inner.CUSTOMER_NAME, '; ')\n WITHIN GROUP (ORDER BY inner.CUSTOMER_NAME) AS CUSTOMERS\n FROM (\n SELECT rel.MAIL_ID,\n cust.CUSTOMER_NAME,\n ROW_NUMBER() OVER\n (PARTITION BY rel.MAIL_ID ORDER BY cust.CUST_ID) AS RN\n FROM CUSTOMERS_MAILS rel INNER JOIN\n CUSTOMERS cust ON (cust.CUST_ID = rel.CUST_ID)\n ) inner\n WHERE inner.RN &lt;= 50\n GROUP BY inner.MAIL_ID\n</code></pre>\n</blockquote>\n\n<p>with:</p>\n\n<pre><code>Select CM.MAIL_ID,\n substr(xmlcast(\n xmlagg(\n xmlelement(E, '; ' || C.CUSTOMER_NAME)\n ORDER BY C.CUSTOMER_NAME\n ) AS CLOB -- or AS VARCHAR2(4000)\n ), 3\n) as CUSTOMERS\nfrom CUSTOMERS C, CUSTOMER_MAIL CM\nwhere C.CUST_ID = CM.CUST_ID\ngroup by CM.MAIL_ID\n</code></pre>\n\n<p>I have put together <a href=\"http://sqlfiddle.com/#!4/af5bf/2/0\" rel=\"nofollow\">a simple SQLFiddle</a> that shows this select in action. It assumes two sets of users, (some male names, some female names), and it puts the different users in to different MAIL_ID's.</p>\n\n<p>Once you have swapped out these nested statements, it will significantly shorten your query.... Your handling code though will have to change. Getting a CLOB back from the view is a big change.... and it is best to handle that in a different way....</p>\n\n<p><strong>Edit: About this operation as a general problem</strong></p>\n\n<p>At an academic level, the problem you are experiencing is because you are doing a non-relational operation in a relational database. Data in a relational database is treated using set arithmetic. You have sets of data that you can intersect, union, filter, and otherwise manipulate. The problem you are tying to solve in this question is the conversion of a set of values in to a single merged value (with internal consistency requirements). This type of operation is not well defined in set theory.</p>\n\n<p>The standard/recommended mechanism for solving this problem is to export the data set in to an external application, and process the data from there. Any system you use in an SQL query to remove the set-like nature of the data is a 'hack', and that is why you are unsatisfied with the result you are seeing. The right solution is to not use SQL.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T11:19:20.933", "Id": "87079", "Score": "0", "body": "Thanks for your suggestion. But in my opinion, while this is shorter, it's way harder to understand if you'r not familiar with that hack. I prefer self speaking code above short code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T11:21:04.440", "Id": "87080", "Score": "0", "body": "@cremor - I agree, which is why I suggested the UDF as well. Also, this works, which is more than what you have (and it's only shorter because it is not doing the 50-at-a-time system)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T11:32:21.393", "Id": "87086", "Score": "0", "body": "Maybe I should have made it clearer that I'm fine with a result that is limited to 4000 chars (or near it). A solution with UDFs will indeed make the view easier to read, but then again I'll need length checking code in my custom type. I'll need to test how this affects performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-14T11:49:01.243", "Id": "87493", "Score": "0", "body": "The performance with user defined aggregate functions is good for a single row. But when I select my whole view (430,000 rows) it's very bad. Tkprof shows an increase of CPU time from 12 to 72 seconds and of elapsed time from 18 to 76 seconds. Selecting the whole view is not a real use case, but at least selecting 5000 rows needs to be at the same speed, which it isn't (6/16 CPU/elapsed seconds vs. 38/46). I gave you the bounty since the code is indeed quite nice with that solution (although the user defined aggregate functions itself aren't very nice), but I'll leave the question open." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-14T12:00:15.940", "Id": "87496", "Score": "0", "body": "@cremor - edited my answer to include a section on why SQL is not the right tool." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-14T12:27:44.463", "Id": "87498", "Score": "0", "body": "But aren't aggregations set operations? At least they are in the SQL standard, so SQL can't be *that* wrong for it, can it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-14T12:40:31.753", "Id": "87501", "Score": "0", "body": "@cremor But you are not manipulating the whole set, you are trying to aggregate just a small part of a set, based on criteria that are not part of set-theory (the length of each value in the set, up to a limit of 4000 bytes, where this has to be calculated before the aggregation happens) In other words you are trying to aggregate a small part of a set, using conditions that are not known until the set is part-built" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-11T02:52:26.453", "Id": "49448", "ParentId": "47441", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T07:00:31.513", "Id": "47441", "Score": "5", "Tags": [ "sql", "oracle" ], "Title": "Length limited listagg for muliple m:n relations in a view" }
47441
<p>If you have a Gmail ID, then you can also receive emails on the same account even if you add extra dots in the username or add '+' and some characters. </p> <p>Say your Gmail ID is montypython@gmail.com. You will receive emails on same account even if it is sent to:</p> <ul> <li>monty.python@gmail.com</li> <li>montypython+python@gmail.com</li> <li>m.o.nty.p.y.t.hon@gmail.com</li> </ul> <p>Following is the code, which gives me back username removing dots and characters after '+' symbol. Do note that I really don't care if user enters an invalid Gmail ID. </p> <pre><code>import re def return_gmail_user(email): username = email.split('@')[0] domain = email.split('@')[1] valid_email_char = '[\w\d\.]+' # check if email is of gmail if domain != 'gmail.com': return False # get username m = re.match(valid_email_char, username) if m: username = m.group(0) #print username return "".join(username.split('.')) return False def main(): assert('my' == return_gmail_user('my@gmail.com')) assert('my' == return_gmail_user('m.y@gmail.com')) assert('avinassh' != return_gmail_user('avinassh@reddit.com')) assert('avinassh' == return_gmail_user('avinassh+reddit@gmail.com')) assert('avinassh' == return_gmail_user('av.ina.s.sh@gmail.com')) assert('avinassh' == return_gmail_user('avi.na.ss.h+reddit@gmail.com')) assert('avinassh' == return_gmail_user('avi.na.ssh+red+dit@gmail.com')) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T01:29:12.547", "Id": "84402", "Score": "0", "body": "Note that `gmail.com` is not the only domain used for Google's mail service; `googlemail.com` works as well." } ]
[ { "body": "<pre><code>def return_gmail_user(email):\n</code></pre>\n\n<p><code>Return</code> isn't a very descriptive word to use as the beginning of a function name. Call it <code>parse_gmail_user</code> or something along those lines instead.</p>\n\n<pre><code> username = email.split('@')[0]\n domain = email.split('@')[1]\n</code></pre>\n\n<p>Read up about <a href=\"https://docs.python.org/3.4/tutorial/datastructures.html#tuples-and-sequences\"><strong>sequence unpacking</strong></a>. There's no need to use indices directly, just assign the result of the split operation directly to both variables.</p>\n\n<pre><code> valid_email_char = '[\\w\\d\\.]+'\n # check if email is of gmail\n if domain != 'gmail.com':\n</code></pre>\n\n<p>The comment is redundant, it adds nothing to the code — remove it.</p>\n\n<pre><code> return False\n</code></pre>\n\n<p>It would be more Pythonic to raise an exception instead of returning <code>False</code>.</p>\n\n<pre><code> # get username\n m = re.match(valid_email_char, username) \n</code></pre>\n\n<p>Give <code>m</code> a descriptive name, such as <code>valid_user</code>, making the code more fluent.</p>\n\n<pre><code> if m:\n</code></pre>\n\n<p>You could combine the two <code>if</code> statements to fail early if an incorrect value is given for <code>email</code>.</p>\n\n<pre><code> username = m.group(0)\n</code></pre>\n\n<p><code>group</code> retrieves the first group by default, no need to supply <code>0</code>.</p>\n\n<pre><code> #print username\n</code></pre>\n\n<p>This comment is probably a remnant from testing; commented-out code should be removed immediately as it adds clutter and serves only to confuse.</p>\n\n<pre><code> return \"\".join(username.split('.'))\n</code></pre>\n\n<p><code>replace('.', '')</code> would be a more descriptive option of achieving the above.</p>\n\n<pre><code> return False\n</code></pre>\n\n<hr>\n\n<p>Following my suggestions, you could arrive the below solution.\nNote that the semantics are insignificantly different (the match is performed regardless of the validity of the domain), but readability and simplicity is substantially better.</p>\n\n<pre><code>def return_gmail_user(email):\n user, domain = email.split('@')\n valid_user = re.match('[\\w\\d\\.]+', user)\n if domain != 'gmail.com' or not valid_user:\n raise ValueError('invalid gmail address: ' + email)\n return valid_user.group().replace('.', '')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T10:48:33.820", "Id": "83617", "Score": "0", "body": "Thanks a lot! So much clean code. Will implement all of your suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:10:47.717", "Id": "47458", "ParentId": "47451", "Score": "8" } } ]
{ "AcceptedAnswerId": "47458", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:00:14.500", "Id": "47451", "Score": "5", "Tags": [ "python", "email" ], "Title": "Giving actual username from Gmail ID" }
47451
<p>I am running this query and it takes several minutes to complete. How can I tune it (unfortunately I don't have the privileges to run an SQL tuning advisor)?</p> <pre><code>select 'Master' || d.ntt_id || '_' || d.deal_nummas, p.prof_currency, sum(p.prof_ts1), sum(p.prof_ts2), sum(p.prof_ts3), sum(p.prof_ts4), sum(p.prof_ts5), sum(p.prof_ts6), sum(p.prof_ts7), sum(p.prof_ts8), sum(p.prof_ts9), sum(p.prof_ts10), sum(p.prof_ts11), sum(p.prof_ts12), sum(p.prof_ts13), sum(p.prof_ts14), sum(p.prof_ts15), sum(p.prof_ts16), sum(p.prof_ts17), sum(p.prof_ts18), sum(p.prof_ts19), sum(p.prof_ts20), sum(p.prof_ts21), sum(p.prof_ts22), sum(p.prof_ts23), sum(p.prof_ts24), sum(p.prof_ts25), sum(p.prof_ts26), sum(p.prof_ts27), sum(p.prof_ts28), sum(p.prof_ts29), sum(p.prof_ts30), sum(p.prof_ts31), sum(p.prof_ts32), sum(p.prof_ts33), sum(p.prof_ts34), sum(p.prof_ts35), sum(p.prof_ts36), sum(p.prof_ts37), sum(p.prof_ts38), sum(p.prof_ts39), sum(p.prof_ts40), sum(p.prof_ts41), sum(p.prof_ts42), sum(p.prof_ts43), sum(p.prof_ts44), sum(p.prof_ts45), sum(p.prof_ts46), sum(p.prof_ts47), sum(p.prof_ts48), sum(p.prof_ts49), sum(p.prof_ts50), sum(p.prof_ts51), sum(p.prof_ts52), sum(p.prof_ts53), sum(p.prof_ts54), sum(p.prof_ts55), sum(p.prof_ts56), sum(p.prof_ts57) from profiles p join deals d on d.deal_id = p.deal_id and d.deal_scope='Y' join runs r on r.deal_cnt_id = d.deal_cnt_id where r.run_id=7 and d.deal_nummas!=0 and d.deal_nummas is not null group by d.ntt_id, d.deal_nummas, p.prof_currency; </code></pre> <p>Some explanation on what I am doing:</p> <p>I want to compute the sum on each timestep of a deal's profile, with deals being grouped by the node they belong to (identified by their <code>deal_nummas</code>). I only take into account deals which are in scope, and in the specified run.</p> <p>The execution plan:</p> <pre><code>SELECT STATEMENT 3540470 |_ HASH GROUP BY 3540470 |_ HASH JOIN 2957025 | |_ Access Predicates | | |_ D.DEAL_ID = P.DEAL_ID | |_ HASH JOIN 624679 | |_ Access Predicates | | |_ R.DEAL_CNT_ID = D.DEAL_CNT_ID | |_ TABLE ACCESS RUNS BY INDEX ROWID 1 | | |_ INDEX PK_RUN_ID UNIQUE SCAN 0 | | |_ Access Predicates | | |_ R.RUN_ID = 7 | |_ TABLE ACCESS DEALS FULL 624091 | |_ Filter Predicates | |_ AND | |_ D.DEAL_SCOPE = 'Y' | |_ TO_NUMBER(D.DEAL_NUMMAS) &lt;&gt; 0 | |_ D.DEAL_NUMMAS IS NOT NULL |_ TABLE ACCESS PROFILES FULL 922142 </code></pre> <p>The table profiles stores what we could call curves, each with an identifier and 57 points (y-axis values), the columns being the x-axis values.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:15:45.340", "Id": "83147", "Score": "2", "body": "Could you tell us more about what the `profiles` table is for? I really have to question the sanity of a schema with so many columns." } ]
[ { "body": "<p>I'll echo what 200_success said about the schema. But working with what you have, I would think breaking it down into two steps (via temp table if this is a one-time aggregation, or via a view if repeat query) may improve performance. Then just perform your <code>SUM()</code> operations on the temp table/view. Preferably though, I would think a better organized schema would be more useful, but this may not be an option in your situation. I would also use a more explicit <code>JOIN</code> to reduce the amount of guessing the SQL engine has to do. I'm less familiar with what seems to be Oracle syntax but here is my take on it based on SQL Server syntax. Anyone else feel free to correct any Oracle-related syntax errors I make. </p>\n\n<pre><code>-- Create temp table, leaving out group by clause\nselect || d.ntt_id || '_' || d.deal_nummas, p.*\nINTO #tmp_nummas\nfrom profiles p \ninner join deals d on d.deal_id = p.deal_id and d.deal_scope='Y' \ninner join runs r on r.deal_cnt_id = d.deal_cnt_id \nwhere r.run_id=7 and d.deal_nummas!=0 and d.deal_nummas is not null;\n\n-- Perform operation\nselect 'Master' ntt_id || '_' || deal_nummas, prof_currency\nsum(prof_ts1), sum(prof_ts2), sum(prof_ts3), sum(prof_ts4), sum(prof_ts5), \nsum(prof_ts6), sum(prof_ts7), sum(prof_ts8), sum(prof_ts9), sum(prof_ts10), \nsum(prof_ts11), sum(prof_ts12), sum(prof_ts13), sum(prof_ts14), sum(prof_ts15), \nsum(prof_ts16), sum(prof_ts17), sum(prof_ts18), sum(prof_ts19), sum(prof_ts20), \nsum(prof_ts21), sum(prof_ts22), sum(prof_ts23), sum(prof_ts24), sum(prof_ts25), \nsum(prof_ts26), sum(prof_ts27), sum(prof_ts28), sum(prof_ts29), sum(prof_ts30), \nsum(prof_ts31), sum(prof_ts32), sum(prof_ts33), sum(prof_ts34), sum(prof_ts35), \nsum(prof_ts36), sum(prof_ts37), sum(prof_ts38), sum(prof_ts39), sum(prof_ts40), \nsum(prof_ts41), sum(prof_ts42), sum(prof_ts43), sum(prof_ts44), sum(prof_ts45), \nsum(prof_ts46), sum(prof_ts47), sum(prof_ts48), sum(prof_ts49), sum(prof_ts50), \nsum(prof_ts51), sum(prof_ts52), sum(prof_ts53), sum(prof_ts54), sum(prof_ts55), \nsum(prof_ts56), sum(prof_ts57) \nfrom #tmp_nummas\ngroup by ntt_id, deal_nummas, prof_currency;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-21T09:28:24.547", "Id": "88547", "Score": "0", "body": "Why would using a a temp table or view improve performance?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-21T22:19:38.903", "Id": "88656", "Score": "0", "body": "I would think at the very least performing the aggregate functions on an isolated data set would free up the tables from locks while the long sum and group operations are done. Also I would think if this were a view then the view and operation could be refreshed as the business need called for it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-21T22:23:52.643", "Id": "88658", "Score": "0", "body": "I doubt it. Writing a row to a temporary table would probably be a lot more work than adding a number in memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-21T22:25:58.410", "Id": "88659", "Score": "0", "body": "Possible. How would you approach it yourself? Would be curious to see your answer (other than scrapping it lol). There might be a way to make the data set more useful by pivoting it or something like that, but hard to say without seeing it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-20T16:49:20.833", "Id": "51229", "ParentId": "47453", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:30:01.213", "Id": "47453", "Score": "5", "Tags": [ "sql", "oracle" ], "Title": "Tuning a query for performance" }
47453
<p>I have a Symfony2 project. I have an Entity <code>Asset</code> which can have relations with <code>Category</code>. I store a <code>categoryCount</code>-field within the <code>Asset</code> to determine if an asset has one, to select those fast via a DQL-query depending on the current user state.</p> <p>Now found myself writing something along the lines of this in my <code>AssetRepository</code>:</p> <pre><code>/** * @param string $orderBy * @param int $mode * * @return \Doctrine\ORM\Query */ public function getQueryForAll($orderBy = 'DESC', $mode = self::FILTER_WITHOUT_QUARANTINED) { $qb = $this-&gt;createQueryBuilder('asset'); $qb-&gt;orderBy('asset.updatedAt', $orderBy); $filter = $this-&gt;getQuarantinedCriteria($mode); if ($filter) { $qb-&gt;addCriteria($filter); } return $query = $qb-&gt;getQuery(); } /** * @param int $mode * * @return Criteria|null */ protected function getQuarantinedCriteria($mode = self::FILTER_WITHOUT_QUARANTINED) { $filter = null; if ($mode === self::FILTER_WITHOUT_QUARANTINED) { $filter = Criteria::create() -&gt;andWhere(Criteria::expr()-&gt;gt('categoryCount', 0)); } else if ($mode === self::FILTER_ONLY_QURANTINED) { $filter = Criteria::create() -&gt;andWhere(Criteria::expr()-&gt;eq('categoryCount', 0)); } return $filter; } </code></pre> <p>This doesn't <em>feel</em> right to me. The <code>$mode</code> flag triggers my code smell alarm, I also am worrying about passing it into each asset querying method.</p> <p>Furthermore, since I will have to set the mode depending on the state of the current logged in user, I also am worried that I will produce code duplications by doing a lot of if-user-has-the-rights-checks in my actions or services:</p> <pre><code>/** * @Route("/all_assets/{page}", * name="get_paginated_assets", * requirements={"page" = "\d+"}, * defaults={"page" = "1"}, * options={"expose"=true} * ) */ public function getPaginatedAssetActions($page) { $repo = $this-&gt;getAssetRepository(); $isAllowedToViewRestrictedAssets = $this-&gt;getCurrentUser()-&gt;isAdmin(); if ($isAllowedToViewRestrictedAssets) { $mode = Entity\AssetRepository::FILTER_SHOW_ALL; } $query = $repo-&gt;getQueryForAll($mode); $pagerfanta = new Pagerfanta(new DoctrineORMAdapter($query)); $data = $this-&gt;getCurrentPagedResults($pagerfanta, $page); $view = $this-&gt;view(); $view-&gt;setFormat('json'); $view-&gt;setData($data); return $view; } </code></pre> <p>Is this the right way to implement the logic to enable filters in a Repository? Feedback on whether there is a more decoupled way would be highly appreciated.</p>
[]
[ { "body": "<p>You can try to use <a href=\"https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Query/Filter/SQLFilter.php\" rel=\"nofollow noreferrer\">SQLFilter</a> for this purpose. It allows you to tune SQL query based on some logic. You can pass information about your user's state into filter through DI container and use this information to tune your SQL query. Please note that unlike repositories - SQLFilter works on SQL level, not on DQL. More information can be found into Doctrine's <a href=\"http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/filters.html\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-21T21:14:03.887", "Id": "163902", "ParentId": "47455", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T10:46:31.663", "Id": "47455", "Score": "5", "Tags": [ "php", "php5", "doctrine" ], "Title": "Filtering queries based on the current user state" }
47455
<p>How can I shorten this (working) code to create future dates in ruby for use as params in URLs?</p> <p>I'm doing:</p> <pre><code>require 'cgi' require 'time' now=Time.new() now_year=now.strftime('%Y').to_i now_month=now.strftime('%m').to_i now_day=now.strftime('%d').to_i now_hour=now.strftime('%H').to_i start_hour=(now_hour + 1) end_hour=(now_hour + 2) start_datetime=Time.new(now_year, now_month, now_day, start_hour) end_datetime=Time.new(now_year, now_month, now_day, end_hour) starts=CGI.escape(start_datetime.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ")) ends=CGI.escape(end_datetime.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ")) </code></pre> <p>and it works, but it seems long and clumsy. Is there an easier way?</p>
[]
[ { "body": "<p>You can <a href=\"http://www.ruby-doc.org/core-2.1.1/Time.html#method-i-2B\" rel=\"noreferrer\">add seconds directly to a <code>Time</code> object</a>, so you could do:</p>\n\n<pre><code>now = Time.now.utc\nstarts = now + 3600 # Add 1 hour's worth of seconds (60 * 60)\nends = now + 7200 # Add 2 hours\n</code></pre>\n\n<p>and then do the <code>strftime</code>-formatting.</p>\n\n<p>Of course, since you need to do this twice, I'd suggest adding a method to avoid the repetition, i.e.:</p>\n\n<pre><code>def offset_utc_timestamp(offset, format = \"%Y-%m-%dT%H:%M:%S.%3NZ\")\n time = Time.now.utc + offset\n time.strftime(format)\nend\n</code></pre>\n\n<p>You may want to split it up differently (i.e. have the method just return a <code>Time</code> object, which you make into a string elsewhere; or have the method also do the URL escaping).</p>\n\n<p>I'd also recommend using the <a href=\"http://www.ruby-doc.org/stdlib-2.1.1/libdoc/uri/rdoc/URI/Escape.html#method-i-escape\" rel=\"noreferrer\"><code>URI.escape</code> method</a> instead, if this is intended for URLs</p>\n\n<p>With all that your code becomes:</p>\n\n<pre><code>starts = URI.escape(offset_utc_timestamp(3600))\nends = URI.escape(offset_utc_timestamp(7200))\n</code></pre>\n\n<p>Alternatively, the <a href=\"https://github.com/rails/rails/tree/master/activesupport\" rel=\"noreferrer\">ActiveSupport gem</a> has a ton of helpful time stuff, letting you do things like <code>2.hours.from_now.utc</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:31:12.643", "Id": "83166", "Score": "0", "body": "Looks good. btw I had tried using the URI.escape but it didn't code things correctly for me (or at all) so I switched to CGI.escape at the suggestion of a colleague" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:43:46.730", "Id": "83172", "Score": "0", "body": "@MichaelDurrant Gotcha. I am curious, though, how these URLs should end up looking; there shouldn't really be anything that needs escaping, really. Also, you can pass a regexp or string to `URI.escape` (see docs), telling it what should be forcibly escaped. With your input, `URI.escape(string, \":\")` will produce the exact same output as `CGI.escape(string)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:55:03.177", "Id": "83179", "Score": "0", "body": "I should have been more specific, I need it to end up with characters like \":\" as `%3A` as I am trying to just replicate what a current param is in our system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:02:06.960", "Id": "83182", "Score": "0", "body": "@MichaelDurrant Ah, ok. Well, it's totally up you. I'd probably end up sticking with `CGI.escape` as well, since it does what you want by default. As mentioned, you can use `URI.escape` too, if you provide the 2nd argument, but it's more work." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:16:53.747", "Id": "47460", "ParentId": "47456", "Score": "7" } }, { "body": "<p>Once you start storing some strings in percent-encoded form, you have the added burden of keeping track of which strings are encoded, and which strings aren't.<sup>1</sup> Therefore, you should avoid <em>ad hoc</em> escaping.</p>\n\n<p>Instead, I recommend <strong>keeping all strings in unescaped form,</strong> and performing the escaping at the last minute when constructing the URL. That also forces you to use a URL-construction procedure that handles all escaping for you — the way it should be done. For example,</p>\n\n<pre><code>import urllib\n\nstart = (Time.now.utc + 3600).strftime(…)\nend = (Time.now.utc + 7200).strftime(…)\n\nquery_string = urllib.urlencode({ 'start': start, 'end', end })\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup> One way to keep track of which variables contain encoded strings is to use <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow\">some form of Hungarian Notation</a> (see the section called <em>The Real Solution</em>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T10:56:29.190", "Id": "83374", "Score": "0", "body": "+1 for advocating \"just in time\"-encoding" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T23:04:25.860", "Id": "47521", "ParentId": "47456", "Score": "2" } } ]
{ "AcceptedAnswerId": "47460", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:01:04.560", "Id": "47456", "Score": "5", "Tags": [ "ruby", "datetime", "url" ], "Title": "Adding time offsets to create future dates" }
47456
<p>For a website, I've got some inline PHP, posted below. It's supposed to log traffic to the website, and it does its job fine. But at the end of the day, I'm not even close to a PHP developer, and this is really just hacked together from Googling and inferring from other, more familiar languages. How can I improve this? Is using PHP in the actual file like this bad? (This is in <code>index.html</code>.) Also, I don't believe I'm open to an SQL injection attack since the variables are all drawn directly from the server rather than the user, but I could be wrong.</p> <pre><code>&lt;body&gt; &lt;?php $ip = (!empty($_SERVER["HTTP_CLIENT_IP"]) ? $_SERVER["HTTP_CLIENT_IP"] : $_SERVER["REMOTE_ADDR"]); $fwd = (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]) ? "\"".$_SERVER["HTTP_X_FORWARDED_FOR"]."\"" : "null"); $hostname = gethostbyaddr($ip); if($ip !== "127.0.0.1" &amp;&amp; $ip !== "192.168.1.1") { $con = mysqli_connect("localhost","username","password","database"); if(!mysqli_connect_errno($con)) { $result = mysqli_query($con, "INSERT INTO table_name VALUES(\"".$ip."\", now(), \"".$hostname."\", ".$fwd.")"); } } ?&gt; &lt;div class="container-fluid"&gt; &lt;div class="row-fluid"&gt; &lt;!-- etc. --&gt; </code></pre>
[]
[ { "body": "<p>I don't think its really SQL-injection, but <code>$hostname</code> is not taken from server but from DNS.</p>\n\n<p>Theoretically i can add some kind of malicious domain name and affect your query. But from other hand, domain syntax is really limited. I don't think you can use it to do some serious thing.</p>\n\n<p>Though i would recommend some error protection to avoid SQL-errors.</p>\n\n<p>And correct mysql-escaping can never be bad ))</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:14:20.513", "Id": "83146", "Score": "1", "body": "Thanks for your comments. What do you mean by \"correct MySQL escaping\"? I thought I was escaping the values appropriately in the string. At least, appropriately enough for the INSERT to work, haha." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:24:03.593", "Id": "83148", "Score": "0", "body": "I mean mysql_real_escape_string. E.g. mysql_real_escape_string($hostname) instead of $hostname. You think you always get correct domain or ip. But what if you get an error message, or faked domain name." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:11:04.157", "Id": "47467", "ParentId": "47461", "Score": "6" } }, { "body": "<p>a couple of things.</p>\n\n<p><code>gethostbyaddr()</code> is notoriously slow and unpredictable in speed. So be careful with that.</p>\n\n<p>You may wish to use a prepared SQL statement to injection-proof your code. That would go like this, with error checking:</p>\n\n<pre><code>if (!($stmt = $con-&gt;prepare(\"INSERT INTO table_name VALUES (?, ?, ?)\"))) {\n echo \"prepare failed: (\" . $mysqli-&gt;errno . \") \" . $mysqli-&gt;error;\n}\nif (!($stmt-&gt;bind_param('sss', $ip, $hostname, $fwd))) {\n echo \"bind_param failed: (\" . $mysqli-&gt;errno . \") \" . $mysqli-&gt;error;\n}\nif (!($stmt-&gt;execute())) {\n echo \"execute failed: (\" . $mysqli-&gt;errno . \") \" . $mysqli-&gt;error;\n}\n$stmt-&gt;close();\n</code></pre>\n\n<p>It's a little more overhead, but it's safer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T17:41:11.613", "Id": "83250", "Score": "0", "body": "Thank you for your comments, sir. I actually have a follow-up question which you reminded me about. Should I be closing `$con` somehow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T19:14:42.693", "Id": "83661", "Score": "0", "body": "Yes, it's good practice to close the mysqli connection. Those connections are pooled, so there won't be much of a performance hit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:43:51.173", "Id": "47498", "ParentId": "47461", "Score": "5" } }, { "body": "<p>I prefer to use <a href=\"http://www.php.net/manual/en/intro.pdo.php\" rel=\"nofollow noreferrer\">PDO</a> when working with database. I would say, that it is a standard these days.</p>\n\n<p>You should always escape input that is not directly under your control. That includes values which come from $_SERVER as well. It might look like safe source of data, but that is not always correct. <a href=\"https://stackoverflow.com/questions/6474783/which-server-variables-are-safe\">This</a> is a good read regarding values coming from $_SERVER.</p>\n\n<p>You can easily avoid SQL injection by using <a href=\"http://cz1.php.net/pdo.prepared-statements\" rel=\"nofollow noreferrer\">prepared statements</a>. There is no need to create your SQL queries by putting values from variables directly inside SQL queries. </p>\n\n<ul>\n<li><code>\"\\\"\"</code> can be simplified to this <code>'\"'</code></li>\n<li>if a string does not contain any variables it should be wrapped into <code>''</code> instead of <code>\"\"</code>, because PHP interpreter does not need to check if a string contains variables in that case</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T20:51:25.393", "Id": "47741", "ParentId": "47461", "Score": "4" } } ]
{ "AcceptedAnswerId": "47498", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:28:55.233", "Id": "47461", "Score": "3", "Tags": [ "php", "mysql", "php5", "mysqli" ], "Title": "Inline PHP IP access log" }
47461
<p>Which one of these two would you prefer writing in your code?</p> <p><strong>This:</strong></p> <pre><code>tweet = tweet.replaceAll("@\\w+|#\\w+|\\bRT\\b", ""); tweet = tweet.replaceAll("\n", " "); tweet = tweet.replaceAll("[^\\p{L}\\p{N} ]+", " "); tweet = tweet.replaceAll(" +", " ").trim(); </code></pre> <p><strong>Or this:</strong></p> <pre><code>tweet = tweet.replaceAll("@\\w+|#\\w+|\\bRT\\b", "") .replaceAll("\n", " ") .replaceAll("[^\\p{L}\\p{N} ]+", " ") .replaceAll(" +", " ") .trim(); </code></pre> <p>Which one looks cleaner (in my opinion the second one but it obstructs you from commenting every line if you wanted to) and which one should perform better? (my guess is that there is no difference since regex doesn't create a new string everytime and it does everything internally if I am correct)</p> <hr> <p><strong>Additional Information:</strong></p> <p>Using one <code>.replaceAll()</code> is not possible because if the content that I want to be removed is not removed in this order then the output will be wrong.</p> <p><strong>Here is a short compilable example:</strong></p> <pre><code>public class StringTest { public static void main(String args[]) { String text = "RT @AshStewart09: Vote for Lady Gaga for \"Best Fans\"" + " at iHeart Awards\n" + "\n" + "RT!!\n" + "\n" + "My vote for #FanArmy goes to #LittleMonsters #iHeartAwards\n" + "for ART!" + "htt… è, é, ê, ë asdf324 ah_"; System.out.println("Before: " + text + "\n"); text = text.replaceAll("@\\w+|#\\w+|\\bRT\\b", "") .replaceAll("\n", " ") .replaceAll("[^\\p{L}\\p{N} ]+", " ") .replaceAll(" +", " ").trim(); System.out.println("After: " + text + "\n"); } } </code></pre> <p>I have tried merging some of the <code>.replaceAll()</code> but the output was always wrong if I did the operations in any other order than this. In the end I want to be left with just the words of the tweet and nothing else. Bare in mind that this is the first time I'm using regex so I am far from a pro at it so if there actually is a way to merge them then do tell.</p> <hr> <p><strong>This is the closest I'm currently at merging the <code>replaceAll()</code>:</strong></p> <pre><code>text = text .replaceAll("@\\w+|#\\w+|\\bRT\\b|\n|[^\\p{L}\\p{N} ]+", " ") .replaceAll(" +", " ") .trim(); </code></pre> <p>I basically made everything a <code>space</code> and then removed all the extra spaces. Is that better than before? Is it even possible to merge the last <code>replaceAll</code> as well?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:10:25.263", "Id": "83256", "Score": "1", "body": "FWIW, (and I'm sure you know this) even in the second example you can comment each line by putting the comment at the end of the code with a // comment. I find those pretty readable and helpful if the comment is short enough to fit on the same line. Doesn't always work out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:13:28.907", "Id": "83257", "Score": "0", "body": "@matt yes I knew that, I just personally do not really like commenting on the side unless it's a closing bracket." } ]
[ { "body": "<p>This is probably a matter of preference. <s>But performance-wise it's definitely faster to do the second one. Especially as there should be a new instance of String created for every assignment you perform.This means, you create 3 Instances of String, that are just \"useless garbage\".</s> </p>\n\n<p>@skiwi and @200_success put me right on my incorrect belief, that the second approach were faster. In fact, every Call to <code>.replaceAll()</code> creates a new Instance of String, whether you concat the next call or not.<br>\nThis makes it a relatively expensive operation.</p>\n\n<p>Concerning the possibility of commenting your code:<br>\nyour code / regex should be \"selfdocumenting\" enough to not need comments.</p>\n\n<p>If that is not the case, I suggest you extract at least your regexes to named constants:</p>\n\n<pre><code>tweet = tweet.replaceAll(HASHTAG_REGEX, \"\")\n .replaceAll(\"\\n\", \" \")\n .replaceAll(DO_NOT_KNOW_WHAT_REGEX, \" \")\n .replaceAll(MULTIPLE_WHITESPACE_REGEX, \" \")\n .trim();\n</code></pre>\n\n<p><sub>Thanks to @Amon for valuable critique on my indentation-style</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:11:37.887", "Id": "83144", "Score": "2", "body": "I like the `CONSTANTS`. I'm not so sure that the second one performs significantly faster, though. It would still create intermediate strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:13:38.087", "Id": "83145", "Score": "4", "body": "A disadvantage of your suggested indentation style is that when the `tweet` variable is renamed, the indentation of the other lines will be off again. It is therefore sensible to put a newline in fron of the first method invocation as well: `tweet = tweet<NL><TAB>.replaceAll(…)<NL><TAB>.replaceAll(…) ...`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:29:40.017", "Id": "83205", "Score": "0", "body": "I agree with having the code documented well enough and I will do that. By the way the third regex removes all special characters. @amon I thought having the first function not indented was the norm..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:45:38.527", "Id": "83208", "Score": "0", "body": "I tried merging them but I have a feeling that the performance might be the same and the code worse. Will for example the `|` improve performance or is it the same as before? (see bottom code for latest changes)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:06:19.943", "Id": "47466", "ParentId": "47465", "Score": "13" } }, { "body": "<p>I agree mostly with @Vogel612's answer, the second version is more concise and there is no need to litter variables all over the place as is done in the first version.</p>\n\n<p>Another point is that code should be self-documenting, which @Vogel612 also suggests, but else you can still add a comment behind the code lines.</p>\n\n<p><strong>My review</strong></p>\n\n<p>I wanted to talk about a more interesting point, as this question seems to be a subproblem of a bigger question of yours, which involves creating a high throughput program that does something with tweets.<br>\n<strong>Perhaps this is a premature optimization given that I do not know how well your program performs, but your program may very well hit a threshold limit because of the way you handle regexes.</strong></p>\n\n<p>You should consider what a <code>String.replaceAll</code> does:</p>\n\n<pre><code>public String replaceAll(String regex, String replacement) {\n return Pattern.compile(regex).matcher(this).replaceAll(replacement);\n}\n</code></pre>\n\n<p>For every provided regex it creates a pattern and matches and replaces the occurences with the replacement.<br>\nIt is also important to look into <code>Pattern.replaceAll</code> now:</p>\n\n<pre><code>public String replaceAll(String replacement) {\n reset();\n boolean result = find();\n if (result) {\n StringBuffer sb = new StringBuffer();\n do {\n appendReplacement(sb, replacement);\n result = find();\n } while (result);\n appendTail(sb);\n return sb.toString();\n }\n return text.toString();\n}\n</code></pre>\n\n<p>Here you can see, that because of four regex replaces, you create four times a <code>StringBuffer</code>, which is synchronized, and a <code>String</code> object, which can count up if you are processing tons of tweets.</p>\n\n<p>There are two things you can do:</p>\n\n<ol>\n<li>Create a single regex that captures what you want to do, thus needing only one <code>replaceAll</code> call.</li>\n<li>Go really into micro-optimizing and get rid of the regexes in a whole, operate on a <code>char[]</code> and only store the resulting character array.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:33:16.550", "Id": "83167", "Score": "0", "body": "The problem with having one `replaceAll` is that the processing must be done in that order. I will provide an example when I get back home to show you what I mean exactly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:26:28.563", "Id": "83204", "Score": "0", "body": "I updated my code to reflect why I can't use a single `replaceAll`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:47:39.333", "Id": "83209", "Score": "0", "body": "I updated it again with a somewhat merged `replaceAll` but I have a feeling that the `|` operator will still create separate regex's." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T00:41:43.880", "Id": "83314", "Score": "1", "body": "@SilliconTouch Like skiwi wrote, it may be a premature optimization to combine all of the regexes. If it's hard for you to do, AND you don't expect to process very many strings at any one time, you can get away with performance testing the unoptimized code at some point before production and leaving it unoptimized if you're happy with the way it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T15:09:02.233", "Id": "83401", "Score": "1", "body": "In the end I decided to do a bit of a mix of all the answers here (since every one of them was pretty good) but mainly I liked this answer for the good explanation of `replaceAll()` which made me understand how to go about this performance wise. I decided to keep things readable for now and not do anything fancy thus going with the second of my original options and in the future if I decide optimization is needed I will make a proper class with pre-compiled patterns." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:24:38.667", "Id": "47469", "ParentId": "47465", "Score": "15" } }, { "body": "<p>My recommendation for this would be to first focus on readability and then only concern yourself with performance if you know it's an issue.</p>\n\n<p>I find regex hard to read myself, especially when you're just glancing at it, so my recommendation for that is to move the regexes into their own methods that have better names.</p>\n\n<p>Usage:</p>\n\n<pre><code>string before = \"bla bla blah\"; \nstring after = TweetFormatter.format(before);\n\nSystem.out.println(\"Before: \" + before + \"\\n\");\nSystem.out.println(\"After: \" + after + \"\\n\");\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>public class TweetFormatter\n{\n public static string format(string tweet)\n {\n tweet = removeHashTags(tweet);\n tweet = someOtherMethod(tweet);\n tweet = convertNewlinesToSpaces(tweet);\n tweet = normalizeWhitespace(tweet);\n\n return tweet.trim();\n }\n\n private static string removeHashTags(string tweet)\n {\n return tweet.replaceAll(\"@\\\\w+|#\\\\w+|\\\\bRT\\\\b\", \"\");\n }\n\n private static string someOtherMethod(string tweet)\n {\n return tweet.replaceAll(\"[^\\\\p{L}\\\\p{N} ]+\", \" \");\n } \n\n private static string convertNewlinesToSpaces(string tweet)\n {\n return tweet.replaceAll(\"\\n\", \" \");\n }\n\n private string string normalizeWhitespace(string tweet)\n {\n return tweet.replaceAll(\"\\\\s+\", \" \");\n }\n}\n</code></pre>\n\n<p>The advantage to doing this is that if you determine that this performs too slowly, you can write unit tests to ensure the <code>TweetFormatter</code> behaves properly, and then refactor its innards to make it more performant without worrying about duplicated code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T00:35:33.177", "Id": "83468", "Score": "2", "body": "Normally I like methods, but `convertNewlinesToSpaces` seems a bit much. I mean, the content of the method `tweet.replaceAll(\"\\n\", \" \")` is a more descriptive than the name." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:08:50.410", "Id": "47517", "ParentId": "47465", "Score": "6" } }, { "body": "<p>As shown by skiwi each \"replaceAll\" call compiles a regexp pattern, then apply it to a String and finally performs the replacement.</p>\n\n<p>If you pre-compile your patterns you can have your code running a bit faster (I've tried on my machine, got it 15% faster - not such a big deal but if performances are important for you, you can consider it)</p>\n\n<p>You can do it in this way:</p>\n\n<pre><code>private static class ReplacementPattern {\n ReplacementPattern(Pattern pattern, String replace) {\n this.pattern = pattern;\n this.replace = replace;\n }\n Pattern pattern;\n String replace;\n}\n</code></pre>\n\n<p>Your patterns must be initialized somewhere in your code, just once:</p>\n\n<pre><code>private List&lt;ReplacementPattern&gt; patterns = new ArrayList&lt;ReplacementPattern&gt;(4);\n\n patterns.add(new ReplacementPattern(Pattern.compile(\"@\\\\w+|#\\\\w+|\\\\bRT\\\\b\"), \"\"));\n patterns.add(new ReplacementPattern(Pattern.compile(\"\\n\"), \" \"));\n patterns.add(new ReplacementPattern(Pattern.compile(\"[^\\\\p{L}\\\\p{N} ]+\"), \" \"));\n patterns.add(new ReplacementPattern(Pattern.compile(\" +\"), \" \"));\n\n\nprivate String cleanTweet(String text) {\n for (ReplacementPattern rp : patterns) {\n text = rp.pattern.matcher(text).replaceAll(rp.replace);\n }\n return text.trim();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T05:21:44.793", "Id": "83353", "Score": "3", "body": "+1 - pre-compiling the regexes is the most obvious performance gain to me. Though if you're going to go to the trouble to put it in its own class, you ought to have an `applyTo` or `replace` method in that class rather than accessing the internals. It would aid readability." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T04:55:06.123", "Id": "47538", "ParentId": "47465", "Score": "8" } } ]
{ "AcceptedAnswerId": "47469", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T11:49:38.633", "Id": "47465", "Score": "11", "Tags": [ "java", "performance", "strings", "regex" ], "Title": "What would be preferred aesthetically and performance wise?" }
47465
<p>I cannot figure out why I didn't get 100% success from the Codility's Perm-Missing-Element test even I solve with \$O(n)\$. I will appreciate any advice/answers.</p> <p>You can see the problem, my code, and the scores <a href="https://codility.com/demo/results/demoVTDAWC-P25/">on the Codility site</a>, as well as here.</p> <h2>Problem Definition</h2> <blockquote> <p>A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.<br> Your goal is to find that missing element.<br> Write a function: </p> <pre><code>class Solution { public int solution(int[] A); } </code></pre> <p>that, given a zero-indexed array A, returns the value of the missing element.<br> For example, given array A such that: </p> <pre><code>A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5 </code></pre> <p>the function should return 4, as it is the missing element.<br> <strong>Assume that:</strong><br> N is an integer within the range [0..100,000];<br> the elements of A are all distinct;<br> each element of array A is an integer within the range [1..(N + 1)].<br> <strong>Complexity:</strong><br> expected worst-case time complexity is O(N);<br> expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).<br> Elements of input arrays can be modified. </p> </blockquote> <h2>Solution</h2> <p>Here is the code I wrote as an answer:</p> <pre><code>public class Solution { public int solution(int[] A) { int N = A.length + 1; int total = N * (N + 1) / 2; for (int i : A) { total -= i; } return total; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:19:36.640", "Id": "83161", "Score": "0", "body": "Doesn't codility provide you more details about this ? Type of test cases for instance" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:23:29.383", "Id": "83163", "Score": "0", "body": "I shared a link which just give a brief test report. They don't share a detailed report." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:44:31.423", "Id": "83174", "Score": "0", "body": "Ha ok, I didn't see that. So this is actually a problem of correctness and not of performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-24T16:19:06.903", "Id": "199652", "Score": "1", "body": "I'm confused. Where are people getting the formula for Total? Obviously the result is the sum of all array elements plus the missing element, because that's how we're treating it to get the right answer. But how do we arrive at that formula?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-08T12:36:45.787", "Id": "297724", "Score": "1", "body": "@KairisCharm it's the arithmetic progression formula. Everybody discusses the easy part (implementing) and give math for granted which is the most challenging for reaching the solution. This tests are not testing for software engineering they're testing algebra https://en.wikipedia.org/wiki/Arithmetic_progression" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-22T14:36:51.863", "Id": "489555", "Score": "0", "body": "I got another solution in Python but cannot post because of my rep. It uses `sort()` which has high complexity and uses a counter that is set to the first element. It then compares the counter with the elements increasing the counter by one. If an element is missing it returns." } ]
[ { "body": "<p>From the site :</p>\n\n<pre><code>WRONG ANSWER\ngot -2147483647 expected 1\n</code></pre>\n\n<p>So int has overflow because you count everything up.\nMine solution to that problem :</p>\n\n<pre><code>public int solution(int[] A) {\n int previous = 0;\n if (A.length != 0) {\n Arrays.sort(A);\n for (int i : A) {\n if (++previous != i) {\n return previous;\n }\n }\n }\n return ++previous;\n}\n</code></pre>\n\n<p>result see here : <a href=\"https://codility.com/demo/results/demoS45RNV-37J/\" rel=\"nofollow\">https://codility.com/demo/results/demoS45RNV-37J/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:23:04.910", "Id": "83162", "Score": "4", "body": "Arrays.sort is typically an O(n log n) operation, so it will likely fail the scalability test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-07T03:41:42.367", "Id": "99087", "Score": "0", "body": "Did I miss something in the requirements? When I sent an input of `int[] A = {26,23,21,24,22};`, I did not get the desired result using your method. It could be that I am missing something in the requirement, so please clarify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-07T10:33:59.050", "Id": "99129", "Score": "1", "body": "@KayAshton This won't work cause the pre requirement is that you start at 1 (or 2 if 1 is missing). Also you can't have an exact result when you have `int[] A = {25,23,21,24,22};` because it could be `20` or `26`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-18T20:22:33.510", "Id": "151869", "Score": "0", "body": "This answer isn't correct simply because a solution bounded by N is needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-19T06:40:48.130", "Id": "152001", "Score": "0", "body": "@CodingChief There is a difference between **not correct** and **not optimized**. The code works for every case, but indeed rolfl his code is more optimized, and that is also the reason that his answer is accepted as correct one." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:21:58.563", "Id": "47476", "ParentId": "47471", "Score": "5" } }, { "body": "<p>@chillworld is correct in his observation that the issue is related to the int overflow causing the problems in the performance tests.</p>\n<p>The more accurate solution to this is to use a <code>long</code> to set the score, instead of an <code>int</code>.</p>\n<pre><code>public class Solution {\n\n public int solution(int[] A) {\n\n long N = A.length + 1;\n long total = N * (N + 1) / 2;\n\n for (int i : A) {\n\n total -= i;\n }\n\n return (int)total;\n }\n}\n</code></pre>\n<p>As for your code, I understand why you have variables with names like <code>N</code> and <code>A</code>, because those are the variable names used in the problem.</p>\n<p>Those variable names do not conform to standard Java naming conventions though. They should be meaningful names, and start with a lower-case letter, like <code>sum</code>, and <code>data</code>.</p>\n<p><em><strong>the fact that my code below still uses <code>N</code> is not an indication that it is OK .... Do what I say, not what I do...</strong></em></p>\n<hr />\n<h2>Update</h2>\n<p>Sometimes, the performance tricks in Java can be a PITA.</p>\n<ul>\n<li>Whenever you can, declare your variables as final</li>\n<li>declare your methods as final</li>\n<li>declare variables and for-loop variables as final (if you use the enhanced-for semantics).</li>\n<li>addition may, or may not be faster than subtraction.</li>\n</ul>\n<p>Using this code:</p>\n<pre><code>class Solution {\n\n public final int solution(final int[] data) {\n\n final long N = data.length + 1;\n final long total = (N * (N + 1)) / 2;\n \n long sum = 0L;\n\n for (final int i : data) {\n\n sum += i;\n }\n\n return (int)(total - sum);\n }\n}\n</code></pre>\n<p><a href=\"https://codility.com/demo/results/demoJZQNEU-4CX/\" rel=\"noreferrer\"><strong>Scores 100%</strong></a></p>\n<hr />\n<h2>Update 2 final is not the issue:</h2>\n<pre><code>public int solution(int[] data) {\n\n long N = data.length + 1;\n long total = (N * (N + 1)) / 2;\n \n long sum = 0L;\n\n for (int i : data) {\n\n sum += i;\n }\n\n return (int)(total - sum);\n}\n</code></pre>\n<p><a href=\"https://codility.com/demo/results/demo79VSVE-XT4/\" rel=\"noreferrer\"><strong>Also scores 100%</strong></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:27:13.107", "Id": "83165", "Score": "0", "body": "believe me I tried that solution which gives the same result :). But variable names doesnt affect performance right ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:37:44.570", "Id": "83168", "Score": "0", "body": "@quartaela - updated answer with 100% solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:41:57.690", "Id": "83171", "Score": "0", "body": "thanks a lot but I dont get it. How defining variables as final boost the performance from 60 to 100?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:44:23.040", "Id": "83173", "Score": "0", "body": "@quartaela - I am pretty convinced your code would have passed with just the long-based arithmetic.... the performance tests were *failing*, they were not *slow*. The code above just gives a solution that works in all situations, not just smaller datasets. I will put another test through with the same code, but different final, and see what happens." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:45:49.423", "Id": "83175", "Score": "0", "body": "Impressive, it does not do much for my opinion of Java though :\\" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:48:33.183", "Id": "83177", "Score": "0", "body": "@quartaela - added post without final." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:56:28.913", "Id": "83180", "Score": "0", "body": "@rolfl I've tried analogous code before I asked the question. Just try to make N `int` and let the rest same. It gives 80 score. Very weird.:D" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:26:04.570", "Id": "47477", "ParentId": "47471", "Score": "23" } }, { "body": "<p>You could also use Java 8 <code>IntStream</code> API to sum the array and minimize your code:</p>\n\n<pre><code>public int solution(int[] A) {\n long N = A.length + 1;\n return (int) (((N*(N+1))/2)-IntStream.of(A).sum());\n}\n</code></pre>\n\n<p>This will <a href=\"https://codility.com/demo/results/demo3M9HDD-WKW/\" rel=\"noreferrer\">score 100%</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-10T16:08:39.433", "Id": "80171", "ParentId": "47471", "Score": "9" } } ]
{ "AcceptedAnswerId": "47477", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T12:45:36.860", "Id": "47471", "Score": "30", "Tags": [ "java", "performance", "algorithm", "programming-challenge" ], "Title": "Perm-Missing-Elem: 100% functional score, but only 60% performance" }
47471
<p>Could I get some feedback on my simple start to an admin template: <a href="http://jsfiddle.net/spadez/GHKxW/3/" rel="nofollow">http://jsfiddle.net/spadez/GHKxW/3/</a></p> <p><strong>HTML</strong></p> <pre><code> &lt;div class="wrapper"&gt; &lt;div class="left"&gt; &lt;a href="#"&gt;&lt;img src="nav_sprite.jpg" class="logo" /&gt;&lt;/a&gt; &lt;ul class="navigation"&gt; &lt;li id="dashboard"&gt;&lt;a href="index.html" class="active"&gt;Dashboard&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="right"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;p&gt;Content&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>* { margin: 0; padding: 0; border: 0; } li { list-style: none; } a { text-decoration: none } html, body {height: 100%; max-height: 100%; padding:0; margin:0;} .wrapper {display:table; width:100%; height:100%;} .wrapper &gt; div {display:table-cell; vertical-align: top;} .wrapper .left {width:200px; background-color:#34495E} #btn_pri { background-color: 60A0DF; color: white; } #btn_sec { background-color: #e74c3c; color:white; } .navigation { } .navigation li { } .navigation li span { display: inline-block; background: url(http://www.otlayi.com/web_images/content/free-doc-type-sprite-icons.jpg) no-repeat left center; width: 16px; height: 16px; overflow: hidden; margin-left: 15px; margin-right: 15px; } .navigation li a { display: block; color: white; padding-top: 15px; padding-bottom: 15px; font-family:'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; } .navigation li a:hover { background-color: #495C6D; } .navigation li a.active { background-color: #495C6D } #rss span { background-position: -52px -68px; } #photos span { background-position: -90px -66px; } #links span { background-position: -45px 0; } h1 {font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 30px; font-weight: 500;} .logo {height: 50px; margin-bottom: 30px;} .btn { letter-spacing: 1px; font-weight:bold; padding-left: 10px; padding-right: 10px; height: 34px; border-radius:3px; border: 0px; text-transform:uppercase; font-size:12px; } #btn_pri { background-color: #60A0DF; color: white; } #btn_sec { background-color: #e74c3c; color:white; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T08:05:56.120", "Id": "83502", "Score": "0", "body": "Answers seem pretty on point for what little you have here, but I'd also add that you should remember to use `alt=\"logo\"` to add some more semantic value to your content images. But I know this is still an early build." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T08:12:41.340", "Id": "83504", "Score": "0", "body": "You can also add aria attributes, e.g. <h1 role=\"heading\">, <ul role=\"list\">, <li role=\"listitem\">, <nav role=\"navigation\" class=\"navigation\">, `<div class=\"right\" role=\"main\">` etc. http://www.w3.org/TR/wai-aria/roles" } ]
[ { "body": "<p>This looks pretty good for a start.</p>\n\n<p>the only thing that I see right away is your CSS formatting</p>\n\n<pre><code>a {\n text-decoration: none\n}\n\nhtml, body {height: 100%; max-height: 100%; padding:0; margin:0;}\n.wrapper {display:table; width:100%; height:100%;}\n.wrapper &gt; div {display:table-cell; vertical-align: top;}\n.wrapper .left {width:200px; background-color:#34495E}\n\n#btn_pri {\n background-color: 60A0DF;\n color: white;\n}\n#btn_sec { background-color: #e74c3c;\ncolor:white;\n}\n</code></pre>\n\n<p>Here you switch between what I would call Minified CSS and Egyptian Brackets and the last rule here is a mix.</p>\n\n<p>you should always stay consistent with your Formatting, especially in CSS because it can get confusing when you start adding more rules</p>\n\n<p>so if you did this in all Egyptian Formatting.</p>\n\n<pre><code>a {\n text-decoration: none\n}\n\nhtml, body {\n height: 100%; \n max-height: 100%; \n padding:0; \n margin:0;\n}\n\n.wrapper {\n display:table; \n width:100%; \n height:100%;\n}\n\n.wrapper &gt; div {\n display:table-cell; \n vertical-align: top;\n}\n\n.wrapper .left {\n width:200px; \n background-color:#34495E\n}\n\n#btn_pri {\n background-color: 60A0DF;\n color: white;\n}\n\n#btn_sec { \n background-color: #e74c3c;\n color:white;\n}\n</code></pre>\n\n<p>This is how I would do it personally, it is clear what rule is what, and it looks neat and tidy as well.</p>\n\n<p>but how ever you decide to do it, please be consistent.</p>\n\n<hr>\n\n<p>As far as these Empty Rules.</p>\n\n<pre><code>.navigation {\n}\n.navigation li {\n}\n</code></pre>\n\n<p>I assume that you are going to use them in the future for something, if not, get rid of them, they will clutter up your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:51:51.230", "Id": "47479", "ParentId": "47475", "Score": "2" } }, { "body": "<p>While I agree with Malachi about the formatting for your CSS, my one caveat in development is rules that I consider \"done\" that are still expanded out take up lots of room. In a large CSS sheet this is maddening.</p>\n\n<p>As I am working on the site, and I alone am the only developer then I will condense rules that I consider \"done\". If it is hard to understand what they are then I put in a simple comment temporarily. I feel that for <strong><em>myself</em></strong> this is more readable, especially in a css sheet that contains a few thousand lines.</p>\n\n<p>To that end, I would suggest developing a comprehensive comment system that is easy for you to navigate, especially if you expect your css sheet to become large. Create an index and headings with comments that you can easily find through a scroll or with control-f. For example...</p>\n\n<pre><code>/* ----------------------- */\n/* 1.0 Header Styles */\n/* 2.0 Navigation Styles */\n/* 3.0 Content Styles */\n/* 3.1 -- Specific Content */\n/* ----------------------- */\n\n/* 1.0 Header Styles\n************************************/\n</code></pre>\n\n<p>The above of course is just my preference. It helps to keep me organized.</p>\n\n<p>All in all, my point, is develop however YOU feel is quickest for yourself, assumign you are the only one working on the project. When you are done with development, your CSS should be minified and comments removed, so what it looks like in development doesn't really matter if you're the only one working on it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T14:01:08.753", "Id": "47575", "ParentId": "47475", "Score": "1" } } ]
{ "AcceptedAnswerId": "47479", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:16:27.803", "Id": "47475", "Score": "4", "Tags": [ "html", "css" ], "Title": "Admin CSS sidebar template" }
47475
<p>I really like the ruby <code>?</code> <code>:</code> syntax for <code>if</code>/<code>else</code> statements.</p> <p>However, I'm not sure how to do the following with a nested statement:</p> <pre><code>if information.is_empty? if leader? || possessor? link_to('update ' + contextual('your') + ' credentials!', edit_user_path) else user.name + ' hasn\'t entered this info!' end else information end </code></pre> <p>Should I bother? Does the <code>?</code> <code>:</code> syntax (for want of a term!) actually make code pretty unreadable and non-self-documenting?</p> <p>If you think I should use the <code>?</code> <code>:</code> syntax, how would I tackle this?</p>
[]
[ { "body": "<ol>\n<li><p>The <code>?:</code> is called a <a href=\"http://en.wikipedia.org/wiki/%3F:\" rel=\"nofollow noreferrer\">ternary operator</a>. It's not specific to Ruby; a lot of languages have it (in fact, I believe I linked you to that wikipedia page in a comment <a href=\"https://codereview.stackexchange.com/a/47330/14370\">very recently</a>).</p></li>\n<li><p>Go easy on the newlines; there's a lot of whitespace there (update: question was edited; now it's gone)</p></li>\n<li><p>Use string interpolation</p></li>\n<li><p><a href=\"https://codereview.stackexchange.com/a/47330/14370\">We've talked about</a> that <code>is_</code> prefix on <code>?</code> methods already :)</p></li>\n</ol>\n\n<p>To answer your question: Ternaries have their use, but like everything else, they can also be abused.</p>\n\n<p>In practice, there's no difference between a ternary and and a good ol' <code>if...else</code>, so you can use either - but that argument goes both ways. Don't use ternaries <em>just because you can</em>.</p>\n\n<p>A good case for a ternary (in my opinion), would be something like this (just as an example):</p>\n\n<pre><code>puts some_boolean_value ? \"yes\" : \"no\"\n</code></pre>\n\n<p>or something like</p>\n\n<pre><code>\"You have #{messages.count} new #{messages.one? ? 'message' : 'messages'}\"\n</code></pre>\n\n<p>There's no logic going on in either the <code>if</code> or the <code>else</code> branch, and both are very short, so it's short and sweet to use a ternary.</p>\n\n<p>In Ruby you can also spell the first one out like:</p>\n\n<pre><code>puts if some_boolean_value\n \"yes\"\nelse\n \"no\"\nend\n</code></pre>\n\n<p>It's neat that Ruby treats <code>if...else</code> as an expression, but here it seems like a waste of space for something so simple.</p>\n\n<p><strong>In your case:</strong> Your code <em>does</em> have more branching logic, so I'd definitely avoid ternaries, and keep it as-is. Personally, I'd <em>never</em> nest ternary expressions inside each other, just for readability reasons.</p>\n\n<p>Alternatively, you can return early (assuming this code is in a method):</p>\n\n<pre><code>return information unless information.is_empty?\n\nif leader? || possessor?\n link_to(\"update #{contextual \"your\"} credentials\", edit_user_path)\nelse\n \"#{user.name} hasn't entered this info!\"\nend\n</code></pre>\n\n<p>If you wrote it <em>all</em> in ternaries, it'd be pretty ridiculous:</p>\n\n<pre><code>information.is_empty? ? leader? || professor? ? link_to(\"update #{contextual \"your\"} credentials\", edit_user_path) : \"#{user.name} hasn't entered this info!\" : information # what?\n</code></pre>\n\n<p>The middle road would be to use a ternary for the innermost nested branch only</p>\n\n<pre><code>if information.is_empty?\n leader? || professor? ? link_to(\"update #{contextual \"your\"} credentials\", edit_user_path) : \"#{user.name} hasn't entered this info!\"\nelse\n information\nend\n</code></pre>\n\n<p>But, as you can see, that innermost nested branch is also the one with the most going on, so it's still less readable than a normal <code>if...else</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:12:44.467", "Id": "83284", "Score": "0", "body": "I think you did something strange in some of the examples; syntax highlighting looks wrong (although I don't know ruby)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:26:48.440", "Id": "83286", "Score": "0", "body": "@Izkata Should be fine. The highlighting is just stumbling over the string-inside-a-string in the string interpolations. It's basically `\"text #{ruby code with a string in it} more text\"` and the syntax highlighter doesn't understand that" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:27:17.700", "Id": "47485", "ParentId": "47481", "Score": "11" } }, { "body": "<p>I think that the key concern should be clarity. Specifically, I recommend eliminating the nesting, which would make it clear that one of three branches will be taken no matter what.</p>\n\n<p>In addition…</p>\n\n<ul>\n<li>Standard Ruby style uses two spaces of indentation.</li>\n<li><code>is_empty?</code> is a redundant name. The question mark alone is enough to convey the fact that it is a predicate.</li>\n<li>Use less clumsy string quoting.</li>\n</ul>\n\n\n\n<pre><code>if !information.empty?\n information\nelsif leader? || possessor?\n link_to(\"update #{contextual('your')} credentials!\", edit_user_path) \nelse\n \"#{user.name} hasn't entered this info!\"\nend\n</code></pre>\n\n<p>You <em>could</em> write that using a ternary expression, but I would advise against it on readability grounds.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T17:21:26.277", "Id": "83245", "Score": "0", "body": "I see the `leader? || professor?` thing as orthogonal to whether there's any information. For a litmus test: You can't swap the branches around in your code and get the same result (not saying that's a great test, but just as an example)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T17:15:20.133", "Id": "47501", "ParentId": "47481", "Score": "3" } } ]
{ "AcceptedAnswerId": "47485", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:05:45.577", "Id": "47481", "Score": "5", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Concise nested statements" }
47481
<p>This class (<code>PanelScrollable</code>) is part of my <code>view</code> package, in an MVP designed Java Swing system. I am not using any MVP frameworks, it's all custom.</p> <p>The reason I'm posting this code is that I fear too much of the rendering logic is directly accessing Swing components, making it difficult to unit test; as a result this class has probably had more bugs making it to production than any other single class in the entire application.</p> <p>What I'd like to do is <em>tease apart the logic that decides what actions should be done on Swing components from the actual calls to Swing methods</em>, but I'm finding that a bit challenging.</p> <p>First, some custom classes you need to understand the <code>PanelScrollable</code> class. These are used to encapsulate Swing behavior away from the Presenter classes, generally speaking. <code>Provider</code> is from Guice.</p> <pre><code>public interface Provider&lt;T&gt; { T get(); } abstract class Componentable { abstract Component getComponent(); } public abstract class DataComponentable&lt;E&gt; extends Componentable { public abstract void setData(E data); public abstract boolean isEnabled(); public abstract void setEnabled(boolean enabled); } </code></pre> <p>And here's <code>PanelScrollable</code>:</p> <pre><code>import static com.google.common.base.Preconditions.checkArgument; import java.awt.Component; import java.awt.Dimension; import java.awt.Rectangle; import java.util.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import com.google.common.collect.Lists; import com.google.inject.Provider; abstract class PanelScrollable&lt;E&gt; extends Componentable { private static final int STRUT_SIZE = 2; private JScrollPane outerPane; private ScrollPanel innerPanel; private List&lt;DataComponentable&lt;E&gt;&gt; panels = Lists.newArrayList(); private List&lt;Component&gt; struts = Lists.newArrayList(); private Provider&lt;? extends DataComponentable&lt;E&gt;&gt; panelFactory; PanelScrollable(Provider&lt;? extends DataComponentable&lt;E&gt;&gt; panelFactory) { this.panelFactory = panelFactory; innerPanel = new ScrollPanel(); outerPane = new JScrollPane(innerPanel); outerPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); addPanel(); } // In general this is the contract of Componentable, to allow for Swing encapsulation @Override final Component getComponent() { return outerPane; } private void addPanelAndStrut() { synchronized(innerPanel.getTreeLock()) { Component newStrut = Box.createVerticalStrut(STRUT_SIZE); struts.add(newStrut); innerPanel.add(newStrut); addPanel(); } } private void addPanel() { synchronized(innerPanel.getTreeLock()) { DataComponentable&lt;E&gt; newPanel = panelFactory.get(); innerPanel.add(newPanel.getComponent()); panels.add(newPanel); } } public void setData(Collection&lt;E&gt; data) { boolean dirty = false; dirty = addAndUpdatePanels(data, dirty); dirty |= removeExtraPanels(data.size()); if(dirty) { redrawPanels(); } } private void redrawPanels() { innerPanel.validate(); innerPanel.repaint(); } private boolean addAndUpdatePanels(Collection&lt;E&gt; data, boolean dirty) { Iterator&lt;E&gt; it = data.iterator(); int i = 0; while(it.hasNext()) { if(notEnoughPanels(i)) { addPanelAndStrut(); dirty = true; } E next = it.next(); panels.get(i).setData(next); i++; } return dirty; } private boolean notEnoughPanels(int i) { return i == panels.size(); } private final boolean removeExtraPanels(int index) { checkArgument(index &gt; -1, "Cannot remove more panels than exist!"); if(index &gt;= panels.size()) return false; synchronized(innerPanel.getTreeLock()) { do { removePanelAndStrut(); } while(index &gt;= panels.size()); if(index == 0) addPanel(); } return true; } private void removePanelAndStrut() { synchronized(innerPanel.getTreeLock()) { DataComponentable&lt;E&gt; removedPanel = panels.remove(panels.size() - 1); removedPanel.setEnabled(false); innerPanel.remove(removedPanel.getComponent()); // This is where the bug WAS that made me decide to post this class on code review // if setData was called with an empty collection, this code would (previously) // call struts.remove(-1) if(struts.size() &gt; 0) { Component removedStrut = struts.remove(struts.size() - 1); innerPanel.remove(removedStrut); } else if (panels.size() &gt; 0) { throw new IllegalStateException( String.format("There are too many panels (%d) and no struts!", panels.size())); } } } private class ScrollPanel extends JPanel implements Scrollable { private static final long serialVersionUID = 3823479389541763224L; public ScrollPanel() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(new EmptyBorder(3,3,3,3)); } @Override public final Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } @Override public final int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { Dimension dim = panels.get(0).getComponent().getPreferredSize(); int size; if (orientation == SwingConstants.HORIZONTAL) { size = dim.width; } else { int height = dim.height + STRUT_SIZE; if (direction &gt; 0) size = height - visibleRect.y % (height); else // 1 to height, not 0 to height - 1 size = (visibleRect.y + visibleRect.height - 1) % (height) + 1; } return size; } @Override public final int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { Dimension dim = panels.get(0).getComponent().getPreferredSize(); int size; if (orientation == SwingConstants.HORIZONTAL) { size = dim.width; } else { int height = dim.height + STRUT_SIZE; size = (visibleRect.height / height) * height; } return size; } @Override public final boolean getScrollableTracksViewportWidth() { return true; } @Override public final boolean getScrollableTracksViewportHeight() { if(outerPane.getViewportBorderBounds().height &gt; getMinimumSize().height) { return true; } return false; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T17:44:42.483", "Id": "83251", "Score": "0", "body": "+1 nice code, good thought-out question. One small note: are `Componentable` and `PanelScrollable` both purposefully left with the default access restriction? Otherwise, I'd recommend explicitly having them `public`, `protected`, or `private`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:03:32.767", "Id": "83262", "Score": "0", "body": "@JeffGohlke Yes they are purposefully package-private. I suppose they could be `protected`, but the idea is that I have a package `mydomain.view` which is all `interface`s and this class is in package `mydomain.view.swing`, which is a Swing implementation of those `interface`s. To disallow the presenter from ever accessing Swing methods, they cannot be `public`, and I don't really expect to be overriding them in a different package. `protected final` might make sense but I don't like `final` methods because it forces me to use `PowerMock` in testing. And `private` is obviously wrong." } ]
[ { "body": "<p>This code is awesomely written. I still have a few really small remarks:</p>\n\n<h3>Ordering members:</h3>\n\n<blockquote>\n <p>If openness separates concepts, then vertical density implies close association. So lines of code that are <strong>tightly related should appear vertically dense.</strong><br>\n - <em>Robert C. Martin, Clean Code, Ch. 5 - Vertical Density (p. 79)</em></p>\n</blockquote>\n\n<p>When I skimmed your code from top to bottom (as usually done), I instantly wondered: <code>addPanelAndStrut()</code> - Where does this get called, why is there no parameter and why is it private?</p>\n\n<p>btw. It gets called <strong>5 methods later</strong>, and only there... I prefer to have the called method below the calling method, this makes skimming the code much easier, as you don't have to scroll up to see what the call to method xy does.</p>\n\n<p>Reorder your methods a little. Usually you have from top to bottom:<br>\n<code>fields, constructors, public methods, private methods, getters and setters</code></p>\n\n<h3>Unneeded parameters:</h3>\n\n<p>Your <code>addAndUpdatePanels</code> is only called once, namely from within <code>setData</code>. And It's always called with <code>dirty = false;</code></p>\n\n<p>Why are you passing in dirty? You can assume that it's not dirty for the purpose of your method. You only need to return whether your method dirties the paint area. The method needn't concern itself with the current state of the paint-area. Remove the parameter and instead just call <code>addAndUpdatePanels(data);</code></p>\n\n<h3>Multiline Conditionals:</h3>\n\n<p>This may be only my preference, but I really prefer to assign booleans only once, or rather as seldom as possible.</p>\n\n<p>I'd rewrite your <code>setData</code> as follows:</p>\n\n<pre><code>public void setData(Collection&lt;E&gt; data) {\n boolean dirty = false;\n\n dirty = addAndUpdatePanels(data) || removeExtraPanels(data.size());\n if(dirty) {\n redrawPanels();\n }\n}\n</code></pre>\n\n<h3>Finally:</h3>\n\n<p>Very nicely and descriptively named variables and methods make reading your class a joy ;) Keep it up. The ordering of your methods is a little confusing to me. All else equal: <strong>Good work!</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T14:15:12.820", "Id": "88244", "Score": "0", "body": "Thanks for such positive feedback! Makes me feel good on a Monday morning. A few comments from me, though (going to do it over three comments). 1) I noticed (after I made this post) that I've been making many lists/arrays of the same length and are always linked together; \"A useful test is to ask yourself what would happen if you removed a piece of data or a method. What other fields and methods would become nonsense?\" - Martin Fowler. I should almost certainly make a class here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T14:16:04.487", "Id": "88245", "Score": "0", "body": "2) Do you have any workflow procedures for how you reorder class members? Or, even better, is there an IDE tool that does this for you? Eclipse has \"sort members\" but I think that's alphabetical order, not useful..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T14:16:56.577", "Id": "88246", "Score": "0", "body": "3) This review didn't talk about the main thing that I wanted help with: how to tease apart the logic from swing method calls so I could write automated tests. Any suggestions on that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T14:30:04.307", "Id": "88251", "Score": "0", "body": "@durron597 Concerning reordering. Eclipse can move selections. Just mark your method and press alt+Arrow up/down. About teasing apart logic from swing method calls... your logic is already nicely parted from what I see.. if you want to test it completely separate, you should extract it to a different class" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T08:13:03.123", "Id": "51120", "ParentId": "47486", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:30:35.013", "Id": "47486", "Score": "10", "Tags": [ "java", "swing", "mvp" ], "Title": "PanelScrollable - a reusable class for rendering a changeable number of panels" }
47486
<p>After asking a <a href="https://stackoverflow.com/q/23129913/300996">question on StackOverflow</a> about the two .NET caching systems taking dependencies on each other I gave implementing them a go. I posted them as my own answer there but before accepting the answer I'd like some second opinions on the implementations.</p> <p><strong>HttpCacheChangeMonitor</strong></p> <p>Allows ObjectCache items to take a dependency on HTTPCache</p> <pre><code>public class HttpCacheChangeMonitor : ChangeMonitor { private readonly string _uniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); private readonly string[] _httpCacheKeys; public override string UniqueId { get { return _uniqueId; } } public HttpCacheChangeMonitor(string httpCacheKey) : this(new[] { httpCacheKey }) { } public HttpCacheChangeMonitor(string[] httpCacheKeys) { _httpCacheKeys = httpCacheKeys; Initialise(); } private void Initialise() { HttpRuntime.Cache.Add(_uniqueId, _uniqueId, new CacheDependency(null, _httpCacheKeys), DateTime.MaxValue, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, Callback); InitializationComplete(); } private void Callback(string key, object value, CacheItemRemovedReason reason) { OnChanged(null); } protected override void Dispose(bool disposing) { Debug.WriteLine( _uniqueId + " notifying cache of change.", "HttpCacheChangeMonitor"); HttpRuntime.Cache.Remove(_uniqueId); } } </code></pre> <p><strong>Test</strong></p> <pre><code>public class HttpCacheChangeMonitorTests { [Fact] public void ChangeMonitorTest() { HttpRuntime.Cache.Add("ChangeMonitorTest1", "", null, Cache.NoAbsoluteExpiration, new TimeSpan(0,10,0), CacheItemPriority.Normal, null); HttpRuntime.Cache.Add("ChangeMonitorTest2", "", null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0), CacheItemPriority.Normal, null); using (MemoryCache cache = new MemoryCache("TestCache", new NameValueCollection())) { // Add data to cache for (int idx = 0; idx &lt; 10; idx++) { cache.Add("Key" + idx, "Value" + idx, GetPolicy(idx)); } long middleCount = cache.GetCount(); // Flush cached items associated with "NamedData" change monitors HttpRuntime.Cache.Remove("ChangeMonitorTest1"); long finalCount = cache.GetCount(); Assert.Equal(10, middleCount); Assert.Equal(5, middleCount - finalCount); HttpRuntime.Cache.Remove("ChangeMonitorTest2"); } } private static CacheItemPolicy GetPolicy(int idx) { string name = (idx % 2 == 0) ? "ChangeMonitorTest1" : "ChangeMonitorTest2"; CacheItemPolicy cip = new CacheItemPolicy(); cip.AbsoluteExpiration = System.DateTimeOffset.UtcNow.AddHours(1); cip.ChangeMonitors.Add(new HttpCacheChangeMonitor(name)); return cip; } } </code></pre> <p><strong>MemoryCacheDependency</strong></p> <p>Allows HttpCache items to take a dependency on MemoryCache</p> <pre><code>public class MemoryCacheDependency : CacheDependency { private readonly string _uniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); private readonly IEnumerable&lt;string&gt; _cacheKeys; private readonly MemoryCache _cache; public override string GetUniqueID() { return _uniqueId; } public MemoryCacheDependency(MemoryCache cache, string cacheKey) : this(cache, new[] { cacheKey }) { } public MemoryCacheDependency(MemoryCache cache, IEnumerable&lt;string&gt; cacheKeys) { _cache = cache; _cacheKeys = cacheKeys; Initialise(); } private void Initialise() { var monitor = _cache.CreateCacheEntryChangeMonitor(_cacheKeys); CacheItemPolicy pol = new CacheItemPolicy{AbsoluteExpiration = DateTime.MaxValue, Priority = CacheItemPriority.NotRemovable}; pol.ChangeMonitors.Add(monitor); pol.RemovedCallback = Callback; _cache.Add(_uniqueId, _uniqueId, pol); FinishInit(); } private void Callback(CacheEntryRemovedArguments arguments) { NotifyDependencyChanged(arguments.Source, EventArgs.Empty); } protected override void DependencyDispose() { Debug.WriteLine( _uniqueId + " notifying cache of change.", "ObjectCacheDependency"); _cache.Remove(_uniqueId); base.DependencyDispose(); } } </code></pre> <p><strong>Test</strong></p> <pre><code>public class MemoryCacheDependencyTests { [Fact] public void CacheDependencyTest() { using (MemoryCache cache = new MemoryCache("TestCache", new NameValueCollection())) { cache.Add("HttpCacheTest1", DateTime.Now, new CacheItemPolicy {SlidingExpiration = new TimeSpan(0, 10, 0)}); cache.Add("HttpCacheTest2", DateTime.Now, new CacheItemPolicy {SlidingExpiration = new TimeSpan(0, 10, 0)}); // Add data to cache for (int idx = 0; idx &lt; 10; idx++) { HttpRuntime.Cache.Add("Key" + idx, "Value" + idx, GetDependency(cache, idx), Cache.NoAbsoluteExpiration, new TimeSpan(0,10,0), CacheItemPriority.NotRemovable, null); } int middleCount = HttpRuntime.Cache.Count; // Flush cached items associated with "NamedData" change monitors cache.Remove("HttpCacheTest1"); int finalCount = HttpRuntime.Cache.Count; Assert.Equal(10, middleCount); Assert.Equal(5, middleCount - finalCount); } } private static CacheDependency GetDependency(MemoryCache cache, int idx) { string name = (idx % 2 == 0) ? "HttpCacheTest1" : "HttpCacheTest2"; return new MemoryCacheDependency(cache, name); } } </code></pre>
[]
[ { "body": "<p>Overall looks very good, clean and well done. I only see minor tiny little things...</p>\n<h3>Nitpick - &quot;Initialise&quot; vs &quot;Initialize&quot;</h3>\n<p>This is just a minor nitpick, but it's kind of jumping at me:</p>\n<blockquote>\n<pre><code>private void Initialise()\n{\n HttpRuntime.Cache.Add(_uniqueId, _uniqueId, new CacheDependency(null, _httpCacheKeys), DateTime.MaxValue, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, Callback);\n InitializationComplete();\n}\n</code></pre>\n</blockquote>\n<p>I find it weird that a method called <code>Initialise()</code> is calling one that's called <code>InitializationComplete()</code> - I think for consistency it would be better named <code>Initialize()</code>.</p>\n<p>Also the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.caching.changemonitor(v=vs.110).aspx\" rel=\"nofollow noreferrer\">MSDN</a> for <code>InitializationComplete()</code> says it's <em>called from the constructor of derived classes to indicate that initialization is finished.</em> - you <em>are</em> calling it from within the constructor, and I'm not familiar with using the <code>ChangeMonitor</code> class but it might be clearer to have that call explicitly show up in the constructor (similar to how <code>InitializeComponents()</code> remains in a form's constructor no matter what):</p>\n<pre><code>public HttpCacheChangeMonitor(string[] httpCacheKeys)\n{\n _httpCacheKeys = httpCacheKeys;\n Initialize();\n InitializationComplete();\n}\n</code></pre>\n<p>But then again it's no biggie, the code is very clear and easy to follow.</p>\n<hr />\n<h3>Temporal Coupling</h3>\n<p>That said I like constructors that do very little, and this is what you've got here, but the <code>Initialise</code> method seems of very little use, and has temporal coupling with the setting of <code>_httpCacheKeys</code> - I mean, if your constructor looked like this:</p>\n<pre><code>public HttpCacheChangeMonitor(string[] httpCacheKeys)\n{\n Initialise();\n _httpCacheKeys = httpCacheKeys;\n}\n</code></pre>\n<p>I'd expect it to blow up. One way to eliminate the temporal coupling, would be to take the array as a parameter:</p>\n<pre><code>private void Initialize(string[] httpCacheKeys)\n{\n HttpRuntime.Cache.Add(_uniqueId, _uniqueId, new CacheDependency(null, httpCacheKeys), DateTime.MaxValue, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, Callback);\n InitializationComplete();\n}\n</code></pre>\n<p>...and then the order of operations doesn't matter anymore:</p>\n<pre><code>public HttpCacheChangeMonitor(string[] httpCacheKeys)\n{\n Initialize(httpCacheKeys);\n _httpCacheKeys = httpCacheKeys;\n}\n</code></pre>\n<hr />\n<p>(haven't looked at the test code)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T09:57:14.793", "Id": "83894", "Score": "0", "body": "Thanks Matt. On the first point using British English is automatic for me but I think you're right that consistency here is probably better. `InitializationComplete` is a toss up between explicitness and DRY. Initialize did have more use but I removed a couple of constructors so could probably revisit the need for it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:11:07.853", "Id": "47511", "ParentId": "47488", "Score": "3" } } ]
{ "AcceptedAnswerId": "47511", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:56:22.617", "Id": "47488", "Score": "5", "Tags": [ "c#", ".net", "cache" ], "Title": "HTTPCache and MemoryCache cross dependency" }
47488
<p>After refactors and refactors and the discovery of very common patterns on many of the classes of the software I wrote, I decided that it would be fine to have something like an arbitrary-keyed map, that would require the key to be stored in the object (which allows to use the object's name as a key for instance).</p> <p>I would like to know if it is a good design, and what are possible pitfalls I didn't encounter and might in the future (and how to prevent them).</p> <p>It is far from perfect (no optimisations, not /that/ generic...) but allowed me to have cleaner code.</p> <p>The container code: </p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;set&gt; template&lt;typename T&gt; using SimpleVec = std::vector&lt;T, std::allocator&lt;T&gt;&gt;; template &lt;typename T, template &lt;typename&gt; class Container = SimpleVec, class String = std::string&gt; class Iterable { template &lt;typename friendT, template &lt;typename&gt; class friendContainer, class friendString&gt; friend typename friendContainer&lt;friendT&gt;::iterator begin(Iterable&lt;friendT, friendContainer, friendString&gt;&amp; i); template &lt;typename friendT, template &lt;typename&gt; class friendContainer, class friendString&gt; friend typename friendContainer&lt;friendT&gt;::iterator end(Iterable&lt;friendT, friendContainer, friendString&gt;&amp; i); template &lt;typename friendT, template &lt;typename&gt; class friendContainer, class friendString&gt; friend typename friendContainer&lt;friendT&gt;::iterator cbegin(const Iterable&lt;friendT, friendContainer, friendString&gt;&amp; i); template &lt;typename friendT, template &lt;typename&gt; class friendContainer, class friendString&gt; friend typename friendContainer&lt;friendT&gt;::iterator cend(const Iterable&lt;friendT, friendContainer, friendString&gt;&amp; i); public: Iterable() = default; Iterable(const Iterable&lt;T, Container, String&gt;&amp; c) = delete; Iterable&amp; operator=(const Iterable&lt;T, Container, String&gt;&amp; c) = delete; virtual ~Iterable() = default; template&lt;typename... K&gt; void performUniquenessCheck(const K&amp;... args) { if(std::any_of(begin(*this), end(*this), T::hasSame(args...))) { throw "Element already exists"; } } template&lt;typename... K&gt; T&amp; create(K&amp;&amp;... args) { elements().emplace_back(args...); return elements().back(); } virtual void remove(T&amp; toRemove) { _c.erase(std::remove(begin(_c), end(_c), toRemove), end(_c)); } template&lt;typename... K&gt; T&amp; operator()(const K&amp;... args) { auto it = std::find_if(begin(_c), end(_c), T::hasSame(args...)); if(it == _c.end()) throw "Name not found. Did you call has() ?"; return *it; } template&lt;typename... K&gt; std::vector&lt;std::reference_wrapper&lt;T&gt; &gt; getFamily(const K&amp;... args) { std::vector&lt;std::reference_wrapper&lt;T&gt; &gt; vect; auto cond = T::hasSame(args...); for(auto&amp; elt : _c) { if(cond(elt)) { vect.emplace_back(elt); } } return vect; } template&lt;typename... K&gt; bool has(K&amp;&amp;... args) const { return std::any_of(cbegin(_c), cend(_c), T::hasSame(args...)); } Container&lt;T&gt;&amp; elements() { return _c; } private: Container&lt;T&gt; _c; // Container ex. : std::vector&lt;T&gt; }; template &lt;typename T, template &lt;typename&gt; class Container = SimpleVec, class String = std::string&gt; typename Container&lt;T&gt;::iterator begin(Iterable&lt;T, Container, String&gt;&amp; i) { return begin(i._c); } template &lt;typename T, template &lt;typename&gt; class Container = SimpleVec, class String = std::string&gt; typename Container&lt;T&gt;::iterator end(Iterable&lt;T, Container, String&gt;&amp; i) { return end(i._c); } template &lt;typename T, template &lt;typename&gt; class Container = SimpleVec, class String = std::string&gt; typename Container&lt;T&gt;::iterator cbegin(const Iterable&lt;T, Container, String&gt;&amp; i) { return cbegin(i._c); } template &lt;typename T, template &lt;typename&gt; class Container = SimpleVec, class String = std::string&gt; typename Container&lt;T&gt;::iterator cend(const Iterable&lt;T, Container, String&gt;&amp; i) { return cend(i._c); } </code></pre> <p>It requires, as you can see in <code>performUniquenessCheck</code>, a <code>hasSame</code> method. What I did is a little macro trick to add properties to my classes, for simple properties, but I can also add it by hand if for instance I want a test using two elements.</p> <p>For instance, if you have </p> <pre><code>class A1 {  }; class A2 { }; class B { private: A1&amp; a1; A2&amp; a2; } </code></pre> <p>And there is a collection of B's which share common A1 &amp; A2 you can ask for all the B with a particular A1 or a particular A2.</p> <p>Here is the property macro:</p> <pre><code>#pragma once #include &lt;functional&gt; #define GenerateUniqueProperty(Property, Type) \ class has ## Property \ { \ public: \ has ## Property(Type val): \ _val(val) \ { } \ \ virtual ~has ## Property() = default;\ \ Type get ## Property() const \ { \ return _val; \ } \ \ void set ## Property(const Type&amp; val) \ { \ _val = val; \ } \ \ static std::function&lt;bool(const has ## Property&amp;)&gt; hasSame(const Type&amp; val) \ { \ return [&amp;val] (const has ## Property&amp; p) \ { \ return p._val == val; \ }; \ } \ \ private: \ Type _val; \ }; GenerateUniqueProperty(Name, std::string) GenerateUniqueProperty(Id, int) </code></pre> <p>So we can have our class which is to be contained : </p> <pre><code>#pragma once #include"../properties/hasId.h" #include"../properties/hasName.h" class SomeObject: public hasName, public hasId { public: using hasName::hasSame; using hasId::hasSame; SomeObject(std::string name, int id): hasName(name), hasId(id) { } ~SomeObject() = default; SomeObject(SomeObject&amp;&amp;) = default; SomeObject(const SomeObject&amp;) = default; SomeObject&amp; operator=(SomeObject&amp;&amp; g) = default; SomeObject&amp; operator=(const SomeObject&amp;) = default; bool operator==(const SomeObject&amp; g) const { return g.getId() == getId(); } bool operator!=(const SomeObject&amp; g) const { return g.getId() != getId(); } }; </code></pre> <p>And its custom container: </p> <pre><code>#pragma once #include "SomeObject.h" #include "../Iterable.h" class SomeObjectManager : public Iterable&lt;SomeObject&gt; { private: unsigned int _lastId = 0; public: SomeObject&amp; createSomeObject(std::string&amp;&amp; name) { performUniquenessCheck(std::forward&lt;std::string&gt;(name)); return create(name, _lastId++, SomeObjectChanged); } }; </code></pre> <p>So new we can do nice stuff like: </p> <pre><code>SomeObjectManager manager; manager.createSomeObject("Cool object"); manager.createSomeObject("Cooler object"); std::cerr &lt;&lt; manager("Cool object") == manager(1) &lt;&lt; std::endl; manager.remove(manager(1)); // Maybe here also it should do it by properties ? for(auto&amp; elt : manager) std::cerr &lt;&lt; elt.getName() &lt;&lt; std::endl; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:40:58.553", "Id": "83288", "Score": "1", "body": "`arbitrary-keyed map, that would require the key to be stored in the object` You mean like `std::set<T>` ?" } ]
[ { "body": "<blockquote>\n <p>[...]I decided that it would be fine to have something like an arbitrary-keyed\n map, that would require the key to be stored in the object (which allows to use \n the object's name as a key for instance).</p>\n</blockquote>\n\n<p>To restate your problem: you want the add behavior of a set (i.e., you add the object to the collection without any other information), but you want the retrieve behavior of a map (i.e., you retrieve the object by a key, not by a reference to that object). Additionally, from the code, it seems that you want to be able to retrieve an object by multiple keys (e.g., by both ID # and name), all of which then need to be unique.</p>\n\n<p>First, it's probably a bad idea to have objects being keyed in more than one way in the same container. It effectively means you have aliases for the same object, and that can get quite confusing to manage. It also means your lookups are pretty much stuck at \\$O(N)\\$ (instead of \\$O(log(N))\\$ or \\$O(1)\\$). Why? Because faster than \\$O(N)\\$ lookups require that the data either be sorted (so an \\$O(log(N))\\$ search can be used), or hashed (so that an \\$O(1)\\$ probe can be performed). Using your example, \"name\" and \"Id\" fields won't both be such that sorting one will cause the other to be sorted, nor will their hash values come out identically. Thus, retrieving items from the container degenerates to \\$O(N)\\$ when doing lookups using anything other than the primary key.</p>\n\n<blockquote class=\"spoiler\">\n <p> This isn't entirely true -- with one map, you could jury-rig a string key with namespaces, and in that manner have multiple keys without a slowdown of the map (although the hash calculation time might increase as the strings get longer). More reasonably, you could have one map per key. I have an aggregate_automap proof-of concept that takes this approach. It's templated, and it allows an arbitrary number of maps (each based on an automap translator) to be added to, removed from, and (by selecting a specific map from the group) searched in. However, it's too big and too ugly for me to, in good conscience, put up onto CR at the moment. Know that it -is- possible, if you absolutely need to look up objects using multiple keys... but try to only use multiple keys as an absolute last resort. :)</p>\n</blockquote>\n\n<p>What I would recommend is a wrapper around <code>unordered_set</code>, such that neither your class-to-be-contained nor your container have to be modified to deal with the special details of your auto-keying. I have an example of such a solution below, but due to the limitations of search speed (which I mentioned earlier), it does <em>not</em> implement multi-keying, nor does it implement your getFamily functionality. However, both of those pieces of functionality can be implemented in \\$O(N)\\$ time using iterator traversal logic similar to what you already have.</p>\n\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;unordered_map&gt;\n\n// A class that has data you want to construct automatic keys with.\n// This class can be any existing class you like. It does not need to be\n// modified to support auto-keying.\nclass MyClass\n{\npublic:\n MyClass(const std::string&amp; name, long long ssn) : m_name(name), m_ssn(ssn) {}\n const std::string&amp; getName() const { return m_name; }\n long long getSsn() const { return m_ssn; }\nprivate:\n std::string m_name;\n long long m_ssn;\n};\n\n// A general template that concrete AutomapTranslator classes can be based on.\ntemplate &lt;typename Key, typename Value, typename Hash = std::hash&lt;Key&gt;, typename EqualTo = std::equal_to&lt;Key&gt;&gt;\nclass AutomapTranslator\n{\npublic:\n // The type of object the keys will map to.\n typedef Value mapped_type;\n\n // The type of the key\n typedef const Key key_type;\n\n // Custom hash and equal_to functions, if your Key does not have these\n // provided by default.\n typedef Hash hash;\n typedef EqualTo equal_to;\n};\n\n// A class that implements the logic for automatically generating keys from\n// instances of a class.\n// You will need to implement at least one of these for each class you want to\n// auto-key. You might implement more than one of these for a single class, if\n// you want to have different ways of auto-keying the class (e.g., if you want\n// to be unique by SSN instead of name, or force both SSN and name into the\n// key, or have a key based on a long long instead of a string...)\nclass MyClassAutomapTranslator : public AutomapTranslator&lt;std::string, MyClass&gt;\n{\npublic:\n // For each constructor signature in mapped_type, you will need a\n // matching getKey function signature (for \"emplace\").\n static key_type getKey(const std::string&amp; name, long long ssn) { return name; }\n\n // At minimum, you will also need a getKey that converts an\n // arbitrary mapped_type to key_type.\n static key_type getKey(const mapped_type&amp; val) { return val.getName(); }\n\nprivate:\n};\n\n// An extension of unordered_map, with functions that allow a translator object\n// to auto-generate keys when inserting key-less values.\ntemplate &lt;typename T&gt;\nclass unordered_automap : \n public std::unordered_map&lt;\n typename T::key_type,\n typename T::mapped_type,\n typename T::hash,\n typename T::equal_to&gt;\n{\n // For convenience/brevity... :)\n typedef std::unordered_map&lt;\n typename T::key_type,\n typename T::mapped_type,\n typename T::hash,\n typename T::equal_to&gt; map_type;\npublic:\n template&lt;typename... Args&gt;\n std::pair&lt;typename map_type::iterator, bool&gt; autoemplace(Args&amp;&amp;... args)\n {\n return this-&gt;emplace(T::getKey(args...), args...);\n }\n\n template&lt;typename... Args&gt;\n typename map_type::iterator autoemplace_hint(typename map_type::const_iterator position, Args&amp;&amp;... args)\n {\n return this-&gt;emplace_hint(position, T::getKey(args...), args...);\n }\n\n std::pair&lt;typename map_type::iterator, bool&gt; autoinsert(const typename T::mapped_type&amp; val)\n {\n return this-&gt;insert(typename map_type::value_type (T::getKey(val), val));\n }\n\n typename map_type::iterator autoinsert(typename map_type::const_iterator hint, const typename T::mapped_type&amp; val)\n {\n return this-&gt;insert(hint, typename map_type::value_type(T::getKey(val), val));\n }\n\n // ... along with \"auto\" implementations for the rest of the insert operations ...\n};\n\nint main(int argc, char** argv)\n{\n unordered_automap&lt;MyClassAutomapTranslator&gt; demo;\n\n // Insertion is done by value only. The key is auto-generated, based on MyClassAutomapTranslator.\n demo.autoinsert(MyClass(\"Bob\", 123456789));\n demo.autoinsert(MyClass(\"Phil\", 987654321));\n demo.autoinsert(MyClass(\"Sue\", 121212120));\n demo.autoinsert(MyClass(\"Clara\", 212121210));\n\n // Find is done by key.\n std::cout &lt;&lt; \"Phil's SSN is: \" &lt;&lt; demo.find(\"Phil\")-&gt;second.getSsn() &lt;&lt; std::endl;\n\n // Remove is done by key.\n demo.erase(\"Phil\");\n\n // Iteration is as normal.\n for(auto&amp; elt : demo) std::cout &lt;&lt; elt.second.getName() &lt;&lt; \": \" &lt;&lt; elt.second.getSsn() &lt;&lt; std::endl;\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>The above code compiles with <code>g++ -Wall -pedantic -std=c++11</code> and generates no warnings. IMO, it's a lot easier to read and re-use, especially because there is no macro-magic involved, and because the per-class automapping logic is locked away in a single place.</p>\n\n<p>If you insist on/must continue to use the solution you have outlined in your original question...</p>\n\n<ul>\n<li>In the case where an exception occurs because of a (duplicate, not found, etc.) key/item, you should convert the conflicting item(s) into string representations, and include them at the end of the message string. It tends to be very helpful, when debugging a crash, to be able to see which dynamic values caused the fault. In your case, it would also be helpful to know which specific -mapping- the fault was in (e.g., was it Id or Name that collided?), so consider including that in your error message as well.</li>\n<li>Don't allow <code>Iterable&lt;T&gt;::create(K&amp;&amp;...)</code> to bypass the uniqueness check, or you could wind up with two items in the collection with the same key. If items need to be unique, then <code>Iterable&lt;T&gt;</code> should ensure that constraint, not an external wrapper. </li>\n<li>Comment the functions, especially with regard to the template parameter packs. It's unclear, e.g., how <code>manager(\"Cool Object\", \"Cooler Object\")</code> is supposed to behave, vs. <code>manager.getFamily(\"Cool Object\", \"Cooler Object\")</code>, without a very detailed reading of the code. Even then, that just tells the reader the as-implemented behavior, not the actual intended behavior.</li>\n<li>At the very least, put the macro-generated classes in their own namespace. The \"is-a\" inheritance relationship you're currently using runs contrary to the \"has-a\" naming convention you're using, and the multiple-inheritance conflicts will likely make for misery and mistakes down the line. As such, I personally would consider removing these little \"classlets\" completely, and instead have the macros directly inject the required code into the consuming classes.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T00:55:36.940", "Id": "83316", "Score": "7", "body": "Welcome to Code Review. This is a really, really comprehensive first answer ... you passed the 'first post' review with flying colours. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:09:49.353", "Id": "83363", "Score": "0", "body": "Thanks for the thorought answer ! I will try to see how I can make good use for it. However in my case (explicitely, I understand this does not apply to everyone), I only work with < 100 elements, hence lookup speed is of no concern with regard to ease of use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T10:14:01.573", "Id": "83370", "Score": "0", "body": "Travis: when you say : \"Throw the (duplicate, not found, etc.) key/item in your exceptions. It will make everyone's life a bit easier.\"\n\nHow can I throw at the same time an error message and an item ? Should I make an exception object which bundles both ? (or the message can be the type of the exception).\n\nthanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T17:27:11.110", "Id": "83413", "Score": "1", "body": "@Jean-MichaëlCelerier - short answer: any diagnostic information needs to be encoded in the exception's \"what\" string. I'm not up-to-date on the best practices there, but I presume throwing a real exception (e.g., \"throw new std::range_exception(msg);\") is preferred to throwing a bare string, and you can use an sstream to write important info (like the colliding key and attendant values of the existing/colliding objects) to a dynamic message string." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T00:22:01.850", "Id": "47525", "ParentId": "47491", "Score": "12" } } ]
{ "AcceptedAnswerId": "47525", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:27:46.340", "Id": "47491", "Score": "10", "Tags": [ "c++", "c++11", "template", "collections", "container" ], "Title": "Is my C++11 generic container a good design?" }
47491
<p>I have a project that I've been trying to get just right for the past three months and it's still not quite there yet.</p> <p>I'm injecting some jQuery and jQueryUI code into pages that I have no control over and I need to be able to "sandbox" my code away from anything that may or may not be there at DOM-ready, or at anytime there after...</p> <p>I think I've got it, but I know there's <strong><em>most likely</em></strong> some edge cases and race conditions that I'm missing. Please fork this and tell me what I've missed. I'm tired of spinning my wheels on <a href="http://plnkr.co/edit/iWJWLrpH4RpQwQUL0bYe?p=preview" rel="nofollow">this issue</a>.</p> <p><strong>Markup:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="style.css" /&gt; &lt;link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" /&gt; &lt;script type="text/javascript" src="//www.litmos.com/wp-includes/js/jquery/jquery.js?ver=1.11.0"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Loading multiple versions of jQuery!&lt;/h1&gt; &lt;script type="text/javascript"&gt; ;(function($){ var $h2 = $('&lt;h2&gt;').append('Original jQuery: ' + $.fn.jquery + ' | Original ui: ' + $.ui.version); document.write($h2[0].outerHTML); })(jQuery); &lt;/script&gt; &lt;div&gt;Some other html&lt;/div&gt; &lt;!--// Code that is being "injected into the page" //--&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; ;(function($){ window.myJQuery = jQuery.noConflict(true); })(jQuery); &lt;/script&gt; &lt;script src="jquery-ui.js"&gt;&lt;/script&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;!--// End injection code //--&gt; &lt;script type="text/javascript"&gt; ;(function($){ var $h2 = $('&lt;h2&gt;').append('Original jQuery: ' + $.fn.jquery + ' | Original ui: ' + $.ui.version + ' | After namespacing'); document.write($h2[0].outerHTML); window.setTimeout(function(){ $('h2').not('.namespaced') .addClass('not-namespaced') .hide() .draggable() .toggle( "highlight" ); }, 2000); })(jQuery); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>JavaScript:</strong></p> <pre><code>;(function($, jQuery){ var $h2 = $('&lt;h2 class="namespaced"&gt;').append('Namespaced $: ' + $.fn.jquery + ' | $.ui: ' + $.ui.version); document.write($h2[0].outerHTML); var $jh2 = $('&lt;h2 class="namespaced"&gt;').append('Namespaced jQuery: ' + jQuery.fn.jquery + ' | jQuery.ui: ' + jQuery.ui.version); document.write($jh2[0].outerHTML); //Verify that jQueryUi works on OUR version of jQuery: $(document).ready(function(){ console.log($('h2.namespaced').draggable()); }); })(myJQuery, myJQuery); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T17:39:57.650", "Id": "83249", "Score": "0", "body": "Is the last line of your javascript intentional? `})(myJQuery, myJQuery);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:04:49.983", "Id": "83255", "Score": "0", "body": "@megawac, yes. myJQuery is the name-spaced jQuery. w/o it, the code would not do what it's intended to do, namespace jQuery." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:23:20.857", "Id": "83258", "Score": "0", "body": "@RavenHursT I meant calling with redundant `myJQuery` arguments" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:08:40.790", "Id": "83264", "Score": "0", "body": "@megawac, ah.. I'm wanting to ensure that _both_ the `$` and `jQuery` objects are being \"sandboxed\" just in case any plugins used in the future reference one or the other.\n\nAs for \"redundant\", is there a better way to ensure that both the `$` and `jQuery` params are passed into the anonymous function wrapper as `myJQuery`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:16:41.927", "Id": "83285", "Score": "0", "body": "I'm just suggesting that you proabbly meant `})(jQuery, myJQuery)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T21:44:14.073", "Id": "83294", "Score": "0", "body": "But then wouldn't anything in my \"sandboxed\" code then be accessing the \"parent\" `$` and not `myJQuery`? I want anything in the \"sandbox\" to reference _my_ version of jQuery, whether it's using `$` or `jQuery` as the reference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T13:59:17.897", "Id": "83935", "Score": "0", "body": "@RavenHursT in my my mind, you should pass `})(jQuery)`, then inside your function you do `var $ = jQuery`. Passing knowingly the same object twice is kind of silly ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T15:06:44.097", "Id": "83956", "Score": "0", "body": "Hmmm.. That's a good idea konijn" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-07T21:51:58.023", "Id": "175575", "Score": "0", "body": "So this has been in production for over a quarter now and seems to be working w/o fail. I'm pretty confident now in the original code and would recommend this method to anyone looking to \"sandbox\" jQuery for code that they may be injecting into a page that they don't control :-)" } ]
[ { "body": "<p>As far as experience goes, what my team does is to actually <strong>agree on a single version of a library and <em>stick to it</em></strong> for the entire production release. That way, each developer will not encounter bugs due to differences. We then talk about upgrades in a meeting to agree on the next version to support, then test the switch for any bugs that old code might generate.</p>\n\n<p>I think this isn't a code issue. This is a management issue, and you should talk this over with your team. </p>\n\n<p>Also, if my <a href=\"http://semver.org/\" rel=\"nofollow\">semantic versioning</a> isn't that rusty, changes on the third number in a version are bugfixes. jQuery <code>1.10.x</code> versions should have no big changes and you should have no reason to actually use multiple versions. You can a single <code>1.10.x</code> instead, preferably the latest.</p>\n\n<p>As for sandboxing your code, an IIFE should suffice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T15:57:13.597", "Id": "83405", "Score": "5", "body": "This is a widget that is being injected into pages outside if my organization. I can't manage other organizations' libraries." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T15:20:05.293", "Id": "47583", "ParentId": "47494", "Score": "2" } }, { "body": "<p>I've worked for a media company where ads had to run with their own version of JavaScript libraries, in the end we preferred to let ads run in their own iframe. Especially since some ads required access to <code>document.write</code> which creates havoc to your content ;)</p>\n\n<p>It is a bit scary that your solution has to modify <em>jquery-ui.js</em>, I would be very (very) hesitant to do that. I also dont understand why you employ <code>})(myJQuery, myJQuery);</code> there, since you know you only need 1 of the parameters to initialize jQuery UI.</p>\n\n<p>The worst part is that I played around a bit with a fork and I could not get to a superior solution easily, so if this works for you, then perhaps you should stop researching and just go forth ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T13:57:42.630", "Id": "47783", "ParentId": "47494", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:08:11.623", "Id": "47494", "Score": "11", "Tags": [ "javascript", "jquery", "jquery-ui", "namespaces" ], "Title": "Namespacing jQuery/jQueryUi into markup that I don't control" }
47494
<p>So, I thought I'd do this using scipy.constants:</p> <pre><code>import numpy as np from scipy.constants import physical_constants constants = np.array([(k,)+v+(v[2]/abs(v[0]),) for k,v in physical_constants.items()], dtype=[('name', 'S50'), ('val', 'f8'), ('units', 'S10'), ('abs_unc', 'f8'), ('rel_unc', 'f8')]) constants.sort(order='rel_unc') print(constants[constants['rel_unc'] &gt; 0][['name', 'rel_unc']][-10:]) </code></pre> <p>I was reasonably pleased to be using a structured array, but it all seems a bit... obscure and unpythonic. Any suggestions?</p> <p>OK... so first thing I've realised: the boolean test for constants with relative uncertainties > 0 is not necessary if I want the largest 10 values (which are all non-negative), so I can ditch that. And a few comments wouldn't go amiss:</p> <pre><code>import numpy as np from scipy.constants import physical_constants # Create a structured array with fields for each constant's name, value, units, # absolute uncertainty and relative uncertainty. The first of these is the key # in the physical_constants dictionary; the next three are stored in a tuple # as the corresponding value. Calculate the final field entry, the relative # uncertainty from the absolute uncertainty and the absolute value of the # constant. constants = np.array([(k,)+v+(v[2]/abs(v[0]),) for k,v in physical_constants.items()], dtype=[('name', 'S50'), ('val', 'f8'), ('units', 'S10'), ('abs_unc', 'f8'), ('rel_unc', 'f8')]) constants.sort(order='rel_unc') print(constants[['name', 'rel_unc']][-10:]) </code></pre> <p>However, pace Jeff Gohlke's comment, I'm reluctant to split up the list comprehension (which I think is a nice feature of Python). And something like</p> <pre><code>make_record = lambda k, v: (k,)+v+(v[2]/abs(v[0]),) constants = np.array([make_record(k,v) for k,v in physical_constants.items()], dtype=[('name', 'S50'), ('val', 'f8'), ('units', 'S10'), ('abs_unc', 'f8'), ('rel_unc', 'f8')]) </code></pre> <p>is really the worst of both worlds. How to maintain readability without, e.g. using temporary arrays?</p>
[]
[ { "body": "<p>I think the biggest problem here is that you're trying to do too much in a single line. It seems obscure because it <em>is</em> obscure. If I were looking at this outside of a Code Review setting, I would think that someone had purposefully obfuscated it or condensed it for some character count restriction.</p>\n\n<p>Consider breaking apart your lines in order to make your code more legible. Whoever looks over or has to maintain your code in the future (even if it's just you) will be incredibly grateful for it.</p>\n\n<p>I was going to try and break this down into a legitimate block of code, but I have absolutely no idea what your various variables are supposed to represent. What does the <code>v</code> list hold (e.g., what is <code>v[0]</code>? what is <code>v[2]</code>?). But let's take your last line of code, which is at least somewhat comprehensible:</p>\n\n<pre><code>print(constants[constants['rel_unc'] &gt; 0][['name', 'rel_unc']][-10:])\n</code></pre>\n\n<p>You're doing like four things here. You're comparing to produce a <code>bool</code>, extracting an element of a list, performing a <code>string</code> slice operation, and printing a value. Again, it <em>seems</em> obscure because it <em>is</em> obscure.</p>\n\n<p>I can't even begin to trace out what you're trying to do in your first line of code, unfortunately, or I would.</p>\n\n<p>I have a story which demonstrates the point. On one of my more recent projects at work, a contractor had produced some code with several nested ternary conditions. It looked something like this, in one line of JavaScript:</p>\n\n<pre><code>var_1 ? long_complex_variable_1 : var_2 ? long_complex_variable_2 : \n var_3 === var_4 ? (var_5 ? long_complex_variable_3 : long_complex_variable_4) :\n long_complex_variable_5\n</code></pre>\n\n<p>It took me awhile to figure out exactly what he was trying to accomplish. When I asked him about it later, he said he thought he was being very clever and doing something good for the code by being \"short and succinct\".</p>\n\n<p>But it's not clever, and it's far from helpful. It's just frustrating for the people who have to maintain your code later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:13:59.170", "Id": "83267", "Score": "0", "body": "I appreciate your comments - and I've added some comments to the code and a couple more thoughts on this. I'm reluctant to break from the single-line array construction unless there's a way to do it without an intermediate array, though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:00:06.470", "Id": "47505", "ParentId": "47496", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:30:12.400", "Id": "47496", "Score": "6", "Tags": [ "python", "python-3.x", "numpy" ], "Title": "Determining the least-accurately known physical constants" }
47496
<p>To get an idea of what the controller code reflects, here is a screenshot:</p> <p><img src="https://i.stack.imgur.com/fMeVE.png" alt="enter image description here"></p> <p>Basically, the idea is that you print out a list of football players which you can then filter by their name, price, field position, and team. I'm not sure whether it's better to handle all the scope logic within a single controller, or break it down into separate controllers, isolating the filters from the player list, pagination, and so on. I'm currently going with the single controller approach, and here's what I have:</p> <pre><code>app.controller('playersController', function($scope, $filter, minMax, buildOptions, PlayersModel, TeamsModel, CommonValues){ $scope.basehref = CommonValues.getBaseHref(); $scope.imgbase = CommonValues.getImgBase(); $scope.players = PlayersModel; $scope.teams = TeamsModel; $scope.predicate = 'team.name'; $scope.minMax = minMax($scope.players); $scope.filters = { // filter model searchString: '', // string input from user selectedTeam: {}, // selected team selectedTeamMs: [], // selected teams from multiselect roles: { 1: true, // forward 2: true, // defense 3: true, // midfield 4: true // goalie }, slider: { // set up boundaries for slider filter min: $scope.minMax[0], max: $scope.minMax[1], step: 10000 }, pagination: { // set up pagination totalItems: $scope.players.length, currentPage: 1, maxSize: 5, pages: buildPages() } }; var cache = $scope.players; // save original player model for later use /********** * Watchers **********/ // watch for filter model changes, start filtering $scope.$watch('filters', function(newVal, oldVal){ if (newVal !== oldVal || newVal.id !== oldVal.id || newVal.length !== oldVal.length) { var result; result = $filter('textFilter')(cache, $scope.filters); // filter by phrase result = $filter('roleFilter')(result, $scope.filters); // filter by field position result = $filter('teamFilter')(result, $scope.filters.selectedTeamMs); // filter by team $scope.players = result; } }, true); /*********** * Scope API ***********/ // pagination logic $scope.changePage = function(newVal, oldVal) { var maxSize = $scope.filters.pagination.maxSize; var offset = maxSize * oldVal; var result = []; if (newVal &lt; oldVal) offset = (maxSize * newVal) - maxSize; for (var i = 0; i &lt; cache.length; i++) { if (i &gt;= offset) result.push(cache[i]); } $scope.players = result; }; /**************** * Helper methods ****************/ function buildPages() { return null; } }); </code></pre> <p>Is it ok to encapsulate all the logic into that one controller, including helper methods, and so on, or should I refactor?</p>
[]
[ { "body": "<p>First of all, for a better user experience, I would avoid pagination in favour of infinite scroll. <a href=\"http://jsbin.com/zusal/2/edit\" rel=\"nofollow\">Here is a simple Angular infinite scroll implementation</a></p>\n\n<p>I presume you are aware of minification-proof technique <code>.controller('name', ['$scope', function($scope){}]</code>, so won't go into that.</p>\n\n<p>Next, I see many fields like <code>$scope.players</code>, <code>$scope.teams</code>, ..., mixed with <code>$scope.filters</code>, which can lead to namespace conflicts as the app grows. Hence I would gather all data-related fields into one object like <code>$scope.data</code>. Then you can simply pass the whole object from your service instead of assigning one-by-one.</p>\n\n<p>The hard-coded declation <code>$scope.predicate = 'team.name';</code> is mixed with others provided by the service. Perhaps it belongs to a Config service together with other hard-coded properties.</p>\n\n<p>Also I presume you are aware of the difference between using <code>$scope.field</code> vs <code>$scope.field.subfield</code> in terms of their interactions with parent and child scopes.</p>\n\n<p>EDIT. \nUnless you know what you are doing, a recommended practice is to use <code>$scope.field.subfield</code>. That way, in a child controller, you have both read and write access to it. If instead you use <code>$scope.field</code>, then changing it from a child controller will add a variable on the local scope but won't change the parent scope as you likely intend, <a href=\"http://jsbin.com/sibud/2/edit\" rel=\"nofollow\">see here</a>.</p>\n\n<p>EDIT.\nSee also <a href=\"http://www.youtube.com/watch?v=ZhfUv0spHCY&amp;feature=youtu.be&amp;t=30m\" rel=\"nofollow\">Misko's video on best practices</a>, including putting the dot inside your <code>$scope</code> property.</p>\n\n<p><code>minMax($scope.players);</code> suggests that you are using service <code>minMax</code> just for one function. I would gather those functions into one bigger service like <code>Utils</code>. You already have lots of dependencies for your controller, so lowering that number can be a good thing. Similar for <code>$scope.teams = TeamsModel;</code>.</p>\n\n<p>I am not sure why you define filters inside a controller, rather than with <code>.filter</code> as common. </p>\n\n<p>Usually filters declared via <code>.filter</code> update themselves, so no need for watchers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T09:02:08.223", "Id": "83508", "Score": "0", "body": "1. How can $scope.xy lead to namespace conflicts, when the scope is bound to the current controller? 2. Why encapsulate all data into one service? I'll need each service individually in other controllers, and passing around both as one seems like a waste. 3. How can those filters be defined, when the code correctly executes filters that are passed with the $filter provider and are defined elswhere? 4. How can a filter update itself, when I don't watch for either model changes in the controller, or in the template?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T09:18:42.100", "Id": "83510", "Score": "0", "body": "As a follow up, the pagination is in place out of performance constrains of older devices, like the original iPad, whose responsiveness gets worse as you add DOM nodes. The desktop version will use the infinite scroll as you suggest. And can you elaborate on the $scope.field vs $scope.field.subfield issue?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T10:07:10.837", "Id": "83512", "Score": "0", "body": "1. Namespace conflict will occur in the same controller as it grows. 2. You don't need each service, you need the API service provides. 3. Filters are meant to be used inside HTML. Otherwise the shouldn't be called filters to avoid confusion. 4. If I see it right, you are trying to implement filter's functionality by hand in your controller, whereas the Angular way is to define it in you `.filter()` block and use inside HTML." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T10:34:47.143", "Id": "83513", "Score": "1", "body": "If performance is an issue, you can only keep the visible part and slightly above and below inside the DOM. I find infinite scrolling even more convenient on a device, where scroll is so much easier than navigating the tiny page buttons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T13:19:38.403", "Id": "83928", "Score": "1", "body": "Here is also great explanation why not to use primitives on `$scope`: http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T16:37:20.077", "Id": "83998", "Score": "0", "body": "One more question that ties in with refactoring code out of the controller - I now have a" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T16:44:39.387", "Id": "84000", "Score": "1", "body": "Yes, everything except directly glueing your models to views is generally advised to take out of controller. All configs, filters, helpers... Also you can use `angular.equals` to compare objects in your watcher (but then again, using Angular filters would remove the need for the watcher here in first place)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T16:52:11.397", "Id": "84001", "Score": "0", "body": "So the controller just serves the scope and calls service APIs? I got two separate data models defined as services, but need to manipulate both at one point. Is it advised to directly manipulate one service from the other, or delegate the communication into the controller? E.g. one model are the players, the other one is the playing field, and adding a player to the field should update the playing field layout, as well as flagging the player as added." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T17:03:43.117", "Id": "84004", "Score": "0", "body": "Anyway, sorry for bugging you more with this, I'll take your advice to heart and start refactoring stuff out of the controller." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T17:08:04.600", "Id": "84005", "Score": "1", "body": "Exactly, here is a great article on precisely that: http://blog.safaribooksonline.com/2014/04/08/refactoring-angularjs-get-hands-filthy/. Your data services provide the API to manipulate the data, used from controller. Controller can send raw data to the model service like `field.addPlayer(player)`, which can in turn update the player." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T07:16:52.440", "Id": "47633", "ParentId": "47499", "Score": "2" } } ]
{ "AcceptedAnswerId": "47633", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T16:47:12.940", "Id": "47499", "Score": "4", "Tags": [ "javascript", "angular.js" ], "Title": "Controller structure for a browser game module with filters and pagination" }
47499
<p>Last week I asked to review my "Guess a number" game in Java <a href="https://codereview.stackexchange.com/questions/47028/guess-a-number-game-in-java">here</a></p> <p>I learned so much that I decided to try a little harder game and put into practice all the amazing feedback I received there. Would you please review and give me some feedback?</p> <p>My main concern is if i'm doing ok using so many methods instead of a big block of code in the main function. I've found it was nice to create several methods in the previous project, but here it was difficult. Perhaps I'm having a serious design issue?</p> <p>If the game looks fine, what would be the next simple game challenge I should attempt? Is it a good idea to try to port this to swing? Or would be better to port it to a web application? or android? I want to keep learning while challenging myself to something new. I know I need to learn how to handle exceptions better or how to cast / downcast into subclasses (where can I learn this or how can I practice this in a project? a card game?)</p> <p>I'm new to GitHub, but I created my second repository today to upload this code, perhaps its easier to look at the code <a href="https://github.com/facundop/HangmanGame/blob/master/src/game/HangmanGame.java" rel="nofollow noreferrer">here</a></p> <p>This is the main class:</p> <pre><code>package game; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class HangmanGame { private Scanner input; private String playerName; private String wordToGuess; private boolean gameIsRunning; private int lives; private char letter; private Set&lt;Character&gt; lettersToGuess; private Set&lt;Character&gt; lettersGuessed; private Set&lt;Character&gt; lettersWrong; public static void main(String[] args) { HangmanGame game = new HangmanGame(); game.run(); } private void run() { input = new Scanner(System.in); playerName = getPlayerName(input); wordToGuess = getRandomWordToGuess(); gameIsRunning = true; lives = 5; lettersToGuess = new HashSet&lt;Character&gt;(); lettersGuessed = new HashSet&lt;Character&gt;(); lettersWrong = new HashSet&lt;Character&gt;(); fillLettersToGuess(); // Put first and last letter into lettersGuessed set. lettersGuessed.add(wordToGuess.charAt(0)); lettersGuessed.add(wordToGuess.charAt(wordToGuess.length() - 1)); System.out.println("I've picked a word for you to guess."); while (gameIsRunning) { showHangmanState(); showWordToGuess(wordToGuess, lettersGuessed); System.out.println(playerName + ", guess a letter!"); showWrongLetters(); pickLetter(); if (isLetterInWord(letter, lettersToGuess)) { addLetterToLettersGuessed(letter, lettersGuessed); } else { wrongLetter(letter, lettersWrong); lifeLost(); System.out.println("Your letter is not in the word."); System.out.println("Lives remaining: " + lives); } showWordToGuess(wordToGuess, lettersGuessed); if (isGameOver()) { gameIsRunning = false; System.out.println("You " + ((lives == 0) ? "lost!" : "won!")); } } input.close(); } /* * Method to ask for the player's name */ private String getPlayerName(Scanner keyboard) { System.out.println("Hi there! What's your name?"); String playerName = keyboard.nextLine().trim(); System.out.println("Hi " + playerName + ", let's play!"); return playerName; } /* * Returns a random word to guess and play. */ private String getRandomWordToGuess() { // Load a word from dictionary. To do: Implement a dictionary String[] wordList = { "hello", "test", "elephant", "car", "table", "stack", "help", "someone", "yellow", "purple" }; int min = 0; int max = wordList.length - 1; int wordToGuessPosition = getRandomNumber(min, max); return wordList[wordToGuessPosition]; } /* * Returns a random number. To do: Move it to a helper class. */ private int getRandomNumber(int min, int max) { return min + (int) (Math.random() * ((max - min) + 1)); } /* * Shows the word to guess. */ private void showWordToGuess(String wordToGuess, Set&lt;Character&gt; lettersGuessed) { for (int i = 0; i &lt; wordToGuess.length(); i++) { // Checks lettersGuessed to know what to reveal to the user if (lettersGuessed.contains(wordToGuess.charAt(i))) { System.out.print(wordToGuess.charAt(i)); } else { System.out.print("*"); } } // Hardcoded newline. Is there any fancier way to do this? System.out.println(); } /* * Checks if the letter guessed is in the lettersToGuess. */ private boolean isLetterInWord(char letter, Set&lt;Character&gt; lettersToGuess) { return lettersToGuess.contains(letter); } /* * Adds the guessed letter to the set that contains the guessed letters. */ private void addLetterToLettersGuessed(char letter, Set&lt;Character&gt; lettersGuessed) { lettersGuessed.add(letter); } /* * Adds the wrong letter to the set that contains wrong letters. */ private void wrongLetter(char letter, Set&lt;Character&gt; lettersWrong) { lettersWrong.add(letter); } /* * We lose 1 life per wrong letter. We will use this method to handle the * draw to display. */ private void lifeLost() { lives--; } /* * Fills lettersToGuess from wordToGuess */ private void fillLettersToGuess() { for (Character c : wordToGuess.toCharArray()) { lettersToGuess.add(c); } } /* * Show Hangman state. To do: draw hangman in his 5 stages. */ private void showHangmanState() { System.out.println("+++++++++++++++++++++++++++++++++"); System.out.println("+++++Hangman draw goes here.+++++"); System.out.println("+++++Hangman draw goes here.+++++"); System.out.println("+++++Hangman draw goes here.+++++"); System.out.println("+++++Hangman draw goes here.+++++"); System.out.println("+++++++++++++++++++++++++++++++++"); System.out.println("Word to guess:"); } /* * We check if the game is over (win or lose) */ private boolean isGameOver() { return ((lives == 0) || (lettersGuessed.size() == lettersToGuess.size())); } /* * Show wrong letters (if any) */ private void showWrongLetters() { if (lettersWrong.size() &gt; 0) { System.out.print("Wrong letters: "); for (Character c : lettersWrong) { System.out.print(c + " "); } System.out.println(); } } /* * Ask the user to type a letter and verify if it isn't in the game already */ private void pickLetter() { do { letter = input.nextLine().trim().toLowerCase().charAt(0); if (lettersWrong.contains(letter) || lettersGuessed.contains(letter)) { System.out.println("The letter " + letter + " is already in the game!."); System.out.println(playerName + ", guess a new letter!"); } } while (lettersWrong.contains(letter) || lettersGuessed.contains(letter)); } } </code></pre>
[]
[ { "body": "<p>Nice improvement from the initial version. Good job! Here are a couple of brief notes.</p>\n\n<ol>\n<li>I'm very wary of having any method named <code>run()</code> outside of classes which implement the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html\" rel=\"nofollow\"><code>Runnable</code> interface</a>. This isn't something you'd know about as a beginner, but basically <code>run()</code> has a very specific connotation which regards using multiple threads. I might rename this method to <code>play()</code> or something of the sort.</li>\n<li>It looks like you have a lot of functionality tacked on that is just needless overhead. For example, you have a method <code>addLetterToLettersGuessed()</code> which only has one line of code: <code>lettersGuessed.add(letter)</code>. There's no need for you to have a wrapper method here. The name of your variable and the method you invoke from it state what you're doing very succinctly. Because you've chosen your variable names well, the code is somewhat self-documenting. Over-architecting your solution can be as big of a problem as having all of your code just slapped in the <code>main()</code> method. (This comment applies to a chunk of your methods below <code>showWordToGuess()</code>).</li>\n<li>If you're going to have big block comments over every method, consider formatting them with <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#format\" rel=\"nofollow\">JavaDoc</a>. It's never too early to learn how to properly document your code.</li>\n</ol>\n\n<p>To address your specific questions:</p>\n\n<blockquote>\n <p>Is it a good idea to try to port this to swing? Or would be better to port it to a web application? or android?</p>\n</blockquote>\n\n<p>You should definitely go with Swing before trying to integrate Java code into a web-app. If you're interested in making Android apps, though, you can download the Android SDK and start toying around with that API. I'm sure there are tutorials out there for that. Setting up your environment might be a pain, though (your programs have to run in an emulator or be deployed to an actual phone).</p>\n\n<blockquote>\n <p>I know I need to learn how to handle exceptions better or how to cast / downcast into subclasses (where can I learn this or how can I practice this in a project? a card game?)</p>\n</blockquote>\n\n<p>Casting is actually a kind of \"all else failed\" tactic in Java programming. Ideally, you should never have to explicitly cast anything. I think you're referring to the concept of <a href=\"http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html\" rel=\"nofollow\">polymorphism</a> rather than just casting. A good way to learn about polymorphism is with some game or project involving different kinds of animals. You would have an abstract class or interface named <code>Animal</code>, and below this you might have mammals and birds and all sorts of things. Turns out the world of biology is naturally suited towards hierarchy.</p>\n\n<p>Exceptions you learn naturally when you start actually trying to deal with errors rather than allowing your application to crash when it doesn't go down the \"happy path\". I think most beginners first experience this when they're trying to get a user to input integers and they have to deal with a user maliciously typing in <code>sdfksdjf</code>. As you try to make your applications more robust, Exception-handling skills will develop.</p>\n\n<hr>\n\n<h1>For your next iteration...</h1>\n\n<p>I challenge you to do some file handling! Download <a href=\"https://raw.githubusercontent.com/holoiii/Hangman-Game-Demo/master/wordlist.txt\" rel=\"nofollow\">this file</a> to your workspace and figure out how to read the words into your program and have it \"think up\" a random word from it. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:51:12.653", "Id": "83428", "Score": "0", "body": "Thank you! I improved the game and removed almost 50 lines of code, already updated it in GitHub. I've been trying to do your challenge, but I'm having issues to \"think up\" a VALID word. Any suggestion?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:39:45.363", "Id": "83441", "Score": "0", "body": "@facundop What do you mean? All the words on that list should be valid Hangman words." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T16:14:57.893", "Id": "83524", "Score": "0", "body": "I thought you asked me to think up a new word! I believe I've done it right, should I open a new thread here? The code is [here](https://github.com/facundop/RandomWord/blob/master/src/app/RandomWord.java) !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T21:24:38.413", "Id": "83571", "Score": "0", "body": "@facundop Post it in a new question. :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:08:17.817", "Id": "47506", "ParentId": "47504", "Score": "10" } }, { "body": "<p>Just a nitpick on your random word choice routine, which is:</p>\n\n<blockquote>\n<pre><code>/*\n * Returns a random word to guess and play.\n */\nprivate String getRandomWordToGuess() {\n // Load a word from dictionary. To do: Implement a dictionary\n String[] wordList = { \"hello\", \"test\", \"elephant\", \"car\", \"table\",\n \"stack\", \"help\", \"someone\", \"yellow\", \"purple\" };\n int min = 0;\n int max = wordList.length - 1;\n int wordToGuessPosition = getRandomNumber(min, max);\n return wordList[wordToGuessPosition];\n}\n\n/*\n * Returns a random number. To do: Move it to a helper class.\n */\nprivate int getRandomNumber(int min, int max) {\n return min + (int) (Math.random() * ((max - min) + 1));\n}\n</code></pre>\n</blockquote>\n\n<p>Subtracting 1 to obtain <code>max</code>, then adding 1 in <code>getRandomNumber()</code> is awkward. I suggest that you embrace the concept of inclusive-exclusive ranges. Consider:</p>\n\n<ul>\n<li>In <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring%28int,%20int%29\"><code>String.substring(beginIndex, endIndex)</code></a>, <code>endIndex</code> is just past the last character of the string you want to extract.</li>\n<li>In <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort%28int%5B%5D,%20int,%20int%29\"><code>Arrays.sort(a, fromIndex, toIndex)</code></a>, <code>toIndex</code> is just past the last element of that you want to sort.</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random%28%29\"><code>Math.random()</code></a> produces results such that 0 ≤ result &lt; 1.</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29\"><code>Random.nextInt(n)</code></a> produces an integer strictly less than <em>n</em>.</li>\n</ul>\n\n<p>With that in mind, I'd prefer:</p>\n\n<pre><code>private int getRandomNumber(int lbIncl, int ubExcl) {\n return lbIncl + (int)(Math.random() * (ubExcl - lbIncl));\n}\n</code></pre>\n\n<p>But better still, I'd decompose the problem differently. <code>Random.nextInt()</code> is a better way to accomplish <code>getRandomNumber()</code>. Your real goal is to uniformly sample an array. Furthermore, as you noted in your to-do comment, you want to be able to use a proper word list. By the Single-Responsibility Principle, producing the word list and picking a word from the list should be separate functions. Therefore, I suggest a function:</p>\n\n<pre><code>/**\n * Uniformly sample one element from the pool.\n */\nprivate static &lt;T&gt; T randomElement(T[] pool) {\n int i = (new Random()).nextInt(pool.length);\n return pool[i];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:28:59.937", "Id": "83423", "Score": "0", "body": "Thank you! I had no idea of anything you said, but after some research it makes sense. Thank you for the tips!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:08:23.960", "Id": "47510", "ParentId": "47504", "Score": "6" } } ]
{ "AcceptedAnswerId": "47506", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T17:52:56.100", "Id": "47504", "Score": "10", "Tags": [ "java", "game", "hangman" ], "Title": "\"Hangman\" game follow-on" }
47504
<p>So knowing the little pieces is something different and putting them together is something different. </p> <p>Here is the code where I try to follow good oop practices and 3 - layered structure. </p> <p>Any review is greatly appreciated: </p> <p>The form is located at <strong>registirationform.jsp</strong>.</p> <p>The view layer: </p> <pre><code>public class RegistirationServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { httpServletRequest.setCharacterEncoding("utf-8"); httpServletResponse.setContentType("text/html;charset=utf-8"); try { UserRegistirationService userRegistirationService = new UserRegistirationService(new AppUserAccessObject(new DatabaseConnectionImpl())); String username = httpServletRequest.getParameter("username"); String password = httpServletRequest.getParameter("password"); String email = httpServletRequest.getParameter("email"); if(username.equals("") || password.equals("") || email.equals("")){ List&lt;String&gt; errors = new ArrayList&lt;String&gt;(); errors.add("Can you make sure you fill all the fields?"); httpServletRequest.setAttribute("errors",errors); if(!username.equals("")){ httpServletRequest.setAttribute("username",username); } if(!email.equals("")){ httpServletRequest.setAttribute("email",email); } httpServletRequest.getRequestDispatcher("/registirationform.jsp").forward(httpServletRequest, httpServletResponse); } else { userRegistirationService.registerAppUser(username, password, email); } } catch (SQLException e) { e.printStackTrace(); List&lt;String&gt; errors = new ArrayList&lt;String&gt;(); errors.add("Registiration was not successful. Maybe username/email was already taken?"); httpServletRequest.setAttribute("errors",errors); httpServletRequest.getRequestDispatcher("/registirationform.jsp").forward(httpServletRequest, httpServletResponse); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } </code></pre> <p>and the service layer:</p> <pre><code>public class UserRegistirationService { private AppUserAccessObject appUserAccessObject; public UserRegistirationService(AppUserAccessObject appUserAccessObject) { this.appUserAccessObject = appUserAccessObject; } public void registerAppUser(String username, String password, String email) throws SQLException { appUserAccessObject.insertUser(username, password, email); } } </code></pre> <p>and the db layer:</p> <pre><code>public class AppUserAccessObject extends DataAccessObjectImpl implements DataAccessObject { public AppUserAccessObject(DatabaseConnectionImpl databaseConnection) throws IOException, SQLException, ClassNotFoundException { super(databaseConnection); setTableName("app_user"); } public void insertUser(String username, String email, String password) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO " + tableName + "(username,email,password) VALUES(?,?,?)"); preparedStatement.setString(1, username); preparedStatement.setString(2, email); preparedStatement.setString(3, password); preparedStatement.execute(); } } </code></pre> <p>Is all the code at correct layers? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T11:00:04.117", "Id": "83375", "Score": "0", "body": "Short answer: You have `new DatabaseConnectionImpl()` and `catch (SQLException e)` in your servlet class, therefore your web layer is not separated from data access layer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T12:49:13.740", "Id": "83387", "Score": "0", "body": "@abuzittingillifirca I am not using any dependency injection container or anything else so how can I avoid new DatabaseConnectionImpl()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T13:31:52.873", "Id": "83390", "Score": "0", "body": "You define a `ServletContextListener` in the web.xml. You create your services, factories etc in its `contextInitialized` method, and stick them into the `ServletContext` with `setAttribute(\"some.prefix.xyzService\", xyzService)` etc. You can then get them back in the servlet with `XyzService xyzService = (XyzService)(getServletContext().getAttribute(\"some.prefix.xyzService\"));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T17:14:52.130", "Id": "83779", "Score": "0", "body": "@abuzittingillifirca Thanks. I will try this approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T06:22:45.113", "Id": "83879", "Score": "0", "body": "Of course, if you are doing this not to learn workings of the Servlet API, but to develop production systems; you can use a framework such as *Spring* and save yourself a lot of time. Also, after moving service etc out of your web layer, next in order is to move any passwords etc out of your application code, for example if they exist in DatabaseConnectionImpl`. Standard way to do it is using JNDI. [See here for how it is done for Tomcat.](http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html#JDBC_Data_Sources) Each servlet container has a way of doing this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-26T15:13:46.310", "Id": "84653", "Score": "0", "body": "@abuzittingillifirca Abuzittin, one question. What if I need to access the xyzService something that is not Servlet?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T06:19:46.413", "Id": "84916", "Score": "0", "body": "You should invest some time and learn [Spring Framework](http://projects.spring.io/spring-framework/), even if you do not use it, it will make Java application architecture more clear. Also, you can get more detailed answers from [programmers SE](http://programmers.stackexchange.com/search?tab=relevance&q=dependency%20injection). Most of your questions are probably answered there already." } ]
[ { "body": "<p>I know you're asking strictly for feedback about the layers (which look fine to me), but in case you're looking for other feedback too:</p>\n\n<pre><code>if(username.equals(\"\")\n || password.equals(\"\")\n || email.equals(\"\")){\n</code></pre>\n\n<p>You need to null check these values. <code>getParameter</code> can return null so you will get a NullPointerException if they don't exist.</p>\n\n<pre><code>List&lt;String&gt; errors = new ArrayList&lt;String&gt;();\nerrors.add(\"Registiration was not successful. Maybe username/email was already taken?\");\nhttpServletRequest.setAttribute(\"errors\",errors);\n</code></pre>\n\n<p>Can be done in one line if you want:</p>\n\n<pre><code>errors.add(Arrays.asList(\"Registiration was not successful. Maybe username/email was already taken?\"));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:59:33.960", "Id": "83292", "Score": "0", "body": "If the fields are empty, the getParameter returns \"\". How can they be null? Thanks for the feedback however." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T01:38:12.667", "Id": "83320", "Score": "0", "body": "The result will be null if the parameter you are looking for doesn't exist. If it's not currently causing you problems then it's not an issue, however it's worth noting and possibly adding in the null check anyway, because you never know how the functionality of your program might change in the future and those parameters could be missing from the request, so it's much better to handle the null case than allow for a NPE" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T03:13:13.010", "Id": "83346", "Score": "0", "body": "Bots and hackers are free to omit these parameters in the query, causing a (probably inocuous) NPE. Guave and Apache Commons both provide forms of `Strings.isNullOrEmpty(str)` for happy inlining." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:53:13.730", "Id": "47520", "ParentId": "47507", "Score": "3" } }, { "body": "<p>I'm going to pass by the <a href=\"https://codereview.stackexchange.com/questions/47507/a-simple-web-app-code-user-registration-is-the-layering-ok#comment83375_47507\">setup issue</a> that abuzittin gillifirca mentioned in his comment, and the <a href=\"https://codereview.stackexchange.com/a/47520\">input sanitizing</a> that jimmycarr pointed to, because I have little to add to that. And since you asked about the layering, I'm going to focus on the layering.</p>\n\n<p>First things first: the layers are well divided. You separate the different layers without going overboard and, aside from initialisation, each layer has at most to contend with the one below and/or the one above. That's the very essence, and you have that basic idea right.</p>\n\n<p>Because the basic idea is right, I'll focus on a smaller issue that may or may not trip you up later on.</p>\n\n<p>The important thing to keep in mind about layering is that it is all about <em>isolation</em>. You require the minimum that is needed to function correctly and, in turn, you expose the minimum that is needed to provide a reliable, consistent, and useful service. This makes it easier to change bits in layer X without endangering layers Y and Z.</p>\n\n<ul>\n<li><p><code>UserRegistirationService</code> (typo there, should be \"registration\") has a field <code>AppUserAccessObject appUserAccessObject</code> that can probably be a <code>DataAccessObject</code> instead. Unless you require specific functionality that only <code>AppUserAccessObject</code> provides, go through the interface instead (<em>require less</em>).</p></li>\n<li><p><code>AppUserAccessObject.insertUser</code> and <code>UserRegistirationService.registerAppUser</code> are declared to throw <code>SQLException</code>, but shouldn't (<em>expose less</em>).</p>\n\n<p>In casu the access objects, if your project is small, this is acceptable, but still not recommended. It is the DAO implementation's job to sort out any issues it may encounter, and to translate or at least wrap exceptions it can't handle.</p>\n\n<p>For the service, though, this is a no-no. You don't want to force users of your service to deal with database protocol exceptions. What can your web layer or my console app really do at this point?</p></li>\n</ul>\n\n<p><em>The exceptions you (declare to) throw are as much a part of your API as your return and parameters types.</em> If returning a <code>ResultSet</code> would look out of place, throwing <code>SQLException</code> probably will be, too.</p>\n\n<p>There are three main ways to deal with exceptions:</p>\n\n<ol>\n<li><p><strong>Log and ignore</strong>. If you don't know what to do with it, and the other two options can't help you, this is a viable option. You'll want to be careful not to ignore out of convenience, though.</p></li>\n<li><p><strong>Wrap and rethrow</strong>. The quick way out, and one many people choose when faced with checked exceptions. Wrap in a <code>RuntimeException</code> and bubble away. When done right, it simplifies APIs and speeds up your development. (I don't see it done right often.)</p></li>\n<li><p><strong>Analyse and decide</strong>. The hard way out. Analyse the exception you caught, check for type and error codes, and decide what to do with it. You can throw another exception type (<code>NameTooLongException</code>, <code>InvalidEmailAddressException</code>), try another route, or wait a bit and try again. This takes the most work and effort, and may be overkill for small projects.</p></li>\n</ol>\n\n<p>No size fits all. Pick what you feel is appropriate in a given situation and the effort you can afford to put into it.</p>\n\n<hr>\n\n<p>Two points not related to layering:</p>\n\n<ol>\n<li><p>Instead of writing passwords plaintext into your database, store a salted hash of them.</p></li>\n<li><p>Remember to close your <code>PreparedStatement</code> after use!</p></li>\n</ol>\n\n<hr>\n\n<p><strong>Edit:</strong></p>\n\n<blockquote>\n <p>But one question: UserRegistirationService#registerAppUser method has no checks. Should I put the null checks in this layer? or in this layer AS WELL?</p>\n</blockquote>\n\n<p>Your service layer should check its input at any rate, and it should be your baseline. It is best positioned to know what input it accepts, so it should be the authority on checking it. When you write services, not all input may come from sources that you control, so you need to be defensive in checking. And even if you do control the sources, checking anyway will catch bugs quickly.</p>\n\n<p>For the presentation layer, often some quick &amp; dirty checks are also made. This lets you provide feedback to users without contacting the service layer (potentially on another physical machine). It can check that required fields are filled out, basic syntax followed, and so on. Null checks and length checks are a good choice here, but others are outside its possibilities (such as checking that a user name is not already taken).</p>\n\n<p>There is some balance to be sought, though. Checking in multiple layers also gives you some duplicated code. Usually, it's not so bad, but it's something you'll want to document.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T17:12:32.050", "Id": "83778", "Score": "0", "body": "Thank you for this great response. The passwords, well I was too lazy as it is only a local project and for learning purposes only. But one question: UserRegistirationService#registerAppUser method has no checks. Should I put the null checks in this layer? or in this layer AS WELL?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T19:57:36.573", "Id": "83823", "Score": "0", "body": "I've edited an addition to the answer for that question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T19:44:51.793", "Id": "47735", "ParentId": "47507", "Score": "2" } } ]
{ "AcceptedAnswerId": "47520", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:30:46.290", "Id": "47507", "Score": "6", "Tags": [ "java", "object-oriented", "mvc" ], "Title": "A simple web-app code - user registration. Is the layering ok?" }
47507
<p>Here is my Boyer Moore code in Python:</p> <pre><code>def BoyerMoore(stringy, substring): if stringy == substring: return 0 ASCIIcharset = [-1]*256 for x in xrange(len(stringy)): ASCIIcharset[ord(stringy[x])] = x stringLen = len(stringy) substringLen = len(substring) for i in xrange(stringLen - substringLen): skip = 0 for j in xrange(substringLen - 1 , 0, -1): if stringy[i + j] is not substring[j]: skip = max(1, j - ASCIIcharset[ord(stringy[i + j])]) i += skip break if skip == 0: return i return -1 </code></pre> <p>I was wondering what are some small tweaks here and there that I can do to increase the efficiency. Redesigning this code is fine too.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:11:18.393", "Id": "83283", "Score": "0", "body": "No time for a proper review atm but the pythonic way to write your first loop is : `for i,x in enumerate(stringy): ASCIIcharset[ord(x)] = i`. Also, I have doubts about the `s1[x] is not s2[y]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:48:30.037", "Id": "83289", "Score": "0", "body": "one tweak: don't calculate i + j in more than one place" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:51:38.063", "Id": "83290", "Score": "1", "body": "Are you sure your skip calculation is right? For example, if you are on the letter 'a', then ASCIIcharset[ord('a')] will have the highest index where 'a' appears in stringy. Won't this frequently be greater than j? In that case, does it save you any time to calculate and use skip?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:49:25.070", "Id": "83334", "Score": "0", "body": "Shouldn't `ASCIIcharset` be based on the needle instead of the haystack? Otherwise you'll skip too far ahead, e.g., `BoyerMoore('foo is not a foo', 'foo')` should return `0`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:51:35.363", "Id": "83335", "Score": "0", "body": "I would prefer the needle to proceed the haystack. I don't recall Python's preference, but please ignore PHP's dysfunctional use of both. ;)" } ]
[ { "body": "<p>The following examples show that there is something wrong in your code :</p>\n\n<pre><code>print(BoyerMoore('azertyuiop', 'zertyuio' )) # 1 - fair enough\nprint(BoyerMoore( 'zertyuio' , 'azertyuiop')) # -1 - so far so good\nprint(BoyerMoore('azertyuiop', 'azertyuiop')) # 0 - ok\nprint(BoyerMoore('abcdefgiop', 'iop')) # -1 - looks wrong to me\nprint(BoyerMoore('iop' , 'abcdefgiop')) # -1 - ok (just wanted to check that arguments were in the right order)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T07:55:27.290", "Id": "47548", "ParentId": "47508", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T18:43:00.643", "Id": "47508", "Score": "4", "Tags": [ "python", "performance", "strings" ], "Title": "Increase performance of Boyer Moore" }
47508
<p>As a beginner I am always determined to improve myself. I've got written the following Code using jQuery that is working fine. However, I am sure that there are cleaner ways for achieving the same.</p> <p>Right now, I am struggling with the this keyword and the asynchronous loading of the JSON file. Moreover, I am not sure whether you should call an function for initialization the way I did.</p> <p>Do you have any suggestions for improvements?</p> <pre><code>$(function(){ function Model() { this.data = null; this.init(); }; Model.prototype = { deferred: $.Deferred(), config: { jsonFile: 'dump.json' }, init: function() { this.loadJson(); }, loadJson: function() { var self = this; jQuery.getJSON( this.config.jsonFile, function(data) { self.data = data; self.deferred.resolve(); } ) .fail(function() { console.error("Loading JSON file failed"); }) .always(function() {}); }, getData: function(callback) { console.log("getData") var self = this; $.when(this.deferred) .done(function() { callback(self.data) }) }, }; var model = new Model(); model.getData(function(data) { console.log(data) }); }); </code></pre> <p>(duplicate of <a href="https://stackoverflow.com/q/23142089/3546614">https://stackoverflow.com/q/23142089/3546614</a>)</p> <h2>Update 1</h2> <p>I've just updated my code (and truncated unimportant stuff) taking @jgillich's advices into account. For the moment I feel better reading the JSON file when the object is generated which is why I outsourced the operation into separate function.</p> <pre><code>$(function(){ function Model() { this.loadJson(); }; Model.prototype = { deferred: $.Deferred(), jsonFile: 'dump.json', loadJson: function() { $.getJSON(this.jsonFile) .done(function (data) { this.data = data; this.deferred.resolve(data); }.bind(this)) .fail(this.deferred.reject); }, getData: function() { return this.deferred.promise(); }, }; var model = new Model(); model.getData().done(function(data) { console.log('done') console.log(data) }); }); </code></pre>
[]
[ { "body": "<ul>\n<li><p>Storing <code>deferred</code> in the model and then passing a callback to <code>getData</code> is a bit obscure. You could write it like this instead:</p>\n\n<pre><code>getData: function() {\n var deferred = $.Deferred();\n\n if(!this.data) {\n $.getJSON('...',).done(function (data) {\n this.data = data;\n deferred.resolve(data);\n }.bind(this)).fail(deferred.reject);\n } else {\n deferred.resolve(this.data);\n }\n\n return deferred.promise();\n}\n\nmodel.getData().done(function (data) { /* ... */});\n</code></pre></li>\n<li><p>Use either <code>$</code> or <code>jQuery</code>, don't mix them.</p></li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow\">Function.prototype.bind</a> instead of <code>var self = this</code>.</p></li>\n<li><p>Use semicolons after each statement (or leave them out entirely if you prefer that).</p></li>\n<li><p><code>this.data = null;</code> seems pointless, newly created objects don't have such a property.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:30:05.080", "Id": "47518", "ParentId": "47516", "Score": "3" } } ]
{ "AcceptedAnswerId": "47518", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T19:58:28.160", "Id": "47516", "Score": "6", "Tags": [ "javascript", "jquery", "beginner", "json", "asynchronous" ], "Title": "Load JSON file into model using Javascript / jQuery (deferred, asynchronous)" }
47516
<p>I'm writing a script for others to use on their websites. I'd like to use jQuery in this script. Because I don't have control over what frameworks people use on their sites, I need to make sure jQuery is available and that it's version 1.8 or higher. Here's my take on it. Does anyone see anything I could/should be doing differently? Is there a better way of doing this?</p> <pre><code>//start anon function for whole script ;(function(){ var $, hasOwn = ({}).hasOwnProperty, //get ie version returns false if ie&gt;=11 or not ie ieVersion = function(){ var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while(div.innerHTML = '&lt;!--[if gt IE '+(++v)+']&gt;&lt;i&gt;&lt;/i&gt;&lt;![endif]--&gt;', all[0]); return (v &gt; 4 ? v : ('documentMode' in document ? document.documentMode : false)); }(), //get which version of jQuery is currently added to the site jqVersion = function(){ return 'jQuery' in window &amp;&amp; !!window.jQuery ? parseFloat(window.jQuery.fn.jquery) : false; }, //set the correct jquery version to use based on which version of ie is in use. Use an array in the case of one or more being down jqSrc = (!!ieVersion &amp;&amp; ieVersion &gt; 4 &amp;&amp; ieVersion &lt; 9) ? ['//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js', '//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min.js'] : ['//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js', '//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.min.js'], //check jquery version and if it is above 1.8 use it, if not then get own version jqCheck = function(first){ var version = jqVersion(); if(!version || version &lt; 1.8){ getScript(jqSrc.shift(), jqCheck); }else{ if(!!first){ $ = window.jQuery; }else{ $ = window.jQuery.noConflict(true); } load(); } }, //function to loop and load jquery script getScript = function(url, callback){ var script = document.createElement('script'), tag = document.getElementsByTagName('script')[0], done = false; script.type = 'text/javascript'; script.async = !0; script.src = url; script.onload = script.onreadystatechange = script.onerror = function(){ if(!done &amp;&amp; (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')){ done = true; if(typeof(callback) === 'function'){ callback.call(this); } script.onload = script.onreadystatechange = script.onerror = null; } }; tag.parentNode.insertBefore(script, tag); }, load = function(){ //Start script window.myGlobalFunction = new function(){ var privateVar = 'private', privateFunc = function(){ return true; }; this.publicVar = 'public'; this.publicFunc = function(){ return true; }; }; }; //make sure json is avaiable, if not add it if(!hasOwn.call(window, 'JSON') || !hasOwn.call(JSON, 'parse') || (typeof(JSON.parse) !== 'function')){ getScript('//cdnjs.cloudflare.com/ajax/libs/json3/3.3.1/json3.min.js', function(){ //all functions are built start by checking for jQuery and it's builder jqCheck(true); }); }else{ //all functions are built start by checking for jQuery and it's builder jqCheck(true); } })(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T22:14:04.797", "Id": "83297", "Score": "1", "body": "I'd rather parse `navigator.userAgent` to detect if a browser is IE, what you are doing feels quite hacky and is probably inefficient. Please see http://stackoverflow.com/questions/5916900/detect-version-of-browser" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T22:53:02.373", "Id": "83301", "Score": "1", "body": "@Cu3PO42 thank you for the input. User agents can very easily be manipulated, because of this I would much rather rely on something *more* concrete. Base on the link you provided's top answer & my current version(derived from [here](https://gist.github.com/padolsey/527683)) my current version is only 15% slower after [thousands of operations](http://jsperf.com/ie-version) which is something i'm very much okay with to stay away from user agents." } ]
[ { "body": "<p>Before actually diving into creating a jQuery checker (nice idea by the way), you might really want to check some cases before building the code. There are several issues with your script here:</p>\n\n<ul>\n<li><p>Your script assumes that there is jQuery. What if there's no jQuery at all? How would your script work? I suggest you stick to vanilla JS instead.</p></li>\n<li><p>Documentation too long, didn't read, developer loaded your script first. It will break. You can't detect scripts because they are parsed in order. If your script came first, it cannot see the scripts loaded after it at the point of execution.</p></li>\n<li><p>But what if a plugin already initialized with the version that came with the page? jQuery carries an internal cache for data, event handlers etc. If you switch jQuery now, they will break.</p></li>\n<li><p>Dynamically loading a script is an async operation. You can't pause it right there. JS will continue. Therefore, while your script is loading a more recent version, plugins on your page might have already initialized using the one in your page.</p></li>\n<li><p>Some plugins require a specific version of jQuery (like some prefer 1.4, or 1.6). Developers intentionally use them because some of these plugins use already deprecated API and weren't updated. If you load a newer version, they break.</p></li>\n<li><p>If you really wanted IE support, why not just load the <code>1.x</code> version rather than doing <code>2.x</code>? This removes the need to detect IE. That's why there's a <code>1.x</code> and <code>2.x</code> version in the first place.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T05:17:25.993", "Id": "83591", "Score": "0", "body": "Thanks for your feedback. As for the issues: 1. Because of `'jQuery' in window && !!window.jQuery` if there isn't any jQuery at all it will be loaded. 2. This script should be loaded last. If need be I could force it with defer and/or dynamically setting the script to the bottom or start it on `window.load`. 3. Because of `$.noConflict` this shouldn't be an issue at all. 4. I don't see what you're referring to, every call to `getScript` is using a callback. Can you please elaborate? 5. As before, not a problem because of `$.noConflict` 6. I agree, I will remove `ieVersion` & the 2.0 jQuery." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T15:05:12.407", "Id": "47580", "ParentId": "47519", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T20:37:52.897", "Id": "47519", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Dynamically loading jQuery when it's not available or version isn't high enough" }
47519
<p>I'm fairly new to JS/jQuery (a few months), and I think it's time to start getting involved in the community. So I wrote a little plugin. Nothing revolutionary. Really, the project is to write a clean, workable plugin. Any and all thoughts and suggestions on how I can make the code cleaner, or the animations smoother, or anything, are very much appreciated.</p> <p>Here's the plugin in action: <a href="http://jsfiddle.net/VA7P5/" rel="nofollow">http://jsfiddle.net/VA7P5/</a> </p> <p>Here is the plugin code:</p> <pre><code>(function ($) { $.fn.menuBar = function (options) { var defaults = { width: 145, // Width of Sidebar left: true, // If true, sidebar is positioned left. If false, it's positioned right height: 80, // Height of footer barColor: '#000', // Color of three-bar menu before it's opened menuBackground: '#303030', // Background color of sidebar and footer closeColor: '#fff' // Color of close-button }; var options = $.extend(defaults, options); return this.each(function () { var i = $(this); var o = options; var width = $('nav.sidebar').css('width'); var height = $('footer.hidden').css('height'); var closeColor = $('.bar').css('background'); var barColor = $('.bar').css('background'); var barOne = $('.menu-bar-top'); var barTwo = $('.menu-bar-bottom'); var barThree = $('.menu-bar-mid'); var menuTrigger = $('nav.sidebar a'); var fadeWrapper = $('#fade-wrapper'); var nav = $('nav.sidebar'); var footerHidden = $('footer.hidden'); var bar = $('.bar'); bar.css('background', o.barColor); if (o.left) { nav.css({ 'width': o.width, 'left': o.width - (o.width * 2), 'background': o.menuBackground }); $('.menu-trigger').css({ 'left': 0 }); } else { nav.css({ 'width': o.width, 'right': o.width - (o.width * 2), 'background': o.menuBackground }); $('.menu-trigger').css({ 'right': 0 }); } footerHidden.css({ 'height': o.height, 'bottom': o.height - (o.height * 2), 'background': o.menuBackground }); i.click(function(){ if (i.hasClass('open')) { closeMenu(); i.removeClass('open'); // Allow scrolling again when menu is closed $('body').css('overflow', ''); } else { openMenu(); i.addClass('open'); // No scrolling while menu is open $('body').css('overflow', 'hidden'); } }); $('#fade-wrapper').click(function(){ closeMenu(); i.removeClass('open'); $('body').css('overflow', ''); }); /*=========================================================================================================== Opening/Closing Functions ===========================================================================================================*/ function openMenu() { fadeWrapper.fadeIn(100, function(){ barOne.css({ 'top': '8px', 'transform': 'rotate(405deg)', '-webkit-transform': 'rotate(405deg)', '-moz-transform': 'rotate(405deg)', '-ms-transform': 'rotate(405deg)', '-o-transform': 'rotate(405deg)' }); barTwo.css({ 'top': '8px', 'transform': 'rotate(-405deg)', '-webkit-transform': 'rotate(-405deg)', '-moz-transform': 'rotate(-405deg)', '-ms-transform': 'rotate(-405deg)', '-o-transform': 'rotate(-405deg)' }); if (o.left) { nav.animate({'left': '+=' + o.width}, 200); } else { nav.animate({'right': '+=' + o.width}, 200); } footerHidden.animate({'bottom': '+=' + o.height}, 200); barThree.fadeOut(100); bar.css('background', o.closeColor); }); } function closeMenu() { setTimeout(function(){ barThree.fadeTo(100, 1); fadeWrapper.fadeOut(100); if (o.left) { nav.animate({'left': '-=' + o.width}, 200); } else { nav.animate({'right': '-=' + o.width}, 200); } footerHidden.animate({'bottom': '-=' + o.height}, 200); bar.css('background', o.barColor); barOne.css({ 'top': '3px', 'transform': 'rotate(360deg)', '-webkit-transform': 'rotate(360deg)', '-moz-transform': 'rotate(360deg)', 'ms-transform': 'rotate(360deg)', 'o-transform': 'rotate(360deg)' }); barTwo.css({ 'top': '13px', 'transform': 'rotate(-360deg)', '-webkit-transform': 'rotate(-360deg)', '-moz-transform': 'rotate(-360deg)', '-ms-transform': 'rotate(-360deg)', '-o-transform': 'rotate(-360deg)' });}, 1); } }); }; })(jQuery); </code></pre> <p>The necessary HTML: </p> <pre><code>&lt;nav class="sidebar"&gt; &lt;a class="menu cursor" title="Menu"&gt; &lt;div class="menu-trigger"&gt; &lt;div class="bar-container"&gt; &lt;div class="bar menu-bar-top"&gt;&lt;/div&gt; &lt;div class="bar menu-bar-mid"&gt;&lt;/div&gt; &lt;div class="bar menu-bar-bottom"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;!-- Sidebar content goes here --&gt; &lt;/nav&gt; &lt;div id="fade-wrapper"&gt;&lt;/div&gt; &lt;footer class="hidden"&gt; &lt;!-- Footer content goes here --&gt; &lt;/footer&gt; </code></pre> <p>The necessary CSS: </p> <pre><code>a.cursor { cursor: pointer; } #fade-wrapper { display: none; position: fixed; top: 0; left: 0; height: 100%; width: 100%; background: rgba(0, 0, 0, 0.3); z-index: 5000; } nav.sidebar { position: fixed; top: 0; height: 100%; z-index: 9999; } .menu-trigger { position: fixed; top: 8px; width: 40px; height: 20px; line-height: 40px; } .bar-container { margin-top: 3px; height: 13px; } .bar { position: absolute; height: 3px; width: 90%; outline: 1px solid transparent; -webkit-transition: all .5s ease; -moz-transition: all .5s ease; -ms-transition: all .5s ease; -o-transition: all .5s ease; transition: all .5s ease; } .menu-bar-top { top: 3px; left: 2px; } .menu-bar-mid { top: 8px; left: 2px; } .menu-bar-bottom { top: 13px; left: 2px; } footer.hidden { position: fixed; left: 0; width: 100%; z-index: 9999; } </code></pre>
[]
[ { "body": "<p>I like your code, it is easy to follow, has comments, well named variables etc. The only thing I would point out is that you are repeating yourself here and there. So I will focus on that:</p>\n\n<ul>\n<li><p>This piece of code:</p>\n\n<pre><code>if (o.left) {\n nav.css({\n 'width': o.width,\n 'left': o.width - (o.width * 2),\n 'background': o.menuBackground\n });\n $('.menu-trigger').css({\n 'left': 0\n });\n} else {\n nav.css({\n 'width': o.width,\n 'right': o.width - (o.width * 2),\n 'background': o.menuBackground\n });\n $('.menu-trigger').css({\n 'right': 0\n });\n}\n</code></pre>\n\n<p>Is really repeating the same thing but with <code>left</code> being replaced with <code>right</code>, you could just assign <code>left</code> or <code>right</code> to a variable first.</p>\n\n<pre><code>var key = o.left ? 'left' : 'right';\n nav.css({\n 'width': o.width,\n 'background': o.menuBackground\n }).css( key, o.width - (o.width * 2) );\n $('.menu-trigger').css( key , 0 );\n</code></pre></li>\n<li><p>This piece of code is repeated a few times at well, the only different is the degrees and the value of <code>'top'</code>.</p>\n\n<pre><code>barTwo.css({\n 'top': '13px',\n 'transform': 'rotate(-360deg)',\n '-webkit-transform': 'rotate(-360deg)',\n '-moz-transform': 'rotate(-360deg)',\n '-ms-transform': 'rotate(-360deg)',\n '-o-transform': 'rotate(-360deg)'\n});}, 1);\n</code></pre>\n\n<p>You could consider a helper function that this transformation for you</p>\n\n<pre><code>function generateTransformation( top , transformation ){\n return {\n 'top': top,\n 'transform': transformation,\n '-webkit-transform': transformation,\n '-moz-transform': transformation,\n '-ms-transform': transformation,\n '-o-transform': transformation' \n };\n}\n</code></pre>\n\n<p>Then, you can simply do </p>\n\n<pre><code>barOne.css( generateTransformation( '3px' , 'rotate(360deg)' ));\nbarTwo.css( generateTransformation( '13px' , 'rotate(-360deg)' ));\n</code></pre></li>\n<li><p>These:</p>\n\n<pre><code>if (o.left) {\n nav.animate({'left': '+=' + o.width}, 200);\n} else {\n nav.animate({'right': '+=' + o.width}, 200);\n}\n</code></pre>\n\n<p>I will leave to you as an exercise for the reader.</p></li>\n<li><code>var bar = $('.bar');</code> &lt;- This will select 3 bars, perhaps call it <code>bars</code> ?</li>\n<li><code>var closeColor = $('.bar').css('background');</code> &lt;- This takes the background color of the first bar, I would put that in a comment or make it more obvious by calling <code>$('.bar').eq(0).css('background');</code> or even better determine <code>bars</code> first and then go for <code>bars.eq(0).css('background');</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T17:49:30.340", "Id": "83785", "Score": "0", "body": "Thanks a ton! This kind of feedback is exactly what I'm looking for. I want to post an update, but before I do: Should I A) replace the code in the original post with the new code, B) Add the new code block to the original post or C) post the new code block as an answer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T18:08:27.837", "Id": "83791", "Score": "0", "body": "You are welcome, Option C is the way to go." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T18:47:26.863", "Id": "83801", "Score": "0", "body": "I just posted the update. I've got a quick question, though: Why is it that `elem.css(var, var)` works, but `elem.css({var: var})` does not?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T18:49:41.087", "Id": "83803", "Score": "0", "body": "Gah, I meant Option D -> New Question, my bad, I misread your options" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T18:50:53.373", "Id": "83804", "Score": "0", "body": "For your question: because in the 2nd statement it does not evaluate `var`, it just uses the string `var` as the key, because that is how JS Object Notation works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T19:14:40.943", "Id": "83816", "Score": "0", "body": "Ah. I guess I failed to see that `elem.css({...})` was object notation. One more question: Is there a way to achieve a 405deg rotation every time `openMenu()` fires and only a 45deg rotation every time `closeMenu()` fires? As it is, you only get the 405deg rotation the very first time `openMenu()` fires." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T19:20:10.447", "Id": "83817", "Score": "1", "body": "Last comment, though feel free to ask questions in Chat ( http://chat.stackexchange.com/rooms/8595/the-2nd-monitor ) by addressing @Konijn, that would really be an SO question, I cant tell off hand what is going on." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T12:57:03.933", "Id": "47778", "ParentId": "47524", "Score": "1" } } ]
{ "AcceptedAnswerId": "47778", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T00:10:39.600", "Id": "47524", "Score": "3", "Tags": [ "javascript", "jquery", "beginner", "css", "plugin" ], "Title": "Menu Bar Animation Plugin" }
47524
<p>I'm building a Ruby API client. My brief is to extract ids out of various inputs and fetch the relevant data. It's working just fine at the moment but I think it's a little clumsy.</p> <p>My specs (which pass):</p> <pre><code>shared_examples 'it requests ids' do |resource| it 'sends the ids to Foo::Client' do Foo.stub(:parse) Foo::Client.should_receive(resource).once.with(expected) Foo.send(resource, *args) end end describe Foo do describe 'resources have numeric ids only' [:accounts, :contacts].each do |resource| it_behaves_like 'it requests ids', resource do let(:args) { [1, 2] } let(:expected) { [1, 2] } end it_behaves_like 'it requests ids', resource do let(:args) { [3, 'jesse-pinkman', 5, {'links' =&gt; {resource.to_s =&gt; [98, 99]}}] } let(:expected) { [98, 99, 3, 5] } end end end describe 'resources have numeric and string ids' [:clients, :services].each do |resource| it_behaves_like 'it requests ids', resource do let(:args) { [2,'saul-goodman', 6] } let(:expected) { [2, 6, 'saul-goodman'] } end it_behaves_like 'it requests ids', resource do let(:args) { [3, 'saul-goodman', 5, {'links' =&gt; {resource.to_s =&gt; [202, 234]}}] } let(:expected) { [202, 234, 3, 5, 'saul-goodman'] } end end end end </code></pre> <p>And my code:</p> <pre><code>module Foo class &lt;&lt; self [:accounts, :contacts, :clients, :services].each do |resource| define_method(resource) do |*args| ids = [] unless args.empty? ids += hash_ids(args, resource) ids += numeric_ids(args) ids += text_ids(args) unless numeric_ids_only?(resource) end parse(client.send(resource, ids)) end end private def hash_ids(args, resource) args.collect { |arg| arg['links'][resource.to_s] if arg.is_a? Hash }.compact!.flatten!.to_a end def numeric_ids(ids) ids.select { |id| !id.is_a?(Hash) &amp;&amp; id.to_i &gt; 0 } end def text_ids(ids) ids.select { |id| id.is_a? String } end def numeric_ids_only?(resource) [:accounts, :contacts].include?(resource) end def client Foo::Client end def parse(json) Foo::Adapter::JSON.parse(json) end end end </code></pre> <p>My particular concern is the ugly concatenating of the <code>ids</code> array and passing all those <code>args</code> around. Any tips?</p>
[]
[ { "body": "<p><strong>You should expect</strong><br>\nStarting a couple of years back, <code>rspec</code> is moving to a <a href=\"http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax\" rel=\"nofollow\">new expectation syntax</a>, you should consider porting to it:</p>\n\n<pre><code>shared_examples 'it requests ids' do |resource|\n it 'sends the ids to Foo::Client' do\n allow(Foo).to receive(:parse)\n\n expect(Foo::Client).to receive(resource).once.with(expected)\n\n Foo.send(resource, *args)\n end\nend\n</code></pre>\n\n<p><strong>Be more transparent</strong><br>\nYour code hides pretty well the fact that <code>clients</code> and <code>services</code> is different from <code>accounts</code> and <code>contacts</code> - both in your code and in your tests.<br>\nIt makes your code quite obfuscated (in the name of DRYness?) - you should make it clear that you have two different behaviors - and spell them out:</p>\n\n<pre><code>shared_examples 'resources have numeric ids only' do |resource|\n it_behaves_like 'it requests ids', resource do\n let(:args) { [1, 2] }\n let(:expected) { [1, 2] }\n end\n\n it_behaves_like 'it requests ids', resource do\n let(:args) { [3, 'jesse-pinkman', 5, {'links' =&gt; {resource.to_s =&gt; [98, 99]}}] }\n let(:expected) { [98, 99, 3, 5] }\n end\nend\n\nshared_examples 'resources have numeric and string ids' do |resource|\n it_behaves_like 'it requests ids', resource do\n let(:args) { [2,'saul-goodman', 6] }\n let(:expected) { [2, 6, 'saul-goodman'] }\n end\n\n it_behaves_like 'it requests ids', resource do\n let(:args) { [3, 'saul-goodman', 5, {'links' =&gt; {resource.to_s =&gt; [202, 234]}}] }\n let(:expected) { [202, 234, 3, 5, 'saul-goodman'] }\n end\nend\n\nit_behaves_like 'resources have numeric ids only', :accounts\nit_behaves_like 'resources have numeric ids only', :contacts\nit_behaves_like 'resources have numeric and string ids', :clients\nit_behaves_like 'resources have numeric and string ids', :services\n</code></pre>\n\n<p>And in your code, I would rather use simple method delegation than meta-coding:</p>\n\n<pre><code>class &lt;&lt; self\n def accounts(*args)\n parse(client.accounts(hash_ids(args, :accounts) + numeric_ids(args))\n end\n\n def contacts(*args)\n parse(client.accounts(hash_ids(args, :contacts) + numeric_ids(args))\n end\n\n def clients(*args)\n parse(client.accounts(hash_ids(args, :clients) + numeric_ids(args) + text_ids(args))\n end\n\n def services(*args)\n parse(client.accounts(hash_ids(args, :services) + numeric_ids(args) + text_ids(args))\n end\nend\n</code></pre>\n\n<p>It might be less DRY, but it is a lot clearer what your class actually <em>does</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T23:12:36.777", "Id": "84064", "Score": "0", "body": "Nice. I have refactored my specs to clarify the behaviour a little. I think you're right." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:04:28.723", "Id": "47555", "ParentId": "47526", "Score": "3" } }, { "body": "<p>Rimian, the main suggestions I would make are two:</p>\n\n<ul>\n<li><p>loop through <code>args</code> just once; and</p></li>\n<li><p>use a case statement with argument <code>arg</code>, as it makes it easy to separate the <code>arg</code> objects by class.</p></li>\n</ul>\n\n<p>Here is one way to apply these suggestions:</p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>require 'json'\n\nmodule Foo\n class Client\n class &lt;&lt; self\n [:accounts, :contacts, :clients, :services].each { |resource|\n define_method(resource) { |*args| process(resource, args) } }\n\n private\n\n def process(resource, *args)\n parse(client.send(resource, ids(resource, args)))\n end\n\n def ids(resource, *args)\n args.each_with_object([]) do |arg,a|\n case arg\n when Hash\n v = arg['links'][resource.to_s]\n v.each { |e| a &lt;&lt; e } unless v.nil?\n when Numeric\n a &lt;&lt; arg\n when String\n a &lt;&lt; arg unless [:accounts, :contacts].include?(resource)\n end\n end\n end\n\n def client\n Foo::Client\n end\n\n def parse(json)\n Foo::Adapter::JSON.parse(json)\n end\n end\n end\nend\n</code></pre>\n\n<p><strong>Examples</strong></p>\n\n<p>Actually, I am not 100% certain this is working, because I am not familiar with JSON, but I expect it will not be difficult to repair if there are errors.</p>\n\n<p>I did a poor-man's test by commenting-out <code>private</code> and running:</p>\n\n<pre><code>resource = :accounts\np Foo::Client.ids(resource, 1, 2)\n #=&gt;[1, 2]\n\nresource = :contacts\np Foo::Client.ids(resource, 3, 'jesse-pinkman', 5,\n {'links' =&gt; {resource.to_s =&gt; [98, 99]}})\n #=&gt; [3, 5, 98, 99]\n\nresource = :clients\np Foo::Client.ids(resource, 2,'saul-goodman', 6)\n #=&gt; [2, 6, 'saul-goodman']\n\nresource = :services\np Foo::Client.ids(resource, 3, 'saul-goodman', 5,\n {'links' =&gt; {resource.to_s =&gt; [202, 234]}})\n #=&gt; [202, 234, 3, 5, 'saul-goodman']\n</code></pre>\n\n<p><strong>Explanation and observations</strong></p>\n\n<ul>\n<li><p>Where is your <code>Client</code> class? I assume from the spec that it is to be defined in the module <code>Foo</code>, rather than <code>Client</code> including <code>Foo</code>, but that's a detail. Also, you forgot <code>require 'json'</code>. That's obvious, but it's still a good idea to include all <code>require</code>s when showing your code.</p></li>\n<li><p>I didn't know if you intended to include non-positive numeric values, or that you expect them all to be positive and was using <code>arg.to_i &gt; 0</code> to distinguish them from strings. If you want to exclude non-positive Fixnums, add <code>if arg &gt; 0</code> in the appropriate place.</p></li>\n<li><p>You will recall that <code>case</code> statements use <a href=\"http://ruby-doc.org/core-2.1.1/Object.html#method-i-3D-3D-3D\" rel=\"nofollow\">Object#===</a> rather than <code>==</code> for determining true and false, which is why, for example, <code>when Hash</code> works.</p></li>\n<li><p>I don't think you actually need your <code>client</code> method, as <code>self</code> should be <code>Foo::Client</code> whenever <code>parse(send(resource, ids(resource, args)))</code> is invoked.</p></li>\n<li><p>Rather than using <code>define_method</code> to create four class methods, you could simply make my method <code>process</code> public and pass the resource as an additional argument; for example: <code>Foo::Client.process(:accounts, 1, 2)</code>. Not advocating, just mentioning.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T23:16:34.783", "Id": "84065", "Score": "0", "body": "Good suggestions. I think your ids method might have too many levels of abstractions however. What do you think? I have a preference for short methods that do only one thing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T23:03:38.557", "Id": "47618", "ParentId": "47526", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T01:03:57.033", "Id": "47526", "Score": "5", "Tags": [ "ruby", "api" ], "Title": "Extracting ids out of arguments of different types" }
47526
<p>First of all, I am not using JQuery but <a href="https://github.com/cheeriojs/cheerio" rel="nofollow">Cheerio</a>. I have never actually used JQuery in "real life" -- I started with Cheerio, which is a subset and doesn't actually work in a browser environment.</p> <p><em>(Note: I don't have enough reputation here to create tags, somebody might want to tag this question as "cheerio" and delete this sentence...)</em></p> <p>Here is my code. Questions are inline:</p> <pre><code>$ = cheerio.load( self.formPage.toString() ); $( 'form' ).each( function( index, form ){ // ***************** // QUESTION: // Is this the right way to do this? // I am "converting" each found "DOM" object into a "JQuery" object (although // it's not real DOM, and it's not real JQuery either). // But, if there is no ID set for form, for example, is this _guaranteed_ to always find // the right one? var $form = $( form ); // Work out fullAction, which is the form's action relative to the fetched URL var action; var baseUrl = self.config.url.substr(0, self.config.url.lastIndexOf("/") + 1); var action = $form.attr( 'action' ); var fullAction = require( 'path' ).normalize( baseUrl + action ); console.log("FULL ACTION:", fullAction ); stores.workspacesNinjaFormCodes.apiGetQuery( { filters: { workspaceId: self.workspaceId }, skipHardLimitOnQueries: true }, function( err, codesData ){ //stores.workspacesNinjaFormCodes.dbLayer.select( { conditions: { and: [ { field: 'workspaceId', type: 'eq', value: self.workspaceId } ] } }, { skipHardLimitOnQueries: true }, function( err, codesData ){ codesData.forEach( function( codeData ){ var code = codeData.code; var dataSubmitHash = {}; // ***************** // QUESTION: // Is this the right way to do this? I want to find all 'input' fields // in this particular form. So, I pass $form as context and look for // all 'input' tags. Is this what you are meant to do? // ****************** $( "input", $form ).each( function( index, inputField ){ // ***************** // QUESTION: // Once again, will this always work, regadrless of IDs etc.? I am passing `form` as the // context. // ****************** var $inputField = $( inputField, form ); // See if the field name is already assigned var fieldValue = $inputField.val() ? $inputField.val() : code; // Assign values dataSubmitHash[ $inputField.attr('name') ] = fieldValue; }); console.log("dataSubmitHash:", dataSubmitHash ); }); }); }); </code></pre> <p>Questions are inline, and they are focused on this: how expensive is the "conversion" of cheerio's "DOM" objects into Cheerio "JQuery" objects? And is it always guarantee to get the right one?</p>
[]
[ { "body": "<p>Here's what I did, comments in the code.</p>\n\n<pre><code>$ = cheerio.load(self.formPage.toString());\npath = require('path'); //Move out path from the loop to avoid re-requiring it\n$('form').each(function (index, form) {\n\n var $form = $(form);\n\n // Removed action here. You seem to use it after the next line.\n\n var baseUrl = self.config.url.substr(0, self.config.url.lastIndexOf(\"/\") + 1);\n var action = $form.attr('action');\n var fullAction = path.normalize(baseUrl + action);\n\n // In the next block, input is in the context of this form\n // We can pull it out of the loop to avoid fetching it on every iteration\n var input = $('input', form);\n\n // You don't seem to use fullAction in the next block?\n\n stores.workspacesNinjaFormCodes.apiGetQuery({\n filters: {\n workspaceId: self.workspaceId\n },\n skipHardLimitOnQueries: true\n }, function (err, codesData) {\n codesData.forEach(function (codeData) {\n var code = codeData.code;\n var dataSubmitHash = {};\n\n // here's the input earlier\n input.each(function (index, inputField) {\n\n // Let's keep it readable, place then in variables\n var $inputField = $(inputField, form);\n var inputFieldName = $inputField.attr('name');\n\n // we could use the || operator to check for the first and use it, or use the second if not first.\n var fieldValue = $inputField.val() || code;\n\n dataSubmitHash[inputFieldName] = fieldValue\n });\n\n console.log(\"dataSubmitHash:\", dataSubmitHash)\n })\n })\n});\n</code></pre>\n\n<p>In addition, one should not create functions inside loops. Consider moving them out of the loops.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T14:39:55.520", "Id": "47578", "ParentId": "47528", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T01:45:36.667", "Id": "47528", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Speed and ID concerns converting DOM object into JQuery objects" }
47528
<p>I'm generating domains with random names. I used the map function because it packages the results into a list which I can then <code>join()</code> into a string but the way I used the lambda function could be confusing to people reading this later.</p> <pre><code>def generateHost(): charSet = 'abcdefghijklmnopqrstuvwxyz1234567890' minLength = 5 maxLength = 30 length = random.randint(minLength, maxLength) return ''.join(map(lambda unused : random.choice(charSet), range(length)))+".com" </code></pre> <p>This function calls <code>generateHost()</code> 'size' times and creates an array of hosts. I could write it like the above but it would be the same problem. I wrote it with a <code>for</code> loop which I'm still not satisfied with.</p> <pre><code>def generateHostList(size): result = [] for i in range(size): result += [generateHost()] return result </code></pre>
[]
[ { "body": "<p>The answer to <a href=\"https://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits\">this question</a> suggests the following:</p>\n\n<pre><code>''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))\n</code></pre>\n\n<p>It's close to your solution, but avoids having to type out the whole alphabet by using predefined values and avoids the use of map() and lambda.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T04:53:38.850", "Id": "83350", "Score": "0", "body": "Wow. Set builder notation is amazing. Any idea why 'random.choice(string.ascii_uppercase + string.digits) for _ in range(N)' doesn't have to be in brackets?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T04:53:53.137", "Id": "83351", "Score": "0", "body": "Looks like you missed `[]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T05:08:06.393", "Id": "83352", "Score": "0", "body": "It works without the brackets when it's within joins parenthesis. I've been trying to figure out why." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T06:53:47.643", "Id": "83358", "Score": "3", "body": "@JamesFargotson The reason it works is that it is a [generator expression](https://docs.python.org/3.4/reference/expressions.html#generator-expressions), not a set comprehension, so the parentheses [can be omitted on calls with only one argument](http://stackoverflow.com/questions/9297653/python-generator-expression-parentheses-oddity)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:34:03.370", "Id": "83532", "Score": "0", "body": "@codesparkle Very cool. Thanks for the links." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:44:26.153", "Id": "47531", "ParentId": "47529", "Score": "12" } }, { "body": "<p>A pythonic idiom is to utilize a list comprehension where possible:</p>\n\n<pre><code>def generateHostList(size):\n return [ generateHost() for _ in range(size) ]\n</code></pre>\n\n<p>(notice another idiom of using <code>_</code> for <code>unused</code>).</p>\n\n<p>The <code>generateHost</code> itself may look confusing. The <a href=\"https://codereview.stackexchange.com/users/40599/tom-barron\">TomBarron</a>'s solution is better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T04:55:33.510", "Id": "47539", "ParentId": "47529", "Score": "4" } }, { "body": "<p>The other posts already answered how to generate random strings and a random list of hosts and are totally spot on.</p>\n\n<p>I would just add that if this is for generating hostnames in a network, they might not be very great names. They look more like passwords, which are difficult to remember and won't be practical. I recommend a different approach, as suggested by <a href=\"https://coderwall.com/p/1l5utg\" rel=\"nofollow\">this article</a>. The idea is to pick a themes, and use a mix of them as server names. For example, you could use a mix of cartoon character names, like:</p>\n\n<pre><code>toystory = ('woody', 'buzz', 'jessie', 'rex', 'potato', 'sid')\nwalle = ('walle', 'eve', 'axiom', 'captain')\n'-'.join([random.choice(toystory), random.choice(walle)])\n</code></pre>\n\n<p>Of course, ideally with much longer lists. And you can still throw in a number part at the end, for example:</p>\n\n<pre><code>'-'.join([random.choice(toystory), random.choice(walle), ''.join(random.choice(string.digits) for _ in xrange(3))])\n</code></pre>\n\n<p>Finally, take a look at <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8, the style guide of Python</a>. So far your code is ok, but it's recommended to indent with 4 spaces instead of 2. There is a command line tool called <code>pep8</code> which can check your code for style. As you're learning Python, it's good to follow the recommended style right from the start, easier than correcting bad habits later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T06:04:25.440", "Id": "83357", "Score": "0", "body": "Thanks for letting me know about the style guide. The second entry is an Emerson quote so I think I'm going to like it.The domain names wont be managed by humans so remembering them won't be a problem." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T05:43:11.767", "Id": "47540", "ParentId": "47529", "Score": "3" } } ]
{ "AcceptedAnswerId": "47531", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T02:04:22.857", "Id": "47529", "Score": "12", "Tags": [ "python", "beginner", "strings", "random" ], "Title": "Creating a string of random characters" }
47529
<p>I've created a <code>MovingAverage</code> class, but it is not optimized for performance at all. I care about performance a little bit because I'm using this class in trading (I collocate on exchange and so on and so on; let's talk about performance of this particular class).</p> <p>How would you improve it for better performance?</p> <pre><code>interface Indicator { double? Value { get; } } public class Candle { public Candle(double value) { Minimum = value; Maximum = value; } public void ValueUpdated(double value) { if (value &lt; Minimum) { Minimum = value; } if (value &gt; Maximum) { Maximum = value; } } public double Maximum { get; private set; } public double Minimum { get; private set; } public double Median { get { return (Maximum + Minimum) / 2; } } } public class MovingAverage : Indicator { private int _length; public Queue&lt;Candle&gt; _candles; private Candle _newestCandle; private double _sumExceptNewest; /** * only median supported now */ public MovingAverage(int length) { _length = length; _candles = new Queue&lt;Candle&gt;(length); } public void Add(double val) { if (_candles.Count == _length) { _sumExceptNewest -= _candles.Dequeue().Median; } if (_candles.Count &gt; 0) { _sumExceptNewest += _newestCandle.Median; } // TODO: avoid new _newestCandle = new Candle(val); _candles.Enqueue(_newestCandle); RecalculateValue(); } public void Modify(double val) { if (_newestCandle == null) { Add(val); } else { _newestCandle.ValueUpdated(val); RecalculateValue(); } } private void RecalculateValue() { Value = (_sumExceptNewest + _newestCandle.Median)/_candles.Count; } public double? Value { get; private set; } public void CheckValueAndPrintDelta() { double result = 0; foreach (var candle in _candles) { result += candle.Median; } result /= _candles.Count; Console.WriteLine("checked MA Value = " + Value + " Should be = " + result + " delta (1 = 100%) = " + (Value - result) / result); } } </code></pre>
[]
[ { "body": "<p>If performance of this code is critical, then it could make sense to avoid heap allocations for <code>Candle</code>s. I think the most reasonable way to do that would be make <code>Candle</code> into a <code>struct</code>.</p>\n\n<p>Though <a href=\"https://stackoverflow.com/q/441309/41071\">mutable value types are evil</a>, so I would also refactor <code>Candle</code> to be immutable. This also means the implementation of <code>_newestCandle</code> would have to change, probably into a pair of <code>double</code> fields (or, alternatively, a separate mutable and resettable class).</p>\n\n<p>I don't see any other potential performance issue in your code. But when it comes to performance, you should always rely on profiling, not your (or someone else's) intuition.</p>\n\n<hr>\n\n<p>Also, I don't like some names of your methods. Specifically:</p>\n\n<ul>\n<li><p><code>ValueUpdated</code>. Method names should usually be in the form “do something”, not “something happened”. So I think a better name would be <code>UpdateValue</code>.</p></li>\n<li><p><code>Add</code>, <code>Modify</code>. These are the two fundamental operations of your <code>MovingAverage</code> and I think that those names don't express the meaning well. I would call them something like <code>MoveAndSetCurrent</code> and <code>SetCurrent</code>, respectively. Though such naming indicates that the fundamental operations should rather be <code>Move</code> and <code>SetCurrent</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-30T19:41:58.533", "Id": "48614", "ParentId": "47542", "Score": "2" } } ]
{ "AcceptedAnswerId": "48614", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T06:22:40.143", "Id": "47542", "Score": "3", "Tags": [ "c#", "performance" ], "Title": "Moving average implementation" }
47542
<p>I'm learning go. I wrote a simple logparser for SLF4J in Python some time ago and tried to port it to go as an exercise. The algorithm is identical, but the go-solution isn't quite as fast (the Python solution is about 1.5 times faster for large enough logfiles). Is there any way to get more speed out of it? It do not care, which one is the fastest, but I wanted to know if I could do better with go. Any inspiration is welcome. </p> <p>A typical logline looks like</p> <pre><code>[INFO 05:00:07] CoolServiceImpl.executeReminderCC(601) | ==================Finish transaction with id (REMINDER, 1394424006830) </code></pre> <p>Others include Stacktraces which span multiple lines.</p> <p>My code:</p> <pre><code>package main import ( "bufio" "flag" "fmt" "io" "log" "os" "regexp" "strings" ) func isStampRelevant(level, timestamp string) bool { return level == "ERROR" &amp;&amp; timestamp &gt; "10:00:00" &amp;&amp; timestamp &lt; "10:10:00" } func isMessageRelevant(lineBuffer string) bool { return strings.Contains(lineBuffer, "4020829010703") } func readFile(filename string) { lineStart := regexp.MustCompile("(TRACE|DEBUG|INFO|WARN|ERROR|FATAL).*?(\\d{2}:\\d{2}:\\d{2})") lineBuffer := "" fileHandle, err := os.Open(filename) if err != nil { log.Fatal(err) } buffer := bufio.NewReader(fileHandle) for { line, isPrefix, err := buffer.ReadLine() if err == io.EOF { break } if err != nil { log.Fatal(err) } if isPrefix { log.Fatal("Error: Unexpected long line reading", fileHandle.Name()) } currentLine := string(line) matches := lineStart.FindStringSubmatch(currentLine) if len(matches) == 3 { level := matches[1] timestamp := matches[2] if len(lineBuffer) &gt; 0 { if isMessageRelevant(lineBuffer) { fmt.Println(lineBuffer) } } if isStampRelevant(level, timestamp) { lineBuffer = currentLine } else { lineBuffer = "" } } else if len(lineBuffer) &gt; 0 { lineBuffer += currentLine + "\n" } } if len(lineBuffer) &gt; 0 { if isMessageRelevant(lineBuffer) { fmt.Println(lineBuffer) } } } func printUsage() { fmt.Fprintf(os.Stderr, "usage: %s [inputfile]\n", os.Args[0]) flag.PrintDefaults() os.Exit(2) } func main() { if len(os.Args) &lt; 2 { printUsage() } filename := os.Args[1] readFile(filename) } </code></pre>
[]
[ { "body": "<p>You should use <code>bufio.Scanner</code> rather than a <code>bufio.Reader</code>. It won't make your code any faster, but it'll simplify things a bit.</p>\n\n<p>One reason your code is slow is that you're converting every line from <code>[]byte</code> to <code>string</code>. You can avoid this by using the raw bytes from <code>scanner.Bytes()</code> until you need to print the string. The <code>regexp</code> module provides functions for matching against <code>[]byte</code>, so the translation is rather easy.</p>\n\n<p>A secondary improvement would be to change your regexp to:</p>\n\n<pre><code>`^\\[(TRACE|DEBUG|INFO|WARN|ERROR|FATAL) (\\d{2}:\\d{2}:\\d{2})\\]`\n</code></pre>\n\n<p>By anchoring your regexp and tightening the syntax it recognizes, you'll avoid scanning the entire log line when the regexp doesn't match. Use of raw strings (with backtick), means you don't have to escape the backslashes. This probably won't be a big speed improvement though, since most of your log lines should be single lines.</p>\n\n<p>In terms of structuring the code, I'd probably separate out the part that parses the logs from the part that selects log entries and prints them out.</p>\n\n<p>Perhaps something like this:</p>\n\n<pre><code>type LogReader struct {\n s bufio.Scanner\n ... some internal state\n}\n\ntype LogEntry struct {\n level []byte\n timestamp []byte\n lines [][]byte\n}\n\nfunc (lr *logReader) Next() (LogEntry, error) {\n ... code here\n}\n\nfunc (lr *logReader) Done() bool {\n ... code here\n}\n</code></pre>\n\n<p>This code should deal entirely in <code>[]byte</code> and not <code>string</code>, for the reasons given before.</p>\n\n<p>With this separation, the main code is much easier to read, and you have a nice LogReader abstraction that you can write unit tests for. Here's the main loop using a LogReader:</p>\n\n<pre><code>lr := NewLogReader(filename)\nfor !lr.Done() {\n e, err := lr.Next()\n if err != nil {\n ... handle errors\n }\n if isStampRelevant(e.level, e.timestamp) &amp;&amp; isMessageRelevant(e.level, e.lines) {\n fmt.Println(string(bytes.Join(e.lines, []byte(\"\\n\")))\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T10:27:59.497", "Id": "47770", "ParentId": "47549", "Score": "3" } } ]
{ "AcceptedAnswerId": "47770", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T07:56:43.150", "Id": "47549", "Score": "3", "Tags": [ "performance", "beginner", "go" ], "Title": "Make logparser faster" }
47549
<p>Left view of a Binary Tree is set of nodes visible when tree is visited from left side. Left view of following tree is 12, 10, 25.</p> <pre><code> 12 / \ 10 30 / \ 25 40 </code></pre> <p>Looking for code review, optimizations and best practices. Also verifying space complexity is O(n) and not O(logn) where n is number of nodes in tree.</p> <pre><code>public class LeftView&lt;T&gt; { private TreeNode&lt;T&gt; root; /** * Takes in a BFS representation of a tree, and converts it into a tree. * here the left and right children of nodes are the (2*i + 1) and (2*i + 2)nd * positions respectively. * * @param items The items to be node values. */ public LeftView(List&lt;? extends T&gt; items) { create(items); } private void create (List&lt;? extends T&gt; items) { root = new TreeNode&lt;T&gt;(null, items.get(0), null); final Queue&lt;TreeNode&lt;T&gt;&gt; queue = new LinkedList&lt;TreeNode&lt;T&gt;&gt;(); queue.add(root); final int half = items.size() / 2; for (int i = 0; i &lt; half; i++) { if (items.get(i) != null) { final TreeNode&lt;T&gt; current = queue.poll(); final int left = 2 * i + 1; final int right = 2 * i + 2; if (items.get(left) != null) { current.left = new TreeNode&lt;T&gt;(null, items.get(left), null); queue.add(current.left); } if (right &lt; items.size() &amp;&amp; items.get(right) != null) { current.right = new TreeNode&lt;T&gt;(null, items.get(right), null); queue.add(current.right); } } } } private static class TreeNode&lt;E&gt; { TreeNode&lt;E&gt; left; E item; TreeNode&lt;E&gt; right; TreeNode(TreeNode&lt;E&gt; left, E item, TreeNode&lt;E&gt; right) { this.left = left; this.item = item; this.right = right; } } /** * Returns the left view of the binary tree * * @return the left view of binary tree. */ public List&lt;T&gt; leftView() { if (root == null) { throw new NoSuchElementException("The root is null"); } final List&lt;T&gt; leftView = new ArrayList&lt;T&gt;(); computeLeftView(root, leftView, 1); return leftView; } private void computeLeftView(TreeNode&lt;T&gt; node, List&lt;T&gt; leftView, int currentDepth) { if (node != null) { if (currentDepth &gt; leftView.size()) { leftView.add(node.item); } computeLeftView(node.left, leftView, currentDepth + 1); computeLeftView(node.right, leftView, currentDepth + 1); } } public static void main(String[] args) { final LeftView&lt;Integer&gt; leftView1 = new LeftView&lt;Integer&gt;(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); assertEquals(Arrays.asList(1, 2, 4) , leftView1.leftView()); final LeftView&lt;Integer&gt; leftView2 = new LeftView&lt;Integer&gt;(Arrays.asList(1, 2, 3, 4, null, 6, 7)); assertEquals(Arrays.asList(1, 2, 4) , leftView2.leftView()); final LeftView&lt;Integer&gt; leftView3 = new LeftView&lt;Integer&gt;(Arrays.asList(1, 2, 3, null, 5, 6, 7)); assertEquals(Arrays.asList(1, 2, 5) , leftView3.leftView()); final LeftView&lt;Integer&gt; leftView4 = new LeftView&lt;Integer&gt;(Arrays.asList(1, 2, 3, null, null, 6, 7)); assertEquals(Arrays.asList(1, 2, 6) , leftView4.leftView()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T10:29:50.343", "Id": "83372", "Score": "0", "body": "\"Left view of a Binary Tree is [the] set of nodes ...\" should translate to something like `public static List<T> leftView(BinaryTree<T>)`." } ]
[ { "body": "<p>Although the algorithms seems fine, there are issues with the choosen abstractions.</p>\n\n<p><code>LeftView</code> is a factory of lists, which are left views of an inner tree. <code>LeftView</code> is not a data structure itself, but a factory of it, configured by a list, that are converted to a tree -- too much responsability. Keeping in mind @abuzittin gillifirca advice, a good practise is to refactor factory methods in static, public, methods.</p>\n\n<pre><code>public final class BinaryTrees {\n public static List&lt;T&gt; createLeftViewList(BinaryTree&lt;T&gt; tree) { ... }\n}\n</code></pre>\n\n<p>In your code, <code>LeftView</code> had his own tree representation. To better convey the idea of an algorithm, consider start with simple interfaces, followed by the algorithm itself. That way you get better readability and guarantee further reuse in real code.</p>\n\n<pre><code>public interface BinaryTree&lt;T&gt; {\n BinaryTree&lt;T&gt; left();\n BinaryTree&lt;T&gt; right();\n T element();\n}\n</code></pre>\n\n<p>And than we fill it with runnable code.</p>\n\n<pre><code>public class BinaryTree&lt;T&gt; {\n public BinaryTree&lt;T&gt; left() { return left; }\n public BinaryTree&lt;T&gt; right() { return right; }\n public T element() { return element; }\n\n private BinaryTree&lt;T&gt; left, right;\n private T element;\n\n public BinaryTree(List&lt;? extends T&gt; bfsRepresentation) {\n final List&lt;? extends T&gt; items;\n items = new ArrayList&lt;&gt;( bfsRepresentation );\n create( items );\n }\n ...\n}\n</code></pre>\n\n<p>The <code>create</code> method assumes that <code>items</code> is always random access list. Well, it is if we consider only the test methods. If it gets called with a very large LinkedList, you will get quadratic performance.</p>\n\n<p>Consider copying the list in an <code>java.util.ArrayList</code>. An array, <code>T[]</code>, should do the trick too, and its preferrable.</p>\n\n<p>Last piece of advice, consider parameterized unit tests in JUnit. There's a good example how to use it in their <a href=\"https://github.com/junit-team/junit/wiki/Parameterized-tests\" rel=\"nofollow\">github wiki</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T02:21:12.527", "Id": "47690", "ParentId": "47550", "Score": "1" } }, { "body": "<p>A minor bug: You get an <code>IndexOutOfBoundsException</code> for an empty list in <code>LeftView.create(List&lt;? extends T&gt; items)</code>. You don't have a comment stating you need to input a list containing at least something. Consider returning <code>IllegalArgumentException</code> and adding a comment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-17T11:15:36.220", "Id": "63144", "ParentId": "47550", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T08:01:02.053", "Id": "47550", "Score": "2", "Tags": [ "java", "algorithm", "tree" ], "Title": "Print left view of the tree" }
47550
<p>This post is a <a href="https://codereview.stackexchange.com/questions/47066/check-if-xmlnode-with-certain-attribute-exists-and-create-xmlnode-if-not">follow up question</a>.</p> <p>The purpose of this class should became clear without any further explanation. Raise your hand. If not, then I will have to improve the naming/structure.</p> <p>I would like to know how to improve this code in terms of readability and complexity.</p> <p><strong>Data structure:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;QuoteApp&gt; &lt;Authors&gt; &lt;Author AuthorId="1" Firstname="William" Lastname="Shakespeare"&gt; &lt;Profession&gt;englischer Dramatiker, Lyriker und Schauspieler&lt;/Profession&gt; &lt;DayOfBirth&gt;Sonntag, 26. April 1564&lt;/DayOfBirth&gt; &lt;DayOfDeath&gt;Dienstag, 3. Mai 1616&lt;/DayOfDeath&gt; &lt;/Author&gt; &lt;Author AuthorId="2" Firstname="Friedrich" Lastname="Nietzsche"&gt; &lt;Profession&gt;deutscher Philologe und Philosoph&lt;/Profession&gt; &lt;DayOfBirth&gt;1844-10-15&lt;/DayOfBirth&gt; &lt;DayOfDeath&gt;1900-08-25&lt;/DayOfDeath&gt; &lt;/Author&gt; &lt;/Authors&gt; &lt;Quotes&gt; &lt;/Quotes&gt; &lt;/QuoteApp&gt; </code></pre> <p><strong>XmlFileHandler class</strong></p> <pre><code>public class XmlFileHandler { #region fields private const string FileName = "quotes.xml"; private const string DateFormatPattern = "yyyy-MM-dd"; private readonly XDocument xmlQuotes; #endregion #region XML Element / Attribute names private const string RootNodeName = "QuoteApp"; private const string AuthorsNodeName = "Authors"; private const string AuthorNodeName = "Author"; private const string QuotesNodeName = "Quotes"; private const string QuoteNodeName = "Quote"; private const string AuthorElementAuthorId = "AuthorId"; private const string AuthorElementFirstname = "Firstname"; private const string AuthorElementLastname = "Lastname"; private const string AuthorElementProfession = "Profession"; private const string AuthorElementDayOfBirth = "DayOfBirth"; private const string AuthorElementDayOfDeath = "DayOfDeath"; private const string AuthorElementImage = "Picture"; private const string QuoteElementQuoteId = "QuoteId"; private const string QuoteElementText = "Text"; private const string QuoteElementAuthorId = "AuthorId"; #endregion #region Singleton private static volatile XmlFileHandler instance; private static readonly object SyncRoot = new Object(); public static XmlFileHandler Instance { get { if (instance == null) { lock (SyncRoot) { if (instance == null) instance = new XmlFileHandler(); } } return instance; } } #endregion private XmlFileHandler() { this.xmlQuotes = XDocument.Load(FileName); } #region Create XML File public void CreateXmlFile() { if (File.Exists(FileName)) return; var settings = new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Document, Indent = true }; using (var writer = XmlWriter.Create(FileName, settings)) { writer.WriteStartDocument(); writer.WriteStartElement(RootNodeName); writer.WriteStartElement(AuthorsNodeName); writer.WriteEndElement(); writer.WriteStartElement(QuotesNodeName); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); } } #endregion #region Add Author to XML File public bool AddAuthor(Author author) { var authorExists = CheckIfAuthorAlreadyExists(author.AuthorId); if (!authorExists) { this.AddAuthorToXmlDocument(author); return true; } return false; } private bool CheckIfAuthorAlreadyExists(int authorId) { var xmlAuthorList = xmlQuotes.Descendants(AuthorsNodeName).Descendants(AuthorNodeName); var xElements = from xmlAuthor in xmlAuthorList let xElement = xmlAuthor.Element(AuthorElementAuthorId) where xElement != null &amp;&amp; xElement.Value == authorId.ToString(CultureInfo.InvariantCulture) select xmlAuthor; return xElements.Any(); } private void AddAuthorToXmlDocument(Author author) { var authorsNode = xmlQuotes.Descendants(AuthorsNodeName).FirstOrDefault(); if (authorsNode != null) { authorsNode.Add(this.CreateAuthorXmlNode(author)); xmlQuotes.Save(FileName); } } private XElement CreateAuthorXmlNode(Author author) { var xmlAuthor = new XElement(AuthorNodeName); xmlAuthor.Add(new XAttribute(AuthorElementAuthorId, author.AuthorId.ToString(CultureInfo.InvariantCulture))); xmlAuthor.Add(new XAttribute(AuthorElementFirstname, author.Firstname)); xmlAuthor.Add(new XAttribute(AuthorElementLastname, author.Lastname)); xmlAuthor.Add(new XElement(AuthorElementProfession) { Value = author.Profession }); xmlAuthor.Add(new XElement(AuthorElementDayOfBirth) { Value = author.DayOfBirth.ToString(DateFormatPattern) }); xmlAuthor.Add(new XElement(AuthorElementDayOfDeath) { Value = author.DayOfDeath.ToString(DateFormatPattern) }); return xmlAuthor; } #endregion #region Retrieve Authors public ObservableCollection&lt;Author&gt; RetrieveAuthorCollection() { var authorCollection = new ObservableCollection&lt;Author&gt;(); var authorList = xmlQuotes.Descendants(AuthorsNodeName).Descendants(AuthorNodeName); foreach (var xmlAuthor in authorList) { var tmpAuthor = new Author(); var authorId = xmlAuthor.Attribute(AuthorElementAuthorId); var firstname = xmlAuthor.Attribute(AuthorElementFirstname); var lastname = xmlAuthor.Attribute(AuthorElementLastname); var profession = xmlAuthor.Element(AuthorElementProfession); var dayOfBirth = xmlAuthor.Element(AuthorElementDayOfBirth); var dayOfDeath = xmlAuthor.Element(AuthorElementDayOfDeath); if (authorId != null) tmpAuthor.AuthorId = Convert.ToInt32(authorId.Value); if (firstname != null) tmpAuthor.Firstname = firstname.Value; if (lastname != null) tmpAuthor.Lastname = lastname.Value; if (profession != null) tmpAuthor.Profession = profession.Value; if (dayOfBirth != null) tmpAuthor.DayOfBirth = Convert.ToDateTime(dayOfBirth.Value); if (dayOfDeath != null) tmpAuthor.DayOfDeath = Convert.ToDateTime(dayOfDeath.Value); authorCollection.Add(tmpAuthor); } return authorCollection; } #endregion #region Retrieve next IDs public int NextAuthorId() { var authorList = xmlQuotes.Descendants(AuthorsNodeName).Descendants(AuthorNodeName); //TODO: ReSharper warns about "Possible multiple enumeration of IEnumerable", whats this all about? var authorWithHighestId = authorList.Any() ? authorList.Max(author =&gt; (int)author.Attribute(AuthorElementAuthorId)) : 0; authorWithHighestId++; return authorWithHighestId; } public int NextQuoteId() { var quoteList = xmlQuotes.Descendants(QuotesNodeName).Descendants(QuoteNodeName); //TODO: ReSharper warns about "Possible multiple enumeration of IEnumerable", whats this all about? var quoteWithHighestId = quoteList.Any() ? quoteList.Max(quote =&gt; (int)quote.Attribute(QuoteElementQuoteId)) : 0; quoteWithHighestId++; return quoteWithHighestId; } #endregion } </code></pre>
[]
[ { "body": "<blockquote>\n <p>//TODO: ReSharper warns about \"Possible multiple enumeration of\n IEnumerable\", whats this all about?</p>\n</blockquote>\n\n<p>Because you are working with an <code>IEnumerable</code> it's possible that the underlying implementation of the method will re-execute any re-loading of the data set each time you are enumerating it. Hence if that involved querying a database table you might make multiple calls into the database each time.</p>\n\n<p>So Resharper suggests you do a <code>ToList()</code> on the Enumerable to force the result set to be fetched and returned into a list so that from then on you are only enumerating the objects in the list in memory.</p>\n\n<p>If you know for certain that the <code>IEnumerable</code> will not do any re-fetching etc then you could ignore this warning from resharper. </p>\n\n<p>So in your specific case:</p>\n\n<pre><code>// Will query a datasource\nauthorList.Any()\n\n// Might also requry the same datasource even though it shouldn't need to\nauthorList.Max(author =&gt; (int)author.Attribute(AuthorElementAuthorId))\n</code></pre>\n\n<p>My full (only slightly modified code) is below, but a summary of the mods I made include:</p>\n\n<ol>\n<li><p>I personally like to return early and avoid nesting if I can as I feel it helps readability. For example.</p>\n\n<pre><code>private bool AddAuthorToXmlDocument(Author author)\n{\n var authorsNode = xmlQuotes.Descendants(AuthorsNodeName).FirstOrDefault();\n\n if (authorsNode == null)\n return false;\n // ...\n}\n</code></pre></li>\n<li><p>I noticed a little bit of code duplication so attempted to remove that.</p>\n\n<pre><code>public int NextQuoteId()\n{\n var quoteWithHighestId = NextElementId(\n QuotesNodeName,\n QuoteNodeName,\n QuoteElementQuoteId);\n\n return quoteWithHighestId++;\n}\n</code></pre></li>\n<li><p>I'm not sure of the purpose of the <code>CreateXmlFile</code>() method. If we are reading the file when we first access the singleton instance why do we need this method at all to be public? could we not ensure it exists in our constructor?</p></li>\n<li><p>When using the singleton pattern I always like refer to <a href=\"http://csharpindepth.com/articles/general/singleton.aspx\" rel=\"nofollow\">Jon Skeet's</a> article on it.</p></li>\n</ol>\n\n<p>Here is a crack at a revised code solution:</p>\n\n<pre><code>public sealed class XmlFileHandler\n{\n #region fields\n\n private const string FileName = \"quotes.xml\";\n private const string DateFormatPattern = \"yyyy-MM-dd\";\n private readonly XDocument xmlQuotes;\n\n #endregion\n\n #region XML Element / Attribute names\n private const string RootNodeName = \"QuoteApp\";\n private const string AuthorsNodeName = \"Authors\";\n private const string AuthorNodeName = \"Author\";\n private const string QuotesNodeName = \"Quotes\";\n private const string QuoteNodeName = \"Quote\";\n\n private const string AuthorElementAuthorId = \"AuthorId\";\n private const string AuthorElementFirstname = \"Firstname\";\n private const string AuthorElementLastname = \"Lastname\";\n private const string AuthorElementProfession = \"Profession\";\n private const string AuthorElementDayOfBirth = \"DayOfBirth\";\n private const string AuthorElementDayOfDeath = \"DayOfDeath\";\n private const string AuthorElementImage = \"Picture\";\n\n private const string QuoteElementQuoteId = \"QuoteId\";\n private const string QuoteElementText = \"Text\";\n private const string QuoteElementAuthorId = \"AuthorId\";\n #endregion\n\n #region Singleton\n private static readonly XmlFileHandler instance = new XmlFileHandler();\n\n // Explicit static constructor to tell C# compiler\n // not to mark type as beforefieldinit\n static XmlFileHandler()\n {\n }\n\n private XmlFileHandler()\n {\n this.xmlQuotes = XDocument.Load(FileName);\n }\n\n public static XmlFileHandler Instance\n {\n get\n {\n return instance;\n }\n }\n\n #endregion\n\n #region Create XML File\n\n public void CreateXmlFile()\n {\n if (File.Exists(FileName)) return;\n\n var settings = new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Document, Indent = true };\n\n using (var writer = XmlWriter.Create(FileName, settings))\n {\n writer.WriteStartDocument();\n writer.WriteStartElement(RootNodeName);\n\n writer.WriteStartElement(AuthorsNodeName);\n writer.WriteEndElement();\n\n writer.WriteStartElement(QuotesNodeName);\n writer.WriteEndElement();\n\n writer.WriteEndElement();\n writer.WriteEndDocument();\n }\n }\n\n #endregion\n\n #region Add Author to XML File\n\n public bool AddAuthor(Author author)\n {\n return !AuthorAlreadyExists(author.AuthorId) &amp;&amp;\n AddAuthorToXmlDocument(author);\n }\n\n private bool AuthorAlreadyExists(int authorId)\n {\n var xmlAuthorList = Elements(AuthorsNodeName, AuthorNodeName);\n var xElements = from xmlAuthor in xmlAuthorList\n let xElement = xmlAuthor.Element(AuthorElementAuthorId)\n where xElement != null &amp;&amp; xElement.Value == authorId.ToString(CultureInfo.InvariantCulture)\n select xmlAuthor;\n\n return xElements.Any();\n }\n\n private bool AddAuthorToXmlDocument(Author author)\n {\n var authorsNode = xmlQuotes.Descendants(AuthorsNodeName).FirstOrDefault();\n\n if (authorsNode == null)\n return false;\n\n authorsNode.Add(this.CreateAuthorXmlNode(author));\n xmlQuotes.Save(FileName); \n return true;\n }\n\n private XElement CreateAuthorXmlNode(Author author)\n {\n var xmlAuthor = new XElement(AuthorNodeName);\n\n xmlAuthor.Add(new XAttribute(AuthorElementAuthorId, author.AuthorId.ToString(CultureInfo.InvariantCulture)));\n xmlAuthor.Add(new XAttribute(AuthorElementFirstname, author.Firstname));\n xmlAuthor.Add(new XAttribute(AuthorElementLastname, author.Lastname));\n xmlAuthor.Add(new XElement(AuthorElementProfession) { Value = author.Profession });\n xmlAuthor.Add(new XElement(AuthorElementDayOfBirth) { Value = author.DayOfBirth.ToString(DateFormatPattern) });\n xmlAuthor.Add(new XElement(AuthorElementDayOfDeath) { Value = author.DayOfDeath.ToString(DateFormatPattern) });\n\n return xmlAuthor;\n }\n\n #endregion\n\n #region Retrieve Authors\n\n public ObservableCollection&lt;Author&gt; RetrieveAuthorCollection()\n {\n var authorCollection = new ObservableCollection&lt;Author&gt;();\n\n var authorList = Elements(AuthorsNodeName, AuthorNodeName);\n\n foreach (var xmlAuthor in authorList)\n {\n var authorId = xmlAuthor.Attribute(AuthorElementAuthorId);\n var firstname = xmlAuthor.Attribute(AuthorElementFirstname);\n var lastname = xmlAuthor.Attribute(AuthorElementLastname);\n var profession = xmlAuthor.Element(AuthorElementProfession);\n var dayOfBirth = xmlAuthor.Element(AuthorElementDayOfBirth);\n var dayOfDeath = xmlAuthor.Element(AuthorElementDayOfDeath);\n\n if (authorId != null) tmpAuthor.AuthorId = Convert.ToInt32(authorId.Value);\n if (firstname != null) tmpAuthor.Firstname = firstname.Value;\n if (lastname != null) tmpAuthor.Lastname = lastname.Value;\n if (profession != null) tmpAuthor.Profession = profession.Value;\n if (dayOfBirth != null) tmpAuthor.DayOfBirth = Convert.ToDateTime(dayOfBirth.Value);\n if (dayOfDeath != null) tmpAuthor.DayOfDeath = Convert.ToDateTime(dayOfDeath.Value);\n\n authorCollection.Add(tmpAuthor);\n }\n\n return authorCollection;\n }\n\n #endregion\n\n #region Retrieve next IDs\n\n public int NextAuthorId()\n { \n var authorWithHighestId = NextElementId(AuthorsNodeName,AuthorNodeName,AuthorElementAuthorId);\n\n // Note this isn't exactly thread safe if that is a concern in this application\n return authorWithHighestId++;\n }\n\n public int NextQuoteId()\n {\n var quoteWithHighestId = NextElementId(QuotesNodeName,QuoteNodeName,QuoteElementQuoteId);\n return quoteWithHighestId++;\n }\n\n #endregion\n\n private int NextElementId(string nodesName, string nodeName, string elementId)\n {\n var noteList = Elements(nodesName, nodeName);\n\n return noteList.Any() ? noteList.Max(quote =&gt; (int)quote.Attribute(elementId)) : 0; \n }\n\n private List&lt;Element&gt; Elements(string nodesName, string nodeName)\n {\n return xmlQuotes.Descendants(nodesName).Descendants(nodeName).ToList();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:23:32.430", "Id": "83531", "Score": "0", "body": "Thank you for the great review & explanation! The NextId() method should be thread safe now, I increment the IDs using Interlocked.Increment(ref quoteWithHighestId)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T08:48:24.333", "Id": "47554", "ParentId": "47551", "Score": "2" } } ]
{ "AcceptedAnswerId": "47554", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T08:05:44.573", "Id": "47551", "Score": "2", "Tags": [ "c#", "xml" ], "Title": "Manage XML file with custom XmlFileHandler class" }
47551
<p>I'm working on a Pong game and right now I'm working on being able to register multiple KeyDown presses simulatenously. I used the Win32 native method <code>GetKeyBoardState</code> first to loop through all of the virtual keys and see if any of the keys matched the game input keys. Now this worked just fine but in the interest of optimization I figured that it would be quicker to use <code>GetKeyState</code> since there are only 4 valid input keys and then simply check if any of those keys are pressed down. </p> <p>Surprisingly it is incredibly slow and choppy, a lot worse than <code>GetKeyBoardState</code> so I'm wondering if there's something in my code that's slowing it down. Here's the complete implementation</p> <p><strong>NativeMethods.cs</strong></p> <pre><code>internal static class NativeMethods { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetKeyboardState(byte[] lpKeyState); [DllImport("user32.dll")] internal static extern short GetKeyState(int nVirtKey); } </code></pre> <p><strong>Keyboard.cs</strong></p> <pre><code>static class Keyboard { public static bool GetKeyState(Keys vKey) { short results = NativeMethods.GetKeyState((int)vKey); // We're only going to use this to look for arrow keys so // No need to differntiate results based on low or high order bits switch (results) { case 0: //KEY STATE: NOT PRESSED return false; case -127: //KEY STATE: PRESSED return true; } return false; } </code></pre> <p><strong>GameForm.cs</strong></p> <pre><code> private void GameForm_KeyDown(object sender, KeyEventArgs e) { var movementData = new Tuple&lt;int, Move&gt;(-1, Pong.Move.Down); //Check how many keys that are pressed down (for example both players might be moving their paddles simulatenously) var pressedKeys = inputKeys.Where(key =&gt; Keyboard.GetKeyState(key)); //Check if pressed key equals any of the player assigned keys.. If so call MovePaddle() foreach (Keys key in pressedKeys) { switch (key) { case Keys.Up: movementData = Tuple.Create(0, Pong.Move.Up); break; case Keys.Down: movementData = Tuple.Create(0, Pong.Move.Down); break; case Keys.W: movementData = Tuple.Create(1, Pong.Move.Up); break; case Keys.S: movementData = Tuple.Create(1, Pong.Move.Down); break; } gameController.MovePaddle(movementData.Item1, movementData.Item2); } } </code></pre>
[]
[ { "body": "<p>What is impacting you performance so heavily is the creation of Tuples <strong>everytime</strong> you recieve a keypressed event.</p>\n\n<p>creating objects is <strong>slow</strong>. What you should do instead is, directly apply the changes to the moving objects (your two pong-thingies).</p>\n\n<pre><code>private void GameForm_KeyDown(object sender, KeyEventArgs e)\n{\n var pressedKeys = inputKeys.Where(key =&gt; Keyboard.GetKeyState(key));\n foreach(Keys key in pressedKeys)\n switch(key){\n case Keys.Up:\n leftPong.Positon += FIXEDVALUE;\n break;\n case Keys.Down:\n leftPong.Position -= FIXEDVALUE;\n break;\n //continue...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:46:20.130", "Id": "83366", "Score": "0", "body": "Are you saying that there's a big difference in performance inbetween creating one instance of an integer, one instance of an enum and create one instance of a tuple to hold aforementioned instances? I must admit I didn't think that tuples would take up a lot of resources." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T10:09:44.123", "Id": "83369", "Score": "0", "body": "@Overly It's not the creation in itself, but the interval in which it's perfomed" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T19:12:23.833", "Id": "83660", "Score": "1", "body": "Sounds unlikely. Creating objects only matters if you do it millions of times per second." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:38:54.770", "Id": "47558", "ParentId": "47556", "Score": "2" } }, { "body": "<p>Your <code>bool GetKeyState</code> is incorrect. The reason for this is that the comment</p>\n\n<blockquote>\n <p>No need to differntiate results based on low or high order bits</p>\n</blockquote>\n\n<p>is wrong. The low bit will alternate between 0 and 1 for all keys, not just caps-lock/num-lock/scroll-lock. So the method will return <code>false</code> for every second key-press.</p>\n\n<p>Replace it by:</p>\n\n<pre><code>public static bool GetKeyState(Keys vKey)\n{\n short state = NativeMethods.GetKeyState((int)vKey);\n return (state &amp; 0x80) != 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T19:19:18.097", "Id": "47734", "ParentId": "47556", "Score": "2" } } ]
{ "AcceptedAnswerId": "47734", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:16:00.937", "Id": "47556", "Score": "3", "Tags": [ "c#", "object-oriented", "event-handling" ], "Title": "Registering multiple keypresses simultaneously, very slow" }
47556
<p>Simple idea: just have a plugin (more a basic function). That I can use with jQuery in different ways it offers, means:</p> <pre><code>var myNewVar = $.myNewFunction( myVar ); var myNewVar = $().myNewFunction( myVar ); </code></pre> <p>I want to know if what I did is the good way to doesn't repeat the code, or if their is a better way to.</p> <p>Here my plugin:</p> <pre><code>// New function to jquery to change an array (from form) to an object $.formArrayToObject = function( array ) { var form = {}; $(array).each(function(){ if( !form[this.name] ) { form[this.name] = this.value; } else { if ( !Array.isArray(form[this.name]) ) { form[this.name] = [form[this.name]]; } form[this.name].push(this.value); } }); return form; }; // Second declaration to be able to call both $. and $(). jQuery.fn.formArrayToObject = function() { $.formArrayToObject(); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:49:41.033", "Id": "83367", "Score": "0", "body": "And I'm open to any other suggestion about my code if there is" } ]
[ { "body": "<p>Since your function - as far as I can tell - doesn't rely on a jQuery collection, I'd stick to always using \"1 true way\" of calling it.<br>\nI.e. I assume that</p>\n\n<pre><code>$(\"some &gt; selector\").formArrayToObject(arr) === $.formArrayToObject(arr);\n</code></pre>\n\n<p>that is, the two ways of calling it give the same exact result.</p>\n\n<p>If that's the case, just use <code>$.yourFunction</code> and <em>only</em> that. Having two invocations that <em>should</em> be semantically different but actually aren't is just confusing.</p>\n\n<p>For instance, jQuery doesn't have both <code>$.ajax()</code> <em>and</em> <code>$(...).ajax()</code> simply because the latter doesn't really make sense; the <code>$.ajax</code> function isn't dependent on a certain context or selector, so why would you call it as if it was?</p>\n\n<p>(besides, your second declaration in the code above is broken; it ignores arguments)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T11:09:05.733", "Id": "47565", "ParentId": "47559", "Score": "4" } } ]
{ "AcceptedAnswerId": "47565", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:43:33.130", "Id": "47559", "Score": "1", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "jQuery plugin creation and declaration for usage with $(). or $" }
47559
<p>For my Advanced Data Mining class (undergrad) we were to design a program that would predict the next word a user is likely to type via automatic text classification using the n-gram model.</p> <p>The following is what I came up with. The reason I am posting this is because I am about to graduate and I want to be aware of any bad habits, inefficiencies, or examples of poor implementation that I might be prone to before I have to go out and interview for Data Science Graduate programs. Unfortunately, my professors are too busy to give this kind of analysis and it seems like they just grade us on whether a program works or not (this one does).</p> <p>Note: This program uses the AOL search data from <a href="http://www.infochimps.com/datasets/aol-search-data" rel="nofollow">here</a> in a text file called searchterms.txt.</p> <pre><code>import java.io.*; import java.util.*; public class AutoComplete { static LinkedList&lt;String&gt; sentences = new LinkedList&lt;String&gt;(); public static void main(String[] args) throws FileNotFoundException { /* Define Variables */ int n = 3; Hashtable&lt;String, Hashtable&lt;String, Double&gt;&gt; nGram = new Hashtable&lt;String, Hashtable&lt;String, Double&gt;&gt;(); Scanner inFile = new Scanner(new File("searchterms.txt")); Scanner input = new Scanner(System.in); /* Output for progress tracking */ System.out.println("Reading in search data..."); /* Populate the LinkedList sentences with data from AOL search dataset */ while(inFile.hasNext()) { String unparsed = inFile.nextLine().intern(); String[] parsed = unparsed.split("\t"); sentences.add("&lt;S&gt; " + parsed[1] + " &lt;/S&gt;"); } inFile.close(); /* Output for progress tracking */ System.out.println("Successfully archived searches."); System.out.println("Creating 3 grams..."); /* Split sentences into words */ for(String s : sentences) { String[] words = s.split("[\\s]"); for(int i = 0; i &lt;= words.length-n; i++) { if(nGram.containsKey(words[i] + " " + words[i+1])) { //Output for testing //System.out.println("MATCH FOUND! ("+ words[i+2]+") Incrementing..."); if(nGram.get(words[i]+" "+words[i+1]).containsKey(words[i+2])) { double v = nGram.get(words[i] + " " + words[i+1]).get(words[i+2]); v++; nGram.get(words[i] + " " + words[i+1]).put(words[i+2], v); } else { nGram.get(words[i] + " " + words[i+1]).put(words[i+2], 1.0); } } else { //Output for testing //System.out.println("No match found. Adding..." + words[i+2]); nGram.put(words[i]+" "+words[i+1], createResult(words[i+2])); } } } /* Output for progress tracking */ System.out.println("Successfully created 3 grams."); /* Loop so you can play with this forever */ String sTerm = ""; while(true) { /* Request User Input */ System.out.println("Please enter your search terms (or type /q to quit):"); sTerm = input.nextLine(); if (sTerm.equalsIgnoreCase("/q")) break; /* Format user input */ String[] terms = sTerm.split("[\\s]"); if (terms.length &lt; 2) { sTerm = "&lt;S&gt; " + terms[0]; //Output for testing //System.out.println(sTerm); } else { sTerm = terms[terms.length-2] + " " + terms[terms.length-1]; //Output for testing //System.out.println(sTerm); } /* Normalize to percent values */ double sum = 0; try { for(String s : nGram.get(sTerm).keySet()) { sum += nGram.get(sTerm).get(s); } for(String s : nGram.get(sTerm).keySet()) { nGram.get(sTerm).put(s, nGram.get(sTerm).get(s)/sum); } } catch (Exception NullPointerException) { System.out.println("Search query not found in database."); } /* Give prediction */ try { System.out.println("Prediction: " + prediction(nGram.get(sTerm)) + " ("+ Math.round(predValue(nGram.get(sTerm))*100) +"%)"); } catch (Exception NullPointerException) { System.out.println("Cannot make a prediction."); } /* Testing block */ //System.out.println(nGram.get(sTerm).keySet()); //System.out.println(nGram.get(sTerm).values()); } input.close(); } /* Needed for scope */ static final Hashtable&lt;String, Double&gt; createResult(String s) { Hashtable&lt;String, Double&gt; result = new Hashtable&lt;String, Double&gt;(); result.put(s, 1.0); return result; } /* Prediction methods */ static final String prediction(Hashtable&lt;String, Double&gt; h) { String key = ""; double max = 0; for(String s : h.keySet()) { if(h.get(s) &gt; max) { max = h.get(s); key = s; } } return key; } static final double predValue(Hashtable&lt;String, Double&gt; h) { double max = 0; for(String s : h.keySet()) { if(h.get(s) &gt; max) { max = h.get(s); } } return max; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T09:27:13.537", "Id": "83612", "Score": "0", "body": "Thanks for the edit! I was struggling with the formatting of the post if you couldn't tell haha" } ]
[ { "body": "<p>Your code looks <em>at first glance</em> quite complete and professional, so onto the points. I hereby assume that you are using Java 7, since you have not made any restrictions and it is the most common version, though I may be wrong.</p>\n\n<ol>\n<li><p>Consider changing your programs design. Currently you have an <code>AutoComplete</code> class, with almost everything in the main class. Now what happens if you want to run two <code>AutoComplete</code> instances simultaneously? You cannot do that in one program.<br>\nI would advice to change the following points:</p>\n\n<ol>\n<li>Make an <code>AutoComplete</code> class that can operate on it's own, you tell it what to do, what the inputs are, and you can call methods on it that give you output.</li>\n<li>One candidate for refactoring is the input file, this should be an input argument.</li>\n<li>Another point is that you request user input inside your processing, the user input should be asked beforehand and also be an input parameter.</li>\n<li>The prediction which gets printed while processing, should be an output.</li>\n</ol></li>\n<li><p>Use diamond inference where possible, this means that for example <code>LinkedList&lt;String&gt; sentences = new LinkedList&lt;String&gt;();</code> can be written as <code>LinkedList&lt;String&gt; sentences = new LinkedList&lt;&gt;();</code>.</p></li>\n<li><p>Code against interfaces instead of against classes. Take your <code>LinkedList&lt;String&gt; sentences</code> again. Nowhere I see a <em>requirement</em> to use a <code>LinkedList</code> here, you just want to use a list, so only constrain yourself to writing: <code>List&lt;String&gt; sentences = new LinkedLIst&lt;&gt;()</code>. This allows you to change the exact type of <code>List</code> at a later point.</p></li>\n<li><p>I see that you only loop over the <code>LinkedList&lt;String&gt; sentences</code>, you have no special requirement to use a linked list, consider using the more or less default <code>ArrayList</code>, which provides constant lookup times and <strong>generally</strong> performs better. In your case the performance seems to be equal as all you do is, underlying to the enhanced for-loop, use an <code>Iterator</code>.</p></li>\n<li><p>Consider changing from using the <code>File</code> API to the <code>Path</code> API at some point, it offers more future-ready changes and will coöperate better with Java 8.</p></li>\n<li><p>Prefer a class that receives print statements over directly printing to <code>System.out</code> during processing. In bigger projects this usually is a logger framework, to which you then attach <code>System.out</code> writers and also file writers for logfiles. In your case you may use a simplified version of this.</p></li>\n<li><p>A <code>Hashtable</code> is old, <strong>very old</strong>, use the nowadays standard called <code>Map</code>, with as default implementation a <code>HashMap</code>. Some method names/semantics may have changed, but they both serve the same purpose.</p></li>\n<li><p>Do not catch all exceptions with <code>Exception NullPointerException</code>, you may have confused yourself here, but this catches all exceptions of type <code>Exception</code> (so all), and gives the caught exception the name <code>NullPointerException</code>. But even then, catching <code>NullPointerException</code>s is not good and you should just let them fall through such that they terminate your program (or thread), so you can actually fix the issue, rather than a <em>Cannot make prediction.</em> message.</p></li>\n</ol>\n\n<p>As a whole, the best advice I can give you is to consider more abstraction, make your methods smaller and give them a single responsibility. A very important second advice is to use language features that are the standard in this day.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T10:49:23.367", "Id": "83618", "Score": "1", "body": "Yep, Java 7. \n\n1. That all makes a lot of sense. I think I was a little short-sighted when I wrote it and I didn't think much about scalability. I will definitely do this in the future.\n\n2. I've seen that before, but it isn't something we actively learned. What's the advantage to using diamond inference? \n\n3. Ahh, I totally understand. I guess since I am used to using LinkedLists for that type of operation I didn't think much further. I can see the added flexability I would get from using the interface List instead. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T10:50:18.730", "Id": "83619", "Score": "0", "body": "4. Wow. I hadn't even considered ArrayList. I completely forgot about them. I think I lied above. I'm not used to using LinkedLists for that type of operation... I think I use them for everything. Oops. Glad you pointed that out.\n\n5. Got it. \n\n6. Oh, yeah. I see what you're saying. That makes a lot of sense for industry (which is the way I'm trying to convert my thinking). Since my original concern was more about the theory of what I was doing I just programmed this to run from a .bat on a local machine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T10:50:40.170", "Id": "83620", "Score": "0", "body": "After I finished I wanted to try to make a better standalone program and I never really thought about how larger projects would handle my output. I always envisioned this to be a part of something larger, so definitely something to consider.\n\n7. What the actual f---. We spent a ton of time learning Hashtables and we never touched Maps. That's really frustrating.\n\n8. Definitely confused myself. I thought I was catching an Exception of type NullPointerException. I guess I meant catch(NullPointerException NoDatasetValue)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T10:51:19.983", "Id": "83621", "Score": "0", "body": "The message was more for me playing with the project, so that when I typed in something obscure I didn't have to restart it when it failed. (Building 3 grams for 3.6 million search phrases takes a little bit)\n\nThanks for all the advice, it will definitely help me a lot going forward. I've learned a lot in school, but I know its going to be a whole different world when I graduate and I'd like to be as prepared as possible - as little as that may be!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T11:06:35.433", "Id": "47564", "ParentId": "47560", "Score": "4" } }, { "body": "<p>Although all points made by @skiwi are valid (+1), he missed a few important points:</p>\n\n<h2>\"Use exceptions only for exceptional conditions\" (Effective Java Item 57)</h2>\n\n<pre><code>try {\n /* ... */ nGram.get(sTerm).xyz /* ... */\n} catch (NullPointerException e) {\n System.out.println(\"Search query not found in database.\");\n}\n</code></pre>\n\n<p>Do not use <code>try/catch</code> to control normal program flow.</p>\n\n<pre><code>Map&lt;String, Double&gt; nGramForSearchTerm = nGram.get(sTerm);\n\nif (nGramForSearchTerm == null) {\n System.out.println(\"Search query not found in database.\");\n System.out.println(\"Cannot make a prediction.\");\n System.exit(0);\n}\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>As noted in the comments by @200_success; \"NullPointerExceptions can lurk anywhere in the code, and arise due to programmer error rather than unexpected runtime conditions.\" Therefore catching <code>NullPointerException</code> is practically always a bad idea. Whenever you find yourself writing <code>catch (NullPointerException</code> you should stop and think. If you are catching <code>NullPointerException</code> because some method may return <code>null</code>, convert it to a null checking conditional instead. If you are writing it because it was thrown somewhere else, then first track the cause (to a piece of code you are responsible, most probably the scope where you are writing the <code>try/catch</code>) and handle it at the point it was caused; with a null check as above or checking with <code>Map.containsKey()</code>, <code>Collection.isEmpty()</code>, <code>Iterator.hasNext()</code> etc.</p>\n\n<h2>DRY: Do not repeat yourself. Factor out repeated sections and give them meaningful names.</h2>\n\n<p>One is <code>nGram.get(sTerm)</code>. I called it <code>nGramForSearchTerm</code> but you can give it a more meaningful name.</p>\n\n<p>The more important example is <code>predValue</code>/<code>prediction</code>.\nRepetition is evil. And repetition of algorithm (business logic) is a great evil.\nThe cause of the repetition is that Java does not allow more than one value to be returned.\nBut this is not really a problem unless you suffer from <a href=\"http://c2.com/cgi/wiki?PrimitiveObsession\" rel=\"nofollow\">primitive obsession</a> also. Just define a new <a href=\"http://c2.com/cgi/wiki?ValueObject\" rel=\"nofollow\">value object</a> <code>Prediction</code> and put the values that would be returned as fields in it.</p>\n\n<pre><code>static class Prediction {\n private final String nGram;\n private final double confidence;\n // constructor getters only.\n}\n\nstatic Prediction getBestPrediction(Map&lt;String, Double&gt; /* TODO rename this */ map) {\n if (map.isEmpty()) throw new IllegalArgumentException();\n\n String bestPrediction = null;\n double bestConfidence = 0;\n for(Entry&lt;String, Double&gt; entry : map.entrySet()) {\n String currentPrediction = entry.getKey();\n double currentConfidence = entry.getValue();\n\n if (currentConfidence &gt; bestConfidence) {\n bestConfidence = currentConfidence;\n bestPrediction = currentPrediction;\n }\n }\n return new Prediction(bestPrediction, bestConfidence);\n}\n</code></pre>\n\n<p>Some points to note (and apply to other parts of the original code). If you are iterating over all keys of a <code>Map</code> and looking up that map for all (or many) of those keys, use <code>Map.entrySet()</code> instead.</p>\n\n<h2>Do normalization once in the beginning</h2>\n\n<p>Also in the DRY vein. You should do normalization once in the beginning for all values.</p>\n\n<ul>\n<li><p>Since the latter part of the algorithm depends on normalized values, you should give it a normalized data structure, and relieve the reader of the code from the mental burden of trying to figure out which values of the said data structure are normalized and when.</p></li>\n<li><p>Floating point arithmetic <code>double</code> arithmetic is inexact. So <strong>doing normalization on already normalized values is not idempotent</strong>. (You may not notice a difference, or giving the confidence level false in the nth decimal place may not be important but this is a design issue. It may be serious issue later. Looking up values should be idempotent, should not modify used data structures.)</p>\n\n<p>Some examples of 20 1s normalized repeatedly:</p>\n\n<pre><code> 0.04999999999999999\n 0.049999999999999975\n 0.05000000000000002\n 0.04999999999999998\n 0.050000000000000024\n 0.04999999999999999\n 0.049999999999999975\n 0.05000000000000002\n 0.04999999999999998\n 0.050000000000000024\n</code></pre></li>\n<li><p>Normalizing upfront, it may cause a slight performance depending on the size of the DB, but <em>it will improve the performance of <strong>each</strong> individual lookup</em>, which is what you want. (As a side note: Where there are many possible misses in a lookup, a bloom filter may be indicated.)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T10:14:29.357", "Id": "84270", "Score": "0", "body": "Catching `NullPointerException` is particularly bad, since `NullPointerException`s can lurk anywhere in the code, and arise due to programmer error rather than unexpected runtime conditions. It's akin to reviving a C program after a segmentation fault." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T10:49:10.590", "Id": "84273", "Score": "0", "body": "@200_success I totally agree. I edited in a few words to that effect." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T09:42:10.213", "Id": "48031", "ParentId": "47560", "Score": "3" } } ]
{ "AcceptedAnswerId": "47564", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T10:08:54.473", "Id": "47560", "Score": "5", "Tags": [ "java", "optimization", "data-mining" ], "Title": "AutoComplete program using the n-gram model" }
47560
<p>I have a task to print all zero subsets of 5 numbers, input from the console. I have succeeded in implementing a working code, but it seems it is quite complex (it is like inception) and if the count of the numbers is to be greater, it would be rather pointless to use such a method.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; class ZeroSubset { static void Main() { int number; int[] Numbers = new int[5]; bool result = false; for (int i = 0;i &lt;=4; i++) { here: ; Console.WriteLine("Input number {0}", i + 1); if (int.TryParse(Console.ReadLine(), out number)) { Numbers[i] = number; } else { goto here; } } if (Numbers[0] == 0 &amp;&amp; Numbers[1] == 0 &amp;&amp; Numbers[2] == 0 &amp;&amp; Numbers[3] == 0 &amp;&amp; Numbers[4] == 0) { result = true; Console.WriteLine(String.Join("+", Numbers) + " = 0"); return; } for (int firstNum = 0; firstNum &lt;= 3; firstNum++) { for (int secondNum = firstNum + 1; secondNum &lt;= 4; secondNum++) { if (Numbers[firstNum] + Numbers[secondNum] == 0) { result = true; Console.WriteLine("{0} + {1} = 0", Numbers[firstNum], Numbers[secondNum]); } } } for (int firstNum = 0; firstNum &lt;= 2; firstNum++) { for (int secondNum = firstNum + 1; secondNum &lt;= 3; secondNum++) { for (int thirdNum = secondNum + 1; thirdNum &lt;= 4; thirdNum++) { if (Numbers[firstNum] + Numbers[secondNum] + Numbers[thirdNum]== 0) { result = true; Console.WriteLine("{0} + {1} + {2} = 0", Numbers[firstNum], Numbers[secondNum], Numbers[thirdNum]); } } } } for (int firstNum = 0; firstNum &lt;= 1; firstNum++) { for (int secondNum = firstNum + 1; secondNum &lt;= 2; secondNum++) { for (int thirdNum = secondNum + 1; thirdNum &lt;= 3; thirdNum++) { for (int fourthNum = thirdNum + 1; fourthNum &lt;= 4; fourthNum++) { if (Numbers[firstNum] + Numbers[secondNum] + Numbers[thirdNum] + Numbers[fourthNum]== 0) { result = true; Console.WriteLine("{0} + {1} + {2} + {3} = 0", Numbers[firstNum], Numbers[secondNum] , Numbers[thirdNum], Numbers[fourthNum]); } } } } } if (Numbers.Sum() == 0) { result = true; Console.WriteLine(String.Join("+", Numbers) + " = 0"); } if (result == false) { Console.WriteLine("no zero subsets"); } } } </code></pre> <p>I am asking for a more simple approach to this matter.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T11:24:11.850", "Id": "83376", "Score": "0", "body": "The zero subset sum problem algorithms are briefly [described here](http://en.wikipedia.org/wiki/Subset_sum_problem). Just implement one of them..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T12:27:22.620", "Id": "83383", "Score": "0", "body": "Does it *have* to be an array? I mean, is using LINQ *cheating*? `if (numbers.All(n => n == 0)) { result = true; /* ... */ }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T12:36:55.753", "Id": "84294", "Score": "0", "body": "Your solution does not handle empty set and 1 element subsets." } ]
[ { "body": "<h3>Your input loop:</h3>\n<blockquote>\n<pre><code>for(int i = 0; i &lt;= 4; i++)\n</code></pre>\n</blockquote>\n<p>is overly complicated to understand for the task at hand. Usually you iterate differently:</p>\n<pre><code>for (int i = 0; i &lt; Numbers.Length; i++)\n</code></pre>\n<hr>\n<blockquote>\n<pre><code>here: ;\nif(int.TryParse(Console.ReadLine(), out number))\n Numbers[i] = number;\nelse\n goto here;\n</code></pre>\n</blockquote>\n<p><strong>Do not use <code>goto</code></strong>. It is evil, as it breaks the flow of the program and is extremely unsafe.</p>\n<p>Instead you should decrement the loop-variable:</p>\n<pre><code>if(int.TryParse(Console.ReadLine(), out number))\n Numbers[i] = number;\nelse\n i--;\n</code></pre>\n<hr>\n<h3>Conditionals:</h3>\n<blockquote>\n<pre><code>if(result == false)\n</code></pre>\n</blockquote>\n<p>That is overly complicated and one statement too much. Use this instead:</p>\n<pre><code>if(!result)\n</code></pre>\n<hr>\n<h3>Naming:</h3>\n<p>Be consistent in naming. Local variables in C# are named with <code>camelCase</code> by convention. <code>PascalCasing</code> is reserved for public Methods and Properties. <code>Numbers</code> should be <code>numbers</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T11:29:31.347", "Id": "83377", "Score": "3", "body": "I feel using the else branch to decrement `i` is a hack (changing the loop variable inside the loop makes the code harder to reason about). The natural controlflow would be do undcontionally increment `i` in the for loop and make an extra do while loop that exits when a correct number has been entered." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T11:25:59.950", "Id": "47567", "ParentId": "47562", "Score": "6" } }, { "body": "<p>As soon as I see a <code>goto</code> I get nostalgia, and know that you haven't taken a step back from this program and considered a world without <code>goto</code> (java). There is always a way to avoid using a <code>goto</code>, and this is a rather simple one with multiple alternatives which don't kill your program flow.</p>\n\n<p>I think the best one for your situation though is to only increment up when the <code>TryParse</code> is successful.</p>\n\n<pre><code>for (int i = 0; i &lt; Numbers.Length;)\n{\n Console.WriteLine(\"Input number {0}\", i + 1);\n if (int.TryParse(Console.ReadLine(), out number))\n Numbers[i++] = number;\n}\n</code></pre>\n\n<p>EDIT: Changed to add additional alternative that does not include i in the fail-success of the parse logic. </p>\n\n<pre><code>for (int i = 0; i &lt; Numbers.Length; i++)\n{\n for(bool done = false; !done;)\n {\n Console.WriteLine(\"Input number {0}\", i + 1);\n done = int.TryParse(Console.ReadLine(), out number);\n }\n Numbers[i] = number;\n}\n</code></pre>\n\n<p>Note: I used &lt; Numbers.Length, this way if you ever increase the size of the array, you can support more numbers without having to re-write this part.</p>\n\n<hr>\n\n<p>Next we can simplify some of your code with <code>linq</code>, which you should use any time you want to repeatedly do something to a list. Below, using <code>linq</code>, I query the list of numbers and I ask if all of them equal 0. </p>\n\n<pre><code>if (Numbers.All(n =&gt; n == 0))\n{\n Console.WriteLine(String.Join(\"+\", Numbers) + \" = 0\");\n return;\n}\n</code></pre>\n\n<p>Also note that I removed you setting <code>result = true</code>, because you were not using that since your were returning right away.</p>\n\n<hr>\n\n<p><strong>Naming convention</strong>: All of your method level variables should start with a lowercase letter, be <code>camelCase</code>, ie. <code>numbers</code> vs <code>Numbers</code></p>\n\n<hr>\n\n<p>Your program is a bit flawed. Technically just 0 is a subset of {0,1,2,3,4} however you appear to only care of subsets of 2 or more numbers.</p>\n\n<hr>\n\n<p>A good alternative to your current implementaiton would have been to create a recursive function which takes in <code>int[] remainingNumbers, int[] currentComposite</code>, and the method would simply loop over the remainingNumbers and making new composites to check on, each time you would want to check just the currentComposite to see if that is a valid set.</p>\n\n<p>The way I would do it, would be to create a list of number arrays which hold every combination of the given numbers, then I would simply loop over that collection to determine which sets fit my conditions.</p>\n\n<p>Here is some code I found online (specifically <a href=\"http://gparlakov.wordpress.com/2013/01/19/generate-all-possible-combinations-of-lenght-k-in-an-array123-n-of-lenght-n/\">here</a>), because I did not want to make my own Combination generator. <strike>I'm going to post this code on CR, because I'd like to see someone take a stab at making it better.</strike></p>\n\n<pre><code>static List&lt;List&lt;int&gt;&gt; Combinations(int[] array, int startingIndex = 0, int combinationLenght = 2)\n{\n List&lt;List&lt;int&gt;&gt; combinations = new List&lt;List&lt;int&gt;&gt;();\n if (combinationLenght == 2)\n {\n int combinationsListIndex = 0;\n for (int arrayIndex = startingIndex; arrayIndex &lt; array.Length; arrayIndex++)\n {\n for (int i = arrayIndex + 1; i &lt; array.Length; i++)\n {\n combinations.Add(new List&lt;int&gt;());\n\n combinations[combinationsListIndex].Add(array[arrayIndex]);\n while (combinations[combinationsListIndex].Count &lt; combinationLenght)\n {\n combinations[combinationsListIndex].Add(array[i]);\n }\n combinationsListIndex++;\n }\n }\n return combinations;\n }\n List&lt;List&lt;int&gt;&gt; combinationsofMore = new List&lt;List&lt;int&gt;&gt;();\n for (int i = startingIndex; i &lt; array.Length - combinationLenght + 1; i++)\n {\n combinations = Combinations(array, i + 1, combinationLenght - 1);\n\n for (int index = 0; index &lt; combinations.Count; index++)\n combinations[index].Insert(0, array[i]);\n\n for (int y = 0; y &lt; combinations.Count; y++)\n combinationsofMore.Add(combinations[y]);\n }\n return combinationsofMore;\n}\n</code></pre>\n\n<p>Now just use some linq to only grab results from the Combinations function where the sum of the numbers in the list equates to 0. Foreach of them, print it to the console.</p>\n\n<pre><code>foreach(var list in Combinations(Numbers).Where(list=&gt; list.Sum() == 0))\n Console.WriteLine(string.Join(\" + \", list) + \" = 0\");\n</code></pre>\n\n<hr>\n\n<p>I see that at the bottom of your code you are checking to see if all the values in Numbers are 0, and then printing a message, and returning. Why? You did this earlier, and had an early return, so if that was the case the code should never have made it here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:38:29.887", "Id": "83426", "Score": "0", "body": "Let me nearly repeat the comment I gave to Vogel612's answer: Changing the loop variable (`i`) inside the loop makes the code harder to reason about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:04:33.260", "Id": "83432", "Score": "0", "body": "@Nobody thats what those values are for. otherwise I would have declared a value outside set it equal to 0 and counted up on ever success, oh wait.. that is exactly what the for-loop does. It would make less sense to decremented it to have it re-incremented. But both ideas work better than a goto.. and I like to think mine is the right way to do it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:11:21.553", "Id": "83434", "Score": "0", "body": "@Nobody: actually I just changed it to not include i in the success or fail of the parse. its longer but it doesn't confuse the logic, which some people may indeed like :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T13:56:04.360", "Id": "47574", "ParentId": "47562", "Score": "7" } }, { "body": "<p>Using a <code>List&lt;int&gt;</code> instead of <code>int[]</code> allows your code to not only be more dynamic but also to leverage the <code>GetRange</code> method of the List. This simplifies your code to only 2 loops.</p>\n\n<p>Creating the list would look something like this:</p>\n\n<pre><code>int number;\nList&lt;int&gt; Numbers = new List&lt;int&gt;();\nfor(int i = 0; i &lt;= 4; i++)\n{\n number = 0;\n bool good = false;\n while(!good)\n {\n Console.WriteLine(\"Input number {0}\", i + 1);\n if(int.TryParse(Console.ReadLine(), out number))\n {\n Numbers.Add(number);\n good = true;\n }\n else\n Console.WriteLine(\"Invalid input, try again\");\n }\n\n}\n</code></pre>\n\n<p>The sub routine to get the subsets could look something like this:</p>\n\n<pre><code>public static List&lt;List&lt;int&gt;&gt; AllSubsets2(List&lt;int&gt; mainset, int targetsum)\n{\n List&lt;List&lt;int&gt;&gt; outval = new List&lt;List&lt;int&gt;&gt;();\n for(int num2 = 0; num2 &lt; mainset.Count; num2++)\n {\n if(mainset[num2] == 0)\n outval.Add(new List&lt;int&gt;{mainset[num2]});\n int sum = mainset[num2];\n for(int num = num2+1; num &lt; mainset.Count; num++)\n {\n sum += mainset[num];\n if(sum == 0)\n outval.Add(mainset.GetRange(num2, num - num2));\n }\n }\n\n return outval;\n}\n</code></pre>\n\n<p>This will return a list of all the subsets that add up to the target sum.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:40:28.050", "Id": "83427", "Score": "0", "body": "The variable name `good` is a bit generic (something like `hasEnteredValidInteger` would be more to the point). I like the usability improvement with the extra \"Invalid input\" message. However, it should also mention what a valid input looks like." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T14:58:30.357", "Id": "47579", "ParentId": "47562", "Score": "8" } }, { "body": "<blockquote>\n <p>I have succeeded in implementing a working code, but it seems it is\n quite complex (it is like inception) and if the count of the numbers\n is to be greater, it would be rather pointless to use such a method.</p>\n</blockquote>\n\n<p>This is called <a href=\"http://c2.com/cgi/wiki?ZeroOneInfinityRule\" rel=\"nofollow\">Zero One Infinity Rule</a>. </p>\n\n<p>Here, you enumerate all subsets of some N (=5) numbers. You do this by first enumerating 2-element subsets then 3-element subsets and so on. And you couldn't generalize this to arbitrary N. (Not handling <em>Zero</em> and <em>One</em> cases can impede seeing the <em>Infinity</em> cases.)</p>\n\n<p>When you meet a situation like this, take a step back and reexamine the problem. First restate the problem with N identified clearly and the statement of the problem doesn't include the method used to solve it. (This is another reason why you should extract snippets of your code and give them names indicating what they do and not how they do.)</p>\n\n<p>As I mentioned before what you try to do above can be stated as \"enumerate all subsets of some N (=5) numbers\". The way to generalize this to arbitrary N is to look at how would one \"enumerate <em>all subsets of some N numbers</em>, given <em>all subsets of some N-1 numbers</em>\" and go from there. It is easy to figure out, then, that the subsets of N numbers consist of the subsets of the first N-1 of those numbers and those subsets obtained by adding the Nth element to each of those subsets.</p>\n\n<p>The problem with your decomposition was that from the get go (2 element subsets) you are using all N elements.</p>\n\n<h2>Powerset of an IEnumberable:</h2>\n\n<pre><code>public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; PowerSet&lt;T&gt;(IEnumerable&lt;T&gt; elements)\n{\n return elements.Aggregate(\n new []{new T[]{}} as IEnumerable&lt;IEnumerable&lt;T&gt;&gt;,\n (subsetsSoFar, element) =&gt; subsetsSoFar.Concat(\n subsetsSoFar.Select(subset =&gt; subset.Concat(new[]{element}))));\n}\n</code></pre>\n\n<p>The example of powerset implementations I could find online are not lazy and most copy around lists a lot and so this, apart from being shorter and more readable, also should behave better for larger input, though I haven't tried.</p>\n\n<p>The rest is similar to other answers, except that if the subsets having at least 2 elements is a requirement, it should be stated (in the problem description as well as solution).</p>\n\n<pre><code>var zeroSumSubsets = PowerSet(numbers)\n .Where(subset =&gt; subset.Count() &gt; 1)\n .Where(subset =&gt; subset.Sum() == 0);\n\nforeach(var subset in zeroSumSubsets)\n // Do whatever...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T13:13:19.440", "Id": "48047", "ParentId": "47562", "Score": "1" } } ]
{ "AcceptedAnswerId": "47574", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T10:53:42.990", "Id": "47562", "Score": "7", "Tags": [ "c#", "array", "console" ], "Title": "Sum of subset of 5 numbers equals 0" }
47562
<p>Next is an algorithm to calculate the histogram for a given YUV420sp image. The YUV data is given by the hardware camera as an <code>unsigned char*</code>.</p> <p>The algorithms works correctly, but I'm looking to optimize it for speed.</p> <pre><code>void calculateHistogram(const unsigned char* yuv420sp, const int yuvWidth, const int yuvHeight, const int canvasHeight, int* histogramBins) { const int BINS = 256; // Clear the output memset(histogramBins, 0, BINS * sizeof(int)); // Get the bin values const unsigned int totalPixels = yuvWidth * yuvHeight; for (int index = 0; index &lt; totalPixels; index++) { histogramBins[yuv420sp[index]]++; } // Resolve the maximum count in bins int maxBinValue = 0; for (int index = 0; index &lt; BINS; index++) { if (histogramBins[index] &gt; maxBinValue) { maxBinValue = histogramBins[index]; } } maxBinValue = maxBinValue == 0 ? 1 : maxBinValue; // Normalize to fit into the histogram UI canvas height for (int index = 0; index &lt; BINS; index++) { histogramBins[index] = histogramBins[index] * canvasHeight / maxBinValue; } } </code></pre>
[]
[ { "body": "<p><strong>Style</strong></p>\n\n<p>Everything looks quite good to me.</p>\n\n<p>The only thing that I find a bit disturbing is the empty line after comments : it split relevant things apart and it makes the code harder to read.</p>\n\n<p>You could add a bit of documentation explaining what your code does.</p>\n\n<hr>\n\n<p><strong>Making things more simple</strong></p>\n\n<p>After the <code>for-loop</code> to compute the max value, you perform <code>maxBinValue = maxBinValue == 0 ? 1 : maxBinValue;</code>. As far as I can understand, the point is not to have a division by 0 if max is 0 which corresponds to a situation where <code>histogramBins</code> consist only of 0s which should happen only of <code>totalPixels &lt;= 0</code> which is quite unlikely.</p>\n\n<p>In any case :</p>\n\n<ul>\n<li>I find the usage of a ternary operator a bit inappropriate here as it might as well be a simple : <code>if (maxBinValue == 0) maxBinValue = 1;</code>. Alternatively, if you were to define functions (or macros) for <code>min</code> and <code>max</code>, this could be : <code>maxBinValue = max(1, maxBinValue)</code>.</li>\n<li>You could get rid of this is a very very simple way : if you were to assign <code>1</code> to <code>maxBinValue</code> in the first place (before the loop), you wouldn't have to worry about it being equal to 0.</li>\n</ul>\n\n<p>Please note that if you were to define a <code>max</code> function/macro, it could be useful inside the loop too as it would become : <code>maxBinValue = max(histogramBins[index],maxBinValue)</code>.</p>\n\n<hr>\n\n<p><strong>Getting rid of magic numbers</strong></p>\n\n<p>This <code>256</code> in <code>const int BINS = 256;</code> definitly sounds like a value I've seen in other places. Indeed, it is not just a random setting I can update if I ever want to : it corresponds to the maximum value <code>yuv420sp[index]</code> can take. Its type is <code>unsigned char</code> and the maximum value can be retrieved from <a href=\"http://en.cppreference.com/w/c/types/limits\">limits.h</a> : doing <code>const int BINS = UCHAR_MAX</code> would probably make things easier to understand.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T13:37:29.460", "Id": "47572", "ParentId": "47566", "Score": "5" } }, { "body": "<p>There are a number of things that you could do to make your program run faster. On my machine, all of them together shaved off a little over 8% of the time of your original. Here's what I did:</p>\n\n<h2>Use <code>unsigned</code> where applicable</h2>\n\n<p>Your histogram counts can never be less than zero, so it makes sense to use <code>unsigned</code> instead of <code>int</code> for their type. This often allows a small but measurable performance increase when doing calculations or comparisons, depending on the particulars of your machine.</p>\n\n<h2>Prefer preincrement over postincrement</h2>\n\n<p>On my machine it made no difference with this code, but it's often the case that preincrement (<code>++i</code>) is slightly faster than postincrement (<code>i++</code>) because the postincrement case has to save the original value and then increment while the preincrement can simply save in place. In some cases (especially if the architecture is register-starved), this results in a performance difference.</p>\n\n<h2>Precalculate loop invariants</h2>\n\n<p>The value <code>canvasHeight / maxBinValue</code> doesn't need to be recalculated every loop iteration because the value of it doesn't change within the loop. This kind of calculation is therefore known as a <em>loop invariant</em> and can be precalculated outside the loop for a small but measurable performance increase.</p>\n\n<h2>Eliminate unnecessary operations</h2>\n\n<p>Your code sets the initial <code>maxBinValue = 0</code> and then changes it to 1 if the value is 0 after the loop. Why not just start with the value of 1? That way no post-loop adjustment is required.</p>\n\n<h2>Use pointers rather than indexing</h2>\n\n<p>Pointer arithmetic is often faster than indexing, so rather than having a loop construct <code>for (int index = 0; index &lt; BINS; index++)</code> it is often faster instead to have something like <code>for (unsigned *bin = histogramBins; bin != lastbin; ++bin)</code></p>\n\n<h2>Measure and verify</h2>\n\n<p>All of this is only of theoretical interest until you actually <strong>measure</strong> the performance on your machine. Your computer, operating system, and compiler are all likely different from mine, so what improves performance on my machine could actually slow things down on yours. The only way to know for sure is to measure. </p>\n\n<p>I did so using the <code>time</code> command on my Linux machine and found that your original code took an average of 850ms for the program below, while the final optimized version took an average of 779ms. This is the test harness I used:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\n/* test code goes here */\n\nint main()\n{\n const unsigned height=480;\n const unsigned width=640;\n unsigned char in[height*width];\n unsigned hist[BINS];\n for (unsigned i=0; i &lt; height*width; ++i)\n in[i] = rand();\n for (int i=0; i &lt; 1000; ++i) \n calculateHistogram(in, width, height, 1024, hist);\n\n}\n</code></pre>\n\n<p>This is the optimized version of your code. Note that <code>BINS</code> is moved outside the function so that it may also be used by the calling code.</p>\n\n<pre><code>const int BINS = 256;\n\nvoid calculateHistogram(const unsigned char* yuv420sp, const int yuvWidth,\n const int yuvHeight, const int canvasHeight, unsigned* histogramBins)\n{\n // Clear the output\n memset(histogramBins, 0, BINS * sizeof(unsigned));\n\n // Get the bin values\n const unsigned char *last = &amp;yuv420sp[yuvWidth*yuvHeight];\n\n for ( ; yuv420sp != last; ++yuv420sp)\n ++histogramBins[*yuv420sp];\n\n // Resolve the maximum count in bins\n unsigned maxBinValue = 1;\n const unsigned *lastbin = &amp;histogramBins[BINS];\n\n for (unsigned *bin = histogramBins; bin != lastbin; ++bin)\n if (*bin &gt; maxBinValue)\n maxBinValue = *bin;\n\n // Normalize to fit into the histogram UI canvas height\n unsigned scale = canvasHeight / maxBinValue;\n\n for (unsigned *bin = histogramBins; bin != lastbin; ++bin)\n *bin *= scale;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T16:03:46.277", "Id": "83406", "Score": "1", "body": "Ineresting comments even though I didn't expect any of them to make a difference with any decent compiler. In any case, I am not quite sure that you can pre-compute `canvasHeight / maxBinValue` out of the loop (or at least not with integers operations). Indeed, let's assume for the sake of simplicity that `canvasHeight < maxBinValue`, then `scale = 0` and I guess you can imagine what will happen when performing the multiplication. The division cannot be factorised out of the loop because what gets divised is not `canvasHeight` but `x * canvasHeight`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T16:21:07.653", "Id": "83407", "Score": "0", "body": "You are right Josay, the division cannot be pre-computed outside the loop, otherwise would loose the required precision." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T15:40:58.143", "Id": "47586", "ParentId": "47566", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T11:12:02.153", "Id": "47566", "Score": "4", "Tags": [ "optimization", "c", "statistics" ], "Title": "Optimization for histogram computation algorithm in C" }
47566
<p>I've been developing sites using Dreamweaver for the last 15 years, I do a lot of code editing manually so I have quite a good knowledge of the PHP language.</p> <p>I'm diving into object orientated programming and getting to grips with classes objects and the like.</p> <p>I hope to eventually port the game to a framework such as symfony, I feel at this time there's a lot more to learn before I start diving into frameworks, and would just like to concentrate on getting to grips with OOP, without having to worry about templating frameworks, ORM etc. </p> <p>The game itself is quite simple, its based on a party game called Mafia <a href="http://en.wikipedia.org/wiki/Mafia_%28party_game%29" rel="nofollow">http://en.wikipedia.org/wiki/Mafia_(party_game)</a></p> <p>There's a certain amount of players required, once enough players have joined, the game starts and people vote who they want to eliminate.</p> <p>There are 2 periods of voting during the day and a night round where certain players can vote at night.</p> <p>I've created the initial user login (for which I am using Facebook's PHP SDK).</p> <p>I just wanted to get some advice on the best way to go before I get to far ahead of myself.</p> <p>I think I am probably adding to much functionality to my game class</p> <p>What's the best way to break it down?</p> <p>Most of the data for the game is stored in a MySQL database, where I am using PDO (moving away from the horrendously insecure way that Dreamweaver implements).</p> <p>Some of the questions I Have along the way are:</p> <p>Do I create separate classes for the data in the database.</p> <p>For example for my game table just have a class that fetches a list of games that i can then iterate through and display them as a list on my page. within this class I can create methods to join a game, create a game, leave a game. each method would return the game object <code>$this</code>.</p> <p>Have a class that contains a list of users in the current game, then within that class have methods for processing votes or do i have a separate class called gameFunctions that receives the current game, and list of users in that game with methods that perform the game functions such as voting. </p> <p>I have already started working on it, and what I have so far is below, any tips or suggestions on how to separate the code so its more manageable would be great along with any other advice or resources that would be helpful to my learning process.</p> <p>User Class:</p> <pre><code>&lt;?php require_once('facebook/facebook.php'); // require facebook sdk require_once('config.class.php'); // require config class require_once('dbconn.class.php'); //require database connector class user{ public $_userData; // holds information of our user private $conn; // our database connection public $facebook; // facebook sdk public $fbuser; // the facebook user //Constructor public function __construct(){ $this-&gt;conn = DBconn::getInstance(); //get DB instance $this-&gt;facebook = new Facebook(Config::read('fb.facebook')); $this-&gt;_userData = new stdClass(); } /** * CheckAccess - checks to see if the user is logged in to the session * @return bool: * true: user logged in * false: user not logged in */ public function checkAccess(){ if(session_id() == '') { session_start(); // Start session if we don't already have one } if (isset($_SESSION['loggedin']) &amp;&amp; $_SESSION['loggedin'] == true) { return true; } else{ return false; } } /** * profileExists - Checks to see if a user profile exists * @return bool: true/false */ private function profileExists(){ try{ $pdoQuery = ("SELECT count(*) FROM userprofile_upl WHERE uid_upl = :uid"); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;bindParam(':uid', $this-&gt;_userData-&gt;uid); $stmt-&gt;execute(); if($stmt-&gt;fetchColumn()){ return true; }else{ return false; } }catch(PDOException $e){ echo('There was an error while connecting to your profile&lt;br&gt;'); return false; } } /** * getProfile - querys the database and stores the users profile in $_userData * @return bool */ public function getProfile(){ try{ $pdoQuery = ("SELECT uid_upl as'uid', firstname_upl as 'firstname', lastname_upl as 'lastname', info_upl as 'info' FROM userprofile_upl WHERE uid_upl = :uid" ); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;bindParam(':uid', $this-&gt;_userData-&gt;uid); $stmt-&gt;execute(); $row = $stmt-&gt;fetch(PDO::FETCH_OBJ); $this-&gt;_userData-&gt;firstname = $row-&gt;firstname; $this-&gt;_userData-&gt;lastname = $row-&gt;lastname; $this-&gt;_userData-&gt;info = $row-&gt;info; return (true); }catch(PDOException $e){ echo('There was an error while connecting to your profile&lt;br&gt;'); return false; } } /** * createProfile - Creates a user profile * @param $user object: The Users Data * @return bool: true/false */ private function createProfile(){ try{ //we need to add the facebook user to the profiles table $pdoQuery = ('INSERT INTO userprofile_upl (firstname_upl, lastname_upl, uid_upl) VALUE (:firstname, :lastname, :uid)'); $pdoData = array( 'firstname' =&gt; $this-&gt;_userData-&gt;firstname, 'lastname' =&gt; $this-&gt;_userData-&gt;lastname, 'uid' =&gt; $this-&gt;_userData-&gt;uid ); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;execute($pdoData); return true; }catch(PDOException $e){ echo('There was an error while creating the profile&lt;br&gt;'); return false; } } /** * goDashboard - Redirects a logged in user to the dashboard if they are logged in */ public function goDashboard(){ if($this-&gt;checkAccess()){ header('Location: '.Config::read('url.dashboard')); }else{ return false; } } /** * generates a facebook log-out url * @return String: facebook logout url */ public function getLogoutUrl(){ //set user logout_url $params = array( 'next' =&gt; config::read('url.logout')); $this-&gt;_userData-&gt;logout_url = $this-&gt;facebook-&gt;getLogoutUrl($params); return $this-&gt;_userData-&gt;logout_url; } /** * loginFacebook - Logs a user into the site with facebook * Checks to see if user has an account and if not make one. * Checks to see if user has a profile and if not make one. * Checks to see if user has facebook credentials on this site * @return mixed */ public function loginFacebook(){ $fbuser = $this-&gt;facebook-&gt;getUser();//get facebook user if($fbuser){// if we have a user returned we have user who's authenticated and logged in with facebook try { // Proceed knowing we have a user. $me = $this-&gt;facebook-&gt;api('/me'); // the facebook user //generate a log-out url //set user logout_url $this-&gt;_userData-&gt;logout_url = $this-&gt;facebook-&gt;getLogoutUrl($params); //set the users details $this-&gt;_userData-&gt;uid = $this-&gt;facebook-&gt;getUser(); $this-&gt;_userData-&gt;firstname = $me['first_name']; $this-&gt;_userData-&gt;lastname = $me['last_name']; $this-&gt;_userData-&gt;email = $me['email']; $this-&gt;_userData-&gt;provider = 'facebook'; echo(" facebook account exists: ".$this-&gt;fbAccountExists()); if(!$this-&gt;fbAccountExists($this-&gt;_userData)){ echo("no fb account exists"); $this-&gt;fbCreateAccount($this-&gt;_userData); }; echo("profile exists: ".$this-&gt;profileExists()); if(!$this-&gt;profileExists($this-&gt;_userData)){ echo("no profile exists: "); $this-&gt;createProfile($this-&gt;_userData); } $this-&gt;setSession(); } catch (FacebookApiException $e){ //if theres an error $fbuser = null; //set the user to nothing return false(); } } if(!$fbuser){ //get a login url, returns to this page so we can process the login($fblogin_url) $loginUrl = $this-&gt;facebook-&gt;getLoginUrl(array('redirect_uri'=&gt;Config::read('url.fblogin'), false)); header('Location: '.$loginUrl);//redirect to the login page } } /** * fbAccountExists - checks to see if a facebook account exists * @return bool: true/false */ private function fbAccountExists(){ try{ $pdoQuery = ("SELECT count(*) FROM oauth_auth WHERE uid_auth = :uid and provider_auth = 'facebook'"); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;bindParam(':uid', $this-&gt;_userData-&gt;uid); $stmt-&gt;execute(); if($stmt-&gt;fetchColumn()){ return true; }else{ return false; } }catch(PDOException $e){ echo('There was an error while connecting to your profile&lt;br&gt;'); return false; } } /** * fbCreateAccount - creates a facebook account * @return bool: true/false */ private function fbCreateAccount(){ try{ //we need to add the facebook user to the auth table $pdoQuery = ("INSERT INTO oauth_auth(email_auth, uid_auth, provider_auth) VALUE (:email, :uid, :provider)"); $pdoData = array('email' =&gt; $this-&gt;_userData-&gt;email, 'uid' =&gt; $this-&gt;_userData-&gt;uid, 'provider' =&gt; $this-&gt;_userData-&gt;provider); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;execute($pdoData); return true; }catch(PDOException $e){ echo('There was an error while connecting to your profile&lt;br&gt;'); return false; } } /** * setSession - Stores session variables to imitate user login. */ function setSession(){ if(session_id() == '') {session_start();}// Start session if we dont already have one $_SESSION['loggedin'] = true; $this-&gt;_userData-&gt;loggedin = true; $_SESSION['uid'] = $this-&gt;_userData-&gt;uid; $_SESSION['provider'] = $this-&gt;_userData-&gt;provider; header('Location: '.Config::read('url.dashboard')); } /** * getSession - saves session vars to our user * @return bool: true - session retrieved * @redirect if no session found redirects to login page */ public function getSession(){ if(session_id() == '') {session_start();}// Start session if we dont already have one if (!isset($_SESSION['loggedin']) &amp;&amp; $_SESSION['loggedin'] != true) {//Check to see if user is logged in header("location: ".Config::read('url.baseurl')); // User is logged in Redirect to homepage }else{ //save session to this user $this-&gt;_userData-&gt;loggedin = $_SESSION['loggedin']; $this-&gt;_userData-&gt;provider = $_SESSION['provider']; $this-&gt;_userData-&gt;uid = $_SESSION['uid']; return true; } } } </code></pre> <p>Game Class:</p> <pre><code>&lt;?php /** * Created by Base5 Designs. * and Dizzy Developments * User: Dizzy High * Date: 14/04/14 * Time: 12:08 */ require_once('config.class.php'); // require config class require_once('dbconn.class.php'); //require database connector class game { public $conn; // database handler public $gameID; // id of game public $name; //name of game public $host; // uid of game host (the game creator) public $playerCount; // number of players in game public $roundTime; //round time of game in seconds public $visibility; // public (1) or private game (0) public $alias; // whether game players use an alias name or not (1 yes 2 no) public $status; //status of game (waiting, active, complete) public $currentRound; // current round of game (0 not started, odd day, even night) public $startTime; // datetime - start time of game public $createdTime; // datetime date game created function __construct(){ $this-&gt;conn = DBconn::getInstance(); //get DB instance } /** * assignSettings - assigns settings * @param $name - property name * @param $value - property value */ function assignSetting($name, $value){ $whitelist = array('id', 'name', 'host', 'playerCount', 'roundTime', 'visibility', 'alias', 'status', 'currentRound', 'startTime', 'createdTime'); if (in_array($name, $whitelist)) { $property = $name; $this-&gt;$property = $value; } } /** * makeGame- creates a new game and adds it to the database with the defined settings * @param $settings * @return bool */ function makeGame($settings){ //var_dump($settings); if (is_array($settings)) { foreach($settings as $k=&gt;$v) { $this-&gt;assignSetting($k, $v); } } else { die('Config Error!'); } try{ //add the game to the games table $pdoQuery = ('INSERT INTO games_gam (name_gam, host_gam, playercount_gam, roundtime_gam, visibility_gam, alias_gam) VALUE (:gameName, :gameHost, :playerCount, :roundTime, :visibility, :alias)'); $pdoData = array( 'gameName' =&gt; $this-&gt;name, 'gameHost' =&gt; $this-&gt;host, 'playerCount' =&gt; $this-&gt;playerCount, 'roundTime' =&gt; $this-&gt;roundTime, 'visibility' =&gt; $this-&gt;visibility, 'alias' =&gt; $this-&gt;alias ); var_dump($pdoData); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;execute($pdoData); $this-&gt;gameID = $this-&gt;conn-&gt;dbh-&gt;lastInsertId(); //add creator to game $this-&gt;addPlayer($this-&gt;host); return $this; }catch(PDOException $e){ echo('There was an error while creating the game&lt;br&gt;'); return false; } } /** * getGame - retrieves a game from the database * @param $gameID INT - the id of the game * @return $this */ function getGame($gameID){ try{ $pdoQuery = ("SELECT id_gam as 'id', name_gam as 'name', host_gam as 'host', playercount_gam as 'playerCount', roundtime_gam as 'roundTime', visibility_gam as 'visibility', status_gam as 'status', alias_gam as 'alias', starttime_gam as 'startTime', createdtime_gam as 'createdTime' FROM games_gam WHERE id_gam = :id" ); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;bindParam(':id', $gameID); $stmt-&gt;execute(); $row = $stmt-&gt;fetch(PDO::FETCH_OBJ); $this-&gt;gameID = $row-&gt;id; $this-&gt;name = $row-&gt;name; $this-&gt;host = $row-&gt;host; $this-&gt;playerCount = $row-&gt;playerCount; $this-&gt;roundTime = $row-&gt;roundTime; $this-&gt;visibility = $row-&gt;visibility; $this-&gt;status = $row-&gt;status; $this-&gt;alias = $row-&gt;alias; $this-&gt;startTime = $row-&gt;startTime; $this-&gt;createdTime = $row-&gt;createdTime; return ($this); }catch(PDOException $e){ echo('There was an error while connecting to game: '.$gameID.'&lt;br&gt;'); return false; } } /** * addPlayer - adds player to a game * @param $uid - uid of player * @return bool */ function addPlayer($uid){ if(!$this-&gt;playerInGame($uid)){ try{ $pdoQuery = ('INSERT INTO gameplayers_gpl (idgam_gpl, uid_gpl) VALUE (:idgam, :uid)'); $pdoData = array( ':idgam' =&gt; $this-&gt;gameID, ':uid' =&gt; $uid ); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;execute($pdoData); return true; }catch(PDOException $e){ echo('There was an error while creating the profile&lt;br&gt;'); return false; } } } /** * leaveGame - Removes a player from a game * @param $gameID - the id of the game * @param $uid - the uid of the player * @return $this */ function leaveGame($uid){ if($this-&gt;playerInGame($uid)){ try{ $pdoQuery = ('DELETE FROM gameplayers_gpl WHERE uid_gpl = :uid AND idgam_gpl = id'); $pdoData = array( ':uid' =&gt; $uid, ':id'=&gt; $this-&gt;$gameID ); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;execute($pdoData); return $this; }catch(PDOException $e){ echo('There was an error while removing the player from the game&lt;br&gt;'); return false; } } } /** * gameFull - checks to see if a game has all player slots filled * @return bool true: game is full * @return bool false: has slots */ function gameFull(){ try{ $pdoQuery = ("SELECT count(*) FROM gameplayers_gpl WHERE idgam_gpl = :gameID"); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $stmt-&gt;bindParam(':gameID', $this-&gt;gameID); $stmt-&gt;execute(); $rowCount = (int) $stmt-&gt;fetchColumn(); if($rowCount &lt; $this-&gt;playerCount){ return false; }else{ return true; } }catch(PDOException $e){ echo('There was an error while checking if the game was full&lt;br&gt;'); return false; } } /** * playerInGame - checks to see if a player in the game * @param $uid: id of user * @return bool */ function playerInGame($uid){ try{ $pdoQuery = ("SELECT count(*) FROM gameplayers_gpl WHERE idgam_gpl = :gameID AND uid_gpl = :uid"); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $pdoData = array( ':uid' =&gt; $uid, ':gameID'=&gt; $this-&gt;gameID ); $stmt-&gt;execute($pdoData); $rowCount = (int) $stmt-&gt;fetchColumn(); if($rowCount &gt; 0){ return true; }else{ return false; } }catch(PDOException $e){ echo('There was an error while checking if the user was in the game&lt;br&gt;'); return false; } } function getGamesList($roundtime){ try{ $pdoQuery = ("SELECT id_gam as 'id', name_gam as 'name', host_gam as 'host', playercount_gam as 'playerCount', roundtime_gam as 'roundTime', visibility_gam as 'visibility', status_gam as 'status', alias_gam as 'alias', starttime_gam as 'startTime', createdtime_gam as 'createdTime' FROM games_gam WHERE visibility_gam = :visibility AND roundtime_gam = :roundtime AND status_gam = :gamestatus" ); $stmt = $this-&gt;conn-&gt;dbh-&gt;prepare($pdoQuery); $pdoData = array( 'visibility' =&gt; 0, 'roundtime' =&gt; $roundtime, 'gamestatus' =&gt; 'waiting', ); $stmt-&gt;execute($pdoData); $obj = $stmt-&gt;fetchAll(); return ($obj); }catch(PDOException $e){ echo('There was an error while connecting to game: '.$gameID.'&lt;br&gt;'); return false; } } /** * Convert number of seconds into years, days, hours, minutes and seconds * and return an string containing those values * * @param integer $seconds Number of seconds to parse * @return string */ function secondsToTime($seconds){ $y = floor($seconds / (86400*365.25)); $d = floor(($seconds - ($y*(86400*365.25))) / 86400); $h = gmdate('H', $seconds); $m = gmdate('i', $seconds); $s = gmdate('s', $seconds); $string = ''; if($y &gt; 0){ $yw = $y &gt; 1 ? ' years ' : ' year '; $string .= $y . $yw; } if($d &gt; 0){ $dw = $d &gt; 1 ? ' days ' : ' day '; $string .= $d . $dw; } if($h &gt; 0){ $hw = $h &gt; 1 ? ' hours ' : ' hour '; $string .= $h . $hw; } if($m &gt; 0){ $mw = $m &gt; 1 ? ' minutes ' : ' minute '; $string .= $m . $mw; } if($s &gt; 0){ $sw = $s &gt; 1 ? ' seconds ' : ' second '; $string .= $s . $sw; } return preg_replace('/\s+/',' ',$string); } function getHost($gameID){ } function initGame(){ } function processVotes(){ } function setPlayerRole($uid, $role){ } function getPlayerRole(){ } function getPlayerHealth(){ } function getGameDay(){ } function getGameVotes(){ } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T13:38:49.147", "Id": "83391", "Score": "2", "body": "I think the rule of \"class names should start with a capitalized word\" apply in php too User and Game" } ]
[ { "body": "<h1>Formatting</h1>\n\n<p>@MarcoAcierno's comment is correct, and you also have a few other formatting errors.</p>\n\n<p>We can start with <strong>capitalization</strong>! I'll quote a couple things here that could be considered <a href=\"http://framework.zend.com/manual/1.12/en/coding-standard.html\" rel=\"nofollow noreferrer\">a standardized practice</a>:</p>\n\n<blockquote>\n <p>If a class name is comprised of more than one word, the first letter\n of each new word must be capitalized.</p>\n</blockquote>\n\n<p>So, user -> User and game -> Game.</p>\n\n<blockquote>\n <p>Variables that are declared with the \"private\" or \"protected\"\n modifier, the first character of the variable name must be a single\n underscore. This is the only acceptable application of an underscore\n in a variable name. Member variables declared \"public\" should never\n start with an underscore.</p>\n</blockquote>\n\n<p>In relation to this, there are a couple <strong>variables that need new names</strong>. In both files, you control your PDO statements with the variable <code>$stmt</code>. This is very ambiguous and a simple, yet tremendously vague name. To make it easier to understand, give the variables some meaning.</p>\n\n<blockquote>\n <p>As with classes, the brace should always be written on the line\n underneath the function name.</p>\n</blockquote>\n\n<p>Just nit-picking here. It increases readability though.</p>\n\n<blockquote>\n <p>When a string is literal (contains no variable substitutions), the\n apostrophe or \"<strong>single quote</strong>\" should always be used to demarcate the\n string</p>\n</blockquote>\n\n<p>This one you had followed for the most part, except for your queries, all of which are on double quotes.</p>\n\n<blockquote>\n <p>The opening brace is written on the same line as the conditional\n statement. The closing brace is always written on its own line.</p>\n</blockquote>\n\n<p>You've condensed a couple <code>if</code> statements into one liners, which only <strong>makes it more difficult to follow</strong>.</p>\n\n<p>I've also noticed you've added some <strong>documentation</strong>. Good start, but it needs some fine tuning to actually be efficient. I think a Google for PHPDoc will give you a good insight at to what comments should look like. <a href=\"http://framework.zend.com/manual/1.12/en/coding-standard.coding-style.html#coding-standards.inline-documentation\" rel=\"nofollow noreferrer\">Here's</a> a good section on that too.</p>\n\n<h1>Files/Classes</h1>\n\n<p>I'd agree with \"<em>I think I am probably adding to much functionality to my game class</em>.\"</p>\n\n<p>To me, your Game class is handling database queries, game logic, and presentation.</p>\n\n<p>To rid of the database queries, I'd say you could build a <strong>database class</strong>, something that frameworks usually come with. You want to <strong>decouple</strong> the game and the data as much as possible.</p>\n\n<p>So hopefully from your Game class, you'd only be calling something such as:</p>\n\n<pre><code>function gameFull()\n{\n $playersInGameQuery = 'SELECT count(*) FROM gameplayers_gpl WHERE idgam_gpl = :gameID';\n if (!$playersInGame = $someDatabaseClass-&gt;query($playersInGameQuery, array(':gameID' =&gt; $this-&gt;gameID))-&gt;fetchColumn()) {\n throw new DataBaseException('Checking for player amount failed.');\n }\n\n if ($playersInGame &lt; $this-&gt;playerCount) {\n return false;\n }\n return true;\n\n}\n</code></pre>\n\n<p>Which brings us to a new subject. Your Game class is also controlling the <strong>presentation</strong>. It's imperative that classes handle <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow noreferrer\">SOLID rules</a>. I'd suggest taking your PDOExceptions and placing them in your database class, and having that class throw more specific exceptions. Then have your View file handle those exceptions. It's not always necessary that you create exceptions from scratch, but <a href=\"http://www.php.net/manual/en/language.exceptions.extending.php\" rel=\"nofollow noreferrer\">here's PHP's page on custom exceptions</a>. Or you may be able to work with <a href=\"http://us.php.net/manual/en/spl.exceptions.php\" rel=\"nofollow noreferrer\">a preset exception</a>.</p>\n\n<p>Remember, no <code>echo</code>ing in a business logic or data access layer.</p>\n\n<p>And then if we have removed data and presentation, then the Game class is left with game logic! Now it accepts user actions and determines what to do with those actions.</p>\n\n<h1>Coding</h1>\n\n<p>Let's <strong>simplify</strong> some code now! Starting off with <code>checkAccess()</code>.</p>\n\n<p><code>if(session_id() == '')</code> could be <code>if (empty(session_id()))</code>. And then</p>\n\n<pre><code>if (isset($_SESSION['loggedin']) &amp;&amp; $_SESSION['loggedin'] == true) {\n return true;\n} else{\n return false;\n}\n</code></pre>\n\n<p>can be simplified to:</p>\n\n<pre><code>return isset($_SESSION['loggedin']) &amp;&amp; $_SESSION['loggedin'] === true;\n</code></pre>\n\n<p>Notice how I made <code>==</code> into an exact type match too. If not, <code>loggedin</code> could be <code>5</code> and still pass!</p>\n\n<p>Same type of makeover can happen in <code>profileExists()</code>:</p>\n\n<pre><code>return $stmt-&gt;fetchColumn() &gt; 0;\n</code></pre>\n\n<p>Although, if you're to add a Database layer, this may not be required.</p>\n\n<p><code>return (true);</code> is overkill. No parentheses required.</p>\n\n<p>In <code>goDashboard()</code> and other functions, you could simply write:</p>\n\n<pre><code>if ($this-&gt;checkAccess()) {\n header('Location: ' . Config::read('url.dashboard'));\n}\nreturn false;\n</code></pre>\n\n<p>I'm not sure why you're suppressing this error:</p>\n\n<pre><code>catch (FacebookApiException $e){ //if theres an error\n $fbuser = null; //set the user to nothing\n return false();\n}\n</code></pre>\n\n<p>You don't need the parentheses after false.</p>\n\n<p>Your last function in your Game class, <code>secondsToTime()</code>, could use some factoring!</p>\n\n<p>All you really need is the DateTime class and you can create something such as:</p>\n\n<pre><code>$zeroTime = new DateTime('@0');\n$newInputTime = new DateTime(\"@$seconds\");\n$humanTime = $zeroTime-&gt;diff($newInputTime)-&gt;format('%y years, %a days, %h hours, %i minutes and %s seconds');\n\nreturn preg_replace('/(0 \\w+, )/', '', preg_replace('/(1 \\w+)s/', '$1', $humanTime));\n</code></pre>\n\n<h3>SQL</h3>\n\n<p>Your queries look pretty good, so I'm just going to nit-pick here.</p>\n\n<p>From <code>profileExists()</code>, you can alter your query to be a little bit more efficient:</p>\n\n<pre><code>SELECT count(1) FROM `userprofile_upl` WHERE `uid_upl` = :uid;\n</code></pre>\n\n<p>All I've done is take away the <code>*</code> selector, so now it's not counting all columns, yet it returns the same thing. I recommend <a href=\"https://stackoverflow.com/questions/261455/using-backticks-around-field-names\">using backticks</a>, even if you don't have any special characters. Just a good habit.</p>\n\n<p>In this query:</p>\n\n<pre><code>SELECT\n `firstname_upl` as `firstname`,\n `lastname_upl` as `lastname`,\n `info_upl` as `info`\n FROM `userprofile_upl`\n WHERE `uid_upl` = :uid;\n</code></pre>\n\n<p>I took out the the <code>uid</code> select, you don't use it anywhere else in the function.</p>\n\n<p>In <code>leaveGame()</code>, you have:</p>\n\n<pre><code>DELETE FROM gameplayers_gpl WHERE uid_gpl = :uid AND idgam_gpl = id\n</code></pre>\n\n<p>And I'm assuming it's a typo where you forgot the colon in front of id. You may want to have it or else face an issue debugging.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T16:24:30.647", "Id": "83525", "Score": "0", "body": "Thankyou very much for this, i will go through my code and make the changes you suggest, might take me a day or two, i will update the question with the modified code when its done. I really appreciate your time looking at this i have found your comments most helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T16:33:18.323", "Id": "83529", "Score": "0", "body": "Of course, when you update, don't overwrite your original code. That way users may see changes made." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:34:32.393", "Id": "83533", "Score": "0", "body": "I have a question about:\nWhen a string is literal (contains no variable substitutions), the apostrophe or \"single quote\" should always be used to demarcate the string.\n\nIn my queries i need to adjust the single quotes `'` within the query to double quotes `\"`\nso it becomes `'SELECT mycolumn_col AS \"newname\" FROM mytable'`\notherwise this would break the query?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:41:28.580", "Id": "83535", "Score": "0", "body": "@DizzyBryanHigh when adding an alias, use back-ticks. Then you'll have back-ticks inside single quotes which works fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:44:06.183", "Id": "83536", "Score": "0", "body": "Hmm i read on the PHPdoc link you gave `When a literal string itself contains apostrophes, it is permitted to demarcate the string with quotation marks or \"double quotes\". This is especially useful for SQL statements:` but i shall use backticks ``` as you suggest, it seems to keep things more alike..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:46:27.280", "Id": "83537", "Score": "0", "body": "I believe that rule is more for actual literal strings, not really SQL. Because in SQL, you can back tick names, and if you have things back ticked, then there's no need for the double quotes. Thanks for allowing me to think on this! :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T17:32:32.070", "Id": "47595", "ParentId": "47569", "Score": "3" } }, { "body": "<p>Once again thanks for your time, ive gone through my code and made some changes as per your recommendations, i might have missed some things out, but i think its a lot better than it was.</p>\n\n<p>The PHPDoc is great my ide (PHPStorm 6)now auto-suggests correctly where it didnt before, so already my coding is becoming more efficient!!!</p>\n\n<p>I have not implented your seconds to time function, as some game will be 24hrs long per turn, and i belive that php datetime can only handle seconds that are less than a day. if i'm wrong on this i will implement your suggestion as its much cleaner than what i have written!!</p>\n\n<p>User Class:</p>\n\n<pre><code>&lt;?php\n\nrequire_once('facebook/facebook.php'); // require facebook sdk\nrequire_once('config.class.php'); // require config class\nrequire_once('dbconn.class.php'); //require database connector\n\nclass User\n{\n /**\n * @var $userData stdClass\n * @var $_conn customSingleton\n * @var $facebook Facebook - facebook SDK\n * @var $user - Facebook user\n */\n public $userData;\n private $_conn; // our database connection\n public $facebook; // facebook sdk\n public $fbuser; // the facebook user\n //Constructor\n\n public function __construct()\n {\n $this-&gt;_conn = DBconn::getInstance(); //get DB instance\n $this-&gt;facebook = new Facebook(Config::read('fb.facebook'));\n $this-&gt;_userData = new stdClass();\n }\n\n /** checkAccess\n * checks to see if user has logged in and has access to the site\n * @return bool\n */\n public function checkAccess()\n {\n //cant use if(empty(session_id)) as empty and isset both require a variable to be passed\n if(!session_id()){\n session_start(); // Start session if we don't already have one\n return (isset($_SESSION['loggedin']) &amp;&amp; $_SESSION['loggedin'] === true);\n }\n }\n\n /**\n * profileExists - Checks to see if a user profile exists\n * internal @var $PDOQuery\n * @var $PDOStatement PDOStatement\n * @throws Exception - details of PDOException\n * @return bool\n */\n private function profileExists()\n {\n try{\n /** */\n $PDOQuery = ('SELECT count(1) FROM userprofile_upl WHERE uid_upl = :uid');\n $PDOStatement = $this-&gt;_conn-&gt;dbh-&gt;prepare($PDOQuery);\n $PDOStatement-&gt;bindParam(':uid', $this-&gt;_userData-&gt;uid);\n $PDOStatement-&gt;execute();\n return $PDOStatement-&gt;fetchColumn() &gt;0;\n }catch(PDOException $e){\n throw new Exception('Failed to check if profile exists for '.$this-&gt;_userData-&gt;uid, 0, $e);\n }\n }\n\n /**\n * getProfile - querys the database and stores the users profile in $userData\n * @throws Exception\n * @internal param $pdoQuery\n * @internal @var $row User\n * @internal param PDOStatement $PDOStatement\n * @throws Exception\n * @return bool\n */\n public function getProfile()\n {\n try{\n $pdoQuery = ('SELECT\n firstname_upl as `firstname`,\n lastname_upl as `lastname`,\n info_upl as `info`\n FROM userprofile_upl\n WHERE uid_upl = :uid'\n );\n $PDOStatement = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $PDOStatement-&gt;bindParam(':uid', $this-&gt;_userData-&gt;uid);\n $PDOStatement-&gt;execute();\n $row = $PDOStatement-&gt;fetch(PDO::FETCH_OBJ);\n $this-&gt;_userData-&gt;firstname = $row-&gt;firstname;\n $this-&gt;_userData-&gt;lastname = $row-&gt;lastname;\n $this-&gt;_userData-&gt;info = $row-&gt;info;\n return true;\n }catch(PDOException $e){\n throw new Exception('Failed to get Profile for user'.$this-&gt;_userData-&gt;uid, 0, $e);\n }\n }\n\n /**\n * createProfile - Creates a user profile\n * @internal param $pdoQuery\n * @internal @var $pdoData array\n * @throws Exception\n * @return bool\n */\n private function createProfile()\n {\n try{\n //we need to add the facebook user to the profiles table\n $pdoQuery = ('INSERT INTO userprofile_upl (firstname_upl, lastname_upl, uid_upl) VALUE (:firstname, :lastname, :uid)');\n $pdoData = array(\n 'firstname' =&gt; $this-&gt;_userData-&gt;firstname,\n 'lastname' =&gt; $this-&gt;_userData-&gt;lastname,\n 'uid' =&gt; $this-&gt;_userData-&gt;uid\n );\n $pdoStmt = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $pdoStmt-&gt;execute($pdoData);\n return true;\n }catch(PDOException $e){\n throw new Exception('Failed add Profile for user'.$this-&gt;_userData-&gt;uid, 0, $e);\n }\n }\n\n /**\n * goDashboard - Redirects a logged in user to the dashboard if they are logged in\n * @return bool\n */\n public function goDashboard()\n {\n if($this-&gt;checkAccess()){\n header('Location: '.Config::read('url.dashboard'));\n }else{\n return false;\n }\n }\n\n /**\n * generates a facebook log-out url\n * @return String: facebook logout url\n */\n public function getLogoutUrl()\n {\n //set user logout_url\n $params = array( 'next' =&gt; config::read('url.logout'));\n $this-&gt;_userData-&gt;logout_url = $this-&gt;facebook-&gt;getLogoutUrl($params);\n return $this-&gt;_userData-&gt;logout_url;\n }\n\n /**\n * loginFacebook - Logs a user into the site with facebook\n * Checks to see if user has an account and if not make one.\n * Checks to see if user has a profile and if not make one.\n * Checks to see if user has facebook credentials on this site\n *\n * @throws Exception\n * @return mixed\n */\n public function loginFacebook()\n {\n $fbuser = $this-&gt;facebook-&gt;getUser();//get facebook user\n if($fbuser){// if we have a user returned we have user who's authenticated and logged in with facebook\n try { // Proceed knowing we have a user.\n $me = $this-&gt;facebook-&gt;api('/me'); // the facebook user\n //generate a log-out url\n\n //set user logout_url\n $this-&gt;_userData-&gt;logout_url = $this-&gt;facebook-&gt;getLogoutUrl($params);\n //set the users details\n $this-&gt;_userData-&gt;uid = $this-&gt;facebook-&gt;getUser();\n $this-&gt;_userData-&gt;firstname = $me['first_name'];\n $this-&gt;_userData-&gt;lastname = $me['last_name'];\n $this-&gt;_userData-&gt;email = $me['email'];\n $this-&gt;_userData-&gt;provider = 'facebook';\n if(!$this-&gt;fbAccountExists($this-&gt;_userData)){\n $this-&gt;fbCreateAccount($this-&gt;_userData);\n };\n if(!$this-&gt;profileExists($this-&gt;_userData)){\n $this-&gt;createProfile($this-&gt;_userData);\n }\n $this-&gt;setSession();\n }\n catch (FacebookApiException $e){ //if theres an error\n throw new Exception('Failed to Login to facebook '.$this-&gt;_userData-&gt;uid, 0, $e);\n }\n }\n if(!$fbuser){\n //get a login url, returns to this page so we can process the login($fblogin_url)\n $loginUrl = $this-&gt;facebook-&gt;getLoginUrl(array('redirect_uri'=&gt;Config::read('url.fblogin'), false));\n header('Location: '.$loginUrl);//redirect to the login page\n }\n }\n\n /**\n * fbAccountExists - checks to see if a facebook account exists\n * @internal @var $pdoQuery\n * @internal @var $pdoStatement STRING\n * @throws Exception\n * @return bool\n */\n private function fbAccountExists()\n {\n try{\n $pdoQuery = ('SELECT count(1) FROM oauth_auth WHERE uid_auth = :uid and provider_auth = `facebook`');\n /** */\n $pdoStatement = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $pdoStatement-&gt;bindParam(':uid', $this-&gt;_userData-&gt;uid);\n $pdoStatement-&gt;execute();\n return $pdoStatement-&gt;fetchColumn() &gt; 0;\n }catch(PDOException $e){\n throw new Exception('Failed to check if account exists for user '.$this-&gt;_userData-&gt;uid, 0, $e);\n }\n }\n\n /**\n * fbCreateAccount - creates a facebook account\n * @throws Exception\n * @return bool: true/false\n */\n private function fbCreateAccount()\n {\n try{\n //we need to add the facebook user to the auth table\n $pdoQuery = (\"INSERT INTO oauth_auth(email_auth, uid_auth, provider_auth) VALUE (:email, :uid, :provider)\");\n $pdoData = array('email' =&gt; $this-&gt;_userData-&gt;email, 'uid' =&gt; $this-&gt;_userData-&gt;uid, 'provider' =&gt; $this-&gt;_userData-&gt;provider);\n $pdoStmt = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $pdoStmt-&gt;execute($pdoData);\n return true;\n }catch(PDOException $e){\n throw new Exception('There was an error creating an account for '.$this-&gt;_userData-&gt;uid, 0, $e);\n }\n }\n\n /**\n * setSession - Stores session variables to imitate user login.\n */\n function setSession()\n {\n if(session_id() == '') {session_start();}// Start session if we dont already have one\n $_SESSION['loggedin'] = true;\n $this-&gt;_userData-&gt;loggedin = true;\n $_SESSION['uid'] = $this-&gt;_userData-&gt;uid;\n $_SESSION['provider'] = $this-&gt;_userData-&gt;provider;\n header('Location: '.Config::read('url.dashboard'));\n }\n\n /**\n * getSession - saves session vars to our user\n * @return bool: true - session retrieved\n * @redirect if no session found redirects to login page\n */\n public function getSession()\n {\n if(session_id() == '') {session_start();}// Start session if we dont already have one\n if (!isset($_SESSION['loggedin']) &amp;&amp; $_SESSION['loggedin'] != true) {//Check to see if user is logged in\n header(\"location: \".Config::read('url.baseurl')); // User is logged in Redirect to homepage\n }else{\n //save session to this user\n $this-&gt;_userData-&gt;loggedin = $_SESSION['loggedin'];\n $this-&gt;_userData-&gt;provider = $_SESSION['provider'];\n $this-&gt;_userData-&gt;uid = $_SESSION['uid'];\n return true;\n }\n }\n}\n</code></pre>\n\n<p>Game Class:</p>\n\n<pre><code>&lt;?php\n/**\n * Created by Base5 Designs.\n * and Dizzy Developments\n * User: Dizzy High\n * Date: 14/04/14\n * Time: 12:08\n */\n\nrequire_once('config.class.php'); // require config class\nrequire_once('dbconn.class.php'); //require database connector\n\n/**\n * Class Game - instance of a game\n */\nclass Game {\n private $_conn; // database handler\n public $gameID; // id of game\n public $name; //name of game\n public $host; // uid of game host (the game creator)\n public $playerCount; // number of players in game\n public $roundTime; //round time of game in seconds\n public $visibility; // public (1) or private game (0)\n public $alias; // whether game players use an alias name or not (1 yes 2 no)\n public $status; //status of game (waiting, active, complete)\n public $currentRound; // current round of game (0 not started, odd day, even night)\n public $startTime; // datetime - start time of game\n public $createdTime; // datetime date game created\n\n /**\n * Init class with Database Connection\n */\n function __construct(){\n $this-&gt;_conn = DBconn::getInstance(); //get DB instance\n }\n\n /**\n * assignSettings - assigns settings to game instance\n * @param $name - property name\n * @param $value - property value\n */\n function assignSetting($name, $value){\n $whitelist = array('id', 'name', 'host', 'playerCount', 'roundTime', 'visibility', 'alias', 'status', 'currentRound', 'startTime', 'createdTime');\n if (in_array($name, $whitelist)) {\n $property = $name;\n $this-&gt;$property = $value;\n }\n }\n\n /**\n * makeGame - creates a new game and adds it to the database with the defined settings\n * @param array(): $settings- game settings for this game instance\n * @var $pdoQuery STRING\n * @var $pdoData array() - array of column and values to update\n * @var $PDOStatement\n * @return Game - this game instance\n * @throws PDOException - failed to run the pdo statement\n * @throws Exception - throws the exception from the PDOException\n */\n function makeGame($settings){\n if (is_array($settings)) {\n foreach($settings as $k=&gt;$v) {\n $this-&gt;assignSetting($k, $v);\n }\n } else {\n die('Config Error!');\n }\n try{\n //add the game to the games table\n\n $pdoQuery = ('INSERT INTO games_gam (name_gam, host_gam, playercount_gam, roundtime_gam, visibility_gam, alias_gam) VALUE (:gameName, :gameHost, :playerCount, :roundTime, :visibility, :alias)');\n $pdoData = array(\n 'gameName' =&gt; $this-&gt;name,\n 'gameHost' =&gt; $this-&gt;host,\n 'playerCount' =&gt; $this-&gt;playerCount,\n 'roundTime' =&gt; $this-&gt;roundTime,\n 'visibility' =&gt; $this-&gt;visibility,\n 'alias' =&gt; $this-&gt;alias\n );\n $PDOStatement = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $PDOStatement-&gt;execute($pdoData);\n $this-&gt;gameID = $this-&gt;_conn-&gt;dbh-&gt;lastInsertId();\n //add creator to game\n $this-&gt;addPlayer($this-&gt;host);\n return $this;\n }catch(PDOException $e){\n throw new Exception('There was an error creating a new game ', 0, $e);\n }\n }\n\n /**\n * getGame - queries the database and stores the results in this game instance\n * @param $gameID - the id of the game to fetch from the database\n * @var $pdoQuery STRING\n * @var $pdoData array() - array of column and values to update\n * @var $row PDORow\n * @return Game - this game instance\n * @throws PDOException - failed to run the pdo statement\n * @throws Exception - throws the exception from the PDOException\n */\n function getGame($gameID){\n try{\n $pdoQuery = ('SELECT\n id_gam as `id`,\n name_gam as `name`,\n host_gam as `host`,\n playercount_gam as `playerCount`,\n roundtime_gam as `roundTime`,\n visibility_gam as `visibility`,\n status_gam as `status`,\n alias_gam as `alias`,\n starttime_gam as `startTime`,\n createdtime_gam as `createdTime`\n FROM games_gam\n WHERE id_gam = :id'\n );\n $PDOStatemnet = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $PDOStatemnet-&gt;bindParam(':id', $gameID);\n $PDOStatemnet-&gt;execute();\n $row = $PDOStatemnet-&gt;fetch(PDO::FETCH_OBJ);\n $this-&gt;gameID = $row-&gt;id;\n $this-&gt;name = $row-&gt;name;\n $this-&gt;host = $row-&gt;host;\n $this-&gt;playerCount = $row-&gt;playerCount;\n $this-&gt;roundTime = $row-&gt;roundTime;\n $this-&gt;visibility = $row-&gt;visibility;\n $this-&gt;status = $row-&gt;status;\n $this-&gt;alias = $row-&gt;alias;\n $this-&gt;startTime = $row-&gt;startTime;\n $this-&gt;createdTime = $row-&gt;createdTime;\n return $this;\n }catch(PDOException $e){\n throw new Exception('There was an error getting the game: '.$gameID, 0, $e);\n }\n }\n\n /**\n * addPlayer - adds player to a game\n * @param $uid - uid of player\n * @return bool\n * @throws PDOException\n * @throws Exception\n */\n function addPlayer($uid){\n if(!$this-&gt;playerInGame($uid)){\n try{\n $pdoQuery = ('INSERT INTO gameplayers_gpl (idgam_gpl, uid_gpl) VALUE (:idgam, :uid)');\n $pdoData = array(\n ':idgam' =&gt; $this-&gt;gameID,\n ':uid' =&gt; $uid\n );\n $stmt = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $stmt-&gt;execute($pdoData);\n return true;\n }catch(PDOException $e){\n throw new Exception('There was an error adding user '.$uid.' to the game', 0, $e);\n }\n }\n }\n\n /**\n * leaveGame - Removes a player from a game\n * @param $uid - the uid of the player\n * @throws Exception\n * @internal param $gameID - the id of the game\n * @return $this\n */\n function leaveGame($uid){\n if($this-&gt;playerInGame($uid)){\n try{\n $pdoQuery = ('DELETE FROM gameplayers_gpl WHERE uid_gpl = :uid AND idgam_gpl = :id');\n $pdoData = array(\n ':uid' =&gt; $uid,\n ':id'=&gt; $this-&gt;$gameID\n );\n $stmt = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $stmt-&gt;execute($pdoData);\n return $this;\n }catch(PDOException $e){\n throw new Exception('There was an error removing the user '.$uid.' from the game '.$this-&gt;gameID, 0, $e);\n }\n }\n }\n\n /**\n * gameFull - checks to see if a game has all player slots filled\n * @internal $pdoQuery STRING\n * @internal $PDOStatement PDOStatement\n * @throws Exception\n * @return bool true: game is full\n * @return bool false: has slots\n */\n function gameFull(){\n try{\n $pdoQuery = ('SELECT count(1) FROM gameplayers_gpl WHERE idgam_gpl = :gameID');\n $PDOStatement = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $PDOStatement-&gt;bindParam(':gameID', $this-&gt;gameID);\n $PDOStatement-&gt;execute();\n $rowCount = (int) $PDOStatement-&gt;fetchColumn();\n return $rowCount &lt; $this-&gt;playerCount;\n }catch(PDOException $e){\n throw new Exception('There was an error while checking if the game '.$this-&gt;gameID.' was full', 0, $e);\n }\n }\n\n /**\n * playerInGame - checks to see if a player in the game\n * @param $uid: id of user\n * @internal @var $pdoQuery String\n * @internal @var $PDOStatement\n * @internal @var $pdoData array\n * @throws Exception\n * @return bool\n */\n function playerInGame($uid){\n try{\n $pdoQuery = ('SELECT count(1) FROM gameplayers_gpl WHERE idgam_gpl = :gameID AND uid_gpl = :uid');\n $PDOStatement = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $pdoData = array(\n ':uid' =&gt; $uid,\n ':gameID'=&gt; $this-&gt;gameID,\n );\n $PDOStatement-&gt;execute($pdoData);\n $rowCount = (int) $PDOStatement-&gt;fetchColumn();\n return $rowCount &gt; 0;\n }catch(PDOException $e){\n throw new Exception('There was an error while checking if '.$uid.' is in game '.$this-&gt;gameID, 0, $e);\n }\n }\n\n /**\n * @param $roundtime int - roundtime in seconds\n * @return array\n * @throws Exception\n */\n function getGamesList($roundtime){\n try{\n $pdoQuery = ('SELECT\n id_gam as `id`,\n name_gam as `name`,\n host_gam as `host`,\n playercount_gam as `playerCount`,\n roundtime_gam as `roundTime`,\n visibility_gam as `visibility`,\n status_gam as `status`,\n alias_gam as `alias`,\n starttime_gam as `startTime`,\n createdtime_gam as `createdTime`\n FROM games_gam\n WHERE visibility_gam = :visibility AND roundtime_gam = :roundtime AND status_gam = :gamestatus'\n );\n $PDOStatement = $this-&gt;_conn-&gt;dbh-&gt;prepare($pdoQuery);\n $pdoData = array(\n 'visibility' =&gt; 0,\n 'roundtime' =&gt; $roundtime,\n 'gamestatus' =&gt; 'waiting',\n );\n $PDOStatement-&gt;execute($pdoData);\n return $PDOStatement-&gt;fetchAll();\n }catch(PDOException $e){\n throw new Exception('There was an error while getting the games list ', 0, $e);\n }\n\n }\n /**\n * Convert number of seconds into years, days, hours, minutes and seconds\n * and return an string containing those values\n * the value of seconds could be greater than 1 day so unable to use phps datetime function\n * @param integer $seconds: Number of seconds to parse\n * @return string\n */\n function secondsToTime($seconds){\n $y = floor($seconds / (86400*365.25));\n $d = floor(($seconds - ($y*(86400*365.25))) / 86400);\n $h = gmdate('H', $seconds);\n $m = gmdate('i', $seconds);\n $s = gmdate('s', $seconds);\n\n $string = '';\n\n if($y &gt; 0){\n $yw = $y &gt; 1 ? ' years ' : ' year ';\n $string .= $y . $yw;\n }\n if($d &gt; 0){\n $dw = $d &gt; 1 ? ' days ' : ' day ';\n $string .= $d . $dw;\n }\n if($h &gt; 0){\n $hw = $h &gt; 1 ? ' hours ' : ' hour ';\n $string .= $h . $hw;\n }\n if($m &gt; 0){\n $mw = $m &gt; 1 ? ' minutes ' : ' minute ';\n $string .= $m . $mw;\n }\n if($s &gt; 0){\n $sw = $s &gt; 1 ? ' seconds ' : ' second ';\n $string .= $s . $sw;\n }\n\n return preg_replace('/\\s+/',' ',$string);\n }\n\n function getHost($gameID){\n\n }\n function initGame(){\n\n }\n\n function processVotes(){\n\n }\n\n function setPlayerRole($uid, $role){\n\n\n }\n\n function getPlayerRole(){\n\n }\n\n function getPlayerHealth(){\n\n }\n\n function getGameDay(){\n\n }\n\n function getGameVotes(){\n\n }\n</code></pre>\n\n<p>for completness heres my database singleton, i have read this is a bad idea and some say its ok.</p>\n\n<pre><code>&lt;?php\n//php class for connecting to database\n\nrequire_once('config.class.php');\nclass DBConn\n{ \n public $dbh; // handle of the db connexion\n private static $instance;\n\n private function __construct()\n {\n\n // building data source name from config\n $dsn = Config::read('db.dsn');\n // getting DB username from config\n $user = Config::read('db.user');\n // getting DB password from config \n $password = Config::read('db.password');\n // set database handler\n $this-&gt;dbh = new PDO($dsn, $user, $password);\n }\n\n /**\n * getInstance\n * creayes a singleton of a pdo connection\n * @return DBConn\n */\n public static function getInstance()\n {\n if (!isset(self::$instance))\n {\n $object = __CLASS__;\n self::$instance = new $object;\n }\n return self::$instance;\n }\n}\n</code></pre>\n\n<p>really i think the way i need to go is to do as you suggest and create a Database layer class that connects to my db, then perhaps extend this class with any of my functions that do reading and writing to the db, there's likely to be a lot of these methods so maybe its going to make it too big??</p>\n\n<p>something along the lines off:</p>\n\n<pre><code>&lt;?php\n//php class for connecting to database\nclass DBLayer\n{\n public $dbh; // handle of the db connexion\n\n private function __construct($config)\n {\n // building data source name from config\n $dsn = $config-&gt;read('db.dsn');\n // getting DB username from config\n $user = $config-&gt;read('db.user');\n // getting DB password from config \n $password = $config-&gt;read('db.password');\n // set database handler\n $this-&gt;dbh = new \\PDO($dsn, $user, $password);\n }\n\n public function getConnection()\n {\n if ($this-&gt;dbh)\n {\n return $this-&gt;dbh;\n }\n return false;\n }\n}\n\nclass GameLayer EXTENDS DBLayer\n{\n\n}\n</code></pre>\n\n<p>This extended class would maybe need to have the current user and current game injected into it via dependency injection, the DBLayer already has a dependency is it possible to inject other dependencies into the GameLayer class?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T22:07:42.913", "Id": "83683", "Score": "0", "body": "At a quick glance, it looks a lot neater. Two more things that I notice right off the bat, [learn what dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) is all about, and only apply comments you need. Comments such as `// getting DB password from config` only duplicate something the code itself easily explains." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T18:55:02.993", "Id": "47731", "ParentId": "47569", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T11:44:30.300", "Id": "47569", "Score": "1", "Tags": [ "php", "object-oriented", "game", "classes" ], "Title": "Creating a Party Game to learn OOP" }
47569
<p>I'm working on a <a href="http://en.wikipedia.org/wiki/Bookmarklet" rel="nofollow">bookmarklet</a> that will be cached for 24 hours only, after that time it will be reloaded from the original source. Is there something I could improve?</p> <pre><code>javascript:(function () {var currentTime=new Date();var month=currentTime.getMonth()+1;var day=currentTime.getDate();var year=currentTime.getFullYear();document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = 'http://bookmarklet.example.com/js/bookmarklet.js?v='+month+'-'+day+'-'+year}()); </code></pre>
[]
[ { "body": "<h1>Use timestamps.</h1>\n\n<p>It's faster since you don't need to get the date, month and year. In the following script, the only function called for the date is <code>getTime()</code>. Additionally, if you use the newer <code>Date.now()</code>, you skip creating a date object.</p>\n\n<p>In the example, we get the current timestamp and modulo it by a day. The remainder is the milliseconds that have passed since midnight. We then subtract it from the current timestamp so that the timestamp for the url is always based on the day. The only time it changes is when it's the next day.</p>\n\n<h1>Write to read</h1>\n\n<p>Sure, you're building a bookmarklet. But that does not mean making it unreadable. Write to read. Let the minifier do the shrinking for you. Besides, the bookmarklets themselves are copy-pasted, and not loaded. There's no overhead in size.</p>\n\n<p>So in the following script, we pluck out the url so it's easily editable. We also make some parts verbose for easy reading.</p>\n\n<h1>The script</h1>\n\n<pre><code>var url = 'http://bookmarklet.example.com/js/bookmarklet.js?v='\n\nvar currentTimestamp = new Date().getTime(); // or Date.now()\nvar currentDayTimestamp = currentTimestamp - (currentTimestamp % 86400000);\n\nvar script = document.createElement('script');\ndocument.getElementsByTagName('head')[0].appendChild(script);\n\nscript.src = url + currentDayTimestamp;\n</code></pre>\n\n<h1>Perf tests</h1>\n\n<p>Well, if you are bent on performance, then here's some <a href=\"http://jsperf.com/24hr-bookmarklet\" rel=\"nofollow\">perf tests.</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T13:42:42.150", "Id": "47573", "ParentId": "47571", "Score": "1" } }, { "body": "<p>As Joseph The Dreamer mentioned, the version you work on should not be the one liner, work on a properly formatted version and then let the minifier do it's thing. Since you are going for low character count, I would definitely suggest to use a single <code>var</code> statement. I also tend to end my bookmarklets with <code>void(0);</code>.</p>\n\n<pre><code>javascript:(function (){\n var now=new Date(),\n month=now.getMonth()+1;\n day=now.getDate();\n year=now.getFullYear(),\n script=document.createElement('script'),\n url='http://bookmarklet.example.com/js/bookmarklet.js?v='+month+'-'+day+'-'+year;\n document.getElementsByTagName('head')[0].appendChild( script ).src = url\n}());void(0);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T01:24:55.813", "Id": "47687", "ParentId": "47571", "Score": "0" } } ]
{ "AcceptedAnswerId": "47573", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T13:00:40.120", "Id": "47571", "Score": "2", "Tags": [ "javascript", "cache", "bookmarklet" ], "Title": "JavaScript bookmarklet with a 24 hour cache" }
47571
<p>I have these relevant tables in an MVC website:</p> <ul> <li><code>Server</code></li> <li><code>ServerPlayer</code></li> <li><code>ServerPlayerChat</code></li> </ul> <p>Servers have <code>serverPlayers</code> and <code>ServerPlayers</code> have <code>ServerPlayerChats</code>. Simple enough and expectable.</p> <p>I have a feeling my code could be drastically condensed (particularly the <code>GetServerPlayer</code> method) and that the <code>GetServerPlayer</code> method is named wrong, although I couldn't think of a better name other than <code>GetOrCreateServerPlayer</code>, which is really long-winded. Also, this is in the Server model. I think I could move the add chat to the server player model, but my concern is that this might be more appropriate in a controller.</p> <p>Is it good practice to do what I'm doing where I'm not only adding the new chat to the <code>ServerUserChats</code> collection, but also setting <code>ServerPlayer = player</code> inside the new chat? I'm aware that LINQ/EF/... is capable of figuring out relations like this from just one variable but it felt right to do this, so feedback on that is accepted too.</p> <pre><code>public void AddChat(string playername, string chat, int time) { LastChat = time; ServerPlayer player = GetServerPlayer(playername); player.ServerUserChats.Add(new ServerPlayerChat() { Content = chat, Time = time, ServerPlayer = player }); } public ServerPlayer GetServerPlayer(string playername) { ServerPlayer player = GetPlayer(playername); if (player == null) { player = new ServerPlayer() { Server = this, UserName = playername, }; Players.Add(player); } return player; } public ServerPlayer GetPlayer(string playername) { return Players.Where(x =&gt; x.UserName == playername).FirstOrDefault(); } </code></pre>
[]
[ { "body": "<p>Use Players.SingleOrDefault() instead of Where and FirstOrDefault.\nIf you use the function GetPlayer just one time, remove it.</p>\n\n<pre><code>public ServerPlayer GetServerPlayer(string playername)\n{\n ServerPlayer player = Players.SingleOrDefault(x =&gt; x.UserName == player name);\n if (player == null)\n {\n player = new ServerPlayer() {\n Server = this,\n UserName = playername,\n };\n\n Players.Add(player);\n }\n\n return player;\n}\n</code></pre>\n\n<p>Personally, I think you should change GetServerPlayer to GetOrCreateServerPlayer especially if you are a team. We don't have to know or look your function to understand its purpose. Or keep the name and add the appropriates comments (summary, return, etc).</p>\n\n<p>In the case of ASP.NET which follow MVC pattern, I think you must separate the logic and the model. \nFor my part I create Manager for logic and my controller just serve to call the appropriates methods of my manager.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T08:47:00.640", "Id": "48130", "ParentId": "47582", "Score": "3" } }, { "body": "<p><code>GetOrCreate</code> methods are inherently dual-purpose which violates the Single Responsibility Principle. The further <code>GetOrCreate</code> gets buried in your code, the harder it will be to strip that behavior out when you don't want it. Think of it this way: what objects/entities are actually able to create <code>ServerChats</code>? The answer isn't <code>playernames</code>, it's <code>ServerPlayers</code>. I would refactor like so:</p>\n\n<pre><code>public void AddChat(ServerPlayer player, string chat, int time)\n{\n if(player == null)\n throw new ArgumentException(\"player\";\n ...\n}\n\npublic ServerPlayer GetServerPlayer(string playerName)\n{\n return Players.SingleOrDefault(x =&gt; x.UserName == playername);\n}\n</code></pre>\n\n<p>Now you have to consider when a <code>ServerPlayer</code> should be created, but at least it isn't \"magic\" and can be done explicitly elsewhere. Maybe you some sort of session management code that ensures someone on the server always has a <code>ServerPlayer</code> in place, etc. The point is that this is now possible:</p>\n\n<pre><code>ServerPlayer currentPlayer = GetServerPlayer(this.Request.PlayerName);\n\nif(currentPlayer == null)\n{\n RedirectToLogin();\n}\nelse\n{\n AddChat(currentPlayer, chat, time);\n}\n</code></pre>\n\n<p>You may not have a requirement for <code>RedirectToLogin</code> now, but the \"create by default\" code isn't trapped deep in your system so it allows for this type of code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T14:07:49.470", "Id": "48982", "ParentId": "47582", "Score": "2" } } ]
{ "AcceptedAnswerId": "48982", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T15:19:49.283", "Id": "47582", "Score": "2", "Tags": [ "c#", "linq", "asp.net", "entity-framework", "chat" ], "Title": "Adding chat to an MVC database" }
47582
<p>I’ve got a matrix of data and I want to take the average of the positive and negative parts of the values. Is there a more Pythonic way of doing it?</p> <pre><code>from numpy import * … exposures = matrix([0]*numPaths*numExposures) exposures.shape = numPaths, numExposures … # fill matrix @vectorize def plusv(x): return max(x,0) @vectorize def minv(x): return min(x,0) ee = transpose(exposures.mean(axis=0)) epe = transpose(plusv(exposures).mean(axis=0)) ene = transpose(minv(exposures).mean(axis=0)) </code></pre>
[]
[ { "body": "<p>There are a few things which we could improve:</p>\n\n<p>When importing a module, you would not usually import all symbols from that module. You can however rename the module to make it more convenient, e.g.:</p>\n\n<pre><code>import numpy as np\n# now we can do np.matrix(…), np.transpose(…), etc.\n</code></pre>\n\n<p>Instead of initializing a matrix and then reshaping it, create it directly in the shape you need:</p>\n\n<pre><code>exposures = np.zeros((numPaths, numExposures))\n</code></pre>\n\n<p>When <code>def</code>ining a function put the function body on a new line, no matter how short it might be:</p>\n\n<pre><code>def plusv(x):\n return max(x, 0)\n</code></pre>\n\n<p>Instead of stuffing this normalization into a custom function, you could just use the builtin <code>clip</code>. It takes two arguments: a minimum and maximum bound, both inclusive. So <code>plusv(a)</code> would be equivalent to <code>a.clip(0, np.inf)</code> for floats and <code>a.clip(0, np.iinfo(np.int).max)</code> for integers.</p>\n\n<p>The numpy functions can either be called as functions or as methods. Using them as methods is usually easier to read for people used to reading left-to-right.</p>\n\n<pre><code>ee = exposures.mean(axis=0).transpose()\nepe = exposures.clip(0, np.inf).mean(axis=0).transpose()\nene = exposures.clip(-np.inf, 0).mean(axis=0).transpose()\n</code></pre>\n\n<p>Oh dear, we are repeating code! Well, let's just use a list comprehension/generator expression instead:</p>\n\n<pre><code>positive_exposures = exposures.clip(0, np.inf)\nnegative_exposures = exposures.clip(-np.inf, 0)\nee, epe, ene = (xs.mean(axis=0).transpose() for xs in\n (exposures, positive_exposures, negative_exposures))\n</code></pre>\n\n<p>In the above snippet, the temporary variables <code>positive_exposure</code> and <code>negative_exposure</code> are entirely optional, but they make the code more <em>self-documenting</em>.</p>\n\n<p>Note that I use <code>snake_case</code> for my variables. This is the convention in Python for normal variables or method names. The <code>lowerCamelCase</code> scheme is not generally used. While I recommend you follow the general Python convention of words separated by underscores, the only important thing is to be consistent. Whatever your naming scheme, names like <code>ee</code> and <code>epe</code> are <em>not acceptable</em>. Prefer full words over abbreviations, unless the abbreviations are common enough (<code>i</code> for an index is ok, and everyone understands <code>str</code> means “string“).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:18:03.950", "Id": "47603", "ParentId": "47584", "Score": "3" } } ]
{ "AcceptedAnswerId": "47603", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T15:20:58.327", "Id": "47584", "Score": "7", "Tags": [ "python", "matrix", "numpy" ], "Title": "Average of positive and negative part of numpy matrix" }
47584
<p>Is this repository code written according to best practices? The Last Section I included it in the repository as well.</p> <pre><code>class HR_Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class { private readonly LoginDataContext dataContext; public HR_Repository(LoginDataContext dataContext) { this.dataContext = dataContext; } public void Commit() { dataContext.SubmitChanges(); } public IList&lt;T&gt; FindAll() { var table = this.LookupTableFor(typeof(T)); return table.Cast&lt;T&gt;().ToList(); } public IQueryable&lt;T&gt; Find() { var table = this.LookupTableFor(typeof(T)); return table.Cast&lt;T&gt;(); } public void Add(T item) { var table = this.LookupTableFor(typeof(T)); table.InsertOnSubmit(item); } public void Delete(T item) { var table = this.LookupTableFor(typeof(T)); table.DeleteOnSubmit(item); } private ITable LookupTableFor(Type entityType) { return dataContext.GetTable(entityType); } } public static class UserQueries { public static Employee ByUserName(this IQueryable&lt;Employee&gt; employees, string username) { return employees.Where(u =&gt; u.User_Name == username).FirstOrDefault(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:12:47.853", "Id": "83435", "Score": "1", "body": "I don't feel like compiling this, but I assume that it must not work? That seems to be why this was closed, since its clearly written. I rather wish someone who cared enough to close this would explain what the problem is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T22:02:23.567", "Id": "83451", "Score": "0", "body": "Agreed. This at least deserves an explanation. At a glance, I don't see why this wouldn't compile, but I don't have a C# compiler on my home machine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T23:11:41.520", "Id": "83457", "Score": "0", "body": "It works. I guarantee it!" } ]
[ { "body": "<p>I don't like the underscore in the class name, <code>HR_Repository</code>. It's a generic name for a <em>generic class</em>, which is good, but seeing that it <em>implements</em> <code>IRepository&lt;T&gt;</code> I would expect something like this:</p>\n<pre><code>public class EmployeeRepository : IRepository&lt;Employee&gt;\n</code></pre>\n<p>I like that you're initializing your <code>private readonly LoginDataContext</code> in the constructor, from a constructor argument.</p>\n<pre><code>private readonly LoginDataContext dataContext;\npublic HR_Repository(LoginDataContext dataContext)\n{\n this.dataContext = dataContext;\n}\n</code></pre>\n<p>I like it because this implementation of <code>IRepository&lt;T&gt;</code> has a <em>dependency</em> on the <code>LoginDataContext</code> - by passing it into the constructor, you're doing <em>constructor injection</em> and that's awesome. Ideally the dependency would be an <em>abstraction</em> (abstract class or interface), which makes it easier to inject as a <em>mock</em> or <em>fake</em> implementation when you're writing unit tests. Even if you never write these tests, the fact that your code would be <em>testable</em> is a very good thing.</p>\n<p>I don't like that your static helper provides extension methods to <code>IQueryable&lt;Employee&gt;</code>, it's not clear how/where this code is being used, the benefits aren't immediately apparent.</p>\n<hr />\n<p>As for the pattern itself, it looks like a hybrid Unit-of-Work / Repository implementation, because of the <code>Commit</code> method. But your implementation exposes <code>ITable</code> and <code>IQueryable</code>, which leaks out the ORM into the calling code.</p>\n<p>If you consider the <em>client</em> as, say, a <em>controller</em> class (assuming MVC), the controller would have a dependency on the <em>unit-of-work</em>, which has a dependency on the <em>data context</em> and lets you work with one or more <em>repositories</em>, which all share the data context of the unit-of-work:</p>\n<p><img src=\"https://i.stack.imgur.com/lUWWz.png\" alt=\"UoW+Repository\" /></p>\n<p><sub>(I skipped UML classes, hope this doesn't look too weird)</sub></p>\n<hr />\n<blockquote>\n<p><strong>Disclaimer</strong></p>\n<p>I'm biased. I'm not a fan of unit-of-work/repository pattern, at least not with Entity Framework. I think Entity Framework's <code>DbContext</code> <em>is a</em> unit-of-work, and the <code>IDbSet&lt;TEntity&gt;</code> properties it exposes <em>are</em> repositories - I think wrapping this in another level of abstraction has very little benefits and adds a considerable amount of complexity to the code.</p>\n<p>Instead, I simply wrap <code>DbContext</code> with an interface:</p>\n<pre><code>public interface IUnitOfWork\n{\n void SaveChanges();\n IDbSet&lt;TEntity&gt; Set&lt;TEntity&gt;();\n}\n\npublic class MyContext : DbContext, IUnitOfWork\n{\n IDbSet&lt;MyEntity&gt; MyEntities { get; set; }\n // ...\n}\n</code></pre>\n<p>Then I usually have a &quot;service&quot; class that takes an <code>IUnitOfWork</code> dependency; I write closely related queries inside that class, but the &quot;service&quot; only returns materialized results, it doesn't expose <code>IQueryable&lt;T&gt;</code>, even less so <code>ITable</code>. A controller will take a factory that can instantiate such a &quot;service&quot;, wrapping its instance in a <code>using</code> block to ensure proper disposal.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T19:45:05.590", "Id": "83665", "Score": "1", "body": "Here's some rantage from the great and powerful Rob Conery supporting your distaste for unit-of-work+repository: http://www.wekeroad.com/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T04:47:56.810", "Id": "47632", "ParentId": "47587", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T15:47:50.320", "Id": "47587", "Score": "2", "Tags": [ "c#", "design-patterns" ], "Title": "Is the following repository pattern properly applied?" }
47587
<p>I'm working on Ocaml.org 99 problems, and I solved the <a href="http://ocaml.org/learn/tutorials/99problems.html#Decodearunlengthencodedlistmedium" rel="nofollow">run-length decode one</a>.</p> <p>Here is the solution given by the site:</p> <blockquote> <pre><code>let decode l = let rec many acc n x = if n = 0 then acc else many (x :: acc) (n-1) x in let rec aux acc = function | [] -&gt; acc | One x :: t -&gt; aux (x :: acc) t | Many (n,x) :: t -&gt; aux (many acc n x) t in aux [] (List.rev l);; </code></pre> </blockquote> <p>And here is mine:</p> <pre><code>let decode l = let rec aux acc = function | [] -&gt; acc | One elem :: t -&gt; aux (elem :: acc) t | Many(cnt, elem) :: t -&gt; if cnt &gt; 0 then aux (elem::acc) (Many(cnt - 1, elem) :: t) else aux acc t in List.rev (aux [] l);; </code></pre> <p>Test:</p> <pre><code>type 'a rld = | One of 'a | Many of int * 'a;; (* result expected : ["a"; "a"; "a"; "a"; "b"; "c"; "c"; "a"; "a"; "d"; "e"; "e"; "e"; "e"] *) decode [Many (4,"a"); One "b"; Many (2,"c"); Many (2,"a"); One "d"; Many (4,"e")];; </code></pre> <p>Could my solution become more optimal?</p>
[]
[ { "body": "<p>Elegance is a matter of taste, so you'll probably get different answers for that point. Personally, I find your solution easier to understand: it makes good use of the algebra defined through the <code>rld</code> type.</p>\n\n<p>From an efficiency standpoint, your algorithm creates as <code>Many</code> values as the repetition count in the original one. That means that your algorithm will generate memory allocation. It will also have to match it again as many times through recursion, so there's a computational extra load as well. The solution proposed by the site is more efficient in that regard: it only allocates the necessary values to construct the resulting list, and only matches once each element of the input list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-19T10:16:59.160", "Id": "57448", "ParentId": "47588", "Score": "2" } } ]
{ "AcceptedAnswerId": "57448", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T16:09:55.053", "Id": "47588", "Score": "2", "Tags": [ "functional-programming", "comparative-review", "compression", "ocaml" ], "Title": "Comparing run-length decoding algorithms" }
47588
<p>I recently had to work in a tricky piece of work for a project I am working on. You can find its code <a href="https://github.com/mariosangiorgio/RateMyApp/tree/experiments" rel="nofollow">on GitHub</a> and I'd like to have a feedback about some specific parts of it.</p> <p>The project is a library and if you look at the README you will see how it needs to be integrated with an android application. I report it here:</p> <pre><code>public class YOUR_APP_NAMEApplication extends Application{ private RateMyApp rateMyApp; @Override public void onCreate(){ RateMyAppBuilder builder = new RateMyAppBuilder(); builder.setLaunchesBeforeAlert(3); builder.setDaysBeforeAlert(7); builder.setEmailAddress("mariosangiorgio@gmail.com"); PreferencesManager preferencesManager = SharedPreferencesManager.buildFromContext(this); rateMyApp = builder.build(preferencesManager); } public void activityCreated(Activity activity){ if(rateMyApp != null) rateMyApp.appLaunched(activity); } public void activityDestroyed(){ if(rateMyApp != null) rateMyApp.activityDestroyed(); } } public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_main); super.onCreate(savedInstanceState); FutsalCoachApplication application = (FutsalCoachApplication) getApplicationContext(); application.activityCreated(this); } @Override public void onDestroy(){ FutsalCoachApplication application = (FutsalCoachApplication) getApplicationContext(); application.activityDestroyed(); super.onDestroy(); } } </code></pre> <p>The first thing I'd like to ask is if it acceptable to require the creation of a new class extending <code>Application</code> just to hold the main component of my library.</p> <p>I'd also like to get a feedback about the fact that my library needs to create instances of <code>DialogFragment</code> and to start new activities. Both these tasks require an active <code>Activity</code> and this is a source of a bit of trickery.</p> <p>I like the fact that <code>RateMyApp</code> class has the dependency on the <code>Activity</code> instance isolated in the <code>RateMyApp.appLaunched(Activity)</code> method.</p> <p>I don't really like how I get the class extending <code>Application</code> to get a reference of the current <code>Activity</code>. Needing to override <code>Activity.onCreate(Bundle)</code> and <code>Activity.onDestroy()</code> feels a bit dirty.</p> <p>What do you think about this approach? Would you do it in an alternative (and possible cleaner) way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T15:29:44.380", "Id": "83971", "Score": "1", "body": "Even though this code is reviewable (and I'm working on an answer for it), code that is expected to be reviewed should be contained within the question. Do you also want your `RateMyApp` class to be reviewed? If so, add that class to your question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T20:21:12.787", "Id": "84229", "Score": "0", "body": "I think that for now it would be enough to review only this piece of code. Actually I received a pull request with an alternate solution, which looks much better, but I'm still interested in comments about the code I wrote." } ]
[ { "body": "<p>First, I would recommend that you take a look at the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow noreferrer\">null object pattern</a> to avoid the <code>!= null</code> check here:</p>\n<pre><code>if (rateMyApp != null)\n rateMyApp.appLaunched(activity);\n</code></pre>\n<p>By using a &quot;null object&quot;, simply <code>rateMyApp.appLaunched(activity);</code> would be enough. Your null object is an instance of a special class that just doesn't do anything in the <code>appLaunched</code> method.</p>\n<hr />\n<blockquote>\n<p>The first thing I'd like to ask is if it acceptable to require the creation of a new class extending Application just to hold the main component of my library.</p>\n</blockquote>\n<p>No. Absolutely not. I don't really see why you are using the <code>Application</code> to do that. You could write a regular Java class for holding the main component of your library. Or rather, you could let the user of your library determine how to hold the main component of your library.</p>\n<p>Instead of using the <code>onCreate</code> method of the <code>Application</code>, you could let the user initialize the <code>RateMyApp</code> object in the <code>onCreate</code> of a regular <code>Activity</code>.</p>\n<blockquote>\n<p>I'd also like to get a feedback about the fact that my library needs to create instances of DialogFragment and to start new activities. Both these tasks require an active Activity and this is a source of a bit of trickery.</p>\n</blockquote>\n<p>Technically, those tasks don't need an active Activity. They need a <code>Context</code>. However, &quot;acquiring&quot; an activity should not be that much of a problem. See below.</p>\n<blockquote>\n<p>I don't really like how I get the class extending Application to get a reference of the current Activity.</p>\n</blockquote>\n<p>Me neither. Why does it need a reference of the current activity?</p>\n<blockquote>\n<p>Would you do it in an alternative (and possible cleaner) way?</p>\n</blockquote>\n<p>Let the user whenever he likes create a <code>RateMyApp</code> object, and call the <code>.appLaunched</code> method on it (as you've done in <a href=\"https://github.com/mariosangiorgio/RateMyApp/blob/master/sample/src/main/java/com/mariosangiorgio/ratemyapp/sample/MainActivity.java\" rel=\"nofollow noreferrer\">the sample</a>). There is no need for your <code>RateMyApp</code> to know which is the current showing activity, it only needs to know about an activity (or rather, <code>Context</code>) when it should do something - i.e. possibly show a dialog or read/write the preferences to keep track on how many times/days the application has been used. When the user of your library wants your library to possibly show the dialog, let it call a method on your library and pass along the current <code>Activity</code> as a parameter. That's it. No need to make things more complicated than necessary.</p>\n<h3>Summary</h3>\n<p>By extending Application as you've done in your question, you have only added a middle hand that doesn't add any value at all. All the things that are done there can, and in this case really <strong>should</strong>, be done in the <code>MainActivity</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T20:40:21.803", "Id": "84372", "Score": "0", "body": "Thanks for your answer. Actually the real issue was another. The reason I used the class extending `Application` was to discriminate between the creation of an `Activity` at the startup of the application and the creation of the activity for another reason.\n\nI then discovered, as you can see in the sample, that the parameter of `onCreate` is null when the activity is created for the first time and I used this knowledge to get rid of the class extending `Application`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T06:31:00.563", "Id": "85394", "Score": "0", "body": "Minor note: As to the first point, `rateMyApp` will never be null, so the null check is just unnecessary anyway. (Application.onCreate() will always be called before any activities are created)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T14:53:33.693", "Id": "48056", "ParentId": "47590", "Score": "3" } } ]
{ "AcceptedAnswerId": "48056", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T16:23:50.833", "Id": "47590", "Score": "3", "Tags": [ "java", "android" ], "Title": "Holding a reference of the active Android Activity" }
47590
<p>I implemented my own sorting in VBA because it doesn't provide its own, and it's healthy to test yourself. It was surprisingly difficult and I ended up make a few tweaks that I didn't expect to make in order for it to sort.</p> <pre><code>Public Sub quicksort(ByRef arr As Variant, _ ByVal left As Integer, _ ByVal right As Integer) If right &lt;= left Then Exit Sub ' length == 1 already sorted 'swap pivot it to end. I'm not yet concerned about pivot selection Call swap(arr(CInt((left + right) \ 2)), arr(right)) Dim r As Integer: r = right ' include the pivot in case it's the greatest value Dim l As Integer: l = left Dim p As Variant: p = arr(right) ' again pivot is at the end While l &lt; r While arr(l) &lt; p And l &lt; r l = l + 1 Wend While arr(r) &gt;= p And l &lt; r ' Right claims values which equal pivot r = r - 1 Wend If l &lt;&gt; r Then Call swap(arr(l), arr(r)) Wend ' Don't swap the same thing If l &lt;&gt; right Then Call swap(arr(right), arr(l)) Call quicksort(arr, left, l - 1) Call quicksort(arr, l + 1, right) End Sub </code></pre>
[]
[ { "body": "<p>Few notes.</p>\n\n<ul>\n<li>All algorithms on ranges are much simpler if the range is considered semi-open (that is, <code>right</code> is just beyond the last interesting element.</li>\n<li>The <code>While l &lt; r</code> loop does a very important job; important enough to factor it into a separate function, <code>Public Sub Partition</code></li>\n<li>One more thing you want to do is to eliminate a last tail-recursive call to quicksort. It is very well possible that the compiler will do it for you; still it is better to be explicit.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:32:07.787", "Id": "83424", "Score": "0", "body": "You mean to init `r = right - 1`? But that breaks if the pivot is the single greatest value." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T17:36:06.790", "Id": "47597", "ParentId": "47591", "Score": "7" } }, { "body": "<p>VB6/VBA is a \"bulky\" language to read - <code>If...End If</code>, <code>Sub...End Sub</code>, <code>While...Wend</code>; compared to <em>curly braces</em> languages (Java, C#, etc.), VB6/VBA code, by the nature of its <em>code block</em> delimiters, makes pretty crowded code, even when written cleanly.</p>\n\n<p>Give it some breathing vertical space:</p>\n\n<pre><code>Public Sub QuickSort(arr As Variant, ByVal left As Integer, ByVal right As Integer)\n\n 'if length is 1, there's nothing to sort:\n If right &lt;= left Or Not IsArray(arr) Then Exit Sub\n\n 'swap pivot it to end. I'm not yet concerned about pivot selection\n Swap arr((left + right) \\ 2), arr(right)\n\n ' include the pivot in case it's the greatest value:\n Dim r As Integer\n r = right \n\n Dim l As Integer\n l = left\n\n ' pivot is at the end:\n Dim p As Variant\n p = arr(right) \n\n While l &lt; r\n\n While arr(l) &lt; p And l &lt; r\n l = l + 1\n Wend\n\n ' right claims values equal to pivot:\n While arr(r) &gt;= p And l &lt; r \n r = r - 1\n Wend\n\n If l &lt;&gt; r Then Swap arr(l), arr(r)\n\n Wend\n\n ' only swap if values aren't equal:\n If l &lt;&gt; right Then Swap arr(right), arr(l)\n\n QuickSort arr, left, l - 1\n QuickSort arr, l + 1, right\n\nEnd Sub\n</code></pre>\n\n<p>Couple points:</p>\n\n<ul>\n<li>Unless you have a massive parameters list, keep signatures on a single line.</li>\n<li>Method names should be <code>PascalCase</code>.</li>\n<li><code>:</code> instruction separator is great for the <em>immediate pane</em>, but should be avoided in actual code - keep it single instruction per line as much as possible.</li>\n<li>Place comments just above the code you're commenting, this makes reading more vertically flowing.</li>\n<li>I don't think <code>CInt</code> cast/conversion is needed here, you're using the <code>\\</code> <em>integer division</em> operator, on two <code>Integer</code> variables - the result <em>has to be</em> an <code>Integer</code>, hence the conversion would be redundant.</li>\n<li><code>Call</code> is a relic from ancient, stone-tablet-BASIC versions; dropping it allows you to also drop the parentheses that surround the parameters (<em>not</em> dropping the parentheses wouldn't compile).</li>\n<li>@user58697 is correct, the outer <code>While</code> loop could be extracted into its own method.</li>\n<li>What happens if <code>arr</code> isn't an array? I know, dumb edge case, but your method takes a <code>Variant</code> (it <em>has</em> to), and that could be literally <em>anything</em>. Guarding against that dumb error is fairly easy: <code>IsArray(arr)</code> must return <code>True</code>.</li>\n<li><p>I would avoid chopped-off and single-letter names, especially when they involve a lowercase <code>l</code>:</p>\n\n<ul>\n<li><code>arr</code> => <code>items</code> or <code>values</code></li>\n<li><code>p</code> => <code>pivotValue</code></li>\n<li><code>r</code> => <code>rightIndex</code></li>\n<li><code>l</code> => <code>leftIndex</code></li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T00:53:42.537", "Id": "47624", "ParentId": "47591", "Score": "4" } }, { "body": "<p>Just one comment: use Longs instead of Integers, sometimes it causes a dramatic improvement in speed (Excel converts Integers to Longs in the background).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T06:38:40.023", "Id": "222385", "ParentId": "47591", "Score": "0" } } ]
{ "AcceptedAnswerId": "47624", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T16:24:15.670", "Id": "47591", "Score": "10", "Tags": [ "algorithm", "sorting", "vba", "quick-sort" ], "Title": "In place quicksort" }
47591
<p>I've implemented a Segment Tree in Python3:</p> <pre><code>import math INF = int(2e9) class SegmentTreeNode: def __init__(self, l, r, v=INF): self.left = l self.right = r self.value = v def merge(self, left, right): if left is not None and right is not None: self.value = min(left.value, right.value) elif left is None and right is None: self.value = INF elif left is None: self.value = right.value else: self.value = left.value class SegmentTree: def __init__(self, a): n = len(a) power = math.ceil(math.log(n, 2)) total = 2 ** (power + 1) self.__tree = [None] * int(total) self.__leaf_length = int(total/2)-1 self.__build(1, 0, self.__leaf_length, a) def __build(self, node, l, r, a): if l == r: self.__tree[node] = SegmentTreeNode(l, r) try: self.__tree[node].value = a[l] except IndexError: self.__tree[node].value = INF return leftchild = 2 * node rightchild = leftchild + 1 mid = (l + r) // 2 self.__build(leftchild, l, mid, a) self.__build(rightchild, mid + 1, r, a) self.__tree[node] = SegmentTreeNode(l, r) l = self.__tree[leftchild] r = self.__tree[rightchild] self.__tree[node].merge(l, r) def __query(self, node, l, r, i, j): if l &gt;= i and r &lt;= j: return self.__tree[node] elif j &lt; l or i &gt; r: return None else: leftchild = 2 * node rightchild = leftchild + 1 mid = (l + r) // 2 l = self.__query(leftchild, l, mid, i, j) r = self.__query(rightchild, mid + 1, r, i, j) if l is not None and r is not None: return SegmentTreeNode(-1, -1, min(l.value, r.value)) elif l is None and r is None: return SegmentTreeNode(-1, -1, INF) elif l is None: return SegmentTreeNode(-1, -1, r.value) else: return SegmentTreeNode(-1, -1, l.value) def query(self, i, j): return self.__query(1, 0, self.__leaf_length, i, j) def __update(self, node, l, r, i, v): if l == i and r == i: self.__tree[node].value = v elif i &lt; l or i &gt; r: return None else: leftchild = 2 * node rightchild = leftchild + 1 mid = (l + r) // 2 self.__update(leftchild, l, mid, i, v) self.__update(rightchild, mid + 1, r, i, v) l = self.__tree[leftchild] r = self.__tree[rightchild] self.__tree[node].merge(l, r) def update(self, i, value): self.__update(1, 0, self.__leaf_length, i, value) in_n, in_m = map(int, input().rsplit()) in_array = list(map(int, input().rsplit())) segment_tree = SegmentTree(in_array) for row in range(in_m): command = input().rsplit() x, y = map(int, command[1:]) if command[0] == 'Min': print(segment_tree.query(x - 1, y - 1).value) else: segment_tree.update(x-1, y) </code></pre> <p>I take <code>n</code> and <code>m</code> from <code>stdin</code> after I read an <code>array[n]</code>. And then I read <em>m</em> operations "Set I X" or "Min L R".</p> <p>Here is profiler log for relevant testcase:</p> <pre><code> ncalls tottime percall cumtime percall filename:lineno(function) 2969521/49877 3.871 0.000 4.753 0.000 test.py:51(__query) 1754305/50123 1.792 0.000 2.685 0.000 test.py:74(__update) 1721965 0.829 0.000 0.829 0.000 test.py:8(__init__) 983162 0.732 0.000 1.081 0.000 test.py:13(merge) 1619481 0.576 0.000 0.576 0.000 {built-in method min} 100002 0.548 0.000 0.551 0.000 {built-in method input} 262143/1 0.545 0.000 0.907 0.907 test.py:33(__build) 1 0.429 0.429 9.550 9.550 test.py:1(&lt;module&gt;) 49877 0.076 0.000 0.076 0.000 {built-in method print} 100002 0.068 0.000 0.068 0.000 {method 'rsplit' of 'str' objects} 49877 0.045 0.000 4.799 0.000 test.py:71(query) 50123 0.034 0.000 2.719 0.000 test.py:89(update) 339 0.002 0.000 0.002 0.000 {built-in method utf_8_decode} 1 0.002 0.002 0.908 0.908 test.py:25(__init__) 339 0.001 0.000 0.003 0.000 codecs.py:310(decode) 2 0.000 0.000 0.000 0.000 {built-in method __build_class__} 1 0.000 0.000 0.000 0.000 {built-in method init_builtin} </code></pre> <p>I guess the problem is in query function. How can it be improved? Any ideas? Here is a relevant <a href="https://drive.google.com/file/d/0B4JKldGNJPOTaGZXY3RJZmhEVGc/edit?usp=sharing" rel="nofollow">test-case</a>. I need to achieve the result at least 2 times faster.</p>
[]
[ { "body": "<p><code>SegmentTreeNode</code> objects have three attributes: <code>left</code>, <code>right</code> and <code>value</code>, but only <code>value</code> is ever used. Using plain integers instead of custom objects should speed things up, as it avoids overhead both in object creation and in attribute access.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T05:44:47.527", "Id": "84757", "Score": "0", "body": "Yeah. You are right.This simple change speeds up code significantly. It can be said that the problem is solved." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T12:41:28.603", "Id": "48143", "ParentId": "47596", "Score": "5" } } ]
{ "AcceptedAnswerId": "48143", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T17:33:48.050", "Id": "47596", "Score": "6", "Tags": [ "python", "algorithm", "python-3.x", "tree" ], "Title": "Segment tree in Python3" }
47596
<p>Have I made any obvious mistakes?<br/> Is this code clean?<br/> Is there a better way to do this in python?<br/></p> <pre><code># -*- coding: utf-8 -*- import feedparser from feedgen.feed import FeedGenerator from random import shuffle from feedformatter import Feed import time from datetime import datetime tstart = datetime.now() # Set the feed/channel level properties # ----------------------------------- # chanTitle = 'Feed Merger' chanLink = 'http://server.com/feed' chanAuthor = 'Bob Dylan' chanDescription = 'Brain Food' # ----------------------------------- # # Apply feed/channel level properties # ----------------------------------- # feed = Feed() feed.feed["title"] = chanTitle feed.feed["link"] = chanLink feed.feed["author"] = chanAuthor feed.feed["description"] = chanDescription # ----------------------------------- # urls = list(set(open('urls.txt', 'r').readlines())) shuffle(urls) extract_entries = lambda url: feedparser.parse(url).entries addEntries = lambda entries: [feed.items.append(entry) for entry in entries] merg = lambda urls: [addEntries(extract_entries(url)) for url in urls] shuffle(feed.entries) save = lambda outfile: feed.format_rss2_file(outfile) merg(urls) save('feed.xml') tend = datetime.now() runtime = tend - tstart print "Runtime &gt; %s" % (runtime) print "Merged &gt; %d items" % (len(feed.entries)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:22:21.607", "Id": "83421", "Score": "4", "body": "While the objective of this site is quite clear, it is always nice when askers give some more context than just the pure code to review. For example, you could highlight parts of the code that you want special reviews for or guide the general direction of the review(e.g.: \"I want tips on performance improvements\" or \"Improve my naming\")." } ]
[ { "body": "<p>These lines appear to be out of order:</p>\n\n<blockquote>\n<pre><code>extract_entries = lambda url: feedparser.parse(url).entries\naddEntries = lambda entries: [feed.items.append(entry) for entry in entries]\nmerg = lambda urls: [addEntries(extract_entries(url)) for url in urls]\nshuffle(feed.entries)\nsave = lambda outfile: feed.format_rss2_file(outfile)\nmerg(urls)\n</code></pre>\n</blockquote>\n\n<p>In particular, when that shuffle runs, the feed has no entries yet, so there's nothing to shuffle. I think you meant this way:</p>\n\n<pre><code>extract_entries = lambda url: feedparser.parse(url).entries\naddEntries = lambda entries: [feed.items.append(entry) for entry in entries]\nmerg = lambda urls: [addEntries(extract_entries(url)) for url in urls]\nmerg(urls)\nshuffle(feed.entries)\n</code></pre>\n\n<p>More importantly, I think you're overusing lambdas for no benefit at all. The flow of the logic would be a lot easier to read if you used loops instead:</p>\n\n<pre><code>urls = list(set(open('urls.txt', 'r').readlines()))\nshuffle(urls)\nfor url in urls:\n for entry in feedparser.parse(url).entries:\n feed.items.append(entry)\nshuffle(feed.entries)\nfeed.format_rss2_file('feed.xml')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T23:14:31.017", "Id": "47682", "ParentId": "47598", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:12:14.173", "Id": "47598", "Score": "4", "Tags": [ "python", "rss" ], "Title": "Simple hack to merge RSS feeds" }
47598
<p>I've been trying to optimize this piece of code:</p> <pre><code>void detect_optimized(int width, int height, int threshold) { int x, y, z; int tmp; for (y = 1; y &lt; width-1; y++) for (x = 1; x &lt; height-1; x++) for (z = 0; z &lt; 3; z++) { tmp = mask_product(mask,a,x,y,z); if (tmp&gt;255) tmp = 255; if (tmp&lt;threshold) tmp = 0; c[x][y][z] = 255-tmp; } return; } </code></pre> <p>So far I've tried "Blocking" and a few other things, but I can't seem to get it to run any faster.</p> <p>Blocking resulted in: </p> <pre><code> for(yy = 1; yy&lt;height-1; yy+=4){ for(xx = 1; xx&lt;width -1; xx+=4){ for (y = yy; y &lt; 4+yy; y++){ for (x = xx; x &lt; 4+xx; x++){ for (z = 0; z &lt; 3; z++) { tmp = mask_product(mask,a,x,y,z); if (tmp&gt;255) tmp = 255; if (tmp&lt;threshold) tmp = 0; c[x][y][z] = 255-tmp; }}}}} </code></pre> <p>Which ran at the same speed as the original program.</p> <p>Any suggestions would be great.</p> <p><code>mask_function</code> cannot be changed, but here is its code:</p> <pre><code>int mask_product(int m[3][3], byte bitmap[MAX_ROW][MAX_COL][NUM_COLORS], int x, int y, int z) { int tmp[9]; int i, sum; // ADDED THIS LINE (sum = 0) TO FIX THE BUG sum = 0; tmp[0] = m[0][0]*bitmap[x-1][y-1][z]; tmp[1] = m[1][0]*bitmap[x][y-1][z]; tmp[2] = m[2][0]*bitmap[x+1][y-1][z]; tmp[3] = m[0][1]*bitmap[x-1][y][z]; tmp[4] = m[1][1]*bitmap[x][y][z]; tmp[5] = m[2][1]*bitmap[x+1][y][z]; tmp[6] = m[0][2]*bitmap[x-1][y+1][z]; tmp[7] = m[1][2]*bitmap[x][y+1][z]; tmp[8] = m[2][2]*bitmap[x+1][y+1][z]; for (i=0; i&lt;9; i++) sum = sum + tmp[i]; return sum; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:51:40.723", "Id": "83429", "Score": "0", "body": "The indentation after `tmp = 255;` indicates that you want that if to be wrapped into the other one's body. Is that correct? If so, then you are missing parenthesis. If not, then the indentation should be fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:53:47.230", "Id": "83430", "Score": "0", "body": "Is `mask_product` some standard function that you may not change? If not then please provide its code as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:53:59.767", "Id": "83431", "Score": "0", "body": "The format must have changed when I copied it. Fixed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:32:08.250", "Id": "83440", "Score": "1", "body": "Did you try optimized compilation? Most of the advisable optimizations can be done automatically by the compiler so you can concentrate on getting the code right (instead of obfuscating it with \"optimizations\")." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T09:48:01.640", "Id": "87071", "Score": "0", "body": "What are `mask` and `a`? Does your function compile?" } ]
[ { "body": "<p>I am afraid I can't do much about the performance but here are some other tips:</p>\n\n<ul>\n<li>The <code>z</code> loop bound is not checked against <code>NUM_COLORS</code> (which I believe is the size of the array for this index).</li>\n<li><code>z</code> should be renamed to something like <code>colorIndex</code>.</li>\n<li>Using prefix increments (<code>++x</code>) might give a speedup</li>\n<li><p>Precalculating loop bounds to avoid repeated recalculation might give another speedup: <code>maxY = width - 1;</code> and then <code>for (y = 1; y &lt; maxY; ++y)</code></p></li>\n<li><p><code>tmp</code> should have a better name (what does it actually contain/represent?)</p></li>\n<li><p>place the <code>if</code>s into an own function (or macro) <code>clamp</code> (which is a widely used name and maybe has a standard implementation) and use it to make the code cleaner: <code>tmp = clamp(tmp, 0, 255);</code></p></li>\n<li><p>do not use global variables instead of function parameters, they introduce hard to debug side effects</p></li>\n<li>Although you cannot change the mask function I would recommend avoiding the <code>tmp</code> array and instead directly summing up into sum.</li>\n</ul>\n\n<p>You could gain some speedup by replacing the inner loop over the colors by MMX functionality which allows to do the same calculation on all colors at once. However, I am no expert in this and it likely requires inline assembly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:21:22.837", "Id": "47604", "ParentId": "47600", "Score": "5" } }, { "body": "<p>Do not expect much:</p>\n\n<pre><code>void detect_optimized(int width, int height, int threshold)\n{\n int x, y, z;\n int tmp;\n int widthM1= width-1;\n int heightM1=height-1;\n\n for (y = 1; y &lt; widthM1; y++){\n for (x = 1; x &lt; heightM1; x++){\n for (z = 0; z &lt; 3; z++){\n tmp = mask_product(mask,a,x,y,z);\n if (tmp&gt;255)\n c[x][y][z] = 0;\n else if (tmp&lt;threshold)\n c[x][y][z] = 255;\n else\n c[x][y][z] = 255 ^ tmp; // in this case xor is the same as -\n }\n } \n }\n return;\n}\n</code></pre>\n\n<p><strong>You can also unroll the <code>z</code>- loop, by copying the inner body 2 more times.</strong></p>\n\n<p>If you can manage to change the mask_function:</p>\n\n<pre><code>int mask_product(int m[3][3], byte bitmap[MAX_ROW][MAX_COL][NUM_COLORS], int x, int y, int z)\n{\n int xp1=x+1;\n int xm1=x-1;\n int yp1=y+1;\n int ym1=y-1;\n return m[0][0]*bitmap[xm1][ym1][z];\n + m[1][0]*bitmap[x][ym1][z];\n + m[2][0]*bitmap[xp1][ym1][z];\n + m[0][1]*bitmap[xm1][y][z];\n + m[1][1]*bitmap[x][y][z];\n + m[2][1]*bitmap[xp1][y][z];\n + m[0][2]*bitmap[xm1][yp1][z];\n + m[1][2]*bitmap[x][yp1][z];\n + m[2][2]*bitmap[xp1][yp1][z];\n }\n</code></pre>\n\n<p>Also have a look if you can make your compiler inline the <code>mask_product</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T14:26:59.073", "Id": "84150", "Score": "0", "body": "Wont an optimization flag help with the unroll? Also, BTW, you should discover the [2nd Monitor - Code Review chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T15:02:46.470", "Id": "84163", "Score": "0", "body": "@rolfl: In this simple case it might be possible that the compiler can unroll the inner loop, but I would not count on it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T19:26:35.070", "Id": "47605", "ParentId": "47600", "Score": "4" } }, { "body": "<p>Your compiler may already optimize this but it might still be interesting to know.</p>\n\n<p>Everytime you do this:</p>\n\n<pre><code>c[x][y][z]\n</code></pre>\n\n<p>What actually happens is this:</p>\n\n<pre><code>*(*(*(a+x)+y)+z)\n</code></pre>\n\n<p>And since x, y and z change at different rates, you can avoid unnecessary arithmetic by caching the intermediate pointers.</p>\n\n<pre><code>for (x = 1; x &lt; height-1; x++) {\n\n int *xx = *(c+x);\n for (y = 1; y &lt; width-1; y++) {\n\n /* 3 is the length of z. Think about the memory layout of a \n * multidimensional array to understand why. */\n int *yy = (xx+(y*3));\n for (z = 0; z &lt; 3; z++) {\n ...\n *(yy+(z) = 255-tmp;\n }\n }\n}\n</code></pre>\n\n<p>As is usually the case with optimization, it's down to you to benchmark the code and decide whether to performance increase is worth to reduced readability and maintainability.</p>\n\n<p>Another optimization that has not been mentioned is switching the order of the loops. Take this loop for example.</p>\n\n<pre><code>for (int x = 0; x &lt; 100; x++) {\n for (int y = 0; y &lt; 5; y++) {\n ...\n }\n}\n</code></pre>\n\n<p>The inner loop executes 100*5=500 times and the outer loop executes 100 times making a total of 600 comparisons. If the order were switched so the busiest loop was on the inside:</p>\n\n<pre><code>for (int y = 0; y &lt; 5; y++) {\n for (int x = 0; x &lt; 100; x++) {\n ...\n }\n}\n</code></pre>\n\n<p>The inner loop still executes 5*100=500 times however the outer loop only executes 5 times making a total of 505 comparisons. That's 16% fewer comparison operations in this example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-13T10:58:10.407", "Id": "49626", "ParentId": "47600", "Score": "2" } } ]
{ "AcceptedAnswerId": "47605", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T18:48:36.473", "Id": "47600", "Score": "10", "Tags": [ "optimization", "c", "image" ], "Title": "Detect optimized" }
47600
<p><strong>Warning: the code below is NOT multi read/write!</strong></p> <p>It'l work fine as long as you don't have multiple writes OR don't require resize. But with multiple writers, the code can enter a deadlock state. I'm revising the code and if I do manage to work around these issues, I'll post them in a linked question.</p> <hr> <p>After, analysing what went wrong in <a href="https://codereview.stackexchange.com/questions/46722/lock-free-job-queue-without-size-restriction-multiple-read-write">lock-free job queue without size restriction (multiple read/write)</a> I've come up with another solution, here's what it does:</p> <p><code>require_lock_</code> is used to signal when we need to leave the lock-free setup and resize our buffers, so technically we don't have a lock-free setup**</p> <p><code>lock_</code> this is the lock which is only used when we need to resize the buffers, so if you create your queue large enough, it is lock-free until all jobs are exhausted</p> <p><code>concurrent_users_</code> keeps track of the number of users accessing the following members</p> <p><code>read_, write_, size_</code> these are used to keep track of the number of jobs in the queue</p> <p><code>storage_</code> this is a vector which allocates the space in which the jobs are stored. If this needs adjusting, a lock is used</p> <p><code>*bitflag_</code> this is an array of bits, used to indicate which positions inside <code>lookup_</code> are taken. This is kept in sync with <code>storage_</code></p> <p>Whenever a job is added, the following happens:</p> <ul> <li><code>concurrent_users_</code> is incremented to indicate we're about to touch <code>storage_</code> and <code>bitflag_</code></li> <li><code>require_lock_</code> is checked to see if we need to acquire the mutex</li> <li><code>write_</code> is increased to retrieve a unique index to which we will write our job</li> <li>if this id is out of bounds, we try to resize our storage which calls for a mutex synchronization</li> <li>we store the job</li> <li>we mark the index in our array of bits, indicating this job is ready to use</li> </ul> <p>When jobs are removed from the queue:</p> <ul> <li><code>concurrent_users_</code> is again incremented, note that this is automatically decreased when the guard goes out of scope</li> <li>we check for the <code>require_lock_</code></li> <li><code>read_</code> is increased, just as <code>write_</code> was increased in the push function</li> <li>if the received id is out of bounds, we return read_ to it's previous value and try a cleanup, since our job supply is exhausted</li> <li>we retrieve the job from our storage and remove the <code>bitflag_</code> indicating the job is ready to use</li> </ul> <p>As stated, this is not a lock-free setup, so technically it is not a solution for the initial question. However, it only locks when the storage is full, so if you really want to prevent mutex locking, you have to allocate enough room for the jobs you anticipate.</p> <p>At this point, the code is not exception safe, I intent to change it so it guarantees a strong exception safety. Also, if you never allow the job queue to become completely empty, you will end up with a lot of memory used for 'old' jobs and/or eventually will reach the maximum value of the <code>write_</code> variable, at which point the code no longer accepts jobs until the queue is completely emptied. The code should also be changed as to allow for a custom allocator, but these points I considered to be easy to implement once the lock-free setup was done.</p> <p>I would love to hear your comments. I think it's rather nice, even though I was not able to make it completely lock-free and this solution feels a tiny bit like cheating.</p> <ul> <li>Is it really thread safe?</li> <li>Apart from the points I mentioned, what functionality could be improved/added?</li> </ul> <p>fifo.h:</p> <pre><code>#pragma once #include &lt;atomic&gt; #include &lt;memory&gt; #include &lt;vector&gt; #include &lt;mutex&gt; #include &lt;thread&gt; #include &lt;algorithm&gt; namespace lock_free { /** * this class is used so we're able to use the RAII mechanism for locking */ template &lt; typename T &gt; class use_count { public: template &lt; typename V &gt; use_count( V &amp;&amp;v ) : data_( std::forward&lt; V &gt;( v ) ) { } const T&amp; operator()() const { return data_; } void lock() { ++data_; } void unlock() { --data_; } private: use_count( const use_count&amp; ); use_count&amp; operator = ( const use_count&amp; ); T data_; }; /** * This is a lock free fifo, which can be used for multi-producer, multi-consumer * type job queue */ template &lt; typename Value &gt; class fifo { public: typedef Value value_type; fifo( size_t size = 1024 ) : require_lock_( false ), lock_(), concurrent_users_( 0 ), read_( 0 ), write_( 0 ), size_( size ), storage_( size ), bitflag_( new std::atomic_size_t[ std::max( size_t( 1 ), size / bits_per_section() ) ] ) { fill_bitflags( 0 ); } ~fifo() { clear(); delete [] bitflag_; } /** * pushes an item into the job queue, may throw if allocation fails * leaving the queue unchanged */ void push( const value_type &amp;value ) { std::lock_guard&lt; use_count&lt; std::atomic_size_t &gt; &gt; lock( concurrent_users_ ); conditional_lock(); if ( write_ == std::numeric_limits&lt; size_t &gt;::max() ) { throw std::logic_error( "fifo full, remove some jobs before adding new ones" ); } const size_t id = write_++; if ( id &gt;= size_ ) { resize_storage( id ); } storage_[ id ] = value; set_bitflag_( id, mask_for_id( id ) ); } /** * retrieves an item from the job queue. * if no item was available, func is untouched and pop returns false */ bool pop( value_type &amp;func ) { auto assign = [ &amp; ]( value_type &amp;dst, value_type &amp;src ) { std::swap( dst, src ); }; return pop_generic( func, assign ); } /** * clears the job queue, storing all pending jobs in the supplied container. * the container is also returned for convenience */ template &lt; typename T &gt; T&amp; pop_all( T &amp;unfinished ) { value_type tmp; while ( pop( tmp ) ) { unfinished.push_back( tmp ); } return unfinished; } /** * clears the job queue. */ void clear() { auto del = []( value_type&amp;, value_type&amp; ) {}; value_type tmp; while ( pop_generic( tmp, del ) ) { // empty } } /** * returns true if there are no pending jobs */ bool empty() const { return read_ == write_; } private: fifo( const fifo&amp; ); fifo&amp; operator = ( const fifo&amp; ); static constexpr size_t bits_per_section() { return sizeof( size_t ) * 8; } template &lt; typename Assign &gt; bool pop_generic( value_type &amp;value, Assign assign ) { std::lock_guard&lt; use_count&lt; std::atomic_size_t &gt; &gt; lock( concurrent_users_ ); conditional_lock(); const size_t id = read_++; if ( id &gt;= write_ ) { --read_; try_cleanup(); return false; } const size_t mask = mask_for_id( id ); while ( !unset_bitflag_( id, mask ) ) { std::this_thread::yield(); } assign( value, storage_[ id ] ); return true; } void try_cleanup() { if ( !write_ || read_ != write_ || require_lock_ ) { // early exit, avoids needless locking return; } bool expected( false ); if ( require_lock_.compare_exchange_strong( expected, true ) ) { std::lock_guard&lt; std::mutex &gt; guard( lock_ ); while ( concurrent_users_() &gt; 1 ) { std::this_thread::yield(); } write_ = 0; read_ = 0; fill_bitflags( 0 ); require_lock_ = false; } } void resize_storage( size_t id ) { while ( size_ &lt;= id ) { if ( id == size_ ) { require_lock_ = true; std::lock_guard&lt; std::mutex &gt; guard( lock_ ); while ( concurrent_users_() &gt; 1 ) { std::this_thread::yield(); } const size_t bitflag_size = size_ / bits_per_section(); storage_.resize( std::max( size_t( 1 ), size_ * 2 ) ); std::atomic_size_t *newbitflag = new std::atomic_size_t[ std::max( size_t( 1 ), bitflag_size * 2 ) ]; std::atomic_size_t *start = newbitflag; const std::atomic_size_t *end = start + bitflag_size; const std::atomic_size_t *src = bitflag_; while ( start != end ) { (start++)-&gt;store( *src++ ); } end = newbitflag + bitflag_size * 2; while ( start != end ) { (start++)-&gt;store( 0 ); } delete [] bitflag_; bitflag_ = newbitflag; size_ = storage_.size(); require_lock_ = false; } else { conditional_lock(); } } } static size_t mask_for_id( size_t id ) { const size_t offset = id / bits_per_section(); id -= offset * bits_per_section(); return size_t( 1 ) &lt;&lt; id; } void set_bitflag_( size_t id, size_t mask ) { bitflag_[ id / bits_per_section() ].fetch_or( mask ); } bool unset_bitflag_( size_t id, size_t mask ) { const size_t old = bitflag_[ id / bits_per_section() ].fetch_and( ~mask ); return ( old &amp; mask ) == mask; } void conditional_lock() { if ( require_lock_ ) { concurrent_users_.unlock(); lock_.lock(); lock_.unlock(); concurrent_users_.lock(); } } void fill_bitflags( size_t value ) { std::atomic_size_t *start = bitflag_; const std::atomic_size_t *end = start + size_ / bits_per_section(); while ( start != end ) { (start++)-&gt;store( value ); } } std::atomic_bool require_lock_; std::mutex lock_; use_count&lt; std::atomic_size_t &gt; concurrent_users_; std::atomic_size_t read_, write_, size_; std::vector&lt; value_type &gt; storage_; std::atomic_size_t *bitflag_; }; } </code></pre>
[]
[ { "body": "<p>When you say this queue doesn't support multiple \"writers\", what do you mean? Do you mean multiple producers? Because both pushing (producing) and popping (consuming) from a queue are mutative (\"writing\") operations. And if you don't support the scenario of \"one writer pushing items and one writer popping them\", then you can't really call it a concurrent queue at all. So I'm going to assume that you <em>meant</em> to support \"one producer, one consumer\"... and then I'll show where the bug is with that scenario.</p>\n\n<hr>\n\n<ul>\n<li><p>You only use <code>use_count&lt;T&gt;</code> with <code>T = std::atomic_size_t</code>, so it probably shouldn't be a class template at all (it should just be a plain old class).</p></li>\n<li><p>If you keep it a template, the constructor should probably be a variadic template. Perfect forwarding and variadic templates go together like peanut butter and jelly. <em>And</em> the constructor should definitely be <code>explicit</code>, to disable unwanted implicit conversions.</p>\n\n<pre><code>template &lt;typename... Args&gt;\nexplicit use_count(Args&amp;&amp;... args) : data_(std::forward&lt;Args&gt;(args)...) { }\n</code></pre></li>\n<li><p>You declare a private copy-constructor and copy-assignment operator for <code>use_count</code>, but never define them. This C++03 idiom is obsolete as of C++11. The better way would be to not declare them at all (since having an <code>atomic_size_t</code> member will prevent the class from being copyable/movable anyway), or to define them as <code>=delete</code>.</p></li>\n<li><p>Your <code>fifo</code> constructor should also be marked <code>explicit</code>.</p></li>\n<li><p><code>bitflag_</code> should probably be a <code>std::unique_ptr&lt;std::atomic_size_t[]&gt;</code> instead of a raw pointer.</p></li>\n<li><p>Your code would be more readable if you removed all the blank lines (except the ones between function definitions, I guess). For example, you wrote <code>push()</code> in 21 lines, 5 of which were blank and 2 of which were uncuddled <code>{</code>s. It could have been 14 lines.</p></li>\n</ul>\n\n<hr>\n\n<p>Okay, here's the bug (I think; please let me know if I missed something). Suppose thread T1 is trying to resize the storage, and thread T2 is coming in as a new reader trying to pop.</p>\n\n<p>T1: enters <code>push</code><br>\nT1: increments <code>concurrent_users_.data_</code> from 0 to 1<br>\nT1: calls <code>conditional_lock</code>, which returns without doing anything<br>\nT1: enters <code>resize_storage</code> with <code>id == size_</code><br>\nT1: sets <code>require_lock_ = true</code><br>\nT1: locks <code>lock_</code><br>\nT1: tests <code>concurrent_users_() &gt; 1</code>, which is false because <code>concurrent_users_.data_ == 1</code><br>\nT1: therefore doesn't execute any iterations of the <code>while</code> loop<br>\nT1: a bunch of unsynchronized stuff culminating in <code>delete [] bitflag_;</code></p>\n\n<p>Meanwhile,</p>\n\n<p>T2: enters <code>pop</code><br>\nT2: enters <code>pop_generic</code><br>\nT2: increments <code>concurrent_users_.data_</code> from 1 to 2<br>\nT2: enters <code>conditional_lock</code><br>\nT2: tests <code>requires_lock_</code>, which is <code>true</code><br>\nT2: decrements <code>concurrent_users_.data_</code> from 2 to 1<br>\nT2: acquires <code>lock_</code> and releases it<br>\nT2: increments <code>concurrent_users_.data_</code> from 1 to 2<br>\nT2: returns from <code>conditional_lock</code><br>\nT2: a bunch of unsynchronized stuff culminating in <code>unset_bitflag_</code></p>\n\n<p>Let's interleave those so it's clear what's going on:</p>\n\n<p>T1: enters <code>push</code><br>\nT1: increments <code>concurrent_users_.data_</code> from 0 to 1<br>\nT1: calls <code>conditional_lock</code>, which returns without doing anything<br>\nT1: enters <code>resize_storage</code> with <code>id == size_</code><br>\nT1: sets <code>require_lock_ = true</code></p>\n\n<p>T2: enters <code>pop</code><br>\nT2: enters <code>pop_generic</code><br>\nT2: increments <code>concurrent_users_.data_</code> from 1 to 2<br>\nT2: enters <code>conditional_lock</code><br>\nT2: tests <code>requires_lock_</code>, which is <code>true</code><br>\nT2: decrements <code>concurrent_users_.data_</code> from 2 to 1<br>\nT2: acquires <code>lock_</code> and releases it</p>\n\n<p>T1: locks <code>lock_</code><br>\nT1: tests <code>concurrent_users_() &gt; 1</code>, which is false because <code>concurrent_users_.data_ == 1</code><br>\nT1: therefore doesn't execute any iterations of the <code>while</code> loop<br>\nT1: a bunch of unsynchronized stuff culminating in <code>delete [] bitflag_;</code></p>\n\n<p>T2: increments <code>concurrent_users_.data_</code> from 1 to 2<br>\nT2: returns from <code>conditional_lock</code><br>\nT2: a bunch of unsynchronized stuff culminating in <code>unset_bitflag_</code></p>\n\n<hr>\n\n<p>So, you've got an unsynchronized data race on the memory pointed to by <code>bitflag_</code>. T1 could easily deallocate that memory before T2 looks at it, which means T2 could be reading garbage memory and/or stomping on memory that's already been reallocated and is now in use by another thread.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-26T10:29:18.107", "Id": "115107", "ParentId": "47606", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T20:28:17.047", "Id": "47606", "Score": "2", "Tags": [ "c++", "c++11", "lock-free", "atomic" ], "Title": "(nearly) lock-free job queue of dynamic size (multiple read/write)" }
47606
<p>I have this regexp working, simple, but I feel like it may not be the best way to code it. Basically, I have a playlist separated by line breaks returned as tcp data like so:</p> <pre><code>file: http://192.168.100.214/Music/justchill.mp3 Artist: Brian G Title: Just Chill Track: 1 Date: 2014 Genre: Instrumental Pos: 0 Id: 0 file: http://192.168.100.214/Music/justchill.mp3 Pos: 1 Id: 1 file: http://streaming.radionomy.com/ABC-Lounge Pos: 2 Id: 2 OK </code></pre> <p>Now you can see the fields aren't always the same, but they always start with file and have the pos and id, always ending with id. I'm, parsing this data by line break to create an object, and then slicing it out of the string. Then I run the regexp on the new string, repeat while checking for Id: If it finds Id, I create a new object and start the whole process over.</p> <p>It works fine, but I don't know, just feels like there may be a more efficient way to do it.</p> <pre><code>var parseplaylist = function(data) { var pattern = /(.+): (.+)\n/; var result = pattern.exec(data); var playlistarray = []; if (result !== null) { var playlistobject = {}; while (result !== null) { playlistobject[result[1]] = result[2]; if (result[1] == "Id") { playlistarray[playlistobject.Pos] = playlistobject; playlistobject = {}; } data = data.substr(result[0].length); result = pattern.exec(data); } } return playlistarray; }; </code></pre>
[]
[ { "body": "<p>You can use the <code>String.prototype.replace</code> function to \"loop\" through all the relevant lines of the data. It accepts a regex pattern, and a function to handle the the matched text and return the replacement text. Here, however, we don't care about actually replacing anything; we just use it to find each key/value pair</p>\n\n<pre><code>function parsePlaylist(data) {\n var tracks = [], currentTrack;\n\n // do a multi-line replace-all for \"(key): (value)\", but don't\n // bother actually replacing anything, or storing the resulting\n // string. We're just using it to walk through the data\n data.replace(/^([^:]+):\\s*(.+)$/gmi, function (match, key, value) {\n // if this is the start of a new track (indicated\n // by a \"file\" field), or the start of the loop,\n // create a new object to hold the data\n if( !currentTrack || key === \"file\" ) {\n currentTrack = {};\n tracks.push(currentTrack);\n }\n\n // add the key/value pair\n currentTrack[key] = value;\n });\n\n return tracks;\n}\n</code></pre>\n\n<p>That'll give you this:</p>\n\n<pre><code>[ { file: 'http://192.168.100.214/Music/justchill.mp3',\n Artist: 'Brian G',\n Title: 'Just Chill',\n Track: '1',\n Date: '2014',\n Genre: 'Instrumental',\n Pos: '0',\n Id: '0' },\n { file: 'http://192.168.100.214/Music/justchill.mp3',\n Pos: '1',\n Id: '1' },\n { file: 'http://streaming.radionomy.com/ABC-Lounge',\n Pos: '2',\n Id: '2' } ]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T21:49:55.470", "Id": "83447", "Score": "0", "body": "Whoa! Awesome man thank you so much, that's much more efficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T21:57:47.740", "Id": "83448", "Score": "0", "body": "@BrianGe No problem. Glad it's useful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T21:01:37.550", "Id": "47608", "ParentId": "47607", "Score": "4" } } ]
{ "AcceptedAnswerId": "47608", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T20:38:46.553", "Id": "47607", "Score": "2", "Tags": [ "javascript", "parsing", "regex" ], "Title": "Parsing playlists efficiently" }
47607
<p>Here is my two-player Tic Tac Toe game. How can I improve it? </p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; //Simple Display void Display(std::vector&lt;char&gt; const &amp;grid){ //Creating a onscreen grid std::cout &lt;&lt; " " &lt;&lt; 1 &lt;&lt; " " &lt;&lt; 2 &lt;&lt; " " &lt;&lt; 3 &lt;&lt; "\n"; for(int a = 0; a &lt; 9; a++){ if(a == 0) std::cout &lt;&lt; "A "; if(a == 3) std::cout &lt;&lt; "\nB "; if(a == 6) std::cout &lt;&lt; "\nC "; //displaying grid. std::cout &lt;&lt; " " &lt;&lt; grid[a] &lt;&lt; " "; } std::cout &lt;&lt; "\n\n"; } //Returns true if the grid is already used. bool Used(int const&amp; position, std::vector&lt;char&gt; const&amp; grid){ if(grid[position] == '-') return false; else return true; } void Turn(std::vector&lt;char&gt; &amp;grid, char player){ int row = 0; char column = 0; int position = 0; bool check = true; std::cout &lt;&lt;"\n" &lt;&lt; player &lt;&lt; ": Please play. \n"; while(check == true){ std::cout &lt;&lt; "Row(1,2,3): "; std::cin &gt;&gt; row; std::cout &lt;&lt; player &lt;&lt; ": Column(A,B,C): "; std::cin &gt;&gt; column; position = 3*(column-'A')+(row-1); if(!Used(position,grid)){ check = false; } else{ std::cout &lt;&lt; "Already Used. Try Again. \n"; } } grid[position] = player; std::cout &lt;&lt; "\n\n"; } bool Win(std::vector&lt;char&gt; const&amp; grid, char player){ for(int a = 0; a &lt; 3; a++){ if(grid[a] == player &amp;&amp; grid[a+3] == player &amp;&amp; grid[a+6] == player){ return true; } if(grid[3*a] == player &amp;&amp; grid[3*a+1] == player &amp;&amp; grid[3*a+2] == player){ return true; } } if(grid[0] == player &amp;&amp; grid[4] == player &amp;&amp; grid[8] == player){ return true; } if(grid[2] == player &amp;&amp; grid[4] == player &amp;&amp; grid[6] == player){ return true; } return false; } int main(){ std::vector&lt;char&gt;grid(9,'-'); while(true){ Display(grid); Turn(grid, 'X'); if(Win(grid, 'X')){ Display(grid); std::cout &lt;&lt; "\nX is the Winner!"; break; } Display(grid); Turn(grid,'O'); if(Win(grid, 'O')){ Display(grid); std::cout &lt;&lt; "\nO is the Winner!"; break; } } } </code></pre>
[]
[ { "body": "<p>I'll just review what you have here, although something like this would work better with classes (you could always attempt this implementation later).</p>\n\n<ul>\n<li><p>Your vector isn't quite grid-like as it's only one-dimensional. It may also be why <code>Display()</code> is a bit confusing, which shouldn't be the case with a 2D structure.</p>\n\n<p>Either way, you just need an <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"noreferrer\"><code>std::array</code></a> since the board's size is fixed:</p>\n\n<pre><code>std::array&lt;std::array&lt;char, 3&gt;, 3&gt; grid;\n</code></pre>\n\n<p>You first need to include <code>&lt;array&gt;</code>, and you can then remove <code>&lt;vector&gt;</code>.</p></li>\n<li><p>In <code>bool Used()</code>, this:</p>\n\n<pre><code>if(grid[position] == '-')\n return false;\nelse\n return true;\n</code></pre>\n\n<p>can simply become this:</p>\n\n<pre><code>return !(grid[position] == '-');\n</code></pre>\n\n<p>The statement already gives a conditional result, so you just have to return it.</p>\n\n<p>Also, you don't need to pass <code>position</code> by <code>const&amp;</code> as it's a native type. Just pass by value, with <code>const</code> if you want to be safe.</p></li>\n<li><p>Don't just list variables at the start of <code>Turn()</code> (or in general). Declare or initialize them as close to their use as possible.</p>\n\n<p>For instance, here's what it should be for the user input portion:</p>\n\n<pre><code>std::cout &lt;&lt; \"Row(1,2,3): \";\nint row;\nstd::cin &gt;&gt; row;\nstd::cout &lt;&lt; player &lt;&lt; \": Column(A,B,C): \";\nchar column = 0;\nstd::cin &gt;&gt; column;\n</code></pre>\n\n<p>Side-note: <code>row</code> and <code>column</code> don't need be initialized; they can just be declared.</p>\n\n<p>Consider having input validation in case the user inputs a valid board spot, otherwise the program will stop working and the game will have to be restarted.</p>\n\n<p>You could also simplify the function <em>and</em> the input validation by using either letters or numbers for <em>both</em> row and column. Using different ones makes the code and interface more confusing.</p></li>\n<li><p>This:</p>\n\n<pre><code>while(check == true)\n</code></pre>\n\n<p>is the same as this but more concise:</p>\n\n<pre><code>while(check)\n</code></pre>\n\n<p>For <code>false</code>, use <code>!</code>:</p>\n\n<pre><code>while(!check)\n</code></pre></li>\n<li><p>The <code>while</code> loop in <code>main()</code> is quite repetitive. You could just have a <code>bool</code> assigned to the winning player, then display that value in the winning (or losing) message after the loop.</p>\n\n<p>You should also have a way of choosing whether to start with X or O. Normally, someone will choose to go first, and they will choose their own symbol.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T07:06:58.783", "Id": "83497", "Score": "0", "body": "Declaring variables inside a loop though is not really efficient as far as I know unless it's a const variable which in this case is not possible. Well in a simple case like this where the loop is not repeated very fast it won't have any significant impact in performance but as a general rule of thumb as far as I know is to usually not declare non-consts in loops." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T21:28:22.783", "Id": "47611", "ParentId": "47609", "Score": "5" } }, { "body": "<p>One improvement you can make is to only use one set of routines for each player. One simple way to do this is with a <code>char</code> array to represent each player:</p>\n\n<pre><code>int main()\n{\n std::vector&lt;char&gt;grid(9,'-');\n char players[] = {'X','O'};\n int player = 1;\n while(true)\n {\n player = abs(player - 1);\n Display(grid);\n Turn(grid, players[player]);\n if(Win(grid, players[player]))\n {\n Display(grid);\n std::cout &lt;&lt; \"\\n\" &lt;&lt; players[player] &lt;&lt; \" is the Winner!\";\n break;\n }\n }\n}\n</code></pre>\n\n<p>One other thing I noticed, is the logic for the turns isn't accurate. The columns and rows seem to get swapped.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T01:09:12.233", "Id": "83470", "Score": "0", "body": "I would move the player swap to the bottom of the loop and start with 0. It's minor, but reading top down I was first confused why you started with O (1). Also, you can simplify `abs(player - 1)` with `1 - player`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T22:59:47.867", "Id": "47617", "ParentId": "47609", "Score": "1" } }, { "body": "<p>I see a number of things that would improve the code:</p>\n\n<h2>Use objects</h2>\n\n<p>C++ is an object-oriented language, and your code would benefit from being more object-oriented. When you have multiple functions that all take a <code>grid</code> as an argument, this is a clear indication that the functions should probably be member functions and that <code>grid</code> should be an object. Here's the class I came up with, based on your code. Note that the constructor takes an argument which defaults to 3. That's the size of one dimension of the square board, which can now be altered to be either the usual 3x3 grid (by default) or made any arbitrary size. More on that later.</p>\n\n<pre><code>class TicTacToe \n{\nprivate:\n unsigned _dim;\n unsigned free;\n std::vector&lt;char&gt;grid;\n // applies turn and returns true unless square is already occupied\n bool Apply(char player, int position);\n\npublic:\n TicTacToe(unsigned dim=3) : _dim(dim), free(_dim*_dim), grid(free,'-') {}\n bool Full() const { return free==0; }\n //Simple Display\n void Display() const;\n void Turn(char player);\n bool Win(char player) const;\n};\n</code></pre>\n\n<h2>Separate input and output from core logic</h2>\n\n<p>Your <code>Turn</code> function does three things: it gets input from the user, it validates the input and then it applies the turn to the grid. It's generally better design to separate things so that each function does just one or maybe two closely related things.</p>\n\n<p>When I changed your code, the <code>Turn</code> code is only responsible for getting the input, delegating the actual application of the move to a private member function named <code>Apply</code>:</p>\n\n<pre><code>bool TicTacToe::Apply(char player, int position) \n{\n if (grid[position] != '-')\n return false;\n grid[position] = player;\n --free;\n return true;\n}\n</code></pre>\n\n<h2>Consider extensions and generalizations</h2>\n\n<p>While your <code>Win</code> function is not incorrect as written, it is not flexible because all of the numbers are hard-coded. Consider that one might want a 4x4 or larger grid, in which it might be good to have a more general method for checking that doesn't have everything hard-coded. </p>\n\n<pre><code>bool TicTacToe::Win(char player) const \n{\n // check for row or column wins\n for(unsigned i = 0; i &lt; _dim; ++i){\n bool rowwin = true;\n bool colwin = true;\n for (unsigned j=0; j &lt; _dim; ++j) {\n rowwin &amp;= grid[i*_dim+j] == player;\n colwin &amp;= grid[j*_dim+i] == player;\n }\n if (colwin || rowwin) \n return true;\n }\n // check for diagonal wins\n bool diagwin = true;\n for (unsigned i=0; i &lt; _dim; ++i) \n diagwin &amp;= grid[i*_dim+i] == player;\n if (diagwin) \n return true;\n diagwin = true;\n for (unsigned i=0; i &lt; _dim; ++i) \n diagwin &amp;= grid[i*_dim+(_dim-i-1)] == player;\n return diagwin; \n}\n</code></pre>\n\n<p>The same thing can also be applied to your <code>Display</code> routine.</p>\n\n<pre><code>void TicTacToe::Display() const \n{\n //Creating a onscreen grid\n std::cout &lt;&lt; ' ';\n for (unsigned i=1; i&lt;=_dim; ++i)\n std::cout &lt;&lt; \" \" &lt;&lt; i;\n for(unsigned i = 0; i &lt; _dim; i++){\n std::cout &lt;&lt; \"\\n\" &lt;&lt; static_cast&lt;char&gt;('A'+i) &lt;&lt; \" \";\n for(unsigned j = 0; j &lt; _dim; j++)\n std::cout &lt;&lt; \" \" &lt;&lt; grid[i*_dim+j] &lt;&lt; \" \";\n }\n std::cout &lt;&lt; \"\\n\\n\";\n}\n</code></pre>\n\n<h2>Recognize a draw</h2>\n\n<p>The code doesn't recognize when the game ends in a draw. An easy way to do so is to simply count how many free spaces are left. Note that this is only legitimately a tie if the last move hasn't actually been a winning move, so as written, this should only be called after we check for a win. This could be further improved by not relying on the calling function to perform this check.</p>\n\n<pre><code>bool Full() const { return free==0; }\n</code></pre>\n\n<h2>Sanitize user input</h2>\n\n<p>User input is inherhently suspect. Make sure that you always validate user input before using it. In this case, consider that if the user enters a number instead of a letter, the code gets stuck in an infinite loop. Worse, the input is not range-checked and could attempt to write to memory far outside the <code>grid</code> vector. </p>\n\n<pre><code>void TicTacToe::Turn(char player)\n{\n char row = 0;\n char column = 0;\n unsigned position = 0;\n bool applied = false;\n std::cout &lt;&lt;\"\\n\" &lt;&lt; player &lt;&lt; \": Please play. \\n\";\n\n while(!applied) {\n std::cout &lt;&lt; \"Row(1,2,3,...): \";\n std::cin &gt;&gt; row;\n std::cout &lt;&lt; player &lt;&lt; \": Column(A,B,C,...): \";\n std::cin &gt;&gt; column;\n position = _dim*(column-'A')+(row-'1');\n if (position &lt; grid.size()) {\n applied = Apply(player, position);\n if (!applied) \n std::cout &lt;&lt; \"Already Used. Try Again. \\n\";\n } else {\n std::cout &lt;&lt; \"Invalid position. Try again.\\n\";\n }\n }\n std::cout &lt;&lt; \"\\n\\n\";\n}\n</code></pre>\n\n<h2>Highlight loop termination conditions</h2>\n\n<p>When you have a loop such as <code>while(true)</code> it implies that the loop never ends, but in the case of your loop in <code>main</code>, the code actually ends when one player wins. In the improved, code, it also ends if there is a tie.</p>\n\n<pre><code>int main()\n{\n TicTacToe ttt;\n\n const char players[2] = {'X', 'O'};\n int player = 1;\n bool win = false;\n bool full = false;\n\n while(!win &amp;&amp; !full){\n player = 1-player;\n ttt.Display();\n ttt.Turn(players[player]);\n win = ttt.Win(players[player]);\n full = ttt.Full();\n }\n ttt.Display();\n if (win) {\n std::cout &lt;&lt; \"\\n\" &lt;&lt; players[player] &lt;&lt; \" is the Winner!\\n\";\n } else {\n std::cout &lt;&lt; \"\\nTie game!\\n\";\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T18:30:52.387", "Id": "47670", "ParentId": "47609", "Score": "3" } } ]
{ "AcceptedAnswerId": "47670", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T21:08:40.480", "Id": "47609", "Score": "6", "Tags": [ "c++", "game", "c++11", "tic-tac-toe" ], "Title": "Tic Tac Toe in C++" }
47609
<p>This is the function which I wrote and am currently using in my project. I want to know if there is a better way to write it:</p> <pre><code>function pageLoader(pageIndex){ $(".ServicesSectionWrapper,.ServicesSectionWrapper .Selector,.ServicesSection,.JournalSectionWrapper,.JournalSectionWrapper .Selector,.JournalSection,.AboutSectionWrapper,.AboutSectionWrapper .Selector,.AboutSection").hide(); switch(pageIndex){ case 1: $(".AboutSectionWrapper").fadeIn(400,function(){$("#AboutWrapper").fadeIn(400,function(){$("#ManagerWrapper").fadeIn(400,function(){$("#DeveloperWrapper").fadeIn(400,function(){$("#DesignerWrapper").fadeIn(400,function(){$(".AboutSection").fadeIn(400,function(){$(".AboutSection").addClass("PreLoadRotate")})})})})})}); break; case 2: $(".JournalSectionWrapper").fadeIn(400,function(){$("#DateOne").fadeIn(400,function(){$("#DateTwo").fadeIn(400,function(){$("#DateThree").fadeIn(400,function(){$("#DateFour").fadeIn(400,function(){$("#DateFive").fadeIn(400,function(){$("#DateSix").fadeIn(400,function(){$("#DateSeven").fadeIn(400,function(){$("#DateEight").fadeIn(400,function(){$(".JournalSection").fadeIn(400,function(){$(".JournalSection").addClass("PreLoadRotate")})})})})})})})})})}); break; case 3: $(".ServicesSectionWrapper").fadeIn(400,function(){$("#AppsWrapper").fadeIn(400,function(){$("#ResponsiveWrapper").fadeIn(400,function(){$("#DigitalWrapper").fadeIn(400,function(){$("#PTRWrapper").fadeIn(400,function(){$(".ServicesSection").fadeIn(400,function(){$(".ServicesSection").addClass("PreLoadRotate")})})})})})}); break; } } </code></pre> <p>And here is the HTML:</p> <pre><code>&lt;div class="AboutSectionWrapper"&gt; &lt;div class="Selector" id="AboutWrapper"&gt;&lt;/div&gt; &lt;div class="Selector" id="DesignerWrapper"&gt;&lt;/div&gt; &lt;div class="Selector" id="ManagerWrapper"&gt;&lt;/div&gt; &lt;div class="Selector" id="DeveloperWrapper"&gt;&lt;/div&gt; &lt;div class="AboutSection"&gt; &lt;div class="Indicator"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <p>This is a menu (<code>AboutSectionWrapper</code>) which has selectors as you can see. I want to load the menu first and then sequentially load the selectors and finally fade in the menu indicator and add a CSS class which has a transition in it.</p> <p>It is the same for other cases but for example in CASE 2, there are more selectors!</p>
[]
[ { "body": "<ol>\n<li>Dont put so much <code>}}}}</code> it just looks bad and you will not know if everything is ok.</li>\n<li><p>I'm wrong or just a</p>\n\n<pre><code>$(\".AboutSectionWrapper, #AboutWrapper, #ManagerWrapper, #DeveloperWrapper, #DesignerWrapper, .AboutSection\").fadeIn(400, function()\n {\n $(\".AboutSection\").addClass(\"PreLoadRotate\");\n });\n</code></pre></li>\n</ol>\n\n<p>Could do the same thing of what you write above? Only if you want an effect \"first one then another\" you could separate the things.. but here are the same time and no differences at all. </p>\n\n<p>The same is for the others...</p>\n\n<pre><code> function pageLoader(pageIndex) {\n\n $(\".ServicesSectionWrapper,.ServicesSectionWrapper .Selector,.ServicesSection,.JournalSectionWrapper,.JournalSectionWrapper .Selector,.JournalSection,.AboutSectionWrapper,.AboutSectionWrapper .Selector,.AboutSection\").hide();\n\n switch (pageIndex) {\n\n case 1:\n $(\".AboutSectionWrapper, #AboutWrapper, #ManagerWrapper, #DeveloperWrapper, #DesignerWrapper, .AboutSection\").fadeIn(400, function()\n {\n $(\".AboutSection\").addClass(\"PreLoadRotate\");\n });\n break;\n\n case 2:\n $(\".JournalSectionWrapper, #DateOne, #DateTwo, #DateThree, #DateFour, #DateFive, #DateSix, #DateSeven, #DateEight, .JournalSection\").fadeIn(400, function()\n {\n $(\".JournalSection\").addClass(\"PreLoadRotate\");\n });\n break;\n\n case 3:\n $(\".ServicesSectionWrapper, #AppsWrapper, #ResponsiveWrapper, #DigitalWrapper, #PTRWrapper, .ServicesSection\").fadeIn(400, function()\n {\n $(\".ServicesSection\").addClass(\"PreLoadRotate\")\n });\n break;\n\n }\n }\n</code></pre>\n\n<hr>\n\n<pre><code>DateOne, #DateTwo, #DateThree, #DateFour, #DateFive, #DateSix, #DateSeven, #DateEight\n</code></pre>\n\n<p>Sounds like something which belong to the same thing, why not make a general &lt;div&gt; (or another container) and let it appear? his child will appear with him</p>\n\n<pre><code>&lt;div id=\"dates\"&gt;\n &lt;div id=\"DateOne\"&gt;&lt;/div&gt;\n &lt;!-- etc !--&gt;\n&lt;/div&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T23:00:27.047", "Id": "83455", "Score": "0", "body": "No I want to sequentially fade in these elements, that is why I did this!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T23:02:33.353", "Id": "83456", "Score": "0", "body": "Well I tested it and I don't see any \"sequentialfade\" but anyway in this case you should indent your code better" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T23:11:46.450", "Id": "83458", "Score": "0", "body": "Ok I got this idea: Make an integer (pointer), an array with all elements to fadeIn and a single function where you increment the pointer and set fadeIn to the current pointer if it reach the max apply the class. It could be more readable (since you use the same fade time)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T22:53:11.203", "Id": "47616", "ParentId": "47615", "Score": "1" } }, { "body": "<h1><code>display:none</code> instead of <code>.hide()</code></h1>\n\n<p>Instead of hiding them like this:</p>\n\n<pre><code> $(\".ServicesSectionWrapper,.ServicesSectionWrapper .Selector,.ServicesS...hide()\n</code></pre>\n\n<p>Add a class common to each (on the HTML) and with that class, use <code>display:none</code>.</p>\n\n<pre><code>.commonClass{display:none}\n</code></pre>\n\n<h1>Sequential Animation</h1>\n\n<p>Well, I haven't found anything elegant for sequential jQuery animation (or haven't looked that hard). However, <a href=\"http://jsfiddle.net/a8gK8/1/\" rel=\"nofollow\">I have made this which executes functions sequentially</a>. It isn't a generic solution for animation, only for this situation.</p>\n\n<pre><code>function animateQueue(q){\n\n // Get the next item\n var next = q.shift();\n\n // Remove from the array the selector (or jquery object) and function name\n var obj = $(next.shift());\n var functionName = next.shift();\n\n // Add in the callback that runs after the animation\n next.push(function(){\n if(!q.length) return; // When done, don't continue\n animateQueue(q); // otherwise, pass on the queue\n });\n\n // Run the animation\n jQuery.fn[functionName].apply(obj,next); \n}\n</code></pre>\n\n<p>All you need to do is write the queue like so:</p>\n\n<pre><code>[selector OR jQuery object, animation function, params except the callback]\nanimateQueue([\n ['#red','fadeIn',400], \n ['#blue','fadeIn',400],\n ['#green','fadeIn',400],\n [$('#red'),'fadeOut',400], \n [$('#blue'),'fadeOut',400],\n [$('#green'),'fadeOut',400] \n]);\n</code></pre>\n\n<p>Added for a jQuery object since...</p>\n\n<h1>Cache objects</h1>\n\n<p>to avoid fetching them from the DOM everytime</p>\n\n<pre><code>var red = $('#red');\nvar blue = $('#blue');\nvar green = $('#green');\n\nanimateQueue([\n [red,'fadeIn',400], \n [blue,'fadeIn',400],\n [green,'fadeIn',400]\n]);\n</code></pre>\n\n<h1>Taking it further</h1>\n\n<p>Since the only vital function for the <code>pageLoader</code> with respect to this functionality is selecting what to animate, we can move out everything but the selection. Further, we can store the animation queues into an array, and have <code>pageIndex</code> select them instead. <code>pageIndex</code> should be 0-indexed, so we subtract 1:</p>\n\n<pre><code>var queues = [\n first : [...],\n second : [...],\n third : [...]\n];\n\nfunction animateQueue(q){...}\n\nfunction pageLoader(pageIndex) {\n animateQueue(queues[pageIndex-1]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T23:24:42.467", "Id": "83464", "Score": "0", "body": "+1 great answer, you did the queue like i said in the comment but more elegant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T02:59:24.923", "Id": "83476", "Score": "0", "body": "Just before *Cache Objects*, why do you mix selector strings and calls to `$(selector_string)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:25:01.327", "Id": "83479", "Score": "0", "body": "@DavidHarkness That's a jQuery object. I realized later that they could be cached outside in advance, rather than repeatedly calling them in the queue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:41:44.800", "Id": "83488", "Score": "0", "body": "What I meant is why pass in a selector string on line 1 and then pass in the same `$(selector string`) a few lines later?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T04:13:00.113", "Id": "83490", "Score": "0", "body": "@DavidHarkness Because the script can use either a selector or a jQuery object. Check the demo." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-26T21:19:36.160", "Id": "84708", "Score": "0", "body": "@JosephtheDreamer Please check this question out my friend: http://stackoverflow.com/questions/23316584/sequential-animation-function-not-working-properly" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T23:11:11.390", "Id": "47619", "ParentId": "47615", "Score": "4" } } ]
{ "AcceptedAnswerId": "47619", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T22:38:11.320", "Id": "47615", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Page loader function" }
47615
<p>I just finished writing a basic binary conversion class in Ruby. I'm curious to see if anyone has suggestions for improvements. In particular, I'm looking for the cleanest, shortest, most succinct code possible, while staying away from hacky shortcut stuff.</p> <p>In creating this I wanted to use a minimum of functions that come with Ruby by default, as that would sort of defeat the purpose of this as a practice program. For instance, the entire thing could have been summed up with a quick line like this.</p> <pre><code>"101".to_i(2) ##&gt; 5 </code></pre> <p>But I wanted to do most of the math by hand, so to speak.</p> <p>There is one place in the <code>get_bits</code> method I did use a string, and I'm not too happy about it. However it was the only way I could think of to get the bits into an array. If there's another way to do so without splitting a string, I'd be glad to hear it.</p> <p>Here's the class.</p> <pre><code>class Converter def initialize binary_number @binary = binary_number @bits = get_bits @total = 0 self end def to_base_ten validate_binary @bits.reverse.each_with_index do |bit, power| append_to_total bit_value(bit, power) end get_total end private def get_bits @binary.to_s.split('').map do |bit| bit.to_i end end def validate_binary @bits.each do |bit| raise "Invalid binary!" unless bit == 0 || bit == 1 end end def bit_value bit, power is_set?(bit) ? two_to_power_of(power) : 0 end def two_to_power_of power total = 1 power.times do total = total * 2 end total end def is_set? bit bit == 1 end def append_to_total amount @total = @total + amount end def get_total @total end end </code></pre> <p>I also used RSpec to test it as best I could, but I won't post the specs here, just because they're long and not <em>directly</em> related to the class itself. If you want to inspect those too, they can be found on <a href="https://github.com/Archer70/BinaryConverter/blob/master/spec/converter_spec.rb" rel="nofollow">GitHub</a>.</p> <p>So there ya have it. Any thoughts are greatly appreciated. Clean code forever!</p>
[]
[ { "body": "<ol>\n<li><p>The name <code>Converter</code> is pretty ambiguous. It could mean anything.</p></li>\n<li><p>I'd suggest doing less work in the initializer, and more lazy evaluation.</p></li>\n<li><p>Skip that <code>self</code> line in the initializer - it's an initializer; it'll always return <code>self</code> (or, technically, it doesn't matter what the initializer returns, since you'll be calling <code>new</code> and <em>that</em> will return the new instance. Point is, skip that line)</p></li>\n<li><p>Use <a href=\"http://www.ruby-doc.org/core-2.0.0/Enumerable.html#method-i-inject\" rel=\"nofollow\"><code>Enumerable#inject</code></a> to do the sum</p></li>\n<li><p>Use <a href=\"http://www.ruby-doc.org/core-2.1.1/String.html#method-i-chars\" rel=\"nofollow\"><code>String#chars</code></a> instead of <code>String#split</code></p></li>\n<li><p>It'd probably be better to <code>raise</code> right away in the initializer if the string isn't a binary number. Also better to raise an <code>ArgumentError</code> while you're at it.</p></li>\n<li><p>You can check the string with a simple regular expression: <code>/^[01]*$/</code></p></li>\n<li><p>Your <code>#two_to_power_of</code> method can be replaced with <code>2 ** n</code></p></li>\n<li><p>Don't use prefixes like <code>is_</code> and <code>get_</code> in your method names (specifically, <code>is_set?</code>, <code>get_bits</code> and <code>get_total</code>); it's not Ruby's style. For instance, the <code>nil?</code> method isn't called <code>is_nil?</code>, and the <code>chars</code> method mentioned above isn't called <code>get_chars</code>.<br>\nAll methods return <em>something</em> so a <code>get_</code> is redundant, and a <code>?</code> suffix is a substitute for an <code>is_</code> prefix, just like a <code>=</code> suffix is a substitute for a <code>set_</code> prefix.</p></li>\n<li><p>Favor accessor methods over directly accessing instance variables. Such indirections allow for better internal decoupling. That is, as soon as you start accessing a value through a method, you make your class more flexible. You can begin with simple <code>attr_reader</code>-synthesized methods, which will of course not do anything special, but should you ever need or want to add more logic, you need only change the accessor method(s). In this case, however, a first step would be to simply use fewer instance variables (see #2)</p></li>\n<li><p>A class method might be nice for quick conversions, so you don't always have to deal with instantiating an object. E.g. a class method could allow you to say <code>Converter.convert(\"101010\")</code> and get <code>42</code> directly. It'd just be a shortcut for <code>Converter.new(\"101010\").to_base_ten</code>, but that's still a nice shortcut to have.</p></li>\n<li><p>Might be nice if you could specify endianness of the binary number, instead of assuming it's always little endian. </p></li>\n</ol>\n\n<p>In the end, I get something like this, if we want <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow\">memoization</a> of the converted values:</p>\n\n<pre><code>class BinaryNumberConverter\n attr_reader :binary\n\n def self.convert(string, little_endian = true)\n self.new(string).base_ten(little_endian)\n end\n\n def initialize(binary)\n if binary =~ /^[01]*$/\n @binary = binary\n else\n raise ArgumentError.new(\"'#{binary}' is not a valid binary number\")\n end\n end\n\n def base_ten(little_endian = true)\n little_endian ? little_endian_value : big_endian_value\n end\n\n private\n\n def little_endian_value\n @little_endian ||= convert(binary.reverse)\n end\n\n def big_endian_value\n @big_endian ||= convert(binary)\n end\n\n def convert(string)\n string.chars.each_with_index.inject(0) do |sum, digit|\n char, index = digit\n sum += char == \"1\" ? 2 ** index : 0\n end\n end\nend\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>instance = BinaryNumberConverter.new(\"101010\")\ninstance.base_ten # =&gt; 42\ninstance.base_ten(false) # =&gt; 21\n\nBinaryNumberConverter.convert(\"101010\") # =&gt; 42\nBinaryNumberConverter.convert(\"101010\", false) # =&gt; 21\n</code></pre>\n\n<p>Of course, it'd be <em>a lot</em> simpler to just extend <code>String</code> rather than make an entire class:</p>\n\n<pre><code>class String\n def bin_to_dec(little_endian = true)\n raise \"'#{self}' is not a valid binary number\" unless self =~ /^[01]*$/\n digits = little_endian ? reverse.chars : chars\n digits.each_with_index.inject(0) do |sum, digit|\n char, index = digit\n sum += char == \"1\" ? 2 ** index : 0\n end\n end\nend\n</code></pre>\n\n<p>And you get</p>\n\n<pre><code>\"101010\".bin_to_dec #=&gt; 42\n\"101010\".bin_to_dec(false) #=&gt; 21\n</code></pre>\n\n<p>No memoization, but I'd call that pretty clean.</p>\n\n<hr>\n\n<p>Took a quick look at your tests, and it's a bit overkill (also, you should use the <a href=\"http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax\" rel=\"nofollow\"><code>expect</code> syntax</a> of rspec; the <code>should</code> syntax is old-school).</p>\n\n<p>I'd actually just do something like</p>\n\n<pre><code>number = rand(12345) # can be anything really\nstring = number.to_s(2)\nexpect(string.bin_to_dec).to eq(number)\n</code></pre>\n\n<p>And call it good. You'll note I'm using <code>to_s(2)</code> above, but here it makes sense. We have to assume that Ruby works anyway, so in this case, it's a perfect yardstick. Similarly, to check big endian conversion, we can use <code>to_i(2)</code> with a clear conscience</p>\n\n<pre><code>string = rand(12345).to_s(2).reverse\nexpect(string.bin_to_dec(false)).to eq(string.to_i(2))\n</code></pre>\n\n<p>Add a test for the exception raising, and you've tested everything.</p>\n\n<hr>\n\n<p>On another note, you say you \"wanted to use a minimum of functions that come with Ruby by default as that would sort of defeat the purpose of this as a practice program\". But I'd recommend you use as much built-in functionality as possible, <em>especially</em> in your practice programs (in this case stopping short of using <code>String#to_i</code>, of course).</p>\n\n<p>Learning any language is usually less about learning the language itself (as in syntax), as it is about learning the conventions, idioms, <em>and</em> the built-in goodies. Intentionally doing things \"the hard way\" will probably teach you the wrong lessons. And the code you write won't teach you conventions and idioms, because it's unconventional to make things hard for yourself and no idioms exist for it.</p>\n\n<p>Besides, at first, the easy solution will actually be the difficult one, because the easy solution is the one that requires experience. But brute-forcing your way though a problem won't earn you that experience and will actually teach you a lot less than trying to use the language to your advantage.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T02:40:39.667", "Id": "83475", "Score": "0", "body": "Can you please expand on points 9 and 10? All the others get a resounding +1 from me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:04:59.910", "Id": "83477", "Score": "1", "body": "@DavidHarkness Thanks! I've fleshed it out a bit more; let me know if it's still lacking" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:13:07.710", "Id": "83478", "Score": "0", "body": "Nope, that was perfect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T02:18:41.660", "Id": "83585", "Score": "0", "body": "Thanks for the excellent answer. There's a lot of useful information there." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T01:31:53.063", "Id": "47625", "ParentId": "47622", "Score": "7" } } ]
{ "AcceptedAnswerId": "47625", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T00:32:27.297", "Id": "47622", "Score": "7", "Tags": [ "ruby", "converting", "rspec" ], "Title": "Binary converter and sufficient tests" }
47622
<p>I want to make sure that the code is correct in terms of its design, code correctness, best practices &amp; Junit testing.</p> <p>The complete description is given below: </p> <p>Functioning of the app quickly estimates the Final Cost depending on different markups. The following are the markups:</p> <ul> <li>Flat Markup of 5% on all jobs </li> <li>Markup of 1.2% for per Working person</li> <li>Type of materials markup: <ul> <li>For pharmaceuticals, 7.5% markup </li> <li>For food, 13% markup </li> <li>For electronics,2% markup </li> <li>For everything else, No markup</li> </ul></li> </ul> <p>The markup calculator should accept the initial base price along with the different categories of markups and calculate a final cost for a project. Example:</p> <p>Input 1: $1299.99<br> 3 people<br> food<br> Output 1: $1591.58</p> <p>The app is designed like a MVC (Model view controller) logic app where the Model is used to store the data &amp; perform calculations, Controller acts as the getter &amp; setter for values from user &amp; View is used to print the final input &amp; output to the user as MVC format helps any developer to understand the structure &amp; can also embed this app into another MVC app for use</p> <h3>MainCalculator</h3> <pre><code>public class MainCalculator { //BASE PRICE private static String BASE_PRICE="$1299.99"; //Number of People private static String NUM_OF_PEOPLE= "3 people"; //Types of materials private static String TYPE_OF_MATERIAL[] = new String[]{"FOOD","food"}; //Error messages are stored in this private static String message; //status remains true if validation for error checking passes the test i.e. program has handled all test cases private static boolean status= true; /* * MSG_ARGUMENT_NULL, MSG_INVALID_BASE_PRICE, MSG_INVALID_NUM_OF_PEOPLE, MSG_INSUFFICIENT_ARGUMENTS are the messages * displayed when a particular test case fails in the below methodsS * */ //@param MSG_ARGUMENT_NULL is printed when validateNullArgument() returns false private static final String MSG_ARGUMENT_NULL = "Mandatory inputs cannot be null, &lt;BASE_PRICE&gt;, &lt;NUM_OF_PEOPLE&gt; is mandatory"; private static final String MSG_ARGUMENT_NULL_TYPE_OF_MATERIAL = "One of the arguments is null in &lt;Type of Material&gt;"; //@param MSG_INSUFFICIENT_ARGUMENTS is printed when validateEmptyArgument() returns false private static final String MSG_INSUFFICIENT_ARGUMENTS = "Insufficient number of values &lt;BASE PRICE&gt;, &lt;NUM OF PEOPLE&gt;, &lt;TYPE OF MATERIAL&gt;(Optional)"; //@param MSG_INVALID_BASE_PRICE and/or MSG_INVALID_NUM_OF_PEOPLE is printed when validateNumberFormat() returns false private static final String MSG_INVALID_VALUE = "The &lt;BASE PRICE&gt;/&lt;NUM OF PEOPLE&gt; is not in correct number format"; //System error code 1 denotes invalid argument from user private static final int SYSTEM_ERROR_CODE_INVALID_INPUT = 1; //Main function instantiates the default constructor public static void main(String[] args) { //Default Constructor MarkupController markupControllerObject = new MarkupController(); //sets base price from MarkupController's setter method markupControllerObject.setBasePrice(BASE_PRICE); //sets number of people from MarkupController's setter method markupControllerObject.setNumOfPeople(NUM_OF_PEOPLE); /* * sets the types of materials from MarkupControllers setter method &amp; is a array as multiple types * of materials can be involved */ for(int i=0;i&lt; TYPE_OF_MATERIAL.length;i++) { markupControllerObject.setTypeOfMaterial(TYPE_OF_MATERIAL); } //gets base price from MarkupController's getter method BASE_PRICE = markupControllerObject.getBasePrice(); //gets number of people from MarkupController's getter method NUM_OF_PEOPLE = markupControllerObject.getNumOfPeople(); /* * Gets the types of materials from MarkupControllers getter method &amp; is a array as multiple types * of materials can be involved */ for(int i=0;i&lt; markupControllerObject.getTypeOfMaterial().length;i++) { TYPE_OF_MATERIAL = markupControllerObject.getTypeOfMaterial(); } //checks if the values in constructor are valid otherwise exits system if(!validateNullArgument(BASE_PRICE,NUM_OF_PEOPLE,TYPE_OF_MATERIAL) || !MainCalculator.validateEmptyArgument(BASE_PRICE,NUM_OF_PEOPLE) || !MainCalculator.validateNumberFormat(BASE_PRICE, NUM_OF_PEOPLE)) { //System must exit if any of the conditions are true in if condition exit(SYSTEM_ERROR_CODE_INVALID_INPUT); } else { /* * Removes $ sign &amp; whitespace from Base Price if present * and returns only the double value */ BASE_PRICE = validateDollarCheck(BASE_PRICE); /* * Removes keyword 'people' &amp; whitespace from Number of * people if present &amp; returns only number */ NUM_OF_PEOPLE = validateNumOfPeopleKeyword(NUM_OF_PEOPLE); MarkupModel.calculateMarkupSystemFormula(BASE_PRICE, NUM_OF_PEOPLE, TYPE_OF_MATERIAL); } } //Validates if BASE PRICE OR NUMBER OF PEOPLE or TYPE OF MATERIAL is NULL public static boolean validateNullArgument(String BASE_PRICE,String NUM_OF_PEOPLE, String[] TYPE_OF_MATERIAL) { //sizeTypeOfMaterial is the length of TYPE_OF_MATERIAL int sizeTypeOfMaterial = TYPE_OF_MATERIAL.length; //countNullCheck counts the number of null arguments in the string array of type of material int countNullCheck=0; for(int i=0;i&lt; sizeTypeOfMaterial;i++) { if(TYPE_OF_MATERIAL[i] == null) { countNullCheck++; } } /* * If one of the arguments in string array "Type of Material" * is null, prints an error to the user but continues execution */ if(countNullCheck &gt; 0) { message = MSG_ARGUMENT_NULL_TYPE_OF_MATERIAL; System.out.println(message); } //if countNullCheck is equal to size of type of material which means all elements in array are null if(BASE_PRICE == null || NUM_OF_PEOPLE == null || TYPE_OF_MATERIAL == null || countNullCheck == sizeTypeOfMaterial) { message = MSG_ARGUMENT_NULL; System.out.println(message); return false; } return status; } /* * Validates if BASE PRICE OR NUMBER OF PEOPLE IS EMPTY * If empty, then returns a message or returns true */ public static boolean validateEmptyArgument(String BASE_PRICE, String NUM_OF_PEOPLE) { if(BASE_PRICE.isEmpty() || NUM_OF_PEOPLE.isEmpty()) { message = MSG_INSUFFICIENT_ARGUMENTS; System.out.println(message); return false; } return status; } //Validates if BASE PRICE OR NUMBER OF PEOPLE Is in valid format public static boolean validateNumberFormat(String BASE_PRICE, String NUM_OF_PEOPLE) { /* * Removes $ sign &amp; whitespace from Base Price if present * and returns only the double value */ BASE_PRICE = validateDollarCheck(BASE_PRICE); /* * Removes keyword 'people' &amp; whitespace from Number of * people if present &amp; returns only number */ NUM_OF_PEOPLE = validateNumOfPeopleKeyword(NUM_OF_PEOPLE); /* * If base price is a proper double value &amp; number of people is a proper integer * else throw exception */ try { Double.parseDouble(BASE_PRICE); Integer.parseInt(NUM_OF_PEOPLE); } catch(NumberFormatException exception) { message = MSG_INVALID_VALUE; System.out.println(message); return false; } return status; } //validates if a '$' sign is in front of Base Price &amp; trims it public static String validateDollarCheck(String BASE_PRICE) { if(BASE_PRICE.length() &gt; 0) { if(BASE_PRICE.charAt(0) == '$') { BASE_PRICE = BASE_PRICE.trim().substring(1); } } return BASE_PRICE; } //Validates if user enters 'Number of people' as '8 people' &amp; removes keyword people with whitespace public static String validateNumOfPeopleKeyword(String NUM_OF_PEOPLE) { //Regular expression where s* removes whitespace &amp; \b checks for people String regexPeople = "\\s*\\bpeople\\b\\s*"; //Regular expression where s* removes whitespace &amp; \b removes 'person' String regexPerson = "\\s*\\bperson\\b\\s*"; NUM_OF_PEOPLE = NUM_OF_PEOPLE.replaceAll(regexPeople, "").replaceAll(regexPerson, ""); return NUM_OF_PEOPLE; } //Exits the system public static void exit(int status) { System.exit(status); } } </code></pre> <h3>MarkupController</h3> <pre><code>public class MarkupController { /** * MarkupController acts as a library for getter &amp; setter methods for * BASE_PRICE, NUM_OF_PEOPLE and TYPE_OF_MATERIAL * * @author Ankita Kulkarni */ private String BASE_PRICE; private String NUM_OF_PEOPLE; private String[] TYPE_OF_MATERIAL; /*Constructor with 3 parameters * @param BASE_PRICE base price of the system * @param NUM_OF_PEOPLE number of people in the system * @param TYPE_OF_MATERIAL type of materials in the system, an array since user can enter multiple materials */ public MarkupController() { } public MarkupController(String BASE_PRICE, String NUM_OF_PEOPLE,String[] TYPE_OF_MATERIAL) { this.BASE_PRICE = BASE_PRICE; this.NUM_OF_PEOPLE = NUM_OF_PEOPLE; this.TYPE_OF_MATERIAL= TYPE_OF_MATERIAL; } //gets the base Price public String getBasePrice() { return this.BASE_PRICE; } //sets the base Price public void setBasePrice(String BASE_PRICE) { this.BASE_PRICE = BASE_PRICE; } //gets the Number of people public String getNumOfPeople() { return NUM_OF_PEOPLE; } //sets the number of people public void setNumOfPeople(String NUM_OF_PEOPLE) { this.NUM_OF_PEOPLE = NUM_OF_PEOPLE; } //Gets the array of types of material public String[] getTypeOfMaterial() { return TYPE_OF_MATERIAL; } //Sets the array of types of material public void setTypeOfMaterial(String[] TYPE_OF_MATERIAL) { this.TYPE_OF_MATERIAL= TYPE_OF_MATERIAL; } } </code></pre> <h3>MarkupModel</h3> <pre><code>import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.math.BigDecimal; import code.MarkupView; public class MarkupModel { /** * MarkupModel acts as a Model where it stores values of the system obtained from * MarkupController &amp; performs calculations * @Author Ankita Kulkarni */ //Flat Markup on all jobs is 5% private static final String FLAT_MARKUP_ALL_JOBS = "0.05"; //For each working person, markup is 1.2% private static final String MARKUP_PER_WORKING_PERSON = "0.012"; /* * HashMap stores &lt;key,value&gt; pairs where key is the type of material &amp; value is * its respective percentage markup * Used HashMap as its easy to lookup any existing value stored in HashMap * Runtime Complexity of finding a element is O(1) hence faster */ public static HashMap&lt;String,String&gt; markupTypeOfMaterials = new HashMap&lt;String,String&gt;(){ { // puts &lt;key,value&gt; in HashMap i.e. &lt;type of material,markup Percent&gt; put("pharmaceuticals", "0.075"); put("drugs", "0.075"); put("food", "0.13"); put("electronics", "0.02"); } }; //FlatMarkup is stored in a Big Decimal object as its a decimal value private static BigDecimal getFlatMarkup() { return new BigDecimal(FLAT_MARKUP_ALL_JOBS); } //Markup for every working person is stored in a Big Decimal object for calculations private static BigDecimal getMarkupPerWorkingPerson() { return new BigDecimal(MARKUP_PER_WORKING_PERSON); } /* * @param TYPE_OF_MATERIAL provides type of material string array from user * This method checks if any key of hashmap matches to a key provided by user &amp; only returns * that key */ public static BigDecimal getMarkupTypeOfMaterialsValues(String TYPE_OF_MATERIAL) { /* * containsKey() checks if there is any matching key in hashmap &amp; TYPE_OF_MATERIAL * toLowerCase() all keys in Type of material is converted to lower case to match the * hashmap key example: FOOD and food are identical materials */ if(markupTypeOfMaterials.containsKey(TYPE_OF_MATERIAL.toLowerCase())) { //Only matched key is returned return new BigDecimal(markupTypeOfMaterials.get(TYPE_OF_MATERIAL.toLowerCase())); } //If key doesn't match, 0 is returned as there is 'No- Markup' return new BigDecimal("0"); } /* * Calculates the main functionality of the system * */ public static String calculateMarkupSystemFormula(String BASE_PRICE, String NUM_OF_PEOPLE, String[] TYPE_OF_MATERIAL) { /* * Removes $ sign &amp; whitespace from Base Price if present * and returns only the double value */ BASE_PRICE = MainCalculator.validateDollarCheck(BASE_PRICE); /* * Removes keyword 'people' &amp; whitespace from Number of * people if present &amp; returns only number */ NUM_OF_PEOPLE = MainCalculator.validateNumOfPeopleKeyword(NUM_OF_PEOPLE); /* * Converts base price, number of people into BigDecimal for * calculations */ BigDecimal basePrice = new BigDecimal(BASE_PRICE); BigDecimal numOfPeople = new BigDecimal(NUM_OF_PEOPLE); /* * The elements from Type of materials are added in a Set as * it helps remove duplicates * for eg: In condition like 'food' and 'food', only 1 type * 'food' markup will be calculated */ Set&lt;String&gt; typeOfMaterialSet = null; for(String element:TYPE_OF_MATERIAL) { //Only adds elements which are not empty or not null to the Set if(!element.isEmpty() &amp;&amp; element !=null) { typeOfMaterialSet = new HashSet&lt;String&gt;(Arrays.asList(element)); } } //When Type of Material does not match hashmap keys then '0' is added BigDecimal totalTypeOfMaterialMarkup = new BigDecimal("0"); /* * Only those elements from Type of material that match * the hashmap keys are added for calculations */ for(String typeOfMaterial:typeOfMaterialSet) { BigDecimal typeOfMaterialMarkup = getMarkupTypeOfMaterialsValues(typeOfMaterial); totalTypeOfMaterialMarkup = totalTypeOfMaterialMarkup.add(typeOfMaterialMarkup); } /* * Formula for calculating flat markups on all jobs * newBasePrice = basePrice * FlatMarkup (0.05)+ basePrice */ BigDecimal newBasePrice = basePrice.multiply(getFlatMarkup()).add(basePrice); /* * Formula for calculating the markup for the number of people * Markup for working people = num of people * markup per working person (0.012) */ BigDecimal totalMarkupForWorkingPeople = numOfPeople.multiply(getMarkupPerWorkingPerson()); /* * Formula for Final Base Price is: * finalbaseprice = newBasePrice * (1+totalMarkupForWorkingPeople+totalTypeOfMaterialMarkup) * */ BigDecimal finalBasePrice = newBasePrice.multiply(BigDecimal.ONE. add(totalMarkupForWorkingPeople). add(totalTypeOfMaterialMarkup)); /* * returns the final base price by rounding upto 2 digits after decimal along with '$' sign */ MarkupView.printInput(basePrice, numOfPeople, typeOfMaterialSet); String outputBasePrice = MarkupView.printOutputFormat(finalBasePrice); System.out.println("Final Output: "+outputBasePrice); return outputBasePrice; } } </code></pre> <h3>MarkupView</h3> <pre><code>import java.math.BigDecimal; import java.util.Set; /** * MarkupView is responsible for displaying the final output to the user * It formats the input &amp; output to provide a clean UI to the user * @author Ankita Kulkarni * */ public class MarkupView { /* * This method formats the basePrice by rounding the 2 numbers after decimal using ROUND_HALF_UP * BigDecimal ROUND_HALF_UP is the ideal way for performing monetary calculations * &amp; ROUND_HALF_UP providing the least bias is recommended * @link http://www.javapractices.com/topic/TopicAction.do?Id=13 */ public static String printOutputFormat(BigDecimal basePrice) { /* * Sets scale of base price to 2 decimal round half up * example, 1591.5777570 turns to 1591.58 */ BigDecimal finalBasePrice = basePrice.setScale(2, BigDecimal.ROUND_HALF_UP); //Prepends '$' sign to base price for representing money String dollarBasePrice = "$"+finalBasePrice.toString(); return dollarBasePrice; } /** * * @param basePrice gets base price that was entered by user * @param numOfPeople gets number of people that was entered by user * @param typeOfMaterial gets the type of material * This method prints all the parameters values on the console along with the * final base price * */ public static void printInput(BigDecimal basePrice,BigDecimal numOfPeople, Set&lt;String&gt; typeOfMaterial) { System.out.println("Base Price: $"+basePrice); System.out.println("Number of People: "+numOfPeople); System.out.println("Type of Material: "+typeOfMaterial.toString().replaceAll("\\[", "").replaceAll("\\]", "") +" "); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T07:10:25.827", "Id": "84263", "Score": "3", "body": "Do not try to document the standard library in comments, as IDEs already conveniently provides that documentation, and there is the Internet for the rest. Just explain what cannot be understood by reading **your** code directly; and keep what you write simple so that such explanation is needed rarely." } ]
[ { "body": "<p>I scanned through your code and also stepped through it with a debugger, line-by-line. The more I looked, the more things I found that I wanted to point out.</p>\n\n<hr>\n\n<p>Let's start by looking at some unnecessary comments:</p>\n\n<pre><code>// BASE PRICE\nprivate static String BASE_PRICE = \"$1299.99\";\n\n// Number of People\nprivate static String NUM_OF_PEOPLE = \"3 people\";\n</code></pre>\n\n<p>(Why aren't these variables a <code>BigDecimal</code> and an int btw?)</p>\n\n<p>Make variable names self-documenting. No need to comment them that much.</p>\n\n<p>Speaking of naming... <code>private static boolean status = true;</code>... what status? Call it <code>programHandledAllTestCases</code> or something similar instead. The name \"status\" is very ambiguous.</p>\n\n<hr>\n\n<p>There is no reason to run this code in a loop:</p>\n\n<pre><code>for (int i = 0; i &lt; TYPE_OF_MATERIAL.length; i++) {\n markupControllerObject.setTypeOfMaterial(TYPE_OF_MATERIAL);\n}\n</code></pre>\n\n<p>I'm not sure you know what you are doing here, or why you do it, or what you intend to do. But given what the code currently actually <em>does</em>, this loop is not needed.</p>\n\n<hr>\n\n<p>Some of your naming don't adhere to the <a href=\"http://en.wikipedia.org/wiki/Naming_convention_%28programming%29#Java\">Java naming conventions</a>, such as <code>private String[] TYPE_OF_MATERIAL;</code></p>\n\n<hr>\n\n<pre><code>markupControllerObject.setBasePrice(BASE_PRICE);\n(...)\nBASE_PRICE = markupControllerObject.getBasePrice();\n</code></pre>\n\n<p>Why set first and get just a bit later? Expecting something different than what you put there just a few lines ago?</p>\n\n<hr>\n\n<blockquote>\n <p>I want to make sure that the code is correct in terms of its design, code correctness, best practices &amp; Junit testing.</p>\n</blockquote>\n\n<p>You're not using the real JUnit at all! Your \"testing\" consists of checking conditions, sometimes catching exceptions, and then printing your own messages. I <strong>strongly recommend</strong> using <strong><a href=\"http://www.junit.org\">the real JUnit</a></strong>, it is the best practice for doing real testing.</p>\n\n<hr>\n\n<p>Your <code>private static String message;</code> is totally useless - and would be very dangerous if this would be a multi-threaded application, it is only used in situations like this:</p>\n\n<pre><code>message = MSG_ARGUMENT_NULL_TYPE_OF_MATERIAL;\nSystem.out.println(message);\n</code></pre>\n\n<p>Instead, simply do:</p>\n\n<pre><code>System.out.println(MSG_ARGUMENT_NULL_TYPE_OF_MATERIAL);\n</code></pre>\n\n<hr>\n\n<p>You're calling <code>NUM_OF_PEOPLE = MainCalculator.validateNumOfPeopleKeyword(NUM_OF_PEOPLE);</code> three times in your code. Why not only do it once?</p>\n\n<p>Or rather, why do it at all? Let <code>NUM_OF_PEOPLE</code> be an int instead. Removing the <code>\" people\"</code> suffix from the String and converting it to a <code>BigDecimal</code> is just... horrible... Why BigDecimal btw? Expecting <code>3.49994513</code> people?</p>\n\n<hr>\n\n<p>Your \"MVC structure\" seems a bit overkill for this application. It mainly seems to be used in order to separate some methods. There are however, plenty of other things to deal with first in this code. If you want them separated, keep your \"MVC structure\".</p>\n\n<hr>\n\n<p>You seem to use <code>static</code> methods a lot. Although this works in this case, I think this might be a bad habit you have. I recommend avoiding that. Java is object oriented, use <em>objects</em>.</p>\n\n<hr>\n\n<p>This method is only used once. And it's easier to call <code>System.exit</code> directly than to call this method.</p>\n\n<pre><code>public static void exit(int status) {\n System.exit(status);\n}\n</code></pre>\n\n<hr>\n\n<p>Overall, I'm very sad to tell you this but there's a whole lot of clutter in this code. Unnecessary comments, unnecessary going back and forth with getting a value that you had just set, using the wrong data types for things...</p>\n\n<p>I don't like writing harsh reviews like this, but I had to. There might be other things to deal with later, but now you have some work ahead of you. Please come back with a follow up to this code, I would like to write a more positive review next time!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T23:08:56.050", "Id": "85543", "Score": "0", "body": "Do you think I havent used getter & setter properly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-02T12:03:49.247", "Id": "85625", "Score": "0", "body": "@fscore No, you haven't. You seem to be over-using them. There's no need to call a setter first and then just a few lines later calling the getter, just to get back the value that you had just set. There's also not any use in calling a setter for an array in a loop (for each item in the array). If it's sets an array, you don't need to call the set in a loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T15:49:23.930", "Id": "48065", "ParentId": "47623", "Score": "14" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T00:34:20.897", "Id": "47623", "Score": "10", "Tags": [ "java", "design-patterns", "unit-testing", "mvc", "console" ], "Title": "Markup calculator application using MVC" }
47623
<p>I have a project (<a href="http://corylutton.com/ldaplib.html" rel="nofollow">ldaplib</a>) I am working on that needs to do ASN1-BER decoding and encoding. The function I have for the decoding portion is slightly more complex but neither are all that complicated. I would like to get some feedback on the overall approach as well as the code/exceptions/inline comments. </p> <p>The decoding specifically uses a named tuple defined much higher in the code as a return type which is then used in many places throughout the code:</p> <pre><code>BER = namedtuple('BER', 'cls pc tag value') </code></pre> <p>The encoding portion:</p> <pre><code>def ber_encode(ber_cls, ber_pc, ber_tag, message): """ Encode a message into ASN1-BER (TLV) bytes. The ber_cls, ber_pc, and ber_tag should be numbers, the message can be bytes, str, or int. """ if type(message) not in (str, int, bytes): raise TypeError("Requires str, int, or bytes object.") encoded = (ber_cls + ber_pc + ber_tag).to_bytes(1, byteorder='big') if type(message) is int: bytelength = (message.bit_length() // 8) + 1 message = message.to_bytes(bytelength, byteorder='big') elif type(message) is str: message = message.encode(encoding='ascii') if len(message) == 0: return encoded + int(0).to_bytes(1, byteorder='big') # Short form or Long form? length = len(message) if length &lt; 0x80: encoded += length.to_bytes(1, byteorder='big') else: bytelength = (length.bit_length() // 8) + 1 encoded += (0x80 + bytelength).to_bytes(1, byteorder='big') encoded += length.to_bytes(bytelength, byteorder='big') # Add the message encoded += message return encoded </code></pre> <p>The decoding portion:</p> <pre><code>def ber_decode(message, result=None): """ Decode a message from ASN1-BER (TLV) bytes into a list of byte values. Values that contain embedded types will need to call this function to break the objects into their individual type/value components. """ if type(message) is not bytes: raise TypeError("Requires bytes object.") if not result: result = [] if len(message) == 0: raise Exception("No message") # Use masks to isolate the binary parts ber_type = message[0] # NOQA ber_cls = ber_type &amp; 0b11000000 ber_pc = ber_type &amp; 0b00100000 ber_tag = ber_type &amp; 0b00011111 ber_len = message[1] # Assume that the ber_value is offset 2 or is blank offset = 2 # Only the definite form of length encoding is used. if ber_len &gt; 0x80: nbytes = ber_len &amp; 0x7f ber_len = int.from_bytes( message[offset:offset + nbytes], byteorder='big') offset = offset + nbytes ber_value = message[offset: offset + ber_len] else: ber_value = message[offset: offset + ber_len] # Append the decoded message part. result.append(BER(ber_cls, ber_pc, ber_tag, ber_value)) message = message[ber_len + offset:] # If the message had only one type then we are done, if not recurse. if len(message) == 0: return result else: return ber_decode(message, result) </code></pre>
[]
[ { "body": "<p>Some ideas:</p>\n\n<h2>String concatenation</h2>\n\n<p>The method you're using for string concatenation (successively using the <code>+=</code> operator) is <a href=\"http://www.skymind.com/~ocrow/python_string/\" rel=\"nofollow\">the slowest method</a> in Python for constructing strings. Consider instead creating a list of strings and concatenating them at the end using <code>return ''.join(created_strings)</code>. Because your BER encoder is likely to be used with a protocol, speed may be important.</p>\n\n<h2>Checking of inputs</h2>\n\n<p>Your <code>cls</code>, <code>pc</code> and <code>tag</code> elements are not checked on input to the <code>ber_encode</code> routine and would allow constructs such as <code>ber_encode(0xc3,7,3,\"bongo\")</code> which gets coded with a tag of <code>0xcd</code>. That isn't necessarily <em>wrong</em> but it's not what I might have expected.</p>\n\n<h2>Orthogonality of <code>ber_encode</code> and <code>ber_decode</code></h2>\n\n<p>It's not unreasonable for a user of your functions to assume that the two complementary functions can each be fed the output of the other, but that's not the case for these functions. While <code>ber_decode</code> will happily digest the output of <code>ber_encode</code>, what <code>ber_decode</code> produces is a named tuple rather than an output that's compatible with <code>ber_encode</code>'s input requirements. Again, this isn't necessarily wrong, but it is a potential impediment to users of your functions.</p>\n\n<h2>Error checking</h2>\n\n<p>Generally, the code does a pretty good job of validating inputs and throwing appropriate errors, but there is at least one case which is accepted that should probably throw an error. Specifically, </p>\n\n<pre><code>ber_decode(b'\\x86\\xff'+('a'*256).encode(encoding='ascii'))\n</code></pre>\n\n<p>results in a BER value which is 129 bytes long. It's probably worth double checking <a href=\"http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf\" rel=\"nofollow\">ITU X.690</a> section 8.1.3.5 which says that an encoded length value of <code>11111111b</code> shall not be used.</p>\n\n<p>Similarly, </p>\n\n<pre><code>ber_decode(b'\\x86\\x80'+('a'*256).encode(encoding='ascii'))\n</code></pre>\n\n<p>is decoded as three BER encodings, the first of which is 128 bytes long (which is suspect), the second is 97 bytes long (which is OK) and the third is 27 bytes long, which may or may not be OK, but shouldn't a truncated message throw an exception?</p>\n\n<h2>Test vectors</h2>\n\n<p>You may simply have omitted them from the posted code, but I'd highly recommend including test vectors with the code. Python has a number of ways to do testing including <a href=\"https://docs.python.org/3.3/library/doctest.html\" rel=\"nofollow\"><code>doctest</code></a> and <a href=\"https://docs.python.org/3.3/library/unittest.html#module-unittest\" rel=\"nofollow\"><code>unittest</code></a>. Not only do they help you make sure you've considered many different types of input (both good and bad), but they also serve as documentation for users of the functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T20:53:02.713", "Id": "83569", "Score": "0", "body": "Thanks for the review. These two functions are actually internal so I should add the _ at the beginning. I have full test coverage just not posted. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T21:14:15.317", "Id": "83570", "Score": "0", "body": "On the error checking for ber_cls, ber_pc, ber_tag. I should validate and raise, nice catch, I will add to my tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T02:10:44.740", "Id": "83583", "Score": "0", "body": "I did a little testing, it seems that doing `encoded = b''.join((encoded, length.to_bytes(1, byteorder='big')))` in the various places does not really have a positive impact. There could be another way to address it by building up a list but from initial tests it is actually slower by about 3.8%. I would guess this is because I am not building up many byte strings. Adding the validation is a larger hit to performance at about 6.3% slower. Removing all validation (it is really for internal library use anyway) makes it 8% faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T02:15:14.597", "Id": "83584", "Score": "0", "body": "@clutton: good for you for actually measuring it. It only makes a difference if it's measurable on *your* computer with *your* data and if you can assure that you don't need the validation, it's perfectly reasonable to omit it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T02:20:14.733", "Id": "83586", "Score": "0", "body": "One question on your comment regarding \"encoded length value of 11111111b shall not be used.\" For my purpose (ldap) in your opinion should I be concerned about an LDAP server sending invalid data? This kind of goes along with the validation needs... this is actually my first time trying to write a library that would deal with potentially many different producers of inbound data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T02:26:28.283", "Id": "83588", "Score": "0", "body": "Thanks so much for your time and comments, it is much appreciated." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T20:44:39.787", "Id": "47677", "ParentId": "47626", "Score": "4" } }, { "body": "<p>In <code>ber_encode</code>:\nthe line <code>bytelength = (length.bit_length() // 8) + 1</code> counts 1 byte too many if <code>bit_length</code> is an exact multiple of 8. (e.g. 8 bits → 2 bytes?!)\nSo this line should be:</p>\n\n<pre><code>bytelength = ((length.bit_length()-1) // 8) + 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-10T10:04:04.047", "Id": "157410", "ParentId": "47626", "Score": "2" } } ]
{ "AcceptedAnswerId": "47677", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T01:45:51.100", "Id": "47626", "Score": "5", "Tags": [ "python", "python-3.x", "serialization", "ldap" ], "Title": "ASN.1 BER Encoding and Decoding" }
47626
<p>I have this implementation of the split algorithm that different from <code>.split()</code> method you can use with multiple delimiters. Is this a good way of implementing it (more performance)?</p> <pre><code>def split(str, delim=" "): index = 0 string = "" array = [] while index &lt; len(str): if str[index] not in delim: string += str[index] else: if string: array.append(string) string = "" index += 1 if string: array.append(string) return array </code></pre> <p><strong>Using the standard</strong> <code>.split()</code> <strong>method:</strong></p> <pre><code>&gt;&gt;&gt; print "hello = 20".split() ['hello', '=', '20'] &gt;&gt;&gt; print "one;two; abc; b ".split(";") ['one', 'two', ' abc', ' b '] </code></pre> <p><strong>Using my implementation:</strong></p> <pre><code>&gt;&gt;&gt; print split("hello = 20") ['hello', '=', '20'] &gt;&gt;&gt; print split("one;two; abc; b ", ";") ['one', 'two', ' abc', ' b '] </code></pre> <p>Multiple delimiters:</p> <pre><code>&gt;&gt;&gt; print split("one;two; abc; b.e. b eeeeee.e.e;;e ;.", " .;") ['one', 'two', 'abc', 'b', 'e', 'b', 'eeeeee', 'e', 'e', 'e'] &gt;&gt;&gt; print split("foo barfoo;bar;foo bar.foo", " .;") ['foo', 'barfoo', 'bar', 'foo', 'bar', 'foo'] &gt;&gt;&gt; print split("foo*bar*foo.foo bar;", "*.") ['foo', 'bar', 'foo', 'foo bar;'] </code></pre> <p>Obs: We can do something like using <code>re.split()</code>.</p>
[]
[ { "body": "<p>There's no need to iterate using that <code>while</code>, a <code>for</code> is good enough.</p>\n\n<p>Also string concatenation (<code>+=</code>) is expensive. It's better to use a list and join its elements at the end<sup>1</sup>.</p>\n\n<pre><code>def split(s, delim=\" \"):\n words = []\n word = []\n for c in s:\n if c not in delim:\n word.append(c)\n else:\n if word:\n words.append(''.join(word))\n word = []\n if word:\n words.append(''.join(word))\n return words\n</code></pre>\n\n<p>As <a href=\"https://codereview.stackexchange.com/questions/47627/function-to-split-strings-on-multiple-delimiters#comment362069_47628\">Maarten Fabré</a> suggested, you could also ditch the <code>words</code> list and transform the function into a generator that iterates over (<code>yield</code>s) each word. This saves some memory if you're examining only one word at a time and don't need all of them in one shot, for example when you're counting word frequency (<code>collections.Counter(isplit(s))</code>).</p>\n\n<pre><code>def isplit(s, delim=\" \"): # iterator version\n word = []\n for c in s:\n if c not in delim:\n word.append(c)\n else:\n if word:\n yield ''.join(word)\n word = []\n if word:\n yield ''.join(word)\n\ndef split(*args, **kwargs): # only converts the iterator to a list\n return list(isplit(*args, **kwargs))\n</code></pre>\n\n<p>There's also a one-liner solution based on <a href=\"https://docs.python.org/2/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>:</p>\n\n<pre><code>import itertools\n\ndef isplit(s, delim=\" \"): # iterator version\n # replace the outer parentheses (...) with brackets [...]\n # to transform the generator comprehension into a list comprehension\n # and return a list\n return (''.join(word)\n for is_word, word in itertools.groupby(s, lambda c: c not in delim)\n if is_word)\n\ndef split(*args, **kwargs): # only converts the iterator to a list\n return list(isplit(*args, **kwargs))\n</code></pre>\n\n<hr>\n\n<p><sub><sup>1</sup> From <a href=\"https://wiki.python.org/moin/PythonSpeed\" rel=\"nofollow noreferrer\">https://wiki.python.org/moin/PythonSpeed</a>: \"String concatenation is best done with <code>''.join(seq)</code> which is an O(n) process. In contrast, using the <code>+</code> or <code>+=</code> operators can result in an O(n**2) process because new strings may be built for each intermediate step. The CPython 2.4 interpreter mitigates this issue somewhat; however, <code>''.join(seq)</code> remains the best practice\".</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:28:49.430", "Id": "83480", "Score": "1", "body": "It does not work properly. ['one', 'two', ' abc', ' b', 'e', [' ', 'b', ' ', 'b', ' ', 'b', ' ']]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:29:31.220", "Id": "83481", "Score": "0", "body": "It'd should return: ['one', 'two', ' abc', ' b', 'e', ' b b b ']" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:29:33.880", "Id": "83482", "Score": "0", "body": "For what input?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:29:59.463", "Id": "83483", "Score": "0", "body": "For this: \"one;two; abc; b.e. b b b \" with these delimiters \";.\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:33:43.417", "Id": "83485", "Score": "0", "body": "You're right, I forgot to join the characters for the last word." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:36:57.593", "Id": "83486", "Score": "0", "body": "Now it works well and it likes more pythonic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T04:08:38.210", "Id": "83489", "Score": "0", "body": "@dxhj, check out the one-liner too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-12T14:59:26.447", "Id": "362069", "Score": "1", "body": "Even more pythonic would be to replace the `words.append(''.join(word))` with `yield ''.join(word)`, and omit the `words` list altogether" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:23:03.437", "Id": "47628", "ParentId": "47627", "Score": "9" } }, { "body": "<p>I would suggest caution if your concerned about the performance vs the built in split. I am fairly sure you would be replacing c code with python code.</p>\n\n<p>A couple of notes about your implementation:</p>\n\n<ul>\n<li>You use the variable name str which is also a built in type, you should avoid if possible.</li>\n<li>Each time you loop around you add a character which really builds another string, perhaps you could keep going until you find a delimiter and just add all those at 1 time.</li>\n<li>Also might be worth thinking about wrapping the built in.. (ie calling multiple times)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T09:39:17.173", "Id": "83511", "Score": "0", "body": "I'd like to add that choosing `string` for a variable name might hide the [`string`](https://docs.python.org/2/library/string.html) module." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T03:38:34.607", "Id": "47629", "ParentId": "47627", "Score": "5" } } ]
{ "AcceptedAnswerId": "47628", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T02:33:46.017", "Id": "47627", "Score": "9", "Tags": [ "python", "strings" ], "Title": "Function to split strings on multiple delimiters" }
47627
<p>TL;DR: The Bash script converts a published, somewhat-structured text file into a format usable by my testing infrastructure. It's slow, I think it's ugly -- although it is fully functional.</p> <hr> <p>The NIST provides <a href="http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip" rel="nofollow">test vectors</a> for verifying the correct operation of a Galois Counter Mode (GCM) when used with the AES block cipher (I only care about the 128-bit key files, and have not looked into the format of the other files).</p> <p>In order to actually use these test vectors for automated testing of my GCM-AES implementation, I have to convert them from the RSP file that they come in, into a debug script that my chip simulator (<a href="http://mspdebug.sourceforge.net/" rel="nofollow">mspdebug</a>) can use. There are also other scripts, as well as driver code, that the test vectors ultimately interact with -- but it is sufficient for this problem to have each variable in the RSP file set in memory with an <code>mw</code> command (e.g., "PT = 010203" should become "mw PT 0x01 0x02 0x03"), so long as each group of tests that share common values is broken into a separate file.</p> <p>As an operational example, from this <a href="http://pastebin.com/1XDHmRn4" rel="nofollow">section</a> of the gcmEncryptExtIV128.rsp input file, this <a href="http://pastebin.com/WqAKttAa" rel="nofollow">output</a> is generated. Note that the input file generates 525 such files, from 525 corresponding sections within itself. The script, as written, will not work on just the subsection linked above, as the complete RSP has some extra junk at the start that gets trimmed out (though you can probably get it to work with some fiddling). Note also that none of the encryption tests are marked with a "FAIL" -- this token occurs only within the decryption tests, but the contents of the two RSP files are otherwise identical. For the sake of uniformity, each encryption test (as well as the non-failing decryption tests) have an output line of mw FAIL 0.</p> <p>The script is incredibly slow (it takes ~15 minutes to run against a single RSP file on a modest modern machine), primarily because of the sed expression for ensuring that every test block has a FAIL setting. It does, however, correctly spit out each test group into a well-named file, and convert all of the input data into a format that my simulator can handle.</p> <p>Any thoughts on how to speed this up, improve the readability, or conform to best practices are welcome. More drastic actions (e.g., re-casting this as an AWK script) are also interesting to me, if folks think this approach is just all-out incorrect.</p> <pre><code>#!/bin/bash if ! [ -f "$1" ]; then echo "You must specify a valid input file." exit fi # Strip off the file extension of the input file name BASEFILE=${1%.*} # Strip off any trailing digits of the input file name until [ "$TEMP" == "$BASEFILE" ]; do TEMP="$BASEFILE" BASEFILE="${BASEFILE%[0-9]}" done unset TEMP # - Convert the file's line endings # - Strip out the RSP file header and leading blank lines dos2unix &lt; "$1" | tail -n +7 &gt; temp.txt # Convert the "len" values from decimal to hex # Process the temp file line by line to do this cat temp.txt | \ while read VARNAME EQUALS VALUE; do # If this line's variable name ends in "len" if [ "${VARNAME%%*len}" != "$VARNAME" ]; then # Output the line (removing the starting "[", up to the = sign echo -n ${VARNAME#[[]} $EQUALS" " # Then convert the value from decimal to hex, printing it at the very end of the line. # s/^(.?.)$/0x\1 0x0/ - If we have a 1 or 2 digit number, put it in the LSB position. # s/^(.?.)(..)$/0x\2 0x\1/ - If we have a 3 or 4 digit number, put it in little-endian order. echo "obase=16; ${VALUE%%[]]*}" | bc | sed -re 's/^(.?.)$/0x\1 0x0/' -e 's/^(.?.)(..)$/0x\2 0x\1/' else # This isn't a length variable? It's already hex, then; just print it straight out. echo $VARNAME $EQUALS $VALUE; fi done &gt; temp2.txt mv temp2.txt temp.txt # - Strip out the block-level variable's enclosing square brackets # - Strip out the "Count" lines (we don't need them for anything). # - Strip lines with no values # - Strip trailing spaces sed -ri -e 's/\[|\]//g' -e '/^Count .*/d' -e '/^[^ ]+ = $/d' -e 's/ +$//' temp.txt # Convert the "var = value" format to "mw var value" used by MSPD sed -rie 's/^([^ ]*) =/mw \1/' temp.txt # Convert hex values to 0x## byte notation MSPD will understand. # :loop - A label we'll need later # ^(mw (Key|IV|PT|AAD|CT|Tag) ) - Match only these keys (and eat them and their trailing space) # ((0x[0-9a-f]{2} )*) - Eat up any parts of the hex string that have already been split into 0x-prefixed bytes # ([0-9a-f]{2}) - Capture the next un-processed byte's worth of digits, if they exist # (.*)$ - Capture the rest of the line. # \1\30x\5 \6 - Paste the key (and its space), the processed hex, the new 0x, hex byte, and space, and then any remainder. # t loop - If we actually replaced something, run the replace again (go back to :loop) sed -ri -e ':loop' -e 's/^(mw (Key|IV|PT|AAD|CT|Tag) )((0x[0-9a-f]{2} )*)([0-9a-f]{2})(.*)$/\1\30x\5 \6/' -e 't loop' temp.txt # Split each test block into its own file. # /^mw Keylen/ - If this is a "Keylen" line, it's the start of a new test block # {x="test-"++i;} - Increment our counter (start printing to a new file) # {print &gt; x;} - Append the current line in the buffer to the current file. awk '/^mw Keylen/{x="test-"++i;}{print &gt; x;}' temp.txt # - Normalize each test so it has an appropriate FAIL line # - Normalize each test so it reads the test round (after setting variables) # - Rename the files to reflect the tests they contain. for FILE in test-*; do # Make sure that there always exists a pass OR fail indicator for each test round. # --- This is incredibly slow :( --- # $!P - If this is not the last buffer, print it. # 7~1N - Process 2 lines, starting from the 7th line on # /FAIL\n$/! - If this is NOT a FAIL line followed by a blank line... # s/(.*)\n$/ - If this IS (then) a line followed by a blank line... # /\1\nmw FAIL 0\n/ - insert "md FAIL 0" as a line. # D - shift out the oldest (first) line, and jump back to the N sed -ri -e '$!P' -e '7~1N' -e '/FAIL\n$/!{s/(.*)\n$/\1\nmw FAIL 0\n/}' -e 'D' "$FILE" # Replace all the "FAIL" lines with appropriate memory sets. sed -rie 's/^FAIL$/mw FAIL 1/' "$FILE" # For each discrete set of test variables, read in the file responsible for actually running a single test round. # 7~1 - Skip the first 7 lines of the file # s/^$/ - If this is a blank line... # /read gcm_test_round.mspd\n/ - Insert the appropriate read line. sed -rie '7~1s/^$/read gcm_test_round.mspd\n/' "$FILE" # Rename the files to reflect the class of tests they contain. # head -n5 "$FILE" - Grab the first five lines of the file, which hold (in order) the values for key length, IV length, text length, AAD length, and tag length for all the test entries contained in that file. # ^.* 0x(.?.) 0x(.?.) - Match the two 1-2 digit hex numbers at the end of the lines # ibase=16; \2\1 - Put the bytes back into big-endian, and strip the 0x (prep for BC) # { while read; do echo $REPLY | bc; done; } - Pipe each line to BC one by one, converting the hex values back to decimal # :a - Label "a" # N - Append another line to the buffer # $!ba - If this is NOT the last line, branch to A # s/\n/-/g - Replace all the newlines in the processing space with dashes mv "$FILE" "$BASEFILE"`head -n5 "$FILE" | sed -re 's/^.* 0x(.?.) 0x(.?.)/ibase=16; \2\1/g' | { while read; do echo $REPLY | bc; done; } | sed -re ':a' -e 'N' -e '$!ba' -e 's/\n/-/g'`.mspd # The resulting renamed files are of the format: # [BASEFILE][Keylen]-[IVlen]-[PTlen]-[AADlen]-[Taglen].mspd # Get rid of the temporary file rm "${FILE}e" done # Get rid of temporary files rm temp.txt{,e} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T05:48:35.340", "Id": "83492", "Score": "0", "body": "I am not sure I understand what the _incredibly slow_ `sed` invocation is supposed to do. When `FAIL\\n$` is encountered, insert an `md FAIL 0` after it, did I get it right? A more formal definition of the input (as well as desired output would help)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T06:10:39.007", "Id": "83496", "Score": "0", "body": "@user58697 I could attempt to define the input, but the most accurate representation is going to come from the source files themselves, as linked in the question. Any definition I give is based solely on my observation of the contents of those files. For the slow case, \"md FAIL 0\" is being inserted when there's a blank line _not_ preceded by FAIL (which becomes \"md FAIL 1\"). Tests without a FAIL are expected to pass by default, but we have to set the FAIL variable to 0 to affirmatively indicate this (otherwise, it would stay 1 after the first expected-failure test)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T09:16:19.133", "Id": "83509", "Score": "0", "body": "Would it be possible to include the essence of the external references into your question? It's always better to have a self-contained question since external sites might be taken down and it makes it a lot easier for readers to get an overview and help you." } ]
[ { "body": "<p>Rewriting it in AWK would definitely result in a huge improvement, enough to say that writing it in Bash was a poor choice. Many of the considerations for this problem favour AWK:</p>\n\n<ul>\n<li>The input is line-oriented.</li>\n<li>Nearly every line has the same <code>key = value</code> format, except for the headers with <code>[key = value]</code> instead. Most importantly, they all share the same <code>=</code> delimiter.</li>\n<li>All of the processing can be done using simple text transformations and arithmetic.</li>\n<li>Processing can be done in one pass, with very little state to maintain.</li>\n</ul>\n\n<p>I think that Bash is underpowered for this problem, and is therefore a poor fit. The repeated use of <code>sed</code> is not only a performance barrier; the constant intermingling of Bash and sed hurts readability.</p>\n\n<p>Of course, any other general-purpose programming language would also work. However, considering that any system that has Bash will also have AWK, and AWK is just powerful enough to handle this problem comfortably, that's what I would choose. Besides, you already used a tiny bit of AWK within your Bash script — why not go all the way? ☺</p>\n\n<p>The AWK program below is much faster than your Bash script, and in my opinion, more readable. That said, there are some minor improvements that could be made to the Bash-based solution. I may eventually return to review it.</p>\n\n\n\n<pre><code>#!/usr/bin/awk -f\n\nBEGIN {\n FS = \" = \";\n NUM_HEADERS = 0;\n}\n\n######################################################################\n# Skip first 6 lines\n######################################################################\nFNR &lt; 7 { next }\n\n######################################################################\n# dos2unix\n######################################################################\n{ sub(\"\\r$\", \"\"); }\n\n######################################################################\n# Read headers, of the form\n# [Keylen = 96]\n######################################################################\n/\\[.*\\]/ {\n gsub(\"\\\\[|\\\\]\", \"\");\n HEADER_NAME[NUM_HEADERS++] = $1;\n HEADER_VALUE[$1] = $2;\n next;\n}\n\n######################################################################\n# End of headers. Determine output file, and write out the headers.\n# Output filename is of the form\n# [BASEFILE][Keylen]-[IVlen]-[PTlen]-[AADlen]-[Taglen].mspd\n######################################################################\nNUM_HEADERS &gt; 0 {\n if (OUT) {\n end_of_stanza();\n close(OUT);\n }\n basename = FILENAME;\n sub(\"\\\\..*\", \"\", basename);\n sub(\"[0-9]*$\", \"\", basename);\n OUT = sprintf(\"%s%d-%d-%d-%d-%d.mspd\",\n basename,\n HEADER_VALUE[\"Keylen\"],\n HEADER_VALUE[\"IVlen\"],\n HEADER_VALUE[\"PTlen\"],\n HEADER_VALUE[\"AADlen\"],\n HEADER_VALUE[\"Taglen\"]);\n\n for (h = 0; h &lt; NUM_HEADERS; h++) {\n header_name = HEADER_NAME[h];\n hex_value = sprintf(\"%04x\", HEADER_VALUE[header_name]);\n printf \"mw %s 0x%s 0x%s\\n\", header_name, substr(hex_value, 3, 2), substr(hex_value, 1, 2) &gt; OUT;\n }\n NUM_HEADERS = 0;\n FAIL = \"\";\n next;\n}\n\n######################################################################\n# Split values of Key, IV, PT, AAD, CT, and Tag into hex bytes\n######################################################################\n$1 ~ /^(Key|IV|PT|AAD|CT|Tag)$/ &amp;&amp; $2 ~ /^([0-9a-f][0-9a-f])+$/{\n split($2, a, \"\");\n $2 = \"\";\n for (i = 1; i &lt; length(a); i += 2) {\n $2 = sprintf(\"%s 0x%s%s\", $2, a[i], a[i + 1]);\n }\n $2 = substr($2, 2);\n}\n\n######################################################################\n# Stanza processing: mark failure or non-failure\n######################################################################\nfunction end_of_stanza() {\n if (FAIL != \"\") {\n print \"mw FAIL\", FAIL &gt; OUT;\n print \"read gcm_test_round.mspd\\n\" &gt; OUT;\n }\n FAIL = \"0\";\n print \"\" &gt; OUT;\n}\n\n$1 == \"FAIL\" {\n FAIL = \"1\";\n next;\n}\n$1 == \"Count\" {\n end_of_stanza();\n next;\n}\nEND {\n end_of_stanza();\n close(OUT);\n}\n\n######################################################################\n# Normal body line\n######################################################################\n!/^$/ {\n if ($2 == \"\") {\n print \"mw\", $1 &gt; OUT;\n } else {\n print \"mw\", $1, $2 &gt; OUT;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:39:57.213", "Id": "83534", "Score": "0", "body": "Why not AWK from the start? Reasons: 1. when I started writing this script, I didn't think it would be as complicated as it wound up, 2. I've never before been unable to do something with sed + coreutils (splitting groups to files stumped me, here), and 3. I'd run the script so infrequently, performance wouldn't be critical. I contemplate using AWK so infrequently (and find sed so much more comfortable), that I've avoided adding that tool to my bag, and I wasn't sure I'd be able to do all I needed in one AWK script. It also doesn't help that it resembles a language I already abhor (Perl). :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:47:35.773", "Id": "83539", "Score": "0", "body": "I have the benefit of hindsight. Consider this a Version 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T18:17:55.447", "Id": "83549", "Score": "0", "body": "Yeah, I'm reading through this carefully and trying as hard as I can to not let my Perl bigotry get in the way. I've already made a small modification to make the start-of-file skip a bit less braindead (I'd also wanted to do this in the original script)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T10:40:14.757", "Id": "47641", "ParentId": "47631", "Score": "2" } } ]
{ "AcceptedAnswerId": "47641", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T04:21:59.633", "Id": "47631", "Score": "6", "Tags": [ "performance", "bash", "converting", "sed" ], "Title": "Bash script to convert NIST vectors to debug scripts" }
47631
<p>I've wanted to make a Pong game for awhile, so I eventually got around to it now, it didn't take that long except for the reflections which I unfortunately didn't end up being satisfied with. I wanted to implement a more elegant solution utilizing trigonometry to calculate ball curvature upon impact, but alas it was my shortcomings in math, not programming, that prevented me from implementing something like this. </p> <p>I did a decent attempt at asking for helping (Math SE, Physics SE, Stack Overflow, Game Dev SE) and I had a look at other source codes of Pong. It seems that the approach people are taking to ball reflection is vastly different from version to version, some people also opt for very elegant solutions using vectors, trigonometry, angle of incidence and even taking the ball mass and radius into account, while others like me opt for a simple reflection. </p> <p>Other than that I feel pretty satisfied, the code definitely isn't very light-weight compared to some other implementations that I've seen but I hope it makes up for that in being very readable and well-structured.</p> <p>I'd love feedback on the rest of the code.</p> <p><strong>IGameView.cs</strong></p> <pre><code>interface IGameView { Size Boundaries { get; } /// &lt;summary&gt; /// This method will draw all game objects. /// &lt;/summary&gt; /// &lt;param name="ball"&gt;&lt;/param&gt; /// &lt;param name="paddle"&gt;&lt;/param&gt; /// &lt;param name="paddle2"&gt;&lt;/param&gt; void Draw(Ball ball, Paddle paddle, Paddle paddle2); void PlayerWon(Player winner); /// &lt;summary&gt; /// Releases all the resources allocated by this IGameView. /// &lt;/summary&gt; void Release(); } </code></pre> <p><strong>IGameController.cs</strong></p> <pre><code> internal enum Move { Up, Down } interface IGameController { Player[] Players { get; } PeriodicTick GameTicker { get; } /// &lt;summary&gt; /// Initializes this instance of the IGameController. /// &lt;/summary&gt; void Start(); void Refresh(); void PlayerScore(Player player); void MovePaddle(int playerId, Move move); event PlayerWonHandler PlayerWin; } </code></pre> <p><strong>Delegates.cs</strong></p> <pre><code>namespace Pong { internal delegate void PlayerWonHandler(Player winner); internal delegate void TickEventHandler(); internal delegate void CollisionHandler(CollisionType collisionType); } </code></pre> <p><strong>NativeMethods.cs</strong></p> <pre><code>internal static class NativeMethods { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetKeyboardState(byte[] lpKeyState); } </code></pre> <p><strong>Keyboard.cs</strong></p> <pre><code>static class Keyboard { public static Keys[] GetPressedKeys() { Byte[] keys = new Byte[256]; var pressedKeys = new List&lt;Keys&gt;(); if (!NativeMethods.GetKeyboardState(keys)) { int err = Marshal.GetLastWin32Error(); throw new Win32Exception(err); } for (int i = 0; i &lt; keys.Length; i++) { byte key = keys[i]; if ((key &amp; 0x80) != 0) { pressedKeys.Add((Keys)i); } } return pressedKeys.ToArray(); } } </code></pre> <p><strong>Vector.cs</strong></p> <pre><code>struct Vector { public int X; public int Y; public Vector(int x, int y) { X = x; Y = y; } } </code></pre> <p><strong>PeriodicTick.cs</strong></p> <pre><code>class PeriodicTick { private int tickInterval; // Defines how often you want the Tick event to be raised in milliseconds public CancellationTokenSource CancellationTokenSrc { get; set; } public Task TickTask { get; private set; } public event TickEventHandler Tick; public PeriodicTick(int tickInterval) { this.tickInterval = tickInterval; CancellationTokenSrc = new CancellationTokenSource(); } public void Start() { var token = CancellationTokenSrc.Token; TickTask = Task.Factory.StartNew( () =&gt; { Thread.CurrentThread.Name = "TickThread"; while (true) { if (token.IsCancellationRequested) { break; } Task.Delay(tickInterval).Wait(); // Wait for tickInterval milliseconds... Tick(); // ...Then tick! } }, token); } } </code></pre> <p><strong>Player.cs</strong></p> <pre><code>class Player { private static int ctr; public readonly int Id; public int Score { get; set; } public Paddle Paddle { get; set; } public Player(Orientation orientation, IGameView view) { Paddle = new Paddle(orientation, view); Id = ctr++; } } </code></pre> <p><strong>Paddle.cs</strong></p> <pre><code>internal enum Orientation { Left, Right } class Paddle { public Point Position; public readonly Orientation Orientation; public readonly Size Size = new Size(0, 20); public Paddle(Orientation orientation, IGameView view) { Orientation = orientation; // Paddle starting position should be in the center Y-axis with differing X values int x = (orientation.Equals(Orientation.Left)) ? view.Boundaries.Width - (view.Boundaries.Width / 20) : view.Boundaries.Width / 20; Position = new Point(x, view.Boundaries.Height / 2); } public Point[] GetHitbox() { var hitLocations = new List&lt;Point&gt;(); for (int i = 0; i &lt; this.Size.Height; i++) { for (int j = 0; j &lt; 3; j++) { if (this.Orientation.Equals(Orientation.Right)) { hitLocations.Add(new Point(this.Position.X + j, this.Position.Y + i)); } else { hitLocations.Add(new Point(this.Position.X - j, this.Position.Y + i)); } } } return hitLocations.ToArray(); } } </code></pre> <p><strong>GameController.cs</strong></p> <pre><code>class GameController : IGameController { private const int WINNING_SCORE = 10; private readonly Ball ball; public readonly IGameView view; public event PlayerWonHandler PlayerWin; public Player[] Players { get; private set; } public PeriodicTick GameTicker { get; private set; } public GameController(IGameView view, Player player, Player player2) { this.view = view; Players = new Player[] { player, player2 }; ball = new Ball(view, this); } public void Start() { const int REFRESH_RATE = 25; // TIME IN MILLISECONDS IN WHICH THE GAME RECALCULATES ALL OBJECT POSITIONS // CHANGING THIS CAN DRAMATICALLY AFFECT GAME PERFORMANCE!!!! GameTicker = new PeriodicTick(REFRESH_RATE); GameTicker.Tick += Refresh; // Each time our PeriodicTick ticks we will refresh the ball position and angle //Start the ticker... GameTicker.Start(); //...then get the ball moving ball.ballController.Center(Players[new Random().Next(Players.Length)]); } public void Refresh() { //Update positions of ball here... ball.ballController.UpdatePosition(); //.. Then call Draw() in the IGameView view.Draw(ball, Players[0].Paddle, Players[1].Paddle); } public void MovePaddle(int playerId, Move move) { const int MOVE_MODIFIER = 15; // THIS DEFINES HOW MANY PIXELS TO MOVE THE PADDLE PER MOVE CALL int id = playerId; if (move.Equals(Move.Up)) { Players[id].Paddle.Position.Y = Math.Max(Players[id].Paddle.Position.Y - MOVE_MODIFIER, 0); } else { // We must add the length of the paddle here because it will transgress the boundary on it's other side Players[id].Paddle.Position.Y = Math.Min( Players[id].Paddle.Position.Y + MOVE_MODIFIER, view.Boundaries.Height - Players[id].Paddle.Size.Height); } } public void PlayerScore(Player player) { if (++player.Score == (WINNING_SCORE)) // Check if player wins if so... { // ... Raise PlayerWin event, cancel the GameTicker // and release all resources used by this instance of IGameView PlayerWin(player); GameTicker.CancellationTokenSrc.Cancel(); view.Release(); } ball.ballController.Center(player); // Recenter the ball } } </code></pre> <p><strong>Ball.cs</strong></p> <pre><code>class Ball { private readonly IGameView view; private readonly IGameController gameController; public readonly BallController ballController; private Vector velocity; private double angle; private event CollisionHandler Collision; public Point Point { get; private set; } public Ball(IGameView view, IGameController controller) { this.view = view; this.gameController = controller; ballController = new BallController(this); } internal class BallController { private Ball ball; private Random rng = new Random(); private int baseMod; public BallController(Ball ball) { this.ball = ball; ball.Collision += OnCollision; } public void Center(Player server) { ball.Point = new Point(ball.view.Boundaries.Width / 2, ball.view.Boundaries.Height / 2); //The ball will start moving from the center Point towards one of the different sides ball.angle = (server.Paddle.Orientation.Equals(Orientation.Left)) ? Math.PI : Math.PI * 2; //Re-randomize the base velocity of the ball baseMod = Math.Max(3, rng.Next(6)); } public void UpdatePosition() { ball.velocity.X = (ball.angle == Math.PI) ? -5 : 5; ball.Point = new Point(ball.Point.X + ball.velocity.X, ball.Point.Y + ball.velocity.Y); //Check if the suggested point is beyond the boundaries of the window if (ball.Point.X &gt; ball.view.Boundaries.Width || ball.Point.Y &gt; ball.view.Boundaries.Height || ball.Point.X &lt; 0 || ball.Point.Y &lt; 0) { ball.Collision(CollisionType.Boundary); // If it does raise collision event } //Check if the new point collides with the hitbox of a player paddle if (ball.gameController.Players[0].Paddle.GetHitbox().Any(point =&gt; point.Equals(ball.Point)) || ball.gameController.Players[1].Paddle.GetHitbox().Any(point =&gt; point.Equals(ball.Point))) { ball.Collision(CollisionType.Paddle); } } public void OnCollision(CollisionType collisionType) { switch (collisionType) { case CollisionType.Paddle: ball.angle = (ball.angle == Math.PI) ? Math.PI * 2 : Math.PI; ball.velocity.Y = (ball.angle == Math.PI) ? 5 : -5; break; case CollisionType.Boundary: // If the collision is with a window boundary check if we need to bounce the ball // or make a player score if (ball.Point.X &gt; ball.view.Boundaries.Width || ball.Point.X &lt; 0) { // If the angle of the ball of the ball is greater than ½ rad then the left paddle was // the shooter so he should score if (ball.angle &gt; Math.PI / 2) { var scoringPlayer = Array.Find(ball.gameController.Players, player =&gt; player.Paddle.Orientation.Equals(Orientation.Left)); ball.gameController.PlayerScore(scoringPlayer); } else // If not, then it's the right paddle { var scoringPlayer = Array.Find(ball.gameController.Players, player =&gt; player.Paddle.Orientation.Equals(Orientation.Right)); ball.gameController.PlayerScore(scoringPlayer); } } else { ball.velocity.Y = (ball.angle == Math.PI) ? -5 : 5; } break; } } } } </code></pre> <p><strong>CollisionType.cs</strong></p> <pre><code>enum CollisionType { Paddle, Boundary } </code></pre> <p><strong>GameForm.cs</strong></p> <pre><code>public partial class GameForm : Form, IGameView { public Size Boundaries { get; private set; } private Bitmap gameObjects; private IGameController gameController; private readonly Pen pen = new Pen(Color.White, 5); private readonly Font myFont = new System.Drawing.Font("Helvetica", 40, FontStyle.Regular); private Keys[] inputKeys = new Keys[] { Keys.Up, Keys.Down, Keys.W, Keys.S }; public GameForm() { InitializeComponent(); } private void GameForm_Load(object sender, EventArgs e) { Boundaries = new Size(ClientSize.Width, ClientSize.Height); // Always set boundaries to size of the view control gameController = new GameController(this, new Player(Orientation.Left, this), new Player(Orientation.Right, this)); gameController.PlayerWin += (this as IGameView).PlayerWon; // Start a seperate worker task for game logic Task.Factory.StartNew( () =&gt; { System.Threading.Thread.CurrentThread.Name = "WorkerThread"; gameController.Start(); }); gameObjects = new Bitmap(Boundaries.Width, Boundaries.Height); } void IGameView.PlayerWon(Player winner) { MessageBox.Show(String.Concat("Player ", winner.Id.ToString() + " won!")); } void IGameView.Draw(Ball ball, Paddle paddle, Paddle paddle2) { // If the game is over we need to cease drawing as that will throw an exception // Due to PlayerWin event calling a release of drawing resources in this instance of IGameView if (gameController.Players.Any(player =&gt; player.Score &gt;= 10)) { return; } //Draw to bitmap using (Graphics gameObj = Graphics.FromImage(gameObjects)) { gameObj.Clear(Color.Black); // Clear area to allow redrawing of all game objects gameObj.DrawEllipse(pen, new Rectangle(ball.Point, new Size(5, 5))); // Ball gameObj.DrawLine(pen, new Point(Size.Width / 2, 0), new Point(Size.Width / 2, Size.Height)); // Net gameObj.DrawString(gameController.Players[0].Score.ToString(), myFont, pen.Brush, Boundaries.Width / 2.7f, 0); // Score p1 gameObj.DrawString(gameController.Players[1].Score.ToString(), myFont, pen.Brush, Boundaries.Width / 1.8f, 0); // Score p2 gameObj.DrawLine(pen, paddle.Position, new Point(paddle.Position.X, paddle.Position.Y + paddle.Size.Height)); gameObj.DrawLine(pen, paddle2.Position, new Point(paddle2.Position.X, paddle2.Position.Y + paddle2.Size.Height)); Invalidate(); // Invalidate to force redraw of game objects } } void IGameView.Release() { pen.Dispose(); myFont.Dispose(); } private void GameForm_Paint(object sender, PaintEventArgs e) { Graphics graphics = e.Graphics; graphics.DrawImage(gameObjects, new Point(0, 0)); // No dispose here because we're using double buffering } private void GameForm_KeyDown(object sender, KeyEventArgs e) { //Check if pressed key equals any of the player assigned keys.. If so call MovePaddle() foreach (Keys key in Keyboard.GetPressedKeys()) { if (inputKeys.Any(entry =&gt; entry.Equals(key))) { switch (key) { case Keys.Up: gameController.MovePaddle(0, Pong.Move.Up); break; case Keys.Down: gameController.MovePaddle(0, Pong.Move.Down); break; case Keys.W: gameController.MovePaddle(1, Pong.Move.Up); break; case Keys.S: gameController.MovePaddle(1, Pong.Move.Down); break; } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T20:19:27.440", "Id": "83562", "Score": "1", "body": "For an extra challenge think about how you can pull all your pong code out into a seperate library and then have another type of GUI (such as WPF, or Silverlight, or ASP)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T20:23:34.907", "Id": "83563", "Score": "0", "body": "I will make sure to do so :). This was my first attempt at an MVC design pattern and \"I think\" I've done a decent job at decoupling the game logic from the UI.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T20:27:30.053", "Id": "83564", "Score": "0", "body": "good job for your first time. I agree that you removed your game logic from your UI, but your game logic depends on WinForms (a type of UI). It would be great if they both were independant" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T06:02:24.880", "Id": "83709", "Score": "1", "body": "Wohoo! Succesfully exported all game logic to a seperate class library in the same solution this morning and the game didn't break. I had about 2 dozen accessability modifiers that I had to change to make it work but other than that I didn't have to modify anything. Next step will be to try and make it work with ASP.NET." } ]
[ { "body": "<p><strong>IGameView.cs</strong></p>\n\n<p>You have a method called Release with the comments of Release as Releases all the resources allocated by this IGameView. This is the purpose of the interface IDisposable in the System namespace. I would recommend changing to that instead of Release.</p>\n\n<p><strong>IGameController.cs</strong></p>\n\n<p>You have a method called Start, but your comment says that it initializes the instance. It's not until I go GameController do we see that you do both an initialization AND a start. This is a violation of the Single Responsibility Pattern (SRP). In short it says your class should be responsible for one thing, your methods should only do one thing, and your variables should only mean one thing. It would be better to use your constructor to initialize all your variables, or to make a method in your interface called Initialize(). The context would say that you should use a method in your interface.\nYour method MovePaddle takes a player ID and a direction, and uses that to move the paddle.\nYour method Refresh is a good idea, but when I look at the implementation I feel like you lie about it's purpose a little bit. You have a GameTicker that calls it... I think it would be better if PeriodicTick had a instance of IGameController instead of the other way around, and then put the Tick to call the refresh command from IGameController. Although it does the EXACT same thing, this would make more sense to put that in the Ticker because I have to ask my self...well what does this do? I can't tell by looking at PeriodicTick. all I know is that it can be cancled. Last note about this too is that it is not a good idea to have a interface depend on a class. Rather it is always a better idea to have a Class depend on a interface.</p>\n\n<p><strong>GameController.cs</strong></p>\n\n<p>there are 2 instances where you have a constant defined in the code. MOVE_MODIFER being one, REFRESH_RATE being another. Nothing wrong with having these, but as your comment says it critically affects the performance of the game. Things like this should be put into a config file, or a setting that can be edited from your form. It may be a good refresh for your computer, but what about mine? how about all 4 of my computers?</p>\n\n<p><strong>In General</strong></p>\n\n<p>Try not to expose your variables in your classes. Expose your methods that act upon your variables. And example of this would be something like this.</p>\n\n<pre><code>public static void main(string[] args)\n{\n BadGasTank badGasTank = new BadGasTank(15);//initialize with 15gallons\n car = new Car(badGasTank);\n car.Drive(100); //drive 100 miles\n double gallonsUsed = 15 - badGasTank.Gallons;\n\n GoodGasTank gasTank = new GoodGasTank(SomeUnknownAmount);\n car = new Car(gasTank);\n car.Drive(100); //drive 100 miles\n gallonsUsed = gasTank.getGallonsUsed();\n}\n</code></pre>\n\n<p>So in your case it would be better to change your PeriodicTick to something like this.</p>\n\n<pre><code>class PeriodicTick\n{\n private int tickInterval; // Defines how often you want the Tick event to be raised in milliseconds\n private readonly IGameController gameController;\n private CancellationTokenSource CancellationTokenSrc;\n\n public PeriodicTick(int tickInterval, IGameController controller)\n {\n this.tickInterval = tickInterval;\n CancellationTokenSrc = new CancellationTokenSource();\n this.gameController = controller;\n }\n\n public void Start()\n {\n var token = CancellationTokenSrc.Token;\n var tickTask = Task.Factory.StartNew(\n () =&gt;\n {\n Thread.CurrentThread.Name = \"TickThread\";\n while (true)\n {\n if (token.IsCancellationRequested) { break; }\n Task.Delay(tickInterval).Wait(); // Wait for tickInterval milliseconds...\n this.gameController.Refresh();\n }\n },\n token);\n }\n\n public void Stop()\n {\n CancellationTokenSrc.Cancel();\n }\n}\n</code></pre>\n\n<p>Really it comes down to it is a bad idea to manipulate/depend on another classes properties. As is the case here <code>gameController.Players.Any(player =&gt; player.Score &gt;= 10)</code> It would be better to have change it to something like <code>gameController.IsGameOver()</code></p>\n\n<p><strong>Keyboard.cs</strong></p>\n\n<p>this class can be a little tricky. But with the principle as before we want to make sure that we don't depend on another classes variables. Granted it may not feel like a variable in this case because you are calling GetKeyboardState from NativeMethods. (side note: I personally would move GetKeyboardState to Keyboard, and mark it as private, but there is nothing wrong with the way you have it now) Now making Keyboard a static class might not be the best idea here. In your GameForm you expressly ask for which keys are down. This might benefit from a queue working in the background and firing an event. Some pseudo code:</p>\n\n<pre><code>class Keyboard()\n{\n private readonly Keys[] keysToWatchFor;\n private bool keepThreadAlive;//or use cancel token like you did before\n public Keyboard(params Keys[] keysToWatchFor)\n {\n this.keysToWatchFor = keysToWatchFor;\n }\n\n public void Start()\n {\n //Make a thread and start it\n }\n public void Stop()\n {\n //Cancel Thread \n }\n private void MonitorKeyPresses()\n {\n while(keepThreadAlive)\n {\n Thread.Sleep(10);\n byte[] keys = nativeMethods.GetKeyboardState(); //&lt;- Notice this! good idea\n for(int i=0; i&lt;keysToWatchFor.Length; i++)\n {\n int key = keysToWatchFor[i];\n if(IsKeyDown(keys[key]))\n FireKeyPressed(key);\n }\n }\n }\n private static bool IsKeyDown(byte keyValue)\n {\n return ((keyValue &amp; 0x80) != 0);\n }\n\n public event KeyPressedEventHandler KeyPressed;\n private void FireKeyPressed(int key)\n {\n if(KeyPressed != null) KeyPressed(key);\n }\n}\n</code></pre>\n\n<p>I would consider putting in a few methods in Player such as MovePaddleUp, and MovePaddleDown. this could possible lead to you not needing the enum Move.</p>\n\n<p>In the end I would think about the few principles I've stated and think over the rest of your classes that I did not cover and see if you can't work them just a little bit more. Lastly, I've ALWAYS hated it when when a Form extends something other than a Form. This makes it very fragile. Instead just override/subscribe to events in your form that you want your controller to do (like you already do with KeyDown)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T20:11:41.633", "Id": "47675", "ParentId": "47635", "Score": "3" } } ]
{ "AcceptedAnswerId": "47675", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T08:27:49.543", "Id": "47635", "Score": "2", "Tags": [ "c#", "object-oriented", "game", "multithreading", "collision" ], "Title": "Pong Game in WinForms" }
47635