body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I want you to pick my code apart and give me some feedback on how I could make it better or more simple. This code finds a common ancestor for binary search tree. This code accounts duplicates as well as incomplete tree, and also throws an exception if input element is not in the tree.</p> <pre><code>public class LeastCommonAncestorBST { private TreeNode root; private static class TreeNode { TreeNode left; TreeNode right; int item; TreeNode (TreeNode left, TreeNode right, int item) { this.left = left; this.right = right; this.item = item; } } public void makeBinarySearchTree(Integer[] a) { for (int i : a) { addElement(i); } } public void addElement(int element) { if (root == null) { root = new TreeNode(null, null, element); } else { TreeNode prevNode = null; TreeNode node = root; while (node != null) { prevNode = node; if (element &lt;= node.item) { node = node.left; } else { node = node.right; } } if (element &lt;= prevNode.item) { prevNode.left = new TreeNode(null, null, element); } else { prevNode.right = new TreeNode(null, null, element); } } } public int leastCommonAncestor(int n1, int n2) { TreeNode node = findLCA(root, n1, n2); if (node != null) { return node.item; } else { throw new IllegalArgumentException(" Input was not valid "); } } private TreeNode findLCA(TreeNode node, int n1, int n2) { if (node == null) return null; if (node.item &gt; n1 &amp;&amp; node.item &gt; n2) { return findLCA(node.left, n1, n2); } if (node.item &lt; n1 &amp;&amp; node.item &lt; n2) { return findLCA(node.right, n1, n2); } boolean bothExist = doesExist(node, n1) &amp;&amp; doesExist(node, n2); return bothExist ? node : null; } private boolean doesExist(TreeNode node, int n) { if (node == null) { return false; } if (n &lt; node.item) { return doesExist(node.left, n); } if (n &gt; node.item ) { return doesExist(node.right, n); } return true; } } </code></pre>
[]
[ { "body": "<p>Most of the code is pretty good!</p>\n\n<p>I find your interface a bit weird. Instead of <code>public void makeBinarySearchTree(Integer[] a)</code>, I suggest <code>public void addElements(int[] elements)</code> to be consistent with your <code>addElement(int)</code> method. There's no need to tell everyone that you're making a binary search tree, since that information is encoded into your class name already.</p>\n\n<p>You might want to generalize the code to handle any <code>Comparable</code>, not just <code>int</code>s. You would get more flexibility for little additional effort.</p>\n\n<p>Instead of throwing <code>IllegalArgumentException</code>, I would throw <code>NoSuchElementException</code>. In fact, I would change <code>doesExist()</code> to</p>\n\n<pre><code>private TreeNode find(TreeNode start, int element) {\n if (start == null) {\n throw new NoSuchElementException(Integer.toString(element));\n }\n if (element &lt; start.item) {\n return find(start.left, element);\n }\n if (element &gt; start.item) {\n return find(start.right, element);\n }\n // Assertion makes the code more readable\n assert element == start.item;\n return start;\n}\n</code></pre>\n\n<p>That way, you can let the exception propagate up all the way, and it would tell you which of the two numbers passed to <code>leastCommonAncestor()</code> is missing.</p>\n\n<p>Your <code>addElement()</code> is a bit repetitive and can be simplified:</p>\n\n<pre><code>public void addElement(int element) {\n // No matter what happens, we're going to attach this\n // new node somewhere.\n TreeNode newNode = new TreeNode(null, null, element);\n\n if (root == null) {\n root = newNode;\n return; // Return early to avoid a layer of nesting\n }\n\n TreeNode node = root;\n while (true) {\n if (element &lt;= node.item) {\n // Test for null before following the pointer.\n // That relieves you from having to keep track\n // of the parent node, and also avoids having\n // to decide again whether to attach to the\n // left or right.\n if (node.left == null) {\n node.left = newNode;\n return;\n }\n node = node.left;\n } else {\n if (node.right == null) {\n node.right = newNode;\n return;\n }\n node = node.right;\n }\n }\n}\n</code></pre>\n\n<h1>Follow-Up Q &amp; A</h1>\n\n<blockquote>\n <p>Not understanding your feedback - I suggest <code>public void\n addElements(int[] elements)</code> to be consistent with your <code>addElement(int)</code>\n method.</p>\n</blockquote>\n\n<p>In Java, you use unboxed primitives most of the time. Boxed types are rare: generally they are only used in Collections (which can't store primitives) and when you want to store a value that might be <code>null</code>. An <code>Integer[]</code> array is therefore rather unnatural — it's neither an <code>int[]</code> nor a <code>List&lt;Integer&gt;</code>, both of which would be more likely to occur.</p>\n\n<blockquote>\n <p>As regards to cleaning up <code>addElement()</code> I had few concerns</p>\n \n <ol>\n <li><p><code>while(true)</code> is said to be bad</p></li>\n <li><p>more checks in your method (a) <code>while(true)</code> (b) null check\n (c) comparison, while my code does only 2 of them for most traversal\n part (a) null and (b) compare.</p></li>\n </ol>\n</blockquote>\n\n<p>There are two common objections to <code>while (true)</code>: one invalid concern about efficiency, and one legitimate concern about style.</p>\n\n<p>Many decades ago, simplistic C compilers might take <code>while (true)</code> literally, and generate code to load 1 into a register, check whether the register was non-zero, and execute a conditional jump. Modern C compilers and all Java compilers are smart enough to handle <code>while (true)</code> efficiently, generating nothing but an unconditional <code>goto</code> at the end of the loop. You can verify this by inspecting the bytecode:</p>\n\n<pre><code>$ cat WhileTrue.java\npublic class WhileTrue {\n private WhileTrue() {} // Suppress default constructor\n\n public static void main(String[] args) {\n System.out.println(\"Before while loop\");\n while (true) {\n System.out.println(\"In while loop\");\n }\n // Compiler would detect this as unreachable\n // System.out.println(\"After while loop\");\n }\n}\n\n$ javap -c WhileTrue\nCompiled from \"WhileTrue.java\"\npublic class WhileTrue extends java.lang.Object{\npublic static void main(java.lang.String[]);\n Code:\n 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;\n 3: ldc #3; //String Before while loop\n 5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V\n 8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;\n 11: ldc #5; //String In while loop\n 13: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V\n 16: goto 8\n\n}\n</code></pre>\n\n<p>That means that your second objection is invalid, since <code>while (true)</code> is not a check. In fact, your original version had more conditionals since you had to decide which side to append to after exiting the loop.</p>\n\n<p>As previously mentioned, there is another problem with <code>while (true)</code>, which is that it keeps the reader in suspense. Most programs are not intended to run in an infinite loop. Therefore, when you see <code>while (true)</code>, you immediately suspect that something within the loop must eventually cause it to terminate: a <code>break</code>, a <code>return</code>, or an exception. Therefore, whenever you feel the urge to write <code>while (true)</code>, it's always worthwhile to think about whether it is possible to restructure the code such that the termination condition can be expressed in the loop header, rather than buried in the loop body. In many instances, it <em>is</em> possible, but here, I think that my proposal is already optimal.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-28T18:46:14.660", "Id": "51035", "Score": "0", "body": "Not understanding your feedback - I suggest public void addElements(int[] elements) to be consistent with your addElement(int) method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-28T18:51:06.577", "Id": "51036", "Score": "0", "body": "As regards to cleaning up addElement() I had few concerns 1) while(true) is said to be bad (2) more checks in your method (a) while(true) (b) null check (c) comparison, while my code does only 2 of them for most traversal part (a) null and (b) compare. Let me know your thoughts, Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-28T21:55:44.887", "Id": "51044", "Score": "1", "body": "I've added a Follow-up Q & A section to address your concerns." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T23:22:41.777", "Id": "31394", "ParentId": "31334", "Score": "4" } } ]
{ "AcceptedAnswerId": "31394", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T00:35:03.810", "Id": "31334", "Score": "2", "Tags": [ "java", "tree" ], "Title": "Least common ancestor for binary search tree" }
31334
<p>My professor wants me to do this:</p> <blockquote> <p>Write a number of interchangeable counters using the Counter interface below:</p> </blockquote> <pre><code>public interface Counter { /** Current value of this counter. */ int value(); /** Increment this counter. */ void up(); /** Decrement this counter. */ void down(); } </code></pre> <p>I need comments on my work so far. Do you think it's sufficient? How do I work on the ResetableCounter? I'm very new to Java and it's been a long time since I've done C++.</p> <p>Develop the following:</p> <blockquote> <p>An interface ResetableCounter that supports the message void reset() in addition to those of Counter.</p> </blockquote> <p>Here's what I did:</p> <pre><code>public interface ResetableCounter { void reset(); int value(); void up(); void down(); } </code></pre> <blockquote> <p>An implementation of ResetableCounter called BasicCounter that starts at the value 0 and counts up and down by +1 and -1 respectively.</p> </blockquote> <p>Here's what I did:</p> <pre><code>public class BasicCounter implements ResetableCounter { int counterVariable = 0; public static void main(String[] args) { BasicCounter cnt = new BasicCounter(); cnt.up(); cnt.down(); System.out.printf("The value is %d", cnt.counterVariable); } public void reset() { this.counterVariable = 0; } public int value() { return this.counterVariable; } public void up() { ++this.counterVariable; } public void down() { --this.counterVariable; } } </code></pre> <blockquote> <p>An implementation of ResetableCounter called SquareCounter that starts at the value 2, counts up by squaring its current value, and counts down by taking the square root of its current value (always rounding up, i.e. 1.7 is rounded to 2, just like 1.2 is rounded to 2).</p> </blockquote> <p>Here's what I did:</p> <pre><code>public class SquareCounter implements ResetableCounter { int counterVariable = 2; public static void main(String[] args) { SquareCounter cnt = new SquareCounter(); cnt.up(); cnt.down(); double d = Math.ceil(cnt.counterVariable); System.out.printf("The value is %f", d); } public void reset() { this.counterVariable = 0; } public int value() { return this.counterVariable; } public void up() { Math.pow(this.counterVariable, 2); } public void down() { Math.sqrt(this.counterVariable); } } </code></pre> <blockquote> <p>An implementation of ResetableCounter called FlexibleCounter that allows clients to specify a start value as well as an additive increment (used for counting up) when a counter is created. For example new FlexibleCounter(-10, 3) would yield a counter with the current value -10; after a call to up() its value would be -7.</p> </blockquote> <pre><code>public class FlexibleCounter implements ResetableCounter { public static void main(String[] args) { int start = Integer.parseInt(args[0]); int step = Integer.parseInt(args[1]); start.up(); System.out.printf("The value is %d", count); } public void reset() { this.count = 0; } public int value() { return this.count; } public void up() { this.count = args[0] + args[1]; } public void down() { --this.count; } } </code></pre> <blockquote> <p>All of your implementations should be resetable, and each should contain a main method that tests whether the implementation works as expected using assert as we did in lecture (this is a simple approach to unit testing which we'll talk about more later).</p> </blockquote>
[]
[ { "body": "<p>Your <code>BasicCounter</code> is impeccable. (The indentation of the braces is a bit off, but maybe that's an artifact from pasting into this site.) I would suggest renaming <code>counterVariable</code> to just <code>count</code>, since it would be silly to name everything <code>fooVariable</code> and <code>barVariable</code>.</p>\n\n<p>Your <code>SquareCounter</code> is buggy. Think about what its <code>reset()</code> should do. (Hint: it would be a good idea for the <code>SquareCounter()</code> constructor to call <code>reset()</code>.) Also, in <code>up()</code> and <code>down()</code>, how is <code>counterVariable</code> being modified? (Hint: right now, it <em>isn't</em> being modified.) Note that <code>Math.pow()</code> and <code>Math.sqrt()</code> return <code>double</code> rather than <code>int</code>, so you'll have to cast to <code>int</code> at some point.</p>\n\n<p>Unfortunately, by the rules of this website, we only improve code that has already been written. Therefore, I'll decline to comment on <code>FlexibleCounter</code> until you present something that at least compiles.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T00:01:28.587", "Id": "50005", "Score": "0", "body": "public class FlexibleCounter implements ResetableCounter\n {\n public static void main(String[] args)\n {\n int start = Integer.parseInt(args[0]);\n int step = Integer.parseInt(args[1]);\n start.up();\n System.out.printf(\"The value is %d\", count); \n }\n \n public void reset() {\n this.count = 0;\n }\n\n public int value() {\n return this.count;\n }\n\n public void up() {\n this.count = args[0] + args[1];\n }\n\n public void down() {\n --this.count;\n }\n }" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T01:40:08.910", "Id": "50008", "Score": "0", "body": "what do you think of the FlexibleCounter I just added?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T06:40:19.577", "Id": "50022", "Score": "1", "body": "It matters not what I think. The compiler doesn't like it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T22:14:39.577", "Id": "50118", "Score": "0", "body": "I know. How do I fix it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T23:29:31.463", "Id": "50121", "Score": "0", "body": "Sorry, that's out of scope for this website, where we only improve working code. We also don't hand out homework answers. I'm going to end this discussion on the following two hints. 1) `start` is an `int`; you can't call `.up()` on it. *Should you construct an object?* 2) `args` is not available within the scope of the `up()` method. *What instance variables should you use instead?*" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T02:39:48.917", "Id": "31337", "ParentId": "31335", "Score": "1" } }, { "body": "<blockquote>\n <p>An interface ResetableCounter that supports the message void reset() in <strong>addition to those of Counter</strong>.</p>\n</blockquote>\n\n<p>Your professor provides this statement to you as a <em>hint</em>. It is practically saying <code>ResetableCounter</code> should <code>extends</code> <code>Counter</code> interface.</p>\n\n<p>make <code>countVariable</code> or <code>count</code>(as @200_success suggested) <strong>private</strong>. As no other outside class should have any permission to change the count. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:57:21.090", "Id": "31365", "ParentId": "31335", "Score": "2" } }, { "body": "<p>I would suggest three changes:</p>\n\n<ul>\n<li>All the advanced counter classes, <code>SquareCounter</code>, <code>FlexibleCount</code>, <code>ResettableCounter</code> should extend the Counter interface. </li>\n<li>Do not add the <code>main()</code> method inside the counters. Instead , have a\nseperate class say <code>Driver</code> which creates and calls methods on the\ncounters. </li>\n<li>The counter variable should be private.</li>\n<li><p>In your <code>MathCounter</code>, when calling <code>Math.pow()</code> or <code>Math.sqrt()</code> , please\nassign these value to the counter variable. E.g: <code>counter= Math.pow();</code></p></li>\n<li><p>e. In your flexible counter down instead of using <code>--counter</code>, you\nshould be doing : <code>counter=counter-step</code></p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-11-07T10:22:44.960", "Id": "179805", "ParentId": "31335", "Score": "1" } } ]
{ "AcceptedAnswerId": "31337", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T01:18:42.310", "Id": "31335", "Score": "2", "Tags": [ "java", "homework", "beginner" ], "Title": "Beginner Java Counter code" }
31335
<p>I'm building a mini-app that will display when changes to the DOM have been made by JavaScript. I have all of the functions that I can think of listed in the code. Is there a way to consolidate the functions into one, and have the overrides still function correctly?</p> <pre><code>var DomChanges = (function() { var a = Element.prototype.appendChild , b = Element.prototype.removeChild , c = Element.prototype.insertBefore , d = Element.prototype.insertAfter , e = Element.prototype.insertAttribute , f = Element.prototype.removeAttribute , g = Element.prototype.replaceChild , h = Element.prototype.createElement; Element.prototype.appendChild = function(){ DomChange('appendChild', arguments); a.apply(this, arguments); }; Element.prototype.removeChild = function() { DomChange('removeChild', arguments); b.apply(this, arguments); }; Element.prototype.insertBefore = function() { DomChange('insertBefore', arguments); c.apply(this, arguments); }; Element.prototype.insertAfter = function() { DomChange('insertAfter', arguments); d.apply(this, arguments); }; Element.prototype.insertAttribute = function() { DomChange('insertAttribute', arguments); e.apply(this, arguments); }; Element.prototype.removeAttribute = function() { DomChange('removeAttribute', arguments); f.apply(this, arguments); }; Element.prototype.replaceChild = function() { DomChange('replaceChild', arguments); g.apply(this, arguments); }; Element.prototype.createElement = function() { DomChange('createElement', arguments); h.apply(this, arguments); }; function DomChange (ftype, arguments) { console.log('Dom has been changed'); }; }()); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T17:24:02.287", "Id": "49945", "Score": "0", "body": "Are you unable to use [Mutation Observers](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)?" } ]
[ { "body": "<pre><code>//\n// maybe this:\n//\n\"appendChild removeChild insertBefore insertAfter insertAttribute removeAttribute replaceChild createElement\"\n.split(\" \")\n.forEach(\n function ( ftype ) {\n var corefn = this[ftype]\n this[ftype] = function () {\n DomChange( ftype, arguments );\n return corefn.apply( this, arguments );\n };\n },\n Element.prototype\n);\n//\n// do you overide .innerHTML somehow?\n//\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T15:35:09.473", "Id": "49940", "Score": "0", "body": "It misses .innerHTML embeds, so you don't get notified when that occurs... Posible solution would be to run the timer fn on elements of interest checkig the state of the property, and running a callback when modification is spotted. I've posted the timer factory on SO here (http://stackoverflow.com/questions/18544237/keep-calling-on-a-function-while-mouseover/18557620#18557620\n), so you might consider using it if want to spot the mod." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T03:54:40.250", "Id": "31340", "ParentId": "31336", "Score": "3" } } ]
{ "AcceptedAnswerId": "31340", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T02:26:31.423", "Id": "31336", "Score": "3", "Tags": [ "javascript", "dom" ], "Title": "DOM override app" }
31336
<p>I'm writing a program for my intro to comp sci course where I'm supposed to prompt the user to enter a stream of integers, and then return the largest two. We were given the hint to use a scanner and a while loop with the condition <code>.hasnext</code>.</p> <p>Please review my code:</p> <pre><code>package Homework; import java.util.*; public class Question1 { public static void main(String[] args) { System.out.println("Please type your integers"); Scanner kbd = new Scanner(System.in); int big = 0; int big2 = 0; while(kbd.hasNext()) { int num = kbd.nextInt(); if(num &gt; big) { // opens If statement big2 = big; big = num; } else if((num &lt; big) &amp;&amp; (num &gt; big2)) { big2 = num; } } System.out.print(big); System.out.print(big2); } } </code></pre>
[]
[ { "body": "<p>Your logic is actually correct. Perhaps you just don't know what to type in your terminal window to terminate the input stream. After typing in your numbers, you need to send an end-of-file (\"EOF\") character. On Unix, you do that by hitting <kbd>Control</kbd><kbd>D</kbd>. On Windows, it's <kbd>Control</kbd><kbd>Z</kbd>.</p>\n\n<p>Note that <code>System.in</code> is the program's \"standard input\" stream, which doesn't have to come straight from the keyboard. You can also do</p>\n\n<pre><code>echo 3 1 4 1 5 9 | java Homework.Question1\n</code></pre>\n\n<p>or</p>\n\n<pre><code>java Homework.Question1 &lt; numbers.txt\n</code></pre>\n\n<p>Therefore, <code>kbd</code> is a misnomer. Try naming your Scanner more generically, like <code>scanner</code> or <code>input</code>.</p>\n\n<p>You don't want to print your two numbers with no space in between. It will look like one long number!</p>\n\n<p>The placement of your braces is inconsistent, with the ones for the <code>main</code> function and the <code>else if</code> being closest to conventions. The brace opening the <code>while</code> loop should be on the same line as the <code>while</code> keyword. The brace closing the <code>if</code> block should be pulled further left, aligned with the <code>if</code> keyword, and <code>else</code> can come immediately after.</p>\n\n<pre><code>public class Question1 {\n public static void main(String[] args) {\n ...\n while (...) {\n ...\n if (...) {\n ...\n } else if (...) {\n ...\n }\n }\n System.out.println(...);\n System.out.println(...);\n }\n}\n</code></pre>\n\n<p>You have interpreted the exercise such that duplicate entries in the input are ignored. That's the easier way. If the exercise requires you to print the same number twice when there is a tie for the maximum, then the program is trickier to implement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:35:37.497", "Id": "49925", "Score": "0", "body": "I don't know if I'm doing it right or not but `echo \"3 1 4 1 5 9\" | java Homework.Question1` is giving me `InputMismatchException` but `echo 3 1 4 1 5 9 | java Homework.Question1` [no double quotes] is giving me correct output..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T20:58:48.927", "Id": "50110", "Score": "1", "body": "@tintinmj Oh, you must be on Windows, with different quoting behaviour. I put the double quotes there out of habit on Unix. They aren't necessary, so I'll edit them out of my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T21:09:16.633", "Id": "50113", "Score": "0", "body": "Yes I'm working in Windows." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T05:07:51.293", "Id": "31343", "ParentId": "31339", "Score": "3" } }, { "body": "<pre><code>package Homework;\n</code></pre>\n\n<p>Just for reference, package names are supposed to be lowercase and give information about the origin or author of the package, for example:</p>\n\n<pre><code>package org.yourdomain.yourproject.subpackage;\npackage com.gmail.youremailaddress.yourproject.subpackage;\n</code></pre>\n\n<p>It doesn't matter for tests, prototypes and similar, but please keep it in mind.</p>\n\n<hr>\n\n<pre><code>import java.util.*;\n</code></pre>\n\n<p>Please don't import whole packages. Only import things you need. A half-decent IDE should be able to manage the imports for you anyway.</p>\n\n<hr>\n\n<pre><code>Scanner kbd = new Scanner(System.in);\n</code></pre>\n\n<p>As already said, <code>System.in</code> is not necessarily the keyboard, renaming this variable is advised.</p>\n\n<hr>\n\n<pre><code>while(kbd.hasNext())\n{\n</code></pre>\n\n<p>Java uses a modified K&amp;R-Style for braces, meaning that opening braces are on the same line.</p>\n\n<pre><code>while (scanner.hasNext()) {\n</code></pre>\n\n<hr>\n\n<pre><code>if(num &gt; big) { // opens If statement\n</code></pre>\n\n<p>Such comments are sign that something is wrong with your code. In this case it seems like a left-over from a previous iteration, but generally if you need to comment on braces and where they belong to, you're doing something wrong.</p>\n\n<hr>\n\n<pre><code>System.out.print(big);\nSystem.out.print(big2);\n</code></pre>\n\n<p>Here is a bug, you'll print the output like this:</p>\n\n<pre><code>25984\n</code></pre>\n\n<p>You should use <code>println()</code> and some informative text:</p>\n\n<pre><code>System.out.println(\"First: \" + Integer.toString(big));\nSystem.out.println(\"Second: \" + Integer.toString(big2));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T07:44:04.390", "Id": "31461", "ParentId": "31339", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T03:46:29.320", "Id": "31339", "Score": "3", "Tags": [ "java", "homework", "beginner" ], "Title": "Print largest two integers from a stream" }
31339
<p>I've been practicing implementing a linked list from scratch. Can someone help review my code?</p> <pre><code>class Node { Node next; int num; public Node(int val) { num = val; next = null; } } public class LinkedList { Node head; public LinkedList(int val) { head = new Node(val); } public void append(int val) { Node tmpNode = head; while (tmpNode.next != null) { tmpNode = tmpNode.next; } tmpNode.next = new Node(val); } public void insert(int val) { Node currentNode = head; Node nextNode = head.next; if (currentNode.num &gt; val) { Node tmpNode = head; head = new Node(val); head.next = tmpNode; return; } if (nextNode != null &amp;&amp; nextNode.num &gt; val) { currentNode.next = new Node(val); currentNode.next.next = nextNode; return; } while (nextNode != null &amp;&amp; nextNode.num &lt; val) { currentNode = nextNode; nextNode = nextNode.next; } currentNode.next = new Node(val); currentNode.next.next = nextNode; } public void delete(int val) { Node prevNode = null; Node currNode = head; if (head.num == val) { head = head.next; return; } while (currNode != null &amp;&amp; currNode.num != val) { prevNode = currNode; currNode = currNode.next; } if (currNode == null) { System.out.println("A node with that value does not exist."); } else { prevNode.next = currNode.next; } } public void print() { Node tmpNode = head; while (tmpNode != null) { System.out.print(tmpNode.num + " -&gt; "); tmpNode = tmpNode.next; } System.out.print("null"); } public static void main(String[] args) { LinkedList myList = new LinkedList(5); myList.append(7); myList.append(16); myList.insert(9); myList.insert(4); myList.insert(6); myList.insert(17); myList.delete(16); myList.delete(5); myList.delete(4); myList.delete(17); myList.delete(34); myList.print(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T18:54:51.097", "Id": "57984", "Score": "1", "body": "Just realized my append function doesn't check if head is null at the beginning also. My current function would throw an NPE if it was null." } ]
[ { "body": "<ol>\n<li><p>Your implementation does not allow for an empty list.</p>\n\n<ol>\n<li>It's a bit odd to only have the constructor which takes a node value.</li>\n</ol></li>\n<li><p>You should probably implement the <code>List</code> interface.</p></li>\n<li><p>You should look into generics instead of hard-coding your list to only take <code>int</code>s.</p></li>\n<li><p>It looks like from looking at <code>insert()</code> that you are trying to create an <strong>ordered</strong> linked list. However, <code>append()</code> does not. (If you really want to define an ordered linked list, you can still use generics, but you'll have to use types which are children of <code>Comparable</code>).</p></li>\n<li><p>In <code>insert()</code> and <code>delete()</code> you have some <code>if</code>-conditions followed by a <code>while</code>-loop. My guess is that they can be merged in a single <code>while</code>-loop. I was lazy and haven't tried doing it, so it might not be true.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:24:31.977", "Id": "31361", "ParentId": "31341", "Score": "7" } }, { "body": "<p>What <a href=\"https://codereview.stackexchange.com/a/31361/26200\">@toto2</a> said plus </p>\n\n<ul>\n<li><p>I would change the <code>print</code> method. Override <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29\" rel=\"nofollow noreferrer\"><code>toString</code></a> method.</p></li>\n<li><p>Do not put <code>System.out.println</code> in an API class. You will be reusing your <code>LinkedList</code> class in future in GUI or Web app. Then unwanted SOPs will hamper your code.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:44:59.623", "Id": "31362", "ParentId": "31341", "Score": "4" } }, { "body": "<p>Exactly as already said:</p>\n\n<ul>\n<li>Mixing <code>insert()</code> with <code>append()</code>? Does it make sense? Choose one</li>\n<li>You do not accept an empty list.</li>\n</ul>\n\n<p>Here is a turbo-fast example with <code>append()</code> accepting an empty list:</p>\n\n<pre><code>class Node {\n Node next;\n int num;\n public Node(int val) {\n num = val;\n next = null;\n }\n}\n\nclass LinkedList {\n\n private Node head = null;\n\n public void append(int val) {\n Node lastNode = getLastNode();\n if (lastNode == null) {\n head = new Node(val);\n } else {\n lastNode.next = new Node(val);\n }\n }\n\n public void delete(int val) {\n if(head == null){\n return;\n }\n\n Node prevNode = null;\n Node currNode = head;\n while (currNode != null &amp;&amp; currNode.num != val) {\n prevNode = currNode;\n currNode = currNode.next;\n }\n if(prevNode == null){\n head = head.next;\n return;\n }\n if (currNode == null) {\n System.out.println(\"A node with that value does not exist.\");\n return;\n }\n prevNode.next = currNode.next;\n }\n\n public void print() {\n System.out.println(\"\");\n if(head == null){\n System.out.print(\"EMPTY\");\n return;\n }\n Node tmpNode = head;\n while (tmpNode != null) {\n System.out.print(tmpNode.num + \" -&gt; \");\n tmpNode = tmpNode.next;\n }\n }\n\n private Node getLastNode() {\n if (head == null) {\n return null;\n }\n Node tmpNode = head;\n while (tmpNode.next != null) {\n tmpNode = tmpNode.next;\n }\n return tmpNode;\n }\n\n public static void main(String[] args) {\n LinkedList myList = new LinkedList();\n myList.print();\n myList.append(35);\n myList.append(33);\n myList.print();\n myList.delete(33);\n myList.delete(35);\n myList.delete(35);\n myList.print();\n }\n}\n</code></pre>\n\n<p>It's just an example, so you would like to implement the absolute minimum, but of course Generics, Comparable, <code>System.out.print</code> are still actual topics.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:53:40.880", "Id": "31368", "ParentId": "31341", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T04:48:26.433", "Id": "31341", "Score": "11", "Tags": [ "java", "linked-list" ], "Title": "Java code for Linked List" }
31341
<p>I wrote a script for validate the input field for following requirements</p> <ol> <li>Not null</li> <li>Multiple of hundreds </li> <li>Less than needed amount</li> </ol> <p>Here is my script:</p> <pre><code> $('#investAmount,#invest-button').bind('keypress', function(event){ if(event.which == 13){ if(amountValidation('#investAmount','#inNeedAmt','#invalidAmt','#mult100','#needAmtValidation')){ return false; } else{$(elementId).removeClass('errorField');} } }); $('#invest-button').click( function(event){ if(amountValidation('#investAmount','#inNeedAmt','#invalidAmt','#mult100','#needAmtValidation')){ return false; } else{$(elementId).removeClass('errorField');} }); function amountValidation(elementId,needAmt,errorMsgId,errorMsgId2,errorMsgId3){ var gvAmount =$(elementId).val(); var errAmount = gvAmount == ''; if(errAmount == true){$(elementId).addClass('errorField');} $(errorMsgId).toggle(errAmount); var errGVAmount = !errAmount &amp;&amp; !gvAmount.match(/^[1-9]\d*00$/); $(errorMsgId2).toggle(errGVAmount); if(errGVAmount == true){$(elementId).addClass('errorField');} var errNeedAmount =parseInt($(needAmt).val()) &lt; parseInt(gvAmount); $(errorMsgId3).toggle(errNeedAmount); if(errNeedAmount == true){$(elementId).addClass('errorField');} return errAmount || errGVAmount || errNeedAmount; } </code></pre> <p>Actually I am going to use this function in my website multiple places please help me to make this better script. My <strong><a href="http://jsfiddle.net/sureshpattu/s3Jts/" rel="nofollow">jsfiddle is here</a></strong></p>
[]
[ { "body": "<p>I'm not much of a jQuery freak, but I still have some points on this code. In your amountValidation function, you have some duplication and overhead:</p>\n\n<blockquote>\n<pre><code>if(errAmount == true)\n</code></pre>\n</blockquote>\n\n<p>can be written:</p>\n\n<pre><code>if(errAmount)\n</code></pre>\n\n<p>Also you always do the same thing when an error occurs, but that's in each statement:</p>\n\n<blockquote>\n<pre><code>if(errAmount == true){/* mark the field */}; \nif(errGVAmount == true){ /* mark the exact same field */};\nif(errNeedAmount == true { /* and yet the same thing again */ };\n</code></pre>\n</blockquote>\n\n<p>you can shorten this to:</p>\n\n<pre><code>if(errAmount || errGVAmount || errNeedAmount){ /*mark field*/ };\n</code></pre>\n\n<hr>\n\n<p>Your variable names could use some change too:</p>\n\n<p><strong>errAmount</strong> on the first look is like the geeneral error overall, not that <strong>amount</strong> is null / empty.<br>\nYou could use <strong>errAmountNull</strong> instead.</p>\n\n<p><strong>errNeedAmount</strong> sounds like you have no amount given yet, which would be <strong>errAmount</strong>.<br>\nI would use <strong>errAmountTooSmall</strong> instead</p>\n\n<p>Nobody knows, what the <em>GV</em> in <strong>errGVAmount</strong> stands for.<br>\nFrom the requirements I would call it: <strong>errAmountUnallowedValue</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T19:48:22.153", "Id": "43243", "ParentId": "31342", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T05:02:22.420", "Id": "31342", "Score": "1", "Tags": [ "javascript", "jquery", "validation" ], "Title": "Simplify jQuery validation" }
31342
<p>This is the original version of code written by my coworker that replaces every null cells with an empty string.</p> <pre><code>for (int i = 0; i &lt; dGV_factory.Rows.Count; i++) { this.dGV_factory["dGV_factory_groupID", i].Value = this.dGV_factory["dGV_factory_groupID", i].Value ?? ""; this.dGV_factory["dGV_factory_groupID", i].Value = this.dGV_factory["dGV_factory_groupID", i].Value ?? ""; this.dGV_factory["dGV_factory_groupID", i].Value = this.dGV_factory["dGV_factory_groupID", i].Value ?? ""; this.dGV_factory["UE", i].Value = this.dGV_factory["UE", i].Value ?? ""; ... } </code></pre> <p>My instant reaction: Ugh.</p> <p>Being a shameless fanatic of LINQ, I decided to rewrite the code using LINQ.</p> <pre><code>foreach(DataGridViewRow row in dGV_factory.Rows) { //Replace every null cells with an empty string row.Cells.Cast&lt;DataGridViewCell&gt;().ToList().ForEach(cell =&gt; cell.Value = cell.Value ?? ""); } </code></pre> <p>However, I'm wondering if this code is less readable than the above version, even though it is definitely compact.</p> <p>In my eyes, it's definitely readable as I'm comfortable with LINQ but my coworkers have not even heard of LINQ.</p> <p>Which is a better change? Should I keep my LINQ version or unroll LINQ to two foreach loops?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T05:20:33.153", "Id": "49895", "Score": "0", "body": "Opinion based close vote?? I'd really appreciate which part sounds very opinionated, and I'd be glad to edit. Really, I'm just looking for a guidance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T05:41:31.763", "Id": "49896", "Score": "0", "body": "\"Is this a better change?\" seems to be it. I'd reword it to ask which follows best coding practice in accordance to [this tag](http://codereview.stackexchange.com/questions/tagged/best-practice)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T09:28:35.093", "Id": "49910", "Score": "0", "body": "For the record, `List.ForEach()` is *not* part of LINQ. In fact, it goes against the whole idea of functional programming, which is what LINQ is based on. (Although a very similar method *is* part of PLINQ.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T16:21:43.230", "Id": "49943", "Score": "2", "body": "No one ever agrees with me on this, but I think the most concise LINQ is the best way to go. Not being comfortable with LINQ is not an excuse to write verbose code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:10:13.667", "Id": "50080", "Score": "0", "body": "I think there is a fundamental problem here. From my painful experience it is best to handle null transparently at the source, so check out [DataGridView.DataSourceNullValue](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcellstyle.datasourcenullvalue.aspx). Beware even the potential for inconsistent `null`/`DBNull` handling." } ]
[ { "body": "<p><code>List.ForEach</code> might have its uses, but I wouldn't use it here. It's not \"wrong\" per se, but a classic <code>foreach</code> loop </p>\n\n<ul>\n<li>is at least as easy to read as your LINQ expression,</li>\n<li>does not require the explicit <code>Cast&lt;...&gt;()</code>,</li>\n<li>does not require <code>ToList()</code>.</li>\n</ul>\n\n<p>If you put it on one line, it is actually <em>shorter</em> than your LINQ-based solution.</p>\n\n<pre><code>foreach(DataGridViewRow row in dGV_factory.Rows)\n{\n //Replace every null cells with an empty string\n foreach (DataGridViewCell cell in row.Cells) cell.Value = cell.Value ?? \"\";\n}\n</code></pre>\n\n<p>Although, for readability, I'd prefer:</p>\n\n<pre><code>foreach (DataGridViewRow row in dGV_factory.Rows)\n{\n foreach (DataGridViewCell cell in row.Cells)\n {\n cell.Value = cell.Value ?? \"\";\n }\n}\n</code></pre>\n\n<p>(Of course, this is still a great improvement over your co-worker's code.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T08:43:33.887", "Id": "31351", "ParentId": "31344", "Score": "8" } } ]
{ "AcceptedAnswerId": "31351", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T05:08:04.857", "Id": "31344", "Score": "5", "Tags": [ "c#", "linq" ], "Title": "Null replacement - Is this LINQ readable?" }
31344
<p>I'm building a rails app that, among other things, imports text markdown files as blog posts. The idea is that the truth is in the markdown files, so any time those are edited, created, or deleted, the blog should reflect this. Of course, I had to make this more complicated and insist that I should be able to edit, add, or delete a post online as well. So I had to build out a sync mechanism between the local markdown files and the remote database.</p> <p>In seemed to me that the best way to do this is to just create a few methods that handle file import, file export, and one that syncs the local files with the remote db. The markdown files have metadata that's encoded very simply.</p> <p>Example:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Title: My Post Date: 2012-03-20 9:10 Link: http://cnn.com/article-post-references Tags: politics, tech, etc Draft: true My post just starts here; as you'll note, there's no indicator for the body. It just proceeds in markdown. New paragraphs are set off according to markdown, etc. </code></pre> </blockquote> <p>I've built the helper and the code is below. I'm not very seasoned, and it seems that some of this is a bit redundant (especially how I iterate over the meta-data) and was wondering if anyone has any suggestions for improvements.</p> <pre class="lang-ruby prettyprint-override"><code>def self.update_or_create_file(post) file_text = "Title: #{post.title}" file_text += "\nDate: #{post.publish_time}" file_text += "\nLink: #{post.link}" if post.link.present? file_text += "\nTags: #{post.tag_list}" if post.tag_list.present? file_text += "\nImg: #{post.header_img}" if post.header_img.present? file_text += "\n \n#{post.body}" if post.body.present? File.open(post.file_name, 'w+') do |file| file.write(file_text) end end def self.update_or_create_post(file) body = '' # Iterate over each file File.open(file, 'r').each_line do |line| # If there's already a post, use that; if not, create one post = Post.find_by_file_name(file) || Post.create(file_name:file) # If the line has a ':', check for meta-data if line.match(/.*:.*/) key, value = line.split(":", 2) key = key.strip.downcase value = value.to_s.strip if key == 'title' post.title = value elsif key == 'date' post.publish_time = value elsif key == 'link' post.link = value elsif key == 'img' post.header_img = value elsif key == 'published' if value.strip.downcase == 'false' post.published = false else post.published = true end elsif key == 'tags' post.tag_list = value else body += line end elsif line.match(/^[-][-]/) # I don't want these lines, so do nothing else # If the line has gotten this far, add it to the body body += line end post.body = body.strip post.save end end def self.sync_posts(path) Dir.chdir(path) # Use Sync Records to check deletion of posts on server or deletion of post files # Note that the order these are checked in is important if SyncRecord.last.present? # skip if this is the first sync # Check for deleted posts; if so, then delete file posts_deleted = SyncRecord.last.posts_present - Post.pluck(:file_name) if posts_deleted.present? posts_deleted.each do |deleted_post_filename| File.delete(deleted_post_filename) if File.exists?(deleted_post_filename) end end # Check for created posts; if so, then create the file posts_added = Post.pluck(:file_name) - SyncRecord.last.posts_present if posts_added.present? posts_added.each do |added_post_filename| post = Post.find_by_file_name(added_post_filename) update_or_create_file(post) end end # Check for deleted files; if so, then delete posts # Note here that I'm checking local vs. server and resolving in favor of local # this is in case there are any odd states in the sync records files_deleted = Post.pluck(:file_name) - Dir.glob('*.{markdown,md}') if files_deleted.present? files_deleted.each do |deleted_filename| Post.find_by_file_name(deleted_filename).delete end end end # Now let's sync the content of the local files # Grab all markdown files Dir.glob('*.{markdown,md}').each do |file| if SyncRecord.last.present? &amp;&amp; Post.find_by_file_name(file).present? post = Post.find_by_file_name(file) # check if the file or post was updated since the last sync if File.mtime(file) &gt; SyncRecord.last.updated_at || post.updated_at &gt; SyncRecord.last.updated_at # if the file was updated more recently, overwrite the post if File.mtime(file) &gt; post.updated_at update_or_create_post(file) # if the post was updated more recently, overwrite the file elsif post.updated_at &gt; File.mtime(file) update_or_create_file(post) end end else # If this is the first sync or if there's a new file, just create it update_or_create_post(file) end end # Save the current state as a new Sync Record record = SyncRecord.new record.files_present = Dir.glob('*.{markdown,md}') record.posts_present = Post.pluck(:file_name) record.save end </code></pre> <p>It may also be helpful to see my schema.rb; the tags/taggings I cheated on by just using the acts_as_taggable_on gem.</p> <pre class="lang-ruby prettyprint-override"><code>create_table "posts", force: true do |t| t.string "title" t.text "body" t.datetime "publish_time" t.string "link" t.string "header_img" t.datetime "created_at" t.datetime "updated_at" t.string "file_name" t.boolean "published" end create_table "sync_records", force: true do |t| t.string "files_present", default: [], array: true t.string "posts_present", default: [], array: true t.datetime "created_at" t.datetime "updated_at" end create_table "taggings", force: true do |t| t.integer "tag_id" t.integer "taggable_id" t.string "taggable_type" t.integer "tagger_id" t.string "tagger_type" t.string "context", limit: 128 t.datetime "created_at" end add_index "taggings", ["tag_id"], name: "index_taggings_on_tag_id", using: :btree add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context", using: :btree create_table "tags", force: true do |t| t.string "name" end </code></pre>
[]
[ { "body": "<p>There are actually 2 kinda distinct pieces of code to review here: The file I/O, and the syncing.</p>\n\n<p><strike>For now, this'll be a partial review, looking only at the file I/O, as I haven't had time to look at the sync code.</strike> Update: Added some thoughts on the syncing at the end of this answer. These first general notes should be of use in either case.</p>\n\n<p>First off, as a rule of thumb, in Ruby your methods should be short. Like, <em>really</em> short. There are of course different schools of thought on what the limit is, but a maximum of 10 lines is a common one. Some say 5 lines maximum.</p>\n\n<p>Again, this is just a general rule/something to aim for, so you're free to do disregard it, but it forces you to justify (and thus rethink) your code if it's longer. And in your case, you've got methods that are <em>very</em> long, so, yeah, that might need some looking into. The benefit of keeping things short is that you end up with code that's easy to read, maintain, and extend.</p>\n\n<p>Second, more specifically, I see a lot of repetition. For instance, the metadata names are repeated (with different casing even) in both the file writer and the file reader methods. So maintenance will be difficult and extending it requires a lot of extra code.</p>\n\n<p>As for your file format, it's actually not that different from plain HTTP: Header and Body separated by a blank line, with headers declared using colons. Easy to parse. The trick, though, is to stick to that format. If you've already got a bunch of files, I'd suggest you go through them now (before you have more), and make sure they're consistent. The less flexibility the parser has to deal with, the better (this includes deciding on a file extension; yes, both \".md\" and \".markdown\" are valid, but pick one and stick to it. Your example also has a \"Draft\" header that's not handled anywhere)</p>\n\n<p>Now, practically, I'd consider moving the file I/O code to the <code>Post</code> model (if it isn't there already), since that's what needs the I/O, and separating your syncing code.</p>\n\n<p>Also: Tests. Learn to love 'em, if you haven't.</p>\n\n<p>Here's how I might write the <code>Post</code> methods. Note that they all directly or indirectly call file methods that may raise exceptions.</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n HEADER_ATTRS = {\n \"Title\" =&gt; :title,\n \"Date\" =&gt; :publish_time,\n \"Link\" =&gt; :link,\n \"Tags\" =&gt; :tags,\n \"Img\" =&gt; :header_img\n }.freeze\n\n BODY_ATTR = :body\n\n # Dump the post to its file\n def write_to_file\n File.open(file_name, 'w+') do |file|\n HEADER_ATTRS.each do |name, method|\n io.puts \"#{name}: #{send(method)}\" if send(method).present?\n end\n file.puts # separate headers and body with a blank line\n io.puts send(BODY_ATTR) if send(BODY_ATTR).present?\n end\n end\n\n # Initialize/find a post by and with a file\n # Note that Post record is not persisted by this method;\n # that's left to the caller\n def self.find_or_initialize_from_file(path)\n attributes = self.parse_file(path)\n post = Post.find_or_initialize_by_file_name(file_name)\n post.assign_attributes attributes\n post\n end\n\n # Parse the given file, returning an attribute hash\n # (this still looks a tad messy to me)\n def self.parse_file(path)\n attributes = {}\n File.open(path, 'r') do |io|\n # read lines until we hit something that doesn't look like a header\n # (i.e. the blank line in a properly formatted file)\n while io.gets =~ /\\A([^:]+): (.+)\\Z/\n attribute = HEADER_ATTRS[$1]\n attributes[attribute] = $2.strip if attribute\n end\n # read the rest\n attributes[BODY_ATTR] = io.read.strip\n end\n attributes\n end\nend\n</code></pre>\n\n<p>The weakness lies in backwards/forwards compatibility. If you add an attribute to the <code>HEADER_ATTRS</code> hash, older files won't get read with a default value. Similarly, if you remove an attribute, it'll be ignored in existing files. This can all be fixed, but write some tests for this basic behavior first.</p>\n\n<p><strong>Update: Syncing</strong></p>\n\n<p>Again, I'd roll all this into a separate class. That would allow you to refactor the logic into separate methods. Start with the repetitive bits, like globbing the markdown files or getting the latest <code>SyncRecord</code>, and move on to the distinct \"steps\" in the process.<br>\nFavor methods that just return stuff for the most part, but do not actually modify files or database - keep those potentially destructive operations separate (similar to the code above, where <code>Post.find_or_initialize_from_file</code> returns a new instance but doesn't assume it should be persisted).</p>\n\n<p>Various notes:</p>\n\n<ul>\n<li>Tests. Aim for a high tests-to-code ratio, as bugs here could be super-destructive. E.g. a bug causes all files to be deleted, next sync faithfully deletes all post records. Oops.</li>\n<li>Your code will, as far as I can tell, <em>always</em> update either a file or a post record, because you don't sync the file's mtime and the record's timestamp. So one or the other will always be ahead. Obviously, this very inefficient.</li>\n<li><code>Dir.chdir()</code>, when used without a block, changes the working director for <em>your entire app</em>. So avoid that(!) in favor of absolute paths.</li>\n<li>Favor <code>any?</code> over <code>present?</code> when checking arrays. Functionally it's the same, but <code>any?</code> makes it obvious what we're dealing with.</li>\n<li>Use <code>post.destroy</code> instead of <code>post.delete</code>. Again, no real difference, but <code>destroy</code> is the Rails convention.</li>\n<li>Speaking of, I might prefer to set a <code>deleted</code> flag on the <code>Post</code> model and delete the file, but otherwise keep the data in the database to avoid accidental data loss. Also makes it simple to find out which post records have been deleted (by the way: Tests!)</li>\n<li>You could consider collecting the tainted file names, and do the updating/deleting in a single (or at least centralized) operation, rather than individual ones. This will be easier if you give yourself methods like <code>deleted_posts</code> or <code>updated_files</code>. It'll also limit (but <em>not</em> eliminate) your exposure to race conditions where things change while syncing is in progress (which is something you should be wary of. Also, tests)</li>\n<li>Beware of exceptions, especially with all those file operations</li>\n<li>Tests? Tests.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-16T17:19:52.630", "Id": "37529", "ParentId": "31345", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T05:35:10.650", "Id": "31345", "Score": "1", "Tags": [ "ruby", "ruby-on-rails", "postgresql", "markdown", "sync" ], "Title": "Importing markdown files" }
31345
<p>I received the following question in a technical interview today (for a devops/SRE position):</p> <blockquote> <p>Write a function which returns true if the two rectangles passed to it as arguments would overlap if drawn on a Cartesian plane. The rectangles are guaranteed to be aligned with the axes, not arbitrarily rotated.</p> </blockquote> <p>I pretty much blew the whole thought process for how to approach the question I wasn't thinking of cases where, for example, one rectangle might be enclosed entirely within the other or of cases where a short wide rectangle might cross wholly through a taller, narrower one forming some sort of cross --- so I was off on a non-productive tangent thinking about whether any corner of either rectangle was within the bounding box of the other.</p> <p>Naturally as soon as I got home, having let the problem settle more in my mind, I was able to write something which seems reasonably elegant and seems to work (for the test cases I've tried so far).</p> <p><img src="https://i.stack.imgur.com/yLhn7.png" alt="Rectangle Overlap Test Cases"></p> <p>This graphic (which took far longer to create than the code, and I don't even know how to make Inkscape show the gridlines in the saved image as it's showing in my working canvas) shows the simplest obvious cases: red/aqua overlapping by a corner, blue completely enclosing fuschia and green/yellow overlapping but without any corner enclosed within the other. My test code uses red/blue, blue/green and similar combinations as the non-overlapping test cases, including those which would overlap only in horizontal or vertical dimensions but are clear in the other dimension.</p> <p>My thought process, when I got home and sat down with a keyboard was as follows:</p> <p>We only care about edges, ultimately. So my <code>Rect()</code> class store just the X scalar of the left and right edges, and the Y scalar of top and bottom edges.</p> <p>For rectangles to overlap there must be some overlap in both the horizontal and vertical directions. So it should be sufficient to just test if either the left or right edge of the first rectangle argument is to the right or left (respectively) of the other rectangle's opposite edge ... and likewise for top and bottom.</p> <p>Here's the code for creating Points and Rectangles. Rectangles are only instantiated using corner points; points are actually trivial and could be named tuples if I were inclined.</p> <pre><code>#/usr/bin/env python class Point(object): def __init__(self, x, y): self.x = x self.y = y class Rect(object): def __init__(self, p1, p2): '''Store the top, bottom, left and right values for points p1 and p2 are the (corners) in either order ''' self.left = min(p1.x, p2.x) self.right = max(p1.x, p2.x) self.bottom = min(p1.y, p2.y) self.top = max(p1.y, p2.y) </code></pre> <p>Note that I'm setting left to the minimum of the two x co-ordinates, right to the max, and so on. I'm not doing any error checking here for zero area rectangles here, they would be perfect valid for the class and probably, arguably, be valid the the same collision "overlap" function. Points and lines would simply be infinitesimal "rectangles" for my code. (However, no such degenerate cases are in my test suite).</p> <p>Here's the overlap function:</p> <pre><code>#/usr/bin/env python def overlap(r1,r2): '''Overlapping rectangles overlap both horizontally &amp; vertically ''' hoverlaps = True voverlaps = True if (r1.left &gt; r2.right) or (r1.right &lt; r2.left): hoverlaps = False if (r1.top &lt; r2.bottom) or (r1.bottom &gt; r2.top): voverlaps = False return hoverlaps and voverlaps </code></pre> <p>This seems to work (for all my test cases) but it also looks wrong to me. My initial attempt was to start with hoverlaps and voverlaps as False, and selectively set them to True using conditions similar to these shown (but with the inequality operators reversed).</p> <p>So, what's a better way to render this code?</p> <p>Oh, yeah: here's the test suite at the end of that file:</p> <pre><code>#!/usr/bin/env python # if __name__ == '__main__': p1 = Point(1,1) p2 = Point(3,3) r1 = Rect(p1,p2) p3 = Point(2,2) p4 = Point(4,4) r2 = Rect(p3,p4) print "r1 (red),r2 (aqua): Overlap in either direction:" print overlap(r1,r2) print overlap(r2,r1) p5 = Point(3,6) # overlaps horizontally but not vertically p6 = Point(12,11) r3 = Rect(p5,p6) print "r1 (red),r3 (blue): Should not overlap, either way:" print overlap(r1,r3) print overlap(r3,r1) print "r2 (aqua),r3 (blue: Same as that" print overlap(r2,r3) print overlap(r3,r2) p7 = Point(7,7) p8 = Point(11,10) r4 = Rect(p7,p8) # completely inside r3 print "r4 (fuschia) is totally enclosed in r3 (blue)" print overlap(r3,r4) print overlap(r4,r3) print "r4 (fuschia) is nowhere near r1 (red) nor r2 (aqua)" print overlap(r1,r4) p09 = Point(13,11) p10 = Point(19,13) r5 = Rect(p09,p10) p11 = Point(13,9) p12 = Point(15,14) r6 = Rect(p11,p12) print "r5 (green) and r6 (yellow) cross without corner overlap" print overlap(r5,r6) print overlap(r6,r5) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T08:47:58.117", "Id": "49909", "Score": "1", "body": "By the way, please excuse the horribly amateurish graphic. I'm NOT a graphics guy and had to go fetch Inkscape to even manage this pathetic thing here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:43:03.607", "Id": "49934", "Score": "0", "body": "The problem was posed with the explicit constraint that the rectangles would be aligned along the axes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T07:25:31.233", "Id": "50025", "Score": "0", "body": "Incidentally if it were not the case that the rectangles were constrained to be aligned to the axes then I suspect the most obvious approach would be a series of tests, solving for each vertex of each (polygon) to find it its enclosed by the other (a series and then of each line segment against the others (any intersection means overlap). The first test is for the case where one completely encloses the other and the tests are all solutions to linear/algebraic equations. If I'm right that approach generalizes to all planar polygons." } ]
[ { "body": "<p>You have common code, which moreover has applications beyond this one, so should you not pull it out into a function? Then you can reduce <code>overlap</code> to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def overlap(r1, r2):\n '''Overlapping rectangles overlap both horizontally &amp; vertically\n '''\n return range_overlap(r1.left, r1.right, r2.left, r2.right) and range_overlap(r1.bottom, r1.top, r2.bottom, r2.top)\n</code></pre>\n\n<p>Now, the key condition encapsulated by <code>range_overlap</code> is that neither range is completely greater than the other. A direct refactor of the way you've expressed this is</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def range_overlap(a_min, a_max, b_min, b_max):\n '''Neither range is completely greater than the other\n '''\n overlapping = True\n if (a_min &gt; b_max) or (a_max &lt; b_min):\n overlapping = False\n return overlapping\n</code></pre>\n\n<p>For such a simple condition I would prefer to use <code>not</code> rather than if-else assignment. I would also reorder the second condition to exhibit the symmetry more clearly:</p>\n\n<pre><code>def range_overlap(a_min, a_max, b_min, b_max):\n '''Neither range is completely greater than the other\n '''\n return not ((a_min &gt; b_max) or (b_min &gt; a_max))\n</code></pre>\n\n<p>Of course, <a href=\"http://mathworld.wolfram.com/deMorgansLaws.html\">de Morgan's laws</a> allow rewriting as</p>\n\n<pre><code>def range_overlap(a_min, a_max, b_min, b_max):\n '''Neither range is completely greater than the other\n '''\n return (a_min &lt;= b_max) and (b_min &lt;= a_max)\n</code></pre>\n\n<p>I think that the last of these is the most transparent, but that's an issue of aesthetics and you may disagree.</p>\n\n<p>Note that I've assumed throughout, as you do, that the rectangles are closed (i.e. that they contain their edges). To make them open, change <code>&gt;</code> to <code>&gt;=</code> and <code>&lt;=</code> to <code>&lt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T10:32:34.047", "Id": "50762", "Score": "0", "body": "Practical use of [de Morgan's Laws](http://en.wikipedia.org/wiki/De_Morgan%27s_laws) was the deciding factor in getting this bounty. (Though a link and proper spelling would have been nice, too). I really should remember to consider those when I'm trying to untangle more complicated boolean expressions in my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T11:12:40.587", "Id": "50763", "Score": "0", "body": "@JimDennis, I'm not sure what complaint you have against my spelling. Fair point on the link, though: I shouldn't assume that everyone has studied formal logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T11:21:43.577", "Id": "50764", "Score": "0", "body": "It was more of a teasing nitpick than a real complaint. I could have sworn that you left out the \"de\" in \"de Morgan.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-01T11:32:26.410", "Id": "355783", "Score": "0", "body": "Nice answer, however one problem with this solution is that it is easy to mix up the arguments to `range_overlap` (is it `amin, amax, bmin, bmax`, or `amin, bmin, amax, bmax`, or ...?)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T09:51:45.657", "Id": "31529", "ParentId": "31352", "Score": "18" } }, { "body": "<p>I would simply apply a logic transformation. Here's your original, verbatim:</p>\n\n<pre><code>def overlap(r1,r2):\n '''Overlapping rectangles overlap both horizontally &amp; vertically\n '''\n hoverlaps = True\n voverlaps = True\n if (r1.left &gt; r2.right) or (r1.right &lt; r2.left):\n hoverlaps = False\n if (r1.top &lt; r2.bottom) or (r1.bottom &gt; r2.top):\n voverlaps = False\n return hoverlaps and voverlaps\n</code></pre>\n\n<p>Each of the variables is True unless you set it to False, so you could just negate each condition.</p>\n\n<pre><code>def overlap(r1,r2):\n hoverlaps = not((r1.left &gt; r2.right) or (r1.right &lt; r2.left))\n voverlaps = not((r1.top &lt; r2.bottom) or (r1.bottom &gt; r2.top))\n return hoverlaps and voverlaps\n</code></pre>\n\n<p>Applying <a href=\"http://en.wikipedia.org/wiki/De_Morgan%27s_laws\">De Morgan's Laws</a>…</p>\n\n<pre><code>def overlap(r1,r2):\n hoverlaps = not(r1.left &gt; r2.right) and not(r1.right &lt; r2.left)\n voverlaps = not(r1.top &lt; r2.bottom) and not(r1.bottom &gt; r2.top)\n return hoverlaps and voverlaps\n</code></pre>\n\n<p>You can eliminate the \"not\"s by reversing the inequalities.</p>\n\n<pre><code>def overlap(r1,r2):\n hoverlaps = (r1.left &lt;= r2.right) and (r1.right &gt;= r2.left)\n voverlaps = (r1.top &gt;= r2.bottom) and (r1.bottom &lt;= r2.top)\n return hoverlaps and voverlaps\n</code></pre>\n\n<p>Personally, I would prefer to rearrange my inequalities for parallelism. Also, I would move the function into the <code>Rect</code> class. Final answer:</p>\n\n<pre><code>class Rect(object):\n def __init__(p1, p2):\n ...\n\n @staticmethod\n def overlap(r1, r2):\n '''Overlapping rectangles overlap both horizontally &amp; vertically\n '''\n h_overlaps = (r1.left &lt;= r2.right) and (r1.right &gt;= r2.left)\n v_overlaps = (r1.bottom &lt;= r2.top) and (r1.top &gt;= r2.bottom)\n return h_overlaps and v_overlaps\n</code></pre>\n\n<p>I'd resist the urge to do anything more than that, because I think you would be running into diminishing returns.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:01:04.070", "Id": "31564", "ParentId": "31352", "Score": "10" } }, { "body": "<p>I just had a bit of a play with this. The solution is at the bottom, but I'll show the steps I took.</p>\n\n<p>Using a visual determination of whether two rectangles overlap.</p>\n\n<p>For rectangles that do overlap:</p>\n\n<pre><code>#1st rectangle\n# (x1,y1)\n# (x2,y2)\n#x1,y1 &lt; x2,y2\n\n#2nd rectangle\n# (x3,y3)\n# (x4,y4)\n#x3,y3 &lt;x4y4\n\ndef rectangleOverlap():\n x1=2\n y1=3\n x2=111\n y2=99\n x3=41\n y3=1\n x4=90\n y4=121\n#find largest x (X) and largest y (Y)\n if y4&gt;y2:\n Y=y4\n else:\n Y=y2\n if x4&gt;x2:\n X=x4\n else:\n X=x2\n pic = makeEmptyPicture (X,Y)\n for y in range (0,Y-1):\n for x in range (0,X-1):\n px = getPixel(pic, x,y)\n\n if (y&gt;y1 and y&lt;y2) and (x&gt;x1 and x&lt;x2):\n setColor(px,makeColor(255,255,0))\n if (y&gt;y3 and y&lt;y4) and (x&gt;x3 and x&lt;x4):\n setColor(px,makeColor(0,255,255)) \n if (y&gt;y1 and y&lt;y2) and (x&gt;x1 and x&lt;x2) and (y&gt;y3 and y&lt;y4) and (x&gt;x3 and x&lt;x4):\n setColor(px,makeColor(255,0,0))\n\n show(pic)\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/ogxsE.jpg\" alt=\"rectanlges\"> </p>\n\n<p>Clearly the overlap can be seen here in red.</p>\n\n<hr>\n\n<p>For rectangles that do not overlap:</p>\n\n<pre><code>def rectangleOverlap():\n x1=2\n y1=3\n x2=11\n y2=9\n x3=41\n y3=11\n x4=90\n y4=121\n#find largest x (X) and largest y (Y)\n if y4&gt;y2:\n Y=y4\n else:\n Y=y2\n if x4&gt;x2:\n X=x4\n else:\n X=x2\n pic = makeEmptyPicture (X,Y)\n for y in range (0,Y-1):\n for x in range (0,X-1):\n px = getPixel(pic, x,y)\n if (y&gt;y1 and y&lt;y2) and (x&gt;x1 and x&lt;x2):\n setColor(px,makeColor(255,255,0))\n if (y&gt;y3 and y&lt;y4) and (x&gt;x3 and x&lt;x4):\n setColor(px,makeColor(0,255,255)) \n if (y&gt;y1 and y&lt;y2) and (x&gt;x1 and x&lt;x2) and (y&gt;y3 and y&lt;y4) and (x&gt;x3 and x&lt;x4):\n setColor(px,makeColor(255,0,0))\n\n show(pic)\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/Q6nSf.jpg\" alt=\"enter image description here\"></p>\n\n<hr>\n\n<p>So if we focus on the part that overlaps:</p>\n\n<pre><code>if (y&gt;y1 and y&lt;y2) and (x&gt;x1 and x&lt;x2) and (y&gt;y3 and y&lt;y4) and (x&gt;x3 and x&lt;x4):\n</code></pre>\n\n<p>Trim down our ranges, to optimise code.</p>\n\n<pre><code>def rectangleOverlap():\n\n for y in range (y1,y2):\n for x in range (x1,x2):\n\n if (y&gt;y3 and y&lt;y4) and (x&gt;x3 and x&lt;x4):\n print \"overlap\"\n return true\n</code></pre>\n\n<p><em>I'm no expert, I enjoy this aspect of python.. hope it helps</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T17:50:56.423", "Id": "60879", "Score": "2", "body": "Aaaargh! JPEGs!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T16:32:22.087", "Id": "31695", "ParentId": "31352", "Score": "0" } } ]
{ "AcceptedAnswerId": "31529", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T08:46:16.267", "Id": "31352", "Score": "32", "Tags": [ "python", "interview-questions", "collision", "computational-geometry" ], "Title": "Overlapping rectangles" }
31352
<p>I'm quite new to Zend and unit testing in general. I have come up with a small application that uses Zend Framework 2 and Doctrine. It has only one model and controller and I want to run some unit tests on them.</p> <p>Here's what I have so far:</p> <p>Base doctrine 'entity' class, containing methods I want to use in all of my entities:</p> <pre><code>&lt;?php /** * Base entity class containing some functionality that will be used by all * entities */ namespace Perceptive\Database; use Zend\Validator\ValidatorChain; class Entity{ //An array of validators for various fields in this entity protected $validators; /** * Returns the properties of this object as an array for ease of use. Will * return only properties with the ORM\Column annotation as this way we know * for sure that it is a column with data associated, and won't pick up any * other properties. * @return array */ public function toArray(){ //Create an annotation reader so we can read annotations $reader = new \Doctrine\Common\Annotations\AnnotationReader(); //Create a reflection class and retrieve the properties $reflClass = new \ReflectionClass($this); $properties = $reflClass-&gt;getProperties(); //Create an array in which to store the data $array = array(); //Loop through each property. Get the annotations for each property //and add to the array to return, ONLY if it contains an ORM\Column //annotation. foreach($properties as $property){ $annotations = $reader-&gt;getPropertyAnnotations($property); foreach($annotations as $annotation){ if($annotation instanceof \Doctrine\ORM\Mapping\Column){ $array[$property-&gt;name] = $this-&gt;{$property-&gt;name}; } } } //Finally, return the data array to the user return $array; } /** * Updates all of the values in this entity from an array. If any property * does not exist a ReflectionException will be thrown. * @param array $data * @return \Perceptive\Database\Entity */ public function fromArray($data){ //Create an annotation reader so we can read annotations $reader = new \Doctrine\Common\Annotations\AnnotationReader(); //Create a reflection class and retrieve the properties $reflClass = new \ReflectionClass($this); //Loop through each element in the supplied array foreach($data as $key=&gt;$value){ //Attempt to get at the property - if the property doesn't exist an //exception will be thrown here. $property = $reflClass-&gt;getProperty($key); //Access the property's annotations $annotations = $reader-&gt;getPropertyAnnotations($property); //Loop through all annotations to see if this is actually a valid column //to update. $isColumn = false; foreach($annotations as $annotation){ if($annotation instanceof \Doctrine\ORM\Mapping\Column){ $isColumn = true; } } //If it is a column then update it using it's setter function. Otherwise, //throw an exception. if($isColumn===true){ $func = 'set'.ucfirst($property-&gt;getName()); $this-&gt;$func($data[$property-&gt;getName()]); }else{ throw new \Exception('You cannot update the value of a non-column using fromArray.'); } } //return this object to facilitate a 'fluent' interface. return $this; } /** * Validates a field against an array of validators. Returns true if the value is * valid or an error string if not. * @param string $fieldName The name of the field to validate. This is only used when constructing the error string * @param mixed $value * @param array $validators * @return boolean|string */ protected function setField($fieldName, $value){ //Create a validator chain $validatorChain = new ValidatorChain(); $validators = $this-&gt;getValidators(); //Try to retrieve the validators for this field if(array_key_exists($fieldName, $this-&gt;validators)){ $validators = $this-&gt;validators[$fieldName]; }else{ $validators = array(); } //Add all validators to the chain foreach($validators as $validator){ $validatorChain-&gt;attach($validator); } //Check if the value is valid according to the validators. Return true if so, //or an error string if not. if($validatorChain-&gt;isValid($value)){ $this-&gt;{$fieldName} = $value; return $this; }else{ $err = 'The '.$fieldName.' field was not valid: '.implode(',',$validatorChain-&gt;getMessages()); throw new \Exception($err); } } } </code></pre> <p>My 'config' entity, which represents a one-row table containing some configuration options:</p> <pre><code>&lt;?php /** * @todo: add a base entity class which handles validation via annotations * and includes toArray function. Also needs to get/set using __get and __set * magic methods. Potentially add a fromArray method? */ namespace Application\Entity; use Doctrine\ORM\Mapping as ORM; use Zend\Validator; use Zend\I18n\Validator as I18nValidator; use Perceptive\Database\Entity; /** * @ORM\Entity * @ORM\HasLifecycleCallbacks */ class Config extends Entity{ /** * @ORM\Id * @ORM\Column(type="integer") */ protected $minLengthUserId; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $minLengthUserName; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $minLengthUserPassword; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $daysPasswordReuse; /** * @ORM\Id * @ORM\Column(type="boolean") */ protected $passwordLettersAndNumbers; /** * @ORM\Id * @ORM\Column(type="boolean") */ protected $passwordUpperLower; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $maxFailedLogins; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $passwordValidity; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $passwordExpiryDays; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $timeout; // getters/setters /** * Get the minimum length of the user ID * @return int */ public function getMinLengthUserId(){ return $this-&gt;minLengthUserId; } /** * Set the minmum length of the user ID * @param int $minLengthUserId * @return \Application\Entity\Config This object */ public function setMinLengthUserId($minLengthUserId){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('minLengthUserId', $minLengthUserId); } /** * Get the minimum length of the user name * @return int */ public function getminLengthUserName(){ return $this-&gt;minLengthUserName; } /** * Set the minimum length of the user name * @param int $minLengthUserName * @return \Application\Entity\Config */ public function setMinLengthUserName($minLengthUserName){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('minLengthUserName', $minLengthUserName); } /** * Get the minimum length of the user password * @return int */ public function getMinLengthUserPassword(){ return $this-&gt;minLengthUserPassword; } /** * Set the minimum length of the user password * @param int $minLengthUserPassword * @return \Application\Entity\Config */ public function setMinLengthUserPassword($minLengthUserPassword){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('minLengthUserPassword', $minLengthUserPassword); } /** * Get the number of days before passwords can be reused * @return int */ public function getDaysPasswordReuse(){ return $this-&gt;daysPasswordReuse; } /** * Set the number of days before passwords can be reused * @param int $daysPasswordReuse * @return \Application\Entity\Config */ public function setDaysPasswordReuse($daysPasswordReuse){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('daysPasswordReuse', $daysPasswordReuse); } /** * Get whether the passwords must contain letters and numbers * @return boolean */ public function getPasswordLettersAndNumbers(){ return $this-&gt;passwordLettersAndNumbers; } /** * Set whether passwords must contain letters and numbers * @param int $passwordLettersAndNumbers * @return \Application\Entity\Config */ public function setPasswordLettersAndNumbers($passwordLettersAndNumbers){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('passwordLettersAndNumbers', $passwordLettersAndNumbers); } /** * Get whether password must contain upper and lower case characters * @return type */ public function getPasswordUpperLower(){ return $this-&gt;passwordUpperLower; } /** * Set whether password must contain upper and lower case characters * @param type $passwordUpperLower * @return \Application\Entity\Config */ public function setPasswordUpperLower($passwordUpperLower){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('passwordUpperLower', $passwordUpperLower); } /** * Get the number of failed logins before user is locked out * @return int */ public function getMaxFailedLogins(){ return $this-&gt;maxFailedLogins; } /** * Set the number of failed logins before user is locked out * @param int $maxFailedLogins * @return \Application\Entity\Config */ public function setMaxFailedLogins($maxFailedLogins){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('maxFailedLogins', $maxFailedLogins); } /** * Get the password validity period in days * @return int */ public function getPasswordValidity(){ return $this-&gt;passwordValidity; } /** * Set the password validity in days * @param int $passwordValidity * @return \Application\Entity\Config */ public function setPasswordValidity($passwordValidity){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('passwordValidity', $passwordValidity); } /** * Get the number of days prior to expiry that the user starts getting * warning messages * @return int */ public function getPasswordExpiryDays(){ return $this-&gt;passwordExpiryDays; } /** * Get the number of days prior to expiry that the user starts getting * warning messages * @param int $passwordExpiryDays * @return \Application\Entity\Config */ public function setPasswordExpiryDays($passwordExpiryDays){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('passwordExpiryDays', $passwordExpiryDays); } /** * Get the timeout period of the application * @return int */ public function getTimeout(){ return $this-&gt;timeout; } /** * Get the timeout period of the application * @param int $timeout * @return \Application\Entity\Config */ public function setTimeout($timeout){ //Use the setField function, which checks whether the field is valid, //to set the value. return $this-&gt;setField('timeout', $timeout); } /** * Returns a list of validators for each column. These validators are checked * in the class' setField method, which is inherited from the Perceptive\Database\Entity class * @return array */ public function getValidators(){ //If the validators array hasn't been initialised, initialise it if(!isset($this-&gt;validators)){ $validators = array( 'minLengthUserId' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(1), ), 'minLengthUserName' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(2), ), 'minLengthUserPassword' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(3), ), 'daysPasswordReuse' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(-1), ), 'passwordLettersAndNumbers' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(-1), new Validator\LessThan(2), ), 'passwordUpperLower' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(-1), new Validator\LessThan(2), ), 'maxFailedLogins' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(0), ), 'passwordValidity' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(1), ), 'passwordExpiryDays' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(1), ), 'timeout' =&gt; array( new I18nValidator\Int(), new Validator\GreaterThan(0), ) ); $this-&gt;validators = $validators; } //Return the list of validators return $this-&gt;validators; } /** * @todo: add a lifecyle event which validates before persisting the entity. * This way there is no chance of invalid values being saved to the database. * This should probably be implemented in the parent class so all entities know * to validate. */ } </code></pre> <p>And my controller, which can read from and write to the entity:</p> <pre><code>&lt;?php /** * A restful controller that retrieves and updates configuration information */ namespace Application\Controller; use Zend\Mvc\Controller\AbstractRestfulController; use Zend\View\Model\JsonModel; class ConfigController extends AbstractRestfulController { /** * The doctrine EntityManager for use with database operations * @var \Doctrine\ORM\EntityManager */ protected $em; /** * Constructor function manages dependencies * @param \Doctrine\ORM\EntityManager $em */ public function __construct(\Doctrine\ORM\EntityManager $em){ $this-&gt;em = $em; } /** * Retrieves the configuration from the database */ public function getList(){ //locate the doctrine entity manager $em = $this-&gt;em; //there should only ever be one row in the configuration table, so I use findAll $config = $em-&gt;getRepository("\Application\Entity\Config")-&gt;findAll(); //return a JsonModel to the user. I use my toArray function to convert the doctrine //entity into an array - the JsonModel can't handle a doctrine entity itself. return new JsonModel(array( 'data' =&gt; $config[0]-&gt;toArray(), )); } /** * Updates the configuration */ public function replaceList($data){ //locate the doctrine entity manager $em = $this-&gt;em; //there should only ever be one row in the configuration table, so I use findAll $config = $em-&gt;getRepository("\Application\Entity\Config")-&gt;findAll(); //use the entity's fromArray function to update the data $config[0]-&gt;fromArray($data); //save the entity to the database $em-&gt;persist($config[0]); $em-&gt;flush(); //return a JsonModel to the user. I use my toArray function to convert the doctrine //entity into an array - the JsonModel can't handle a doctrine entity itself. return new JsonModel(array( 'data' =&gt; $config[0]-&gt;toArray(), )); } } </code></pre> <p>Because of character limits on I was unable to paste in my unit tests, but here are links to my unit tests so far:</p> <p>For the entity: <a href="https://github.com/hputus/config-app/blob/master/module/Application/test/ApplicationTest/Entity/ConfigTest.php" rel="nofollow">https://github.com/hputus/config-app/blob/master/module/Application/test/ApplicationTest/Entity/ConfigTest.php</a></p> <p>For the controller: <a href="https://github.com/hputus/config-app/blob/master/module/Application/test/ApplicationTest/Controller/ConfigControllerTest.php" rel="nofollow">https://github.com/hputus/config-app/blob/master/module/Application/test/ApplicationTest/Controller/ConfigControllerTest.php</a></p> <p>Some questions:</p> <ul> <li>Am I doing anything obviously wrong here?</li> <li>In the tests for the entity, I am repeating the same tests for many different fields? - Is there a way to minimise this? Like have a standard battery of tests to run on integer columns for instance?</li> <li>In the controller I am trying to 'mock up' doctrine's entity manager so that changes aren't really saved into the database - am I doing this properly?</li> <li>Is there anything else in the controller which I should test?</li> </ul> <p>Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T10:59:07.303", "Id": "50158", "Score": "1", "body": "Just a quick question: Are you, at any point, creating a mockup of the actual entities and/or entity manager? If you don't, there's a good chance you might accidentally alter actual data, which probably isn't what you want to do. And a quick tip: to avoid having to write test per field, use [a dataprovider](http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers), through reflection, it'll keep calling a generic test function, that uses the arrays provided by the dataprovider function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:23:50.873", "Id": "50165", "Score": "0", "body": "Hi, yes in my Controller test I create a mockup of the doctrine Entity Manager so the data is not really saved. So for the dataprovider, do you mean something like this? http://pastebin.com/cbNPBqsN Here I just have one test per field which will accept parameters from the data provider." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T14:13:28.000", "Id": "50173", "Score": "1", "body": "Well, sort of, you could also do this: http://pastebin.com/rWR5SvVN. Pass setter and getter methods to the test function, so you have 1 function to test _all_ fields. You could even add an array instead of a value (for argument `$a`) and loop over that array, each time calling the `assertTrue` method. You could also pass the expected Exception per value, to be more specific in your test. This way, you'll test the entire model in 1 test method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T07:57:44.397", "Id": "50364", "Score": "0", "body": "Thanks for that! I was just thinking, is there actually any point in 'unit testing' the controller since there is basically no logic in there, and I would need to write 'functional tests' for the controller to ensure that stuff was actually getting saved to the database anyway? I feel like I would be writing the same tests twice, once with a mocked up entity manager and once with a real one? So I'm kind of thinking of unit testing the models and functionally testing the controllers..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T08:03:50.110", "Id": "50365", "Score": "1", "body": "Well, there is a point in unit-testing controllers: You can test the entities, the entities, and all other objects, but unit-testing the _controller_ (using a client) is the best way of testing how they all come together, because that's what the controller does: it decides which part/method of what object is called where" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T08:13:20.130", "Id": "50366", "Score": "0", "body": "OK, so I need to test the controller, but in my unit test would it be best to use a real database connection (instead of a mocked up one) so that I can also test that things are really saved to the database?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T08:31:17.463", "Id": "50368", "Score": "0", "body": "Well, that's up to you, but I'd just use a temp DB setup, same schema's, but not the actual databases. You can then see if all data was stored correctly" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T09:43:51.367", "Id": "31353", "Score": "1", "Tags": [ "php", "unit-testing", "zend-framework", "doctrine" ], "Title": "Zend Framework and Doctrine 2 - are my unit tests sufficient?" }
31353
<p>This method works correctly and verifies whether a user has permissions to view or edit the first parameter (value). I think it is not the best implementation, because there are too many conditions and the <code>List</code> object isn't necessary. How to improve it?</p> <pre><code>protected override Exception GetValidationException( object value, string name ) { List&lt;Entity&gt; entities = value is int ? new List&lt;Entity&gt;( 1 ) { EntityCache.Entity.GetEntity( (int) value ) } : value is Guid ? new List&lt;Entity&gt;( 1 ) { EntityCache.Entity.GetEntityByGuid( (Guid) value ) } : value is int[] ? (value as int[]).Select( i =&gt; EntityCache.Entity.GetEntity( i ) ).ToList() : value is Entity ? new List&lt;Entity&gt;( 1 ) { value as Entity } : value is Entity[] ? (value as Entity[]).ToList() : null; if( entities == null ) throw new ArgumentException( string.Format( RI.UnknownArgumentType, name, value, value.GetType().Name ) ); bool hasPermission = (from one in entities select EntityPermissionCache.PermissionChecker( one.Id, one.EntityOrganizationId ) &amp;&amp; _checkEditInsteadOfView ? EntityTypePermissionCache.PermissionChecker( true, one.TypeId ) : true) .All( a =&gt; a ); return hasPermission ? null : new AccessViolationException( RI.AccessDenied ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T10:42:29.757", "Id": "49912", "Score": "0", "body": "Unless you call this method very often, I really doubt its performance is going to be a problem. Have you profiled your code? Is this method really the part that's slowing it down? If not, this is a premature optimization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T10:53:41.520", "Id": "49913", "Score": "0", "body": "Yes, it is a premature optimization. I have no way to test performance now, but this method calls everytime when users are trying to get any data from DB." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:11:28.180", "Id": "49923", "Score": "1", "body": "This is not a comment about performance. Maybe you could rethink the design. It does not seem very clean to me to have so many ways to call entities (int, int[], Entity,...). If you do keep that many, maybe you could at least split your method into a first method to convert whatever to `List<Entity>` and then a second method to validate that list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:07:42.227", "Id": "49930", "Score": "0", "body": "I agree. Splitting into different methods is good to understanding code." } ]
[ { "body": "<p>I think the assignment of your <code>entities</code> (bad name) is <strong>uber-abusing</strong> ternary expressions.</p>\n\n<p>That said, my first thought was <em>why on Earth would you want to <strong>return</strong> an <code>Exception</code></em>? So I googled up a bit and found <a href=\"https://softwareengineering.stackexchange.com/questions/207232/are-there-legitimate-reasons-for-returning-exception-objects-instead-of-throwing\">this</a>:</p>\n\n<blockquote>\n <p><em>Is it valid for a function to return exception objects?</em></p>\n \n <p>Absolutely. Here is a short list of examples where this may be appropriate:</p>\n \n <ul>\n <li>An exception factory.</li>\n <li>A context object that reports if there was a previous error as a ready to use exception.</li>\n <li>A function that keeps a previously caught exception.</li>\n <li>A third-party API that creates an exception of an inner type.</li>\n </ul>\n</blockquote>\n\n<p>Fine then. But there's a flaw in your API - you're taking in an <code>Object</code> for what seems to be an <code>Entity</code>.</p>\n\n<p>If I understand what you're trying to do here, I believe you'd be better off with an overloaded method:</p>\n\n<pre><code>protected override Exception GetValidationException(int value, string name)\nprotected override Exception GetValidationException(Guid value, string name)\nprotected override Exception GetValidationException(int[] value, string name)\nprotected override Exception GetValidationException(Entity value, string name)\nprotected override Exception GetValidationException(Entity[] value, string name)\n</code></pre>\n\n<p>...Or I'd find a way to make something like this work:</p>\n\n<pre><code>protected override Exception GetValidationException&lt;TValue&gt;(TValue value, string name)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T02:04:59.993", "Id": "35467", "ParentId": "31354", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T10:16:22.637", "Id": "31354", "Score": "3", "Tags": [ "c#", "performance" ], "Title": "Improve performance by excluding multiple conditions and List" }
31354
<p>I want to run the timer at 2:00 a.m. and shutdown the application. This is my code:</p> <pre><code> var ShutdownTimer = new Timer(); var currentTime = DateTime.Now; int hoursUntilShutdown; switch (currentTime.Hour) { case 1: hoursUntilShutdown = 1; break; case 2: hoursUntilShutdown = 0; break; default: hoursUntilShutdown = (24 - currentTime.Hour) + 2; break; } var shutdownTimeSpan = new TimeSpan(0, hoursUntilShutdown, 0, 0); ShutdownTimer.Interval = (int)shutdownTimeSpan.TotalMilliseconds; ShutdownTimer.Tick += this.OnShutdownTimer; ShutdownTimer.Start(); private void OnShutdownTimer(object sender, EventArgs e) { Environment.Exit(0); } </code></pre> <p>Any help will be greatly appreciated!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T12:33:39.313", "Id": "49917", "Score": "1", "body": "The whole `switch` can be replaced by `hoursUntilShutdown = (26 - currentTime.Hour) % 24`, where `%` is the remainder of the division, as in C (I don't use C#, so I can only assume it's the same)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T12:41:51.847", "Id": "49919", "Score": "0", "body": "@VedranŠego very good idea please post it as answer I just want vote it. this answer mathematically is better!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T12:44:03.310", "Id": "49920", "Score": "1", "body": "Which 2:00 a.m.? It's one of the more popular times for governments to jiggle around." } ]
[ { "body": "<p>The whole <code>switch</code> can be replaced by</p>\n\n<pre><code>hoursUntilShutdown = (26 - currentTime.Hour) % 24\n</code></pre>\n\n<p>where <code>%</code> is the remainder of the division, as in C (I don't use C#, so I can only assume it's the same).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:07:48.737", "Id": "31360", "ParentId": "31357", "Score": "2" } } ]
{ "AcceptedAnswerId": "31360", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T12:06:19.743", "Id": "31357", "Score": "2", "Tags": [ "c#", ".net" ], "Title": "I want to run the timer at 2:00 a.m. and shutdown the application" }
31357
<p>I have been working on a toggle script, but I find myself repeating my code. Is there a way of combining it all? <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery(document).ready(function($) { var topContainer = $("#alles"); var topButton = $(".abutton"); topButton.click(function() { topContainer.slideToggle(1200, 'easeInOutQuart'); $(".hideable").slideToggle(1200, 'easeInOutQuart'); }); var topContainer2 = $("#voorbeelden"); var topButton2 = $(".bbutton"); topButton2.click(function() { topContainer2.slideToggle(1200, 'easeInOutQuart'); $(".hideable").slideToggle(1200, 'easeInOutQuart'); }); var topContainer3 = $("#contact"); var topButton3 = $(".cbutton"); topButton3.click(function() { topContainer3.slideToggle(1200, 'easeInOutQuart'); $(".hideable").slideToggle(1200, 'easeInOutQuart'); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display:block; width:500px; margin:0 auto; } .hideable { width: 500px; margin: 0 auto; } #alles { float:left; width:500px; height:500px; background:#ff4000; } #voorbeelden { float:left; width:500px; height:100px; border-top:1px solid #ddd; background:#cc6600; } #contact { float:left; width:500px; height:100px; border-top:1px solid #ddd; background:#bb3300; } .toggleable { display:none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;header&gt; &lt;h1&gt;stuff&lt;/h1&gt; &lt;h2&gt;more stuff&lt;/h2&gt; &lt;/header&gt; &lt;div id="main" class="hideable"&gt;&lt;img src="imgs/rk.svg" alt="image"&gt;&lt;/div&gt; &lt;div id="alles" class="toggleable"&gt;&lt;/div&gt; &lt;div id="voorbeelden" class="toggleable"&gt;&lt;/div&gt; &lt;div id="contact" class="toggleable"&gt;&lt;/div&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="#" class="abutton"&gt; &lt;h2 class="orsp-title"&gt;a&lt;/h2&gt; &lt;span class="orsp-category"&gt;stuff&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#" class="bbutton"&gt; &lt;h2 class="orsp-title"&gt;b&lt;/h2&gt; &lt;span class="orsp-category"&gt;stuff&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#" class="cbutton"&gt; &lt;h2 class="orsp-title cbutton"&gt;c&lt;/h2&gt; &lt;span class="orsp-category"&gt;stuff&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!--/container--&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:54:01.843", "Id": "49938", "Score": "0", "body": "Have you looked at *event delegation*?" } ]
[ { "body": "<p>You can either write a method that is bound to the global scope and takes two arguments, the onClick element and the slideToggle element, and does just what you want (without writing redundant code).</p>\n\n<pre><code>function bindToggleTwo(cElem, tElem) {\n $(cElem).click(function() {\n $(tElem).slideToggle(1200, 'easeInOutQuart');\n $(\".hideable\").slideToggle(1200, 'easeInOutQuart');\n });\n}\n\njQuery(document).ready(function($) {\n bindToggleTwo(\"#alles\", \".abutton\");\n bindToggleTwo(\"#voorbeelden\", \".bbutton\");\n bindToggleTwo(\"#contact\", \".cbutton\");\n});\n</code></pre>\n\n<p>Alternatively, you could write a jQuery function that is called on a jQuery object to do the very same. Basically this is a function that expects to be scoped such that <code>this</code> is a jQuery object. Anyway, both of these methods work, and will simplify your code. :)</p>\n\n<pre><code>jQuery.fn.bindToggleTwo = function(tElem) {\n $(this[0]).click(function() {\n $(tElem).slideToggle(1200, 'easeInOutQuart');\n $(\".hideable\").slideToggle(1200, 'easeInOutQuart');\n });\n}\n\njQuery(document).ready(function($) {\n $(\"#alles\").bindToggleTwo(\".abutton\");\n $(\"#voorbeelden\").bindToggleTwo(\".bbutton\");\n $(\"#contact\").bindToggleTwo(\".cbutton\");\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T16:32:38.010", "Id": "49944", "Score": "2", "body": "I would +1 this if you had a description of what you are suggesting, and why you are suggesting it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:57:59.330", "Id": "49950", "Score": "0", "body": "added brief explanation" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T15:24:53.680", "Id": "31369", "ParentId": "31367", "Score": "3" } }, { "body": "<p>First, let's clean up your code a bit more to reduce it to it's basics (demo see here <a href=\"http://jsfiddle.net/bjelline/azfXy/\" rel=\"nofollow\">http://jsfiddle.net/bjelline/azfXy/</a>):</p>\n\n<pre><code>&lt;div id=\"alles\" class=\"toggleable\"&gt;alles content&lt;/div&gt;\n&lt;div id=\"voorbeelden\" class=\"toggleable\"&gt;voorbeelden content&lt;/div&gt;\n&lt;div id=\"contact\" class=\"toggleable\"&gt;contact content&lt;/div&gt;\n&lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\" class=\"abutton\"&gt;show alles&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\" class=\"bbutton\"&gt;show voorbeelden&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\" class=\"cbutton\"&gt;show contact&lt;/a&gt;&lt;/li&gt; \n&lt;/ul&gt;\n</code></pre>\n\n<p>there are three buttons that are supposed to toggle three divs in another part of the page. </p>\n\n<p>First we have to create a connection between the buttons and the divs. that's easy: you already made them links to #, we can just add the id of the corresponding div here. Also, I changed the class on the three buttons to be the same - we have the href to distinguish them:</p>\n\n<pre><code>&lt;div id=\"alles\" class=\"toggleable\"&gt;alles content&lt;/div&gt;\n&lt;div id=\"voorbeelden\" class=\"toggleable\"&gt;voorbeelden content&lt;/div&gt;\n&lt;div id=\"contact\" class=\"toggleable\"&gt;contact content&lt;/div&gt;\n&lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#alles\" class=\"button\"&gt;show alles&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#voorbeelden\" class=\"button\"&gt;show voorbeelden&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#contact\" class=\"button\"&gt;show contact&lt;/a&gt;&lt;/li&gt; \n&lt;/ul&gt;\n</code></pre>\n\n<p>Now handling the click on the button is the same for all buttons: preven the normal funktioning of the link, read out the href, toggle the correspondig div:</p>\n\n<pre><code>$('.button').click(function (event) {\n event.preventDefault();\n var id = $(this).attr('href');\n $(id).slideToggle(200);\n});\n</code></pre>\n\n<p>Working Demo at <a href=\"http://jsfiddle.net/bjelline/ZmAK4/\" rel=\"nofollow\">http://jsfiddle.net/bjelline/ZmAK4/</a></p>\n\n<p>And while you are learning jQuery: always try to uphold two principles:</p>\n\n<ul>\n<li>the page should still be readable without javascript (progressive enhancement)</li>\n<li>put all javascript into tags or js-files, not in html attributes</li>\n</ul>\n\n<p>how can we make the page usabel without javascript? easy: without javascript, everything should be visible. how do we achive that? don't use CSS to hide the .togglables but use the first line of javascript instead. </p>\n\n<pre><code>$('.togglables').hide();\n</code></pre>\n\n<p>P.S. now I try to add the image that indicates if any of the divs is visible (demo see here <a href=\"http://jsfiddle.net/bjelline/HmCWr/\" rel=\"nofollow\">http://jsfiddle.net/bjelline/HmCWr/</a>)</p>\n\n<pre><code>$('.button').click(function (event) {\n event.preventDefault();\n var id = $(this).attr('href');\n $(id).toggle();\n\n $('.hideable').toggle( $('.toggleable:visible').length &gt; 0 );\n});\n</code></pre>\n\n<p>Here <strong>$('.toggleable:visible').length</strong> counts the number of divs that are visible. if theres more then one visible, the image is show, else it is hidden (with the method <strong>toggle(true/false)</strong> )</p>\n\n<p>Notice that I removed the Slide-Animation. I'm avoiding the following problem: With the slide animation the div that is just closing still count's as open.</p>\n\n<p>If you insist on the slide animation you probably need javascript variables to record the open/close state of each div.....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T07:43:36.980", "Id": "50026", "Score": "0", "body": "thank you bjelli for cleaning up, only one important element got lost during the cleaning :) the image that needs to be hidden when a hidden div is toggled, and needs to re-appear after that same div is hidden again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T07:44:56.663", "Id": "50027", "Score": "0", "body": "is there only one image? that should be visible if any of the divs is shown?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:38:51.103", "Id": "50041", "Score": "0", "body": "Its the other way around, there is one image that is shown unless one or more toggleable divs are shown, then it needs to be hidden. Thank you by the way very much for helping out here!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:52:14.457", "Id": "50042", "Score": "0", "body": "Maybe the first solution you have written: http://jsfiddle.net/bjelline/ZmAK4/ is combinable with an if else statement that says: if .toggleable = shown .hideable needs to be hidden else (when .togglebale is not visible) .hideable needs to be visible. or doesnt it work like that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T10:38:58.040", "Id": "50047", "Score": "0", "body": "yes, it worked! http://jsfiddle.net/HmCWr/5/" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T02:37:58.753", "Id": "31403", "ParentId": "31367", "Score": "3" } } ]
{ "AcceptedAnswerId": "31403", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:39:22.930", "Id": "31367", "Score": "5", "Tags": [ "javascript", "beginner", "jquery", "html", "css" ], "Title": "jQuery toggle script" }
31367
<p>I need some tips on how I can improve the design of the following code. Everything works correctly in the program. It takes a string and shows each token, the only tokens being numbers and operators. The output shows all the tokens and what type of token they are. </p> <pre><code>public class Tokenizer { int pos; char[] expression; Tokenizer(String expression) { this.expression = expression.toCharArray(); this.pos = 0; } enum Type { OPERATOR, NUMBER, UNKNOWN } class Lexeme { String type, token; Lexeme(String type, String token) { this.type = type; this.token = token; } } Lexeme getToken() { StringBuilder token = new StringBuilder(); boolean endOfToken = false; Type type = Type.UNKNOWN; while (!endOfToken &amp;&amp; hasMoreToken()) { while(expression[pos] == ' ') pos++; switch (expression[pos]) { case '+': case '-': case '*': case '/': if(type != Type.NUMBER) { type = Type.OPERATOR; token.append(expression[pos]); pos++; } endOfToken = true; break; case ' ': endOfToken = true; pos++; break; default: if(Character.isDigit(expression[pos]) || expression[pos] == '.') { token.append(expression[pos]); type = Type.NUMBER; } else { System.out.println("Systax error at position: " + pos); } pos++; break; } } return new Lexeme(type.name().toLowerCase(), token.toString()); } boolean hasMoreToken() { return pos &lt; expression.length; } public static void main(String[] args) { // TODO code application logic here String expression = "12.3 / 5 - 22"; Tokenizer tokenizer = new Tokenizer(expression); while (tokenizer.hasMoreToken()) { Lexeme nextToken = tokenizer.getToken(); System.out.print("Type: " + nextToken.type + "\tLexeme: " + nextToken.token + "\n"); } } } </code></pre>
[]
[ { "body": "<p>This code looks quite nice, actually. If this was a homework assignment, you could almost turn it in right now. I only have some minor issues with the code, plus some bugs, and would then like to talk about alternatives to structure your lexer (the words <em>tokenizer</em>, <em>lexer</em> and <em>scanner</em> are all equivalent here).</p>\n\n<ul>\n<li>I don't see a single comment in your code, aside from that TODO.</li>\n<li><code>hasMoreToken</code> should be <code>hasMoreTokens</code>. Notice the plural-“s”. This makes reading the code more pleasant.</li>\n<li>Each lexeme should have a <code>Type type</code>, not a <code>String type</code>. By using a string, you loose all type safety. (Apparently there is a name for this antipattern: <a href=\"http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html\" rel=\"noreferrer\">Stringly Typed</a>).</li>\n<li>You should probably <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#name%28%29\" rel=\"noreferrer\">use <code>toString()</code> instead of <code>name()</code></a>. This should not happen before the type is actually printed out, i.e. only in the <code>main</code>.</li>\n<li>A seasoned Java programmer will use a lot more visibility modifiers. Especially <code>pos</code> and <code>expression</code> ought to be private. but I personally don't care.</li>\n<li>You have inconsistent formatting. You put the opening braces of class and method declarations on the same line, but you put them under the keyword for control flow statements. In Java, the braces usually open on the same line.</li>\n<li>It looks as if your switch was outdented one level. This happens because you didn't use a block for the preceding <code>while</code>. Always using blocks can make code easier to read.</li>\n<li>General style note: Place blank lines between logically seperate blocks of your code. Inside the <code>Lexeme</code> class, a blank line between the fields and the methods could improve readability.</li>\n<li><p>This piece of code:</p>\n\n<pre><code>while(expression[pos] == ' ')\n pos++;\n</code></pre>\n\n<p>will attempt to access an array entry outside of the allowed range when the strings ends with whitespace. Add a bounds check here.</p></li>\n</ul>\n\n<p>On an architecture level, it would be nice to make your <code>Tokenizer</code> an <code>Iterable</code>. Heck, it implicitly already is a kind of <code>Iterator</code>. If we clean that up, we can do:</p>\n\n<pre><code>for (Token token : new Tokenizer(expression)) {\n System.out.println(...);\n}\n</code></pre>\n\n<p>We can turn it into an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html\" rel=\"noreferrer\"><code>Iterator</code></a> by renaming <code>hasMoreTokens</code> to <code>hasNext</code> and <code>getToken</code> to <code>next</code>. If you can't rename them, a wrapper method will do as well. We also need a dummy method <code>remove</code> that throws an <code>UnsupportedOpertationException</code>. If we want to make it <code>Iterable</code>, we need to add an <code>iterator</code> method that returns the object itself, although this may be considered hackish.</p>\n\n<h1>The State Machine, and Why I Don't Like It</h1>\n\n<p>In your <code>getToken</code> method, you have written a kind of state machine that performs the parsing. You have seemingly flattened it into a single state with one character lookahead, but it actually has three (plus two) different states. Here are all transitions you have written:</p>\n\n<pre><code># transitions that consume a char are written A -- char -&gt; B\n# lookahead transitions are written A --(char)-&gt; B\n\nSTART --(not ' ')-&gt; UNKNOWN\nSTART -- ' ' -&gt; START\n\n# the operator cases\nUNKNOWN -- '+'|'-'|'*'|'/' -&gt; OPERATOR END\nNUMBER --('+'|'-'|'*'|'/')-&gt; END\n\n# the whitespace case\nUNKNOWN -- ' ' -&gt; END # unreachable\nOPERATOR -- ' ' -&gt; END # unreachable\nNUMBER -- ' ' -&gt; END\n\n# the default digit case\nUNKNOWN -- '0'..'9'|'.' -&gt; NUMBER\nNUMBER -- '0'..'9'|'.' -&gt; NUMBER\nOPERATOR -- '0'..'9'|'.' -&gt; NUMBER # unreachable\n\n# the default error case\nUNKNOWN -- not '0'..'9'|'.' -&gt; UNKNOWN\nNUMBER -- not '0'..'9'|'.' -&gt; NUMBER\nOPERATOR -- not '0'..'9'|'.' -&gt; OPERATOR # unreachable\n</code></pre>\n\n<p>There might be a few issues with this.</p>\n\n<ol>\n<li>You can't output good error messages, because you don't have that good of an idea where you are, and because you skip over any junk in the string, allowing for <code>12foobar3</code> to be recognized as <code>123</code>. Any extensions to the lexer would therefore be backwards-incompatible.</li>\n<li>Extending this kind of lexer is difficult with increasing number of different token types, because all possible transitions have to be considered for that type, as all transitions happen in that <em>one</em> switch.</li>\n<li>It obscures the actual flow of control.</li>\n<li>You would consider <code>...</code> to be a number.</li>\n<li>I don't feel comfortable with consuming the char in the whitespace case. It is logically separate from tokenizing a number, and therefore should be separated in your code.</li>\n<li>The existence of an <code>UNKNOWN</code> type is ridiculous. This is a case where having a <code>null</code> type might be preferable, and complaining if it is still null at the end of the method.</li>\n</ol>\n\n<p>It might be better to make your states more explicit as actual states in your code. Also note that single-character lookahead is sufficient for your grammar, but would have difficulties recognizing operators like <code>&lt;=</code>.</p>\n\n<p>Another thing worth considering would be to put the body of your <code>while(hasMoreTokens())</code> loop into a seperate method – this would remove the need for the <code>endOfToken</code> flag, as you could simply <code>return</code>. First, optimize for simplicity and readability, only second for performance.</p>\n\n<p>Together, I might write code like this (untested sketch, no final code):</p>\n\n<pre><code>...\n\nboolean illegalState = false;\n\npublic boolean hasNext() {\n return pos &lt; expression.length &amp;&amp; !illegalState;\n}\n\npublic Lexeme next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n\n // this can be removed if we do it in the constructor,\n // as we remove all WS *after* each token.\n skipWhitespace();\n\n // dispatch actual tokenization based on single character lookahead\n Lexeme lexeme;\n char c = expression[pos];\n if (c == '+' || c == '-' || c == '*' || c == '/') {\n pos++;\n lexeme = new Lexeme(Type.OPERATOR, Character.toString(c));\n } else if ('0' &lt;= c &amp;&amp; c &lt;= '9') {\n lexeme = tokenizeNumber();\n } else {\n illegalState = true;\n throw new java.text.ParseException(\"Expected operator or number\", pos);\n }\n\n // clean up after ourselves, so that hasNext() doesn't recognize\n // trailing whitespace as another token:\n skipWhitespace();\n\n return lexeme;\n}\n\nprivate void skipWhitespace() {\n while(pos &lt; expression.length &amp;&amp; expression[pos] == ' ') {\n pos++;\n }\n}\n\nprivate Lexeme tokenizeNumber() {\n StringBuilder token = new StringBuilder();\n\n // effectively, this method recognizes the language specified by the regex\n // /[0-9]+(?:\\.[0-9]+)?/\n // (PCRE style)\n\n // lex the integer part\n int posBeforeInt = pos;\n while (pos &lt; expression.length &amp;&amp; '0' &lt;= expression[pos] &amp;&amp; expression[pos ] &lt;= '9') {\n token.append(expression[pos++]);\n }\n if (pos == posBeforeInt) {\n illegalState = true;\n throw new java.text.ParseException(\"Every number must have an integer part\", pos);\n }\n\n // optional: lex decimal\n if (expression[pos] == '.') {\n token.append(expression[pos++]);\n\n int posBeforeDecimal = pos;\n while (pos &lt; expression.length &amp;&amp; '0' &lt;= expression[pos] &amp;&amp; expression[pos ] &lt;= '9') {\n token.append(expression[pos++]);\n }\n if (pos == posBeforeDecimal) {\n illegalState = true;\n throw new java.text.ParseException(\"Number has decimal point, but no decimal digits\", pos);\n }\n }\n\n return new Lexeme(Type.NUMBER, token.toString());\n}\n</code></pre>\n\n<p>You may have noticed that this lexer is much more similar to a top-down parser now, which I find easier to reason about. There is no difference between a lexer and parser, both transform a list of X to Y by giving them structure. (Lexer: chars → tokens, Parser: tokens → parse tree).</p>\n\n<p>An abstraction possibility that opens up is the concept of a <em>character class</em> – a <code>Set</code> of characters with common properties. E.g. <code>'0' &lt;= expression[pos] &amp;&amp; expression[pos ] &lt;= '9'</code> ought to be written as <code>digits.contains(expression[pos])</code>. Also, there are dozens more whitespace characters than just the <code>\\x20</code> space character.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T22:19:36.113", "Id": "31391", "ParentId": "31370", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T16:06:34.823", "Id": "31370", "Score": "9", "Tags": [ "java", "strings", "parsing" ], "Title": "String tokenizer design" }
31370
<p>I have the following code which changes the text in a certain element on click depending on the text value present in the element at the time the event is fired.</p> <p><a href="http://jsfiddle.net/TNDhL/" rel="nofollow">http://jsfiddle.net/TNDhL/</a></p> <pre><code>$('#left').on('click', function (){ if ($("#textContainer:contains('something')").length) { $('#textContainer').text('third text replacement'); $('.elsewhere').text('more here'); } else if ($("#textContainer:contains('third text replacement')").length) { $('#textContainer').text('now the next item'); $('.elsewhere').text('something new here'); } else if ($("#textContainer:contains('now the next item')").length) { $('#textContainer').text('new text here'); $('.elsewhere').text('something else here'); } else if ($("#textContainer:contains('new text here')").length) { $('#textContainer').text('something'); $('.elsewhere').text('text here'); } }); $('#right').on('click', function (){ if ($("#textContainer:contains('something')").length) { $('#textContainer').text('new text here'); $('.elsewhere').text('something else here'); } else if ($("#textContainer:contains('new text here')").length) { $('#textContainer').text('now the next item'); $('.elsewhere').text('something new here'); } else if ($("#textContainer:contains('now the next item')").length) { $('#textContainer').text('third text replacement'); $('.elsewhere').text('more here'); } else if ($("#textContainer:contains('third text replacement')").length) { $('#textContainer').text('something'); $('.elsewhere').text('text here'); } }); </code></pre> <p>Please see fiddle above for working version.</p> <p>In this instance clicking on 'Left' or 'Right' would change the text above.</p> <p>Is there a better way to handle this case? Main goal is to allow for easier extension of these simple functions into something more complex that involves several similar click events. Something less error prone and easier to maintain/grow. Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:31:32.570", "Id": "49946", "Score": "0", "body": "do you need that fuzzy match?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:36:44.917", "Id": "49947", "Score": "0", "body": "Ah... hadn't thought about it until you mention it but no I actually don't want :contains but instead an exact match for the string." } ]
[ { "body": "<p>The easier (imho) solution would be to store what you want in an nested object containing the matches :</p>\n\n<pre><code>var selectors = {\n left: {\n 'something': ['third text replacement', 'more here'],\n 'third text replacement': ['now the next item', 'something new here'],\n }\n};\n\nvar $textContainer = $('#textContainer')\n , $elsewhere = $('.elsewhere');\nfor (var sel in selectors) {\n void function(sel, matches) {\n $('#'+sel).click(function() {\n for (var i = 0; i &lt; matches.length; ++i) {\n // change \"this.value\" if it's not an input\n if (this.value == matches[i]) {\n // we found a match, let's update the value\n $textContainer.text(matches[i][0]);\n $elseWhere.text(matches[i][1]);\n // and return early\n break;\n }\n }\n });\n }(sel, selectors[sel]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:53:06.347", "Id": "49949", "Score": "1", "body": "Just for information: `void` is used here to create an IIFE. One could also use parentheses around the function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:44:29.670", "Id": "31380", "ParentId": "31374", "Score": "1" } }, { "body": "<p>Displaying lots of content? This is not a job for Javascript, this is a Job for HTML. Keep the content in HTML, where non-programmers can maintain it:</p>\n\n<pre><code>&lt;div id=\"textContainer\"&gt;\n &lt;div class=\"t1\"&gt;something&lt;/div&gt;\n &lt;div class=\"t2\"&gt;third text replacement&lt;/div&gt;\n &lt;div class=\"t3\"&gt;now the next item&lt;/div&gt;\n &lt;div class=\"t4\"&gt;new text here&lt;/div&gt;\n&lt;/div&gt;\n&lt;hr /&gt;\n&lt;div id=\"left\"&gt;Left&lt;/div&gt;\n&lt;div id=\"right\"&gt;Right&lt;/div&gt;\n&lt;hr /&gt;\n&lt;div class=\"elsewhere\"&gt;\n &lt;div class=\"t1\"&gt;text here&lt;/div&gt;\n &lt;div class=\"t2\"&gt;more here&lt;/div&gt;\n &lt;div class=\"t3\"&gt;something new here&lt;/div&gt;\n &lt;div class=\"t4\"&gt;something else here&lt;/div&gt; \n&lt;/div&gt;\n</code></pre>\n\n<p>and use JS only to display/hide it:</p>\n\n<pre><code>var cursor = 1;\nvar max = $('#textContainer div').length;\n\nfunction redisplay() {\n $('#textContainer div').hide();\n $('#textContainer div.t'+cursor).show();\n $('.elsewhere div').hide();\n $('.elsewhere div.t'+cursor).show();\n}\n\n$('#left').on('click', function (){\n cursor--;\n if(cursor &lt; 1) cursor = max ;\n redisplay();\n});\n\n$('#right').on('click', function (){\n cursor++;\n if(cursor &gt; max) cursor = 1; \n redisplay();\n});\n\nredisplay();\n</code></pre>\n\n<p>(you might want to move the variables cursor + max from the global namespace to something more private)</p>\n\n<p>working demo at <a href=\"http://jsfiddle.net/bjelline/KV63M/\" rel=\"nofollow\">http://jsfiddle.net/bjelline/KV63M/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:48:28.087", "Id": "50085", "Score": "0", "body": "You are correct, it was becoming too much to maintain all the content in JavaScript. Your method requires I do a bit more on the front end to extend a few functions I had planned but overall its much easier. Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T02:11:55.670", "Id": "31402", "ParentId": "31374", "Score": "1" } } ]
{ "AcceptedAnswerId": "31402", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T17:38:13.043", "Id": "31374", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Simplifying multiple click events into something more extendable" }
31374
<p>I've read the docs online explaining Log N and I do understand that the basic concept of it, but I'm still not sure I've managed to nail it.</p> <blockquote> <p><strong>The problem</strong></p> <p>This exercise is called <em>"Complementary Pairs"</em> and given an array <em>A</em> and an integer <em>K</em>, how many pairs of <em>A</em>, sum to <em>K</em>.</p> <p>For example, with this input:</p> <pre><code>k = 6 a = [1, 8, -3, 0, 1, 3, -2, 4, 5] </code></pre> <p>we would have 7 possibilities, like i, j = (5, 5) to add 3 + 3, then the pairs that add 1 + 5 (and the reverse), etc. </p> <p><strong>Naive solution</strong></p> <p>A first very naive solution is to for a \$O(N^2)\$ complexity loop where you just bluntly search the array in two nested loops.</p> </blockquote> <p><strong>\$N * Log N\$ Solution</strong></p> <p>From my understanding a proper \$Log N\$ solution has to include a binary search like quicksort or mergesort, so I applied a divide and conquer algorithm where I split the array in two, until it's down to one element, then I assemble back again, and I for a \$N*N\$ search on array, checking which elements of the first added with the second add to constant <em>K</em>.</p> <p>Although this is very similar to mergesort, it just doesn't feel a \$N * Log N\$ solution, because the worst case, the last recursion step, I'm doing \$N/2 * N/2\$ and for me that's just \$N*N\$ over time.</p> <p>Here is the working solution:</p> <pre><code>var complementary_pairs = function (input, k) { // Base scenario if (input.length == 1) { return input[0] * 2 == k ? 1 : 0 } // Recursion var middle = Math.ceil(input.length / 2) , firstArray = input.slice(0, middle) , secondArray = input.slice(middle) var count = complementary_pairs(firstArray, k) + complementary_pairs(secondArray, k) // Problem condition for (var i = 0; i &lt; firstArray.length; i++) { for (var j = 0; j &lt; secondArray.length; j++) { if (firstArray[i] + secondArray[j] == k) { count += 2 } } } return count } console.log(complementary_pairs([1, 8, -3, 0, 1, 3, -2, 4, 5], 6)) </code></pre>
[]
[ { "body": "<p>This is not O(n log n) algorithm, because this part is quadratic:</p>\n\n<pre><code> for (var i = 0; i &lt; firstArray.length; i++) {\n for (var j = 0; j &lt; secondArray.length; j++) {\n if (firstArray[i] + secondArray[j] == k) {\n count += 2\n }\n }\n }\n</code></pre>\n\n<p>Denoting <code>n = input.length</code>, this has roughly <code>(n/2)^2 = n^2/4</code> steps, which is O(n^2).</p>\n\n<p><strong>The rest of this answer is a result of a misread and is not directly related to the question.</strong> I'll leave it as a comment of a possibly extended exercise.</p>\n\n<p>However, I'm not sure that O(n log n) algorithm does exist. Consider</p>\n\n<pre><code>a = [ 1, 2, 4, 8, ..., 2^n ] (for some n)\n</code></pre>\n\n<p>and <code>k</code> is a sum of all elements in <code>a</code>. Since you can repeat the numbers, and <code>a[k] = 2*a[k-1]</code> for all positive <code>k</code>, you'd have exponential number of sums, so no O(n log n) algorithm will solve this.</p>\n\n<p>It is easy to show that the number of solutions is strictly bigger than 2^n. Just note that</p>\n\n<pre><code>k = (sum of ANY elements in a except a[0] = 1) + (sum of the remaining elements in a) * 1.\n</code></pre>\n\n<p>The first sum can be chosen in 2^n ways. Of course, there are other sums as well, but this is enough to show that you can have an exponential number of solutions, which is enough to show that no sub-exponential algorithm can find them all.</p>\n\n<p>Of course, there may be a mathematical trick to compute only how many such solutions there are, but I don't know it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:45:54.797", "Id": "49948", "Score": "0", "body": "thanks for a great answer, I took this exercise from a repo which has some codility exercises: https://github.com/bitoiu/codility/tree/master/complementary_pairs. It specifically asks for a sub quadratic answer, but like you say, this might dwell on a number trick that would make computing it more trivial. thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:15:15.920", "Id": "49979", "Score": "0", "body": "Scratch that. I've missed the part about **pairs**. My answer proved only that **all sums** cannot be found in sub-exponential time (actually, sometimes such problem has infinitely many solutions!). IMO, you should accept one of the other two answers instead of mine." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:28:29.347", "Id": "31378", "ParentId": "31377", "Score": "4" } }, { "body": "<p>I might have missed something but I think I do have an <code>O(n*log(n))</code> solution.</p>\n\n<p>Assuming <code>A</code> is your array of size n and <code>K</code> is the integer.</p>\n\n<ul>\n<li>Sort <code>A</code> with a efficient sorting algorithm (mergesort, quicksort, etc) : this is <code>O(n*log(n))</code></li>\n<li><p>For each element <code>x</code> in <code>A</code>:</p>\n\n<ul>\n<li>Use binary search to find the first occurrence of <code>K-x</code> (if any) : this is <code>O(log(n))</code></li>\n<li><p>Use binary search to find the last occurrence if <code>K-x</code> (if any) : this is <code>O(log(n))</code></p>\n\n<p>-> These steps allow you to find the number of instances of <code>K-x</code> in <code>O(log(n))</code></p></li>\n</ul>\n\n<p>->This allows you to count the number of pairs in <code>O(n*log(n))</code>. Each pair has been counted twice. </p></li>\n</ul>\n\n<p>Many minimal optimisations could be performed : </p>\n\n<ul>\n<li>Handling the identical values of <code>x</code> in one go</li>\n<li>Looping could stop when <code>2*x &gt; K</code></li>\n<li>Binary search could be limited to a smaller sub-array as we progress through <code>A</code></li>\n<li>Etc</li>\n</ul>\n\n<p>Please let me know if I missed something.</p>\n\n<p><strong>Edit :</strong> \nHere's a quick attempt with an initial array containing the original array twice to make testing somewhat easier.</p>\n\n<p>I've included different versions, more and more optimised. One could go further but I started to have doubts about the correctness :-)</p>\n\n<p><a href=\"http://jsfiddle.net/ZYKPZ/\" rel=\"nofollow\">Corresponding jsfiddle</a></p>\n\n<pre><code>var a = [1, 8, -3, 0, 1, 3, -2, 4, 5, 1, 8, -3, 0, 1, 3, -2, 4, 5];\nvar target = 6;\na.sort(function(a, b) {return a - b});\n\nfunction binarySearch(a, k, lastOcc, min)\n{\n var min = (typeof(min)==='undefined') ? 0 : min\n var max = a.length-1\n while (min &lt;= max)\n {\n var range = max-min\n var midf = min + (range / 2)\n var mid = lastOcc ? Math.ceil(midf) : Math.floor(midf)\n var x = a[mid]\n if (x &lt; k) min = mid+1\n else if (x &gt; k) max = mid-1\n else if (min==max) return mid\n else if (lastOcc) min = mid\n else max = mid\n }\n return -1\n}\n\n// Zeroth solution\nvar count = 0\nfor (var i=0; i&lt;a.length; i++)\n{\n for (var j=0; j&lt;a.length; j++)\n {\n if (a[i]+a[j]==target) count++\n }\n}\nconsole.log(count)\n\n// First solution\nvar count = 0\nfor (var i=0; i&lt;a.length; i++)\n{\n var v = a[i]\n var x = target-v\n var f = binarySearch(a,x,false)\n if (f&gt;-1)\n {\n var l = binarySearch(a,x,true)\n var nb = 1+l-f\n count+=nb\n }\n}\nconsole.log(count)\n\n// Second solution - skipping over identical values\nvar count = 0\nfor (var i=0; i&lt;a.length; i++)\n{\n var v = a[i]\n var coef = 1\n while (i+1&lt;a.length &amp;&amp; a[i+1]==v)\n {\n coef++\n i++\n }\n var x = target-v\n var f = binarySearch(a,x,false)\n if (f&gt;-1)\n {\n var l = binarySearch(a,x,true)\n var nb = 1+l-f\n count+=nb*coef\n }\n}\nconsole.log(count)\n\n// Third solution - stopping once enough is enough\nvar count = 0\nfor (var i=0; i&lt;a.length; i++)\n{\n var v = a[i]\n var coef = 1\n while (i+1&lt;a.length &amp;&amp; a[i+1]==v)\n {\n coef++\n i++\n }\n var x = target-v\n if (v &lt;= x)\n {\n if (v != x) coef*=2\n var f = binarySearch(a,x,false)\n if (f&gt;-1)\n {\n var l = binarySearch(a,x,true)\n var nb = 1+l-f\n count+=nb*coef\n }\n }\n else break\n}\nconsole.log(count)\n\n// Fourth solution - limiting the binary search to a smaller scope\nvar count = 0\nfor (var i=0; i&lt;a.length; i++)\n{\n var oldi=i\n var v = a[i]\n var coef = 1\n while (i+1&lt;a.length &amp;&amp; a[i+1]==v)\n {\n coef++\n i++\n }\n var x = target-v\n if (v &lt; x)\n {\n var f = binarySearch(a,x,false,i)\n if (f&gt;-1)\n {\n var l = binarySearch(a,x,true,f)\n var nb = 1+l-f\n count+=2*nb*coef\n }\n }\n else if (x==v)\n {\n count+=coef*coef\n break\n }\n else break\n}\nconsole.log(count)\n</code></pre>\n\n<p><strong>Re-edit :</strong></p>\n\n<p>I've tested my code with the following inputs and all functions are returning the same values... but not in the same time.</p>\n\n<pre><code>var a = []\nfor (var i=0; i&lt;10000; i++)\n{\n a.push(Math.floor(Math.random()*20))\n}\nvar target = a[0]+a[1]; // ensuring results\n</code></pre>\n\n<p>Zeroth solution is <code>O(n^2)</code>\nFirst solution is <code>O(n*log(n) + n*log(n))</code> which is <code>O(n*log(n))</code>\nSecond solution is stricly better.\nThird solution is stricly better.\nFourth solution is stricly better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:23:35.010", "Id": "49981", "Score": "0", "body": "I think you don't need to *Use binary search to find the last occurrence if `K-x` (if any)*. Just go from the first one, and lineary check how many of them are." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:25:42.363", "Id": "49982", "Score": "0", "body": "I'm just missing what you mean by K-x. I though of sorting the array first, but I didn't see how could I traverse it with a O(n) complexity. I need to find all the pairs (x,x') where A[x] + A[x'] = k. Is that what you said?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:28:50.330", "Id": "49984", "Score": "0", "body": "@bitoiu `x` is an element of `a`, not an index. ;-) So, if `x = a[i]` for some `i`, you're looking for `K - x = K - a[i]` in the array. If you find it, i.e., you find `j` such that `a[j] = K - x = K - a[i]`, you've found a pair." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:32:28.600", "Id": "49985", "Score": "0", "body": "@VedranŠego I wanted to avoid checking *lineary* how many of them we have. Just to be safe, I'd rather perform 2 logarithmic operations. (It's not only about me being paranoid, I was mostly looking for a proof of concept)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:33:22.057", "Id": "49986", "Score": "0", "body": "@VedranŠego This being said, I now have doubts than binary search on first and last occurrences are actually. Let's implement this and see :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:41:21.833", "Id": "49989", "Score": "0", "body": "@VedranŠego can't thank you enough, but I really can't see how you do that search in log n time, that's probably, I can't seem to find the base case of recursion. sorry if I'm not being very helpful and this is trivial." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:42:26.527", "Id": "49990", "Score": "0", "body": "@Josay In extreme cases, 2 logs would be better, i.e., when you have at least log n equal elements in array. But, in an average case, I'd say linear would be better, because it's not linear in `n`, but in \"the number of equal elements\", which I wouldn't expect to grow over 2 or three. It would probably be better to make an associative array with each number repeated once and remembering how many times it occurs in the original array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:44:42.130", "Id": "49992", "Score": "0", "body": "@bitoiu You don't need a recursion. The key is to use the fact that your array is sorted. You check the middle element. If it's to small, you go on to the right half of the array; if it's too big, you continue with left half. In each step you halve the part of array you need to search, thus doing so in at most `log_2 n` steps. Check it [here](http://en.wikipedia.org/wiki/Binary_search_algorithm) and feel free to ask if you have trouble understanding something." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:46:37.797", "Id": "49993", "Score": "0", "body": "@bitoiu Here what I have so far : http://jsfiddle.net/v9ppL/1/\nNot all optimisations have been performed but that's a start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:56:29.353", "Id": "49996", "Score": "0", "body": "It's a bit late now, I'll check both Vedran and @Josey implementations tomorrow, I bet one or both have the right answer, thanks you very much. I'll reply tomorrow morning ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:57:54.907", "Id": "49997", "Score": "0", "body": "@VedranŠego, good suggestion on the iterative log n, I'll look into that as well" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T08:09:07.743", "Id": "50029", "Score": "0", "body": "@Josay you can add the fiddle on top of your answer, it will help people detect it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T08:25:31.460", "Id": "50030", "Score": "0", "body": "@Josay do you have a github account so when I commit the solution I mention this post and yourself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T12:12:58.147", "Id": "50054", "Score": "0", "body": "@bitoiu No worries, my gitub account is https://github.com/SylvainDe ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T12:22:19.377", "Id": "50055", "Score": "0", "body": "if you want some d3 help with https://github.com/SylvainDe/VisualArrayAlgorithms let me know." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T20:59:23.460", "Id": "31386", "ParentId": "31377", "Score": "3" } }, { "body": "<p>It seems to me you can get faster than quadratic if you sort the list first, and use an algorithm like this... (<a href=\"http://jsfiddle.net/v9ppL/4/\" rel=\"nofollow\">JSFiddle</a>)</p>\n\n<pre><code>function complementaryPairs(a, target) {\n var count = 0,\n left = 0,\n right = a.length - 1,\n i;\n a.sort(function (a, b) {\n return a - b\n }); // [-3, -2, 0, 1, 1, 3, 3, 3, 4, 5, 8]\n\n // Eliminate arrays that can't contain any pairs\n if (a[left] * 2 &gt; target || a[right] * 2 &lt; target) {\n return 0;\n }\n for (; left &lt;= right &amp;&amp; a[left] * 2 &lt;= target; left++) {\n // Get rid of any values on the right that are too large \n while (right &gt; left &amp;&amp; a[left] + a[right] &gt; target) right--;\n // Count values in between left and right which match with left\n for (i = right; i &gt; left &amp;&amp; a[left] + a[i] == target; i--) {\n count += 2;\n }\n }\n // Any values that are exactly half the target can also complement themselves\n // so count them again\n while (a[--left] * 2 == target) {\n count++;\n }\n return count;\n}\n</code></pre>\n\n<p>As the starting point for <code>right</code> decreases upon each cycle of <code>left</code>, it must be less than quadratic, right? (I'm happy to be corrected on this.)</p>\n\n<p>And the built in sort is, as far as I know, O(n log n), so we can use it without increasing the order of complexity. (Of course in a high level language this becomes irrelevant because any built in function is likely to be much faster than one we would write ourselves).</p>\n\n<p>Edit: here's an alternative version which I think is slightly faster and makes it easier to see how it works. This is pretty clearly O(n), apart from the initial <code>sort</code> (isn't it...?) (<a href=\"http://jsfiddle.net/v9ppL/12/\" rel=\"nofollow\">JSFiddle</a>)</p>\n\n<pre><code>function complementaryPairs(a, target) {\n var count = 0;\n a.sort(function (a, b) {\n return a - b\n }); \n for (var left = 0, right = a.length - 1; left &lt; right;) {\n if (a[left] + a[right] &lt; target) {\n left++;\n } else if (a[left] + a[right] &gt; target) {\n right--;\n } else if (a[left] == a[right]) {\n // Shortcut if the value is target / 2\n return count + (right - left + 1) * (right - left + 1)\n } else {\n // Found complementary pair. Move towards middle, counting duplicates.\n for (var leftCount = 1; a[left] == a[++left]; leftCount++);\n for (var rightCount = 1; a[right] == a[--right]; rightCount++);\n count += leftCount * rightCount * 2;\n }\n }\n return count;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:23:09.513", "Id": "49980", "Score": "0", "body": "the inner loop for / for is always quadratic even if it's not pure n*n" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:26:11.390", "Id": "49983", "Score": "1", "body": "@bitoiu It's not. Notice that `j` is never reset. This means it gets to go only **once** from `a.length - 1` down to, in the worst case, zero during an execution of a program. That makes the first inner loop overall linear in `a.length`. The second one (by `k`) is similar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:42:51.607", "Id": "49991", "Score": "0", "body": "@VedranŠego I might have this assumption wrong, that anything which is N* (N -C), whatever C, this will eventually lead to N*N? again, might be me being a noob." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:47:37.737", "Id": "49994", "Score": "0", "body": "@bitoiu The point is that C is not a constant but is increasing with each iteration of the outer loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:48:38.037", "Id": "49995", "Score": "1", "body": "@bitoiu Consider this: `for (i = 0; i < n; i += 2) for (j = i; j % 7 > 0; j++) k++;` It's two loops, but the inner one runs at most 7 times each time, so it runs at most `7n/2` times. It's linear. In Stuart's code, consider only variable `j` and ignore the second inner loop for a moment. What happens with `j`? It starts from `j = a.length - 1` and stops, if not before, when `j = 0` (because `j > i >= 0`). It happens through many steps of the outer loop, but it still catches each value only once and, hence, gets at most `a.length - 1` steps. I hope it is more clear now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T22:42:43.797", "Id": "50000", "Score": "0", "body": "@Stuart There is an ambiguity in question. If you have `a=[1,1],k=2`, is the solution 2 (the first `1` summed with itself, and the second `1` summed with itself), or is it 4 (counting also first+second and second+first)? :-) If the later is true (as I think makes sense), your last loop needs fixing (instead of `count++` it needs `tmp++;` and, after the loop, `count+=tmp*tmp;`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T23:11:22.963", "Id": "50001", "Score": "0", "body": "@VedranŠego The latter is true, and this is exactly what it currently does. Check the jsfiddle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T08:02:53.237", "Id": "50028", "Score": "0", "body": "Just trying to catch up, pairs like (1,1) count once, for my example output it returns 7, 3 pairs and a mirror index for position f(5,5) = (3,3)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:00:08.870", "Id": "31387", "ParentId": "31377", "Score": "3" } }, { "body": "<p>This is computable in linear time by creating a hashtable (H) mapping each value in the array to the number of times it appears (a multiset).</p>\n\n<pre><code>A: [1, 8, -3, 0, 1, 3, -2, 4, 5] }\nH: { -3 =&gt; 1, -2 =&gt; 1, 0 =&gt; 1, 1 =&gt; 2, 3 =&gt; 1, 4 =&gt; 1, 5 =&gt; 1, 8 =&gt; 1 }\n</code></pre>\n\n<p>Then the number of complementary pairs is </p>\n\n<pre><code>sum(over i in H.keys) { h[i] * h[K-i]) / 2 }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-31T03:39:34.383", "Id": "179218", "ParentId": "31377", "Score": "0" } }, { "body": "<p>Using a dictionary to look up is better:</p>\n\n<pre><code>private static int solution(int k, int[] arr) {\n Map&lt;Integer, Boolean&gt; map = new HashMap&lt;Integer, Boolean&gt;();\n for(int item: arr) {\n map.put(item, true);\n }\n int count = 0;\n for(int item: arr) {\n int temp = k - item;\n if(map.containsKey(temp)) {\n count ++;\n }\n }\n return count;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:30:09.637", "Id": "453268", "Score": "1", "body": "Hello duybinh0208, you should explain why using the dictionary is better than the approach the OP provided, this makes for a better review :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:41:44.333", "Id": "453271", "Score": "0", "body": "You will get an up vote if you answer @IEatBagels question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-11T16:06:21.450", "Id": "232191", "ParentId": "31377", "Score": "1" } } ]
{ "AcceptedAnswerId": "31386", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:09:40.123", "Id": "31377", "Score": "5", "Tags": [ "javascript", "algorithm", "programming-challenge", "recursion" ], "Title": "Finding complementary pairs" }
31377
<p>I'd like someone to suggest a better way to create this pattern in Java which I'm sure is possible:</p> <pre><code>********* * * * * * * * * * * * * * * ********* </code></pre> <p>I'm working my way through a new Java book and am examining string patterns.</p> <pre><code>public static void drawRectangle() { // y axis for( int y = 0; y &lt;= 8; y++ ) { if( y == 0 || y == 8 ) { System.out.print( "*********\n" ); if( y == 8 ) { // Leave loop break; } } // x axis for( int x = 0; x &lt;= 8; x++ ) { if( x == 0 || x == 8 ) { System.out.print( "*" ); if( x == 8 ) { System.out.println(); } } else { System.out.print( " " ); } } } } </code></pre> <p>Off the top of my head, I'd say that I could replace the values in the loops with constants to work towards. For example:</p> <pre><code>final static int END_POINT = 8; </code></pre> <p>Any thoughts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T01:46:21.247", "Id": "50009", "Score": "0", "body": "When doing a lot of string concatenations, you should instead use a `StringBuilder`. This is for performance reasons, so it is actually not very important for your problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:19:56.340", "Id": "50035", "Score": "0", "body": "it may be for this particular problem but I'm sure I'll come across it again at some point. Thanks" } ]
[ { "body": "<p>It's ok for a first iteration.</p>\n\n<ol>\n<li>But your 2nd iteration should be <code>drawRectangle(int width, int height)</code>. That will force you to not hard-code your numbers.</li>\n<li>Your 3rd iteration should be noticing that your rectangle only has 2 different rows (one row fills up the width with * and the other only has * in the beginning and end). You might want to make a method <code>drawHorizontal</code> to draw the top and bottom and <code>drawEnds</code> to draw the sides. For example</li>\n</ol>\n\n<pre><code>\n void drawHorizontal(int width) {\n for (int i=0 ; i&lt;width ; i++) {\n System.out.print(\"*\"); /* notice I'm using print() not println() */\n }\n System.out.println(\"\"); /* notice I'm using println() */\n }\n\n void drawEnds(int width) {\n System.out.print(\"*\");\n for (int i=1 ; i&lt;width-1 ; i++) {\n System.out.print(\" \");\n }\n System.out.println(\"*\");\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T10:04:25.010", "Id": "50043", "Score": "0", "body": "Just for your information, [I put together a fast speed test](http://pastebin.com/0p0ck4JQ). Creating a string and outputting the whole string instead of printing single characters is a lot faster. Now that I think about it, iteration 4 should most likely return complete strings anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:43:39.780", "Id": "50084", "Score": "0", "body": "@Bobby, yes but I wasn't sure if I should tell the OP about StringBuilder at this point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T16:19:46.233", "Id": "50087", "Score": "0", "body": "I think a fourth or even fifth iteration with changes up to \"I'd do it like this in the end\" would be a very good addition and shouldn't be too hard to understand." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T19:27:22.040", "Id": "31381", "ParentId": "31379", "Score": "9" } }, { "body": "<p>Alternative way to make Rectangle.</p>\n\n<pre><code>public class myclass {\n // Input the size of the Rectangle.\n\n static int hight = 8;\n static int width = 8;\n\n public static void main(String[] args) {\n line(width);\n for (int m = 0; m &lt; hight - 2; m++) {\n starWithSpace();\n System.out.println();\n }\n line(width);\n }\n\n public static void space() {\n System.out.print(\" \");\n }\n\n public static void printStar() {\n System.out.print(\"*\");\n }\n\n public static void starWithSpace() {\n printStar();\n for (int i = 0; i &lt;= hight - 2; i++) {\n space();\n }\n printStar();\n }\n\n public static void line(int width) {\n for (int header = 0; header &lt;= width; header++) {\n printStar();\n }\n System.out.println(\"\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T13:52:22.877", "Id": "50068", "Score": "7", "body": "don't just post plain code,practice to give some explanation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-04T01:12:09.777", "Id": "372223", "Score": "1", "body": "Note, this answer is locked, and undeleted: it is significant as it provides context for a [meta-tag:faq] meta question: [Should code block(s) as answers always require an explanation?](https://codereview.meta.stackexchange.com/q/855/31503)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:09:43.393", "Id": "31412", "ParentId": "31379", "Score": "0" } }, { "body": "<h1>Interface suggestions</h1>\n\n<p>Anything that can be parameterized instead of hard-coded should be. I would pass the dimensions to the <code>Rectangle</code> constructor. Then I would create a <code>draw(PrintStream out)</code> method. In other words, the rectangle knows how to draw itself to a <code>PrintStream</code> of your choice, whether it's <code>System.out</code> or some other output destination.</p>\n\n<h1>Loop Simplification</h1>\n\n<p>You can simplify your code by letting <code>Arrays.fill()</code> do the boring looping work to populate some buffers. Then, you only need one <code>for</code>-loop to iterate over the rows. A bonus is that you take advantage of the fact that many of the lines to be printed are identical to each other.</p>\n\n<h1>Solution</h1>\n\n<pre><code>import java.io.PrintStream;\nimport java.util.Arrays;\n\npublic class Rectangle {\n private int rows, cols;\n\n public Rectangle(int rows, int cols) {\n this.rows = rows;\n this.cols = cols;\n }\n\n public void draw(PrintStream out) {\n char[] buf = new char[cols];\n\n Arrays.fill(buf, '*');\n String cap = new String(buf);\n\n Arrays.fill(buf, 1, cols - 1, ' ');\n String body = new String(buf);\n\n out.println(cap);\n for (int i = rows - 2; i &gt;= 0; i--) {\n out.println(body);\n }\n out.println(cap);\n }\n\n public static void main(String[] args) {\n (new Rectangle(8, 8)).draw(System.out);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-13T09:56:50.973", "Id": "32632", "ParentId": "31379", "Score": "2" } } ]
{ "AcceptedAnswerId": "31381", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T18:30:18.913", "Id": "31379", "Score": "6", "Tags": [ "java", "ascii-art" ], "Title": "Making a rectangular-shaped pattern" }
31379
<p>I have a page where a user needs to click two checkboxes before continuing (agree to two terms of service). My jQuery is fairly straightforward, you have to have both check boxes checked to continue:</p> <pre><code>$("#agree1, #agree2").click(function () { if ($("#agree1").is(':checked') == true &amp;&amp; $("#agree2").is(':checked') == true) { $("#nextPage").removeAttr("disabled"); } else { $("#nextPage").attr("disabled", "disabled"); } }); </code></pre> <p>I'm wondering if there is a simpler way of writing this. I expected a line like this to check for both boxes to be checked, but it doesn't:</p> <pre><code>if ($("#agree1 #agree2").is(':checked') == true) </code></pre> <p>Is there a way to simplify this?</p> <p>Example code: <a href="http://jsfiddle.net/LWd7Z/1/" rel="nofollow noreferrer">jsFiddle</a></p>
[]
[ { "body": "<p>You can look for only the checked checkboxes, and then check that you found two:</p>\n\n<pre><code>if ($(\"#agree1:checked,#agree2:checked\").length == 2) { ... }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-16T21:52:07.483", "Id": "31389", "ParentId": "31382", "Score": "10" } } ]
{ "AcceptedAnswerId": "31389", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T20:04:51.453", "Id": "31382", "Score": "5", "Tags": [ "javascript", "jquery" ], "Title": "Check if two checkboxes are checked" }
31382
<p>I have the following data structure:</p> <pre><code>data XComposeString = XComposeString { keyEvents :: [Event], s :: Result } deriving (Eq, Show) data XComposeFile = XComposeFile { strings :: [XComposeString] } deriving (Eq, Show) </code></pre> <p>Where <code>Event</code> and <code>Result</code> just <code>String</code> or some combination of several <code>String</code>.</p> <p>I'm creating a <code>Trie</code> from list of type <code>[(keyEvents x, [s x])]</code>:</p> <pre><code>constructTrie list = M.fromListWith comp list where comp = \old new -&gt; old ++ new </code></pre> <p>I want to check on duplicates and prefix overlaps.</p> <pre><code>duplicates :: M.TrieMap Map.Map Event [Result] -&gt; String duplicates m = M.showTrie list "" where list = M.filter (\v -&gt; length v /= 1) m prefixOverlap :: M.TrieMap Map.Map Event [Result] -&gt; String prefixOverlap m = M.showTrie list "" where list = M.filterWithKey (\k v -&gt; not $ null $ catMaybes [M.lookup x m | x &lt;- reverse (inits (init k))]) m </code></pre> <p>How can I improve this, so, there would be three functions: one to create, one to check on duplicates and one to check on prefix overlaps.</p> <p>Useful imports and types definition:</p> <pre><code>import Data.List(inits) import Data.Maybe(catMaybes) import qualified Data.Map as Map import qualified Data.ListTrie.Map as M type Event = String type Result = String </code></pre> <p>Also, <code>cabal install list-tries</code> is needed for <code>ListTrie</code> data structure.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T17:17:01.073", "Id": "52404", "Score": "0", "body": "Are you using [TrieMap](http://hackage.haskell.org/package/TrieMap) package?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T17:21:49.033", "Id": "52405", "Score": "0", "body": "@nponeccop: No, [Data.ListTrie.Map](http://hackage.haskell.org/package/list-tries-0.4.3/docs/Data-ListTrie-Map.html)." } ]
[ { "body": "<p>Can you add minimal imports so your code compiles? I had to guess:</p>\n\n<pre><code>import Data.ListTrie.Map as M hiding (null)\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List\n\n\ndata Event = Event deriving (Show, Eq, Ord)\ndata Result = Result deriving (Show, Eq)\n</code></pre>\n\n<p><code>constructTrie</code> can be easily improved by inlining <code>comp</code>:</p>\n\n<pre><code>constructTrie list = M.fromListWith (++) list\n</code></pre>\n\n<p>Or even to <code>constructTrie = M.fromListWith (++)</code> but that requires turning off monomorphism restriction or adding an explicit signature for <code>constructTrie</code>, so it's up to your taste.</p>\n\n<p>Also you can deduplicate showTrie calls and long trie signatures:</p>\n\n<pre><code>mshow list = M.showTrie list \"\"\n\ntype ResultTrie = M.TrieMap Map.Map Event [Result]\n\nduplicates :: ResultTrie -&gt; String\nduplicates m = mshow list\n where\n list = M.filter (\\v -&gt; length v /= 1) m\n\nprefixOverlap :: ResultTrie -&gt; String\nprefixOverlap m = mshow list\n where\n list = M.filterWithKey (\\k v -&gt; not $ null $ catMaybes [M.lookup x m | x &lt;- reverse (inits (init k))]) m\n</code></pre>\n\n<p>Now it's beneficial to inline <code>list</code> variables in both functions:</p>\n\n<pre><code>duplicates :: ResultTrie -&gt; String\nduplicates m = mshow $ M.filter (\\v -&gt; length v /= 1) m\n\nprefixOverlap :: ResultTrie -&gt; String\nprefixOverlap m = mshow $ M.filterWithKey (\\k v -&gt; not $ null $ catMaybes [M.lookup x m | x &lt;- reverse (inits (init k))]) m\n</code></pre>\n\n<p>Now you can get rid of <code>m</code> in <code>duplicates</code>:</p>\n\n<pre><code>duplicates :: ResultTrie -&gt; String\nduplicates = mshow . M.filter (\\v -&gt; length v /= 1)\n</code></pre>\n\n<p>In <code>prefixOverlap</code> the line is too long, I can split it. I chose to extract the <code>(\\ -&gt; )</code> construct. Note that m is in more that 1 place so we cannot use <code>.</code>.</p>\n\n<pre><code>prefixOverlap :: ResultTrie -&gt; String\nprefixOverlap m = mshow $ M.filterWithKey f m where\n f k _ = not $ null $ catMaybes [M.lookup x m | x &lt;- reverse (inits (init k))]\n</code></pre>\n\n<p>Now remove extra parentheses in the comprehension:</p>\n\n<pre><code>prefixOverlap :: ResultTrie -&gt; String\nprefixOverlap m = mshow $ M.filterWithKey f m where\n f k _ = not $ null $ catMaybes [M.lookup x m | x &lt;- reverse $ inits $ init k]\n</code></pre>\n\n<p>From here I'll only work on <code>f</code>. </p>\n\n<p>Now a trickier part. Long chains of <code>$</code> are equivalent to <code>.</code> following one <code>$</code> in the end:</p>\n\n<pre><code> f k _ = (not . null . catMaybes) [M.lookup x m | x &lt;- reverse $ inits $ init k]\n</code></pre>\n\n<p><code>not . null . catMaybes</code> is a function of <code>[Maybe a] -&gt; Bool</code> that returns <code>True</code> only if there is any <code>Just</code> in the list. I can literally translate this sentence into Haskell: it's just <code>any isJust</code>:</p>\n\n<pre><code> f k _ = any isJust [M.lookup x m | x &lt;- reverse $ inits $ init k]\n</code></pre>\n\n<p>Now even trickier: your comprehension is just a <code>map</code>:</p>\n\n<pre><code> f k _ = any isJust $ map (\\x -&gt; M.lookup x m) $ reverse $ inits $ init k\n</code></pre>\n\n<p>Congratulations, we can again turn a chain of <code>$</code> into a chain of <code>.</code>:</p>\n\n<pre><code> f k _ = any isJust . map (\\x -&gt; M.lookup x m) . reverse . inits . init $ k\n</code></pre>\n\n<p>Now remember that <code>.</code> is associative so you can put parentheses in the middle of the chain wherever you want:</p>\n\n<pre><code>any isJust . (map (\\x -&gt; M.lookup x m) . reverse) . inits . init\n</code></pre>\n\n<p>Now we have <code>map something . reverse</code>. And it doesn't matter when you reverse - before or after map:</p>\n\n<pre><code>map something f . reverse = reverse . map something\n</code></pre>\n\n<p>That is, <code>map</code> and <code>reverse</code> commute and we can swap them and remove parens:</p>\n\n<pre><code>any isJust . reverse . map (\\x -&gt; M.lookup x m) . inits . init\n</code></pre>\n\n<p>Now we can put around <code>any</code> and <code>reverse</code>. It's clear that <code>any</code> works the same way for straight and reversed lists, that is, <code>any something . reverse = any something</code>, so we can throw <code>reverse</code> away:</p>\n\n<pre><code>any isJust . map (\\x -&gt; M.lookup x m) . inits . init\n</code></pre>\n\n<p>And put back into <code>prefixOverlap</code>:</p>\n\n<pre><code>prefixOverlap :: ResultTrie -&gt; String\nprefixOverlap m = mshow $ M.filterWithKey f m where\n f k _ = any isJust . map (\\x -&gt; M.lookup x m) . inits . init $ k\n</code></pre>\n\n<p>Here is the full version of the code:</p>\n\n<pre><code>import Data.ListTrie.Map as M hiding (null, map)\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.List\n\ntype Event = Char\ntype Result = ()\ntype ResultTrie = M.TrieMap Map.Map Event [Result]\n\ndata XComposeString = XComposeString { keyEvents :: [Event], s :: Result }\n deriving (Eq, Show)\n\ndata XComposeFile = XComposeFile { strings :: [XComposeString] }\n deriving (Eq, Show)\n\nconstructTrie list = M.fromListWith (++) list\n\nmshow :: ResultTrie -&gt; String\nmshow list = M.showTrie list \"\"\n\n\nduplicates :: ResultTrie -&gt; String\nduplicates = mshow . M.filter (\\v -&gt; length v /= 1)\n\nprefixOverlap :: ResultTrie -&gt; String\nprefixOverlap m = mshow $ M.filterWithKey f m where\n f k _ = any isJust . map (\\x -&gt; M.lookup x m) . inits . init $ k\n</code></pre>\n\n<p>Note that I used fake <code>Event</code> and <code>Result</code> types. I also checked that old and new <code>prefixOverlap</code> are the same using QuickCheck and smallcheck libraries:</p>\n\n<pre><code>prefixOverlapOld :: ResultTrie -&gt; String\nprefixOverlapOld m = M.showTrie list \"\"\n where\n list = M.filterWithKey (\\k v -&gt; not $ null $ catMaybes [M.lookup x m | x &lt;- reverse (inits (init k))]) m\n\nprop_foo x = prefixOverlap m == prefixOverlapOld m where\n m = M.fromList $ map (first (++ \"X\")) x\n</code></pre>\n\n<p><code>first</code> is from <code>Control.Arrow</code>.</p>\n\n<p>The <code>prefixOverlap</code> probably can still be improved with using <code>lookupPrefix</code> and/or <code>children</code> functions from <code>Data.ListTrie.Map</code>.</p>\n\n<p>Here is my take:</p>\n\n<pre><code>prefixOverlapNew :: ResultTrie -&gt; String\nprefixOverlapNew = mshow . M.unions . map (\\(p,m) -&gt; M.addPrefix [p] m) . Prelude.filter (\\(p, m) -&gt; M.size m /= 1 || (null $ fst $ head $ M.toList m)) . Map.toList . M.children1\n</code></pre>\n\n<p>Note that it differs from both original <code>prefixOverlapOld</code> and refactored <code>prefixOverlap</code>:</p>\n\n<p>QuickCheck found that they differ on a map with 2 keys \"fo\" and \"f\". The <code>prefixOverlapNew</code> version correctly shows both \"fo\" and \"f\" as they overlap. The original version(s) show only value on \"fo\" key which is dubuios.</p>\n\n<p>Here is an improved version using list comprehension to combine filter and map:</p>\n\n<pre><code>prefixOverlapNew :: ResultTrie -&gt; String\nprefixOvelapNew mm = mshow $ \n M.unions [M.addPrefix [p] m | (p, m) &lt;- Map.toList $ M.children1 mm, M.size m /= 1 || null (fst $ head $ M.toList m)]\n</code></pre>\n\n<p>Moved <code>f</code> out:</p>\n\n<pre><code>prefixOverlapNew mm = mshow $ M.unions [M.addPrefix [p] m | (p, m) &lt;- Map.toList $ M.children1 mm, f m] where\n f m = M.size m /= 1 || null (fst $ head $ M.toList m)\n</code></pre>\n\n<p>Finally, a version in list monad, just for fun:</p>\n\n<pre><code>prefixOverlapNew :: ResultTrie -&gt; String\nprefixOverlapNew mm = mshow $ M.unions $ do\n (p, m) &lt;- Map.toList $ M.children1 mm\n guard $ M.size m /= 1 || null (fst $ head $ M.toList m)\n return $ M.addPrefix [p] m\n</code></pre>\n\n<p><code>guard</code> is from <code>Control.Monad</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T17:51:30.363", "Id": "32773", "ParentId": "31383", "Score": "2" } } ]
{ "AcceptedAnswerId": "32773", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T20:18:00.437", "Id": "31383", "Score": "2", "Tags": [ "haskell" ], "Title": "Improve Trie manipulation in Haskell code" }
31383
<p>This is a data structure I wrote:</p> <ul> <li>It is an circular first-in-first-out queue (a ringbuffer); </li> <li>It has batched removal/popping - it returns an array of a fixed buffer size; </li> <li>It is unbounded, and grows itself as needed;</li> <li>It is generics-compliant (at the cost of primitives). </li> <li>It is (supposedly) thread-safe.</li> <li>It is (supposedly) a high-performance data structure </li> </ul> <p></p> <pre><code>package com.fhs.RingBuffer; import java.lang.reflect.Array; /** * Generic, thread-safe, unbounded RingBuffer * * @author Ben.Cole * * @param &lt;T&gt; Element type */ public class RingBuffer&lt;T&gt; { /** Type of contained Objects */ private Class&lt;T&gt; clazz; /** Backing array */ private volatile T[] objs; /** Null array (of size [buffer]) for clearing backing array */ private final T[] nulls; /** Buffer size - initialized to DEFAULT_BUFFER_SZ */ private int buffer = DEFAULT_BUFFER_SZ; /** Index of current buffer start */ private volatile int index = 0; /** Next open spot in backing array */ private volatile int open = 0; /** Default initial backing array size */ private static final int DEFAULT_ARRAY_SZ = 25; /** Default buffer size */ private static final int DEFAULT_BUFFER_SZ = 5; /** * @param clz Generic Type of this RingBuffer's contents * @param cap Initial capacity * @param buff Buffer size */ public RingBuffer(Class&lt;T&gt; clz, int cap, int buff) { this.buffer = buff; this.clazz = clz; this.objs = getArray(cap); this.nulls = getArray(this.buffer); } /** * @param clz Generic Type of this RingBuffer's contents * @param buff Buffer size */ public RingBuffer(Class&lt;T&gt; clz, int buff) { this(clz, DEFAULT_ARRAY_SZ, buff); } /** * Add an object to this RingBuffer. May result in a resize if load factor after adding element passes the internal limit. * * @param obj Object to add to this buffer */ public synchronized void add(T obj) { this.objs[this.open] = obj; this.open = (this.open + 1) % this.objs.length; if (shouldExpand()) { resize(); } } /** * Pop (remove) the next [buffer]'s worth of object from this RingBuffer. * * @return An array of T objects, up to [buffer] in size, but could be empty! */ public synchronized T[] get() { T[] retBuff = getArray(this.buffer); if (this.open &lt; this.index) { // wrapped int segmentLength = this.objs.length - this.index; if (segmentLength &lt; this.buffer) { // buffer contents are wrapped // copy first segment of buffer from backing array to returned array System.arraycopy(this.objs, this.index, retBuff, 0, segmentLength); // check to see if we have enough overflow to fill the buffer int overflow = this.buffer - segmentLength; boolean fillCheck = this.open &gt;= overflow; if (fillCheck) { // can completely fill return buffer // copy overflow segment of buffer from backing array to returned array System.arraycopy(this.objs, 0, retBuff, segmentLength, overflow); // copy nulls from null array to backing array System.arraycopy(this.nulls, 0, this.objs, 0, overflow); System.arraycopy(this.nulls, 0, this.objs, this.index, segmentLength); // update index this.index = overflow; } else { // can't completely fill return buffer // copy overflow segment of buffer from backing array to returned array System.arraycopy(this.objs, 0, retBuff, segmentLength, this.open); // copy nulls from null array to backing array (same as if we could fill buffer) System.arraycopy(this.nulls, 0, this.objs, this.index, segmentLength); // copy nulls to remainder System.arraycopy(this.nulls, 0, this.objs, 0, this.open); this.index = this.open; } } else { // buffer is *not* actually wrapped! // copy contents of buffer from backing array to returned array System.arraycopy(this.objs, this.index, retBuff, 0, this.buffer); // copy nulls from null array to backing array System.arraycopy(this.nulls, 0, this.objs, this.index, this.buffer); // update index, mod-ing by backing array length to account for wrapping this.index = (this.index + this.buffer) % this.objs.length; } } else if (this.index &lt; this.open) { // not wrapped int between = this.open - this.index; if (between &lt; this.buffer) { // insufficient elements // copy contents of buffer from backing array to returned array System.arraycopy(this.objs, this.index, retBuff, 0, between); // copy nulls from null array to backing array System.arraycopy(this.nulls, 0, this.objs, this.index, between); this.index = this.open; } else { // sufficient elements // copy contents of buffer from backing array to returned array System.arraycopy(this.objs, this.index, retBuff, 0, this.buffer); // copy nulls from null array to backing array System.arraycopy(this.nulls, 0, this.objs, this.index, this.buffer); // update index - don't have to mod the result because // we already know that we have sufficent space between // the index and the next open space to fill the buffer // completely without wrapping around. this.index = (this.index + this.buffer); } } else if (this.index == this.open) { // return empty buffer } return retBuff; } /** * @return true if this buffer is empty. */ public boolean isEmpty() { return this.index == this.open; } /** * @return Number of elements in this RingBuffer */ public int size() { int sz = 0; if (this.index &lt; this.open) { sz = this.open - this.index; } else if (this.index &gt; this.open) { sz = this.open + (this.objs.length - this.index); } return sz; } /** * @return Current size of backing array */ protected int backingSize() { return this.objs.length; } /** * Create a new array of type T using reflection. * * @param size Size of desired array * @return A new array of type T */ private T[] getArray(int size) { return (T[]) Array.newInstance(this.clazz, size); } /** * Checks if the internal load factor (number of filled slots vs number of total slots) has reach a set limit * * @return true TODO - SHOULDEXPAND 1 SLOT LEFT */ private boolean shouldExpand() { return // same as empty check, but since we know that // we just added an item, we know the buffer isn't // empty. So it's a 'full?' check. (this.open == this.index-1) || // and check edge case for array wrap (this.index == 0 &amp;&amp; this.open == this.objs.length-1); } /** * Resize the backing array and copy the elements from the old array to the new array, preserving order. */ private void resize() { int newSize = getNewSize(); T[] newObjs = (T[]) Array.newInstance(this.clazz, newSize); if (this.open &lt; this.index) { // buffer is wrapped around end of array int firstSegmentLength = this.objs.length - this.index; // copy first part of contents System.arraycopy(this.objs, this.index, newObjs, 0, firstSegmentLength); // copy second part of contents System.arraycopy(this.objs, 0, newObjs, firstSegmentLength, this.open); // update markers this.index = 0; this.open = this.open + firstSegmentLength; } else if (this.index == 0 /* &amp;&amp; this.open == this.objs.length - 1 */) { System.arraycopy(this.objs, 0, newObjs, 0, this.open); // index and open stay the same } this.objs = newObjs; } /** * TODO - RESIZED ARRAY SIZE [Y = X * 2] * * @return New backing array size */ private int getNewSize() { int oldSize = this.objs.length; // double the backing array size return oldSize * 2; } } </code></pre> <p>Specific questions:</p> <ol> <li>Is this genuinely thread-safe? I'm pretty sure it is, but I'm not confident enough to say either way.</li> <li>Is this truly a high-performance data structure? I believe that it is, based on limited testing (8 producers, 1 consumer, 80k string messages per producer, confident that no messages were dropped).</li> <li>Is there a use-case for a data structure of this type? I have no idea on this one - this data structure is something I literally dreamed up and coded the next day. I've never used something like it, but I can imagine it could be useful for burst-tolerant message passing.</li> </ol>
[]
[ { "body": "<p>0) It seems simpler to me to just copy the remainder of the buffer in a normal array every time some chunk is removed instead of using a circular buffer. Using a LinkedList would not even require copying anything. But I must admit if you have millions of bytes, a <code>LinkedList&lt;Byte&gt;</code> would not be a very good idea.</p>\n\n<p>1) I don't like the use of raw arrays and of reflection. However, since this is supposed to be for high-performance, maybe it is alright.</p>\n\n<p>2) I looked at the code lightly and I believe it is correctly synchronized, except that <code>isEmpty()</code> and <code>size()</code> should probably be synchronized too. However, I would not say it is high performance because you are simply locking <code>add()</code> and <code>get()</code>, which is quite crude. You probably don't need to stop a thread from writing to the RingBuffer when another thread is reading it since they likely affect different parts of the buffer. There are other concepts I would explore for high-performance multi-threading: compare-and-swap and copy-on-write. (If you use a LinkedList as I suggested above, I can see that you could hold the lock for only very short periods of time.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T03:48:31.100", "Id": "50017", "Score": "0", "body": "**0)** Not sure what you mean in the first sentence here. I can understand how a linked list would remove the need for copying, though. \n**1)** Same here, I use lists, etc, in more 'regular' code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T03:49:41.340", "Id": "50019", "Score": "0", "body": "**2)** I thought locking get/add was crude also. I had wondered if, given the possibility of a read/write collision, locking on add/get would be easier (and result in a small enough performance effect) than attempting to allow truly asynchronous access by employing more complex multiplexing strategies. The number of actual operations in the add/get methods is also relatively small (even if a resize occurs, which has a similar footprint to a get() call). However, I will look up compare-and-swap and copy-on-write." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T01:29:45.433", "Id": "31399", "ParentId": "31388", "Score": "1" } }, { "body": "<p>0) - agreed with toto2</p>\n\n<p>2) - no. You did not say how many messages per second your buffer can pass through itself (and did not provide test code to run), but high performance counts in millions, and I doubt your buffer can give even 1 M mps. Main performance loss is copying data in get(). It takes time to allocate, copy, and deallocate arrays. The latter is the worst, as it causes unpredictable garbage collector executions which dramatically increase reaction time.</p>\n\n<p>3) look at <a href=\"http://lmax-exchange.github.io/disruptor/\" rel=\"nofollow\">Disruptor</a> - the most performant ring buffer to connect producer and consumer threads (see <a href=\"https://raw.github.com/LMAX-Exchange/disruptor/master/src/main/java/com/lmax/disruptor/RingBuffer.java\" rel=\"nofollow\">RingBuffer class</a> source code).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T11:44:59.820", "Id": "31422", "ParentId": "31388", "Score": "0" } }, { "body": "<p>Comments for maintenance, simplification, and extensibility:</p>\n\n<ol>\n<li>Consider a static import for <code>System.arraycopy</code>.</li>\n<li>Eliminate the magic number and <code>oldSize</code> variable when resizing:<pre>\nreturn this.objs.length * getExpansionSize();\n</pre></li>\n<li>Nearly all usages of <code>this.</code> are superfluous.</li>\n<li>Class-scoped integer variables are initialized to <code>0</code> by default.</li>\n<li>Stylistically, declare the constants before variables (e.g., define <code>DEFAULT_BUFFER_SZ</code> before use).</li>\n<li>The <code>fillcheck</code> variable is not required (compiler should optimize it away).</li>\n<li>While returning from a method at a single location is desirable, the <code>size()</code> method could be shortened by returning multiple times, eliminating the <code>sz</code> variable and corresponding assignment to <code>0</code> (compiler might do this?).</li>\n<li>The following line:<pre>\nT[] newObjs = (T[]) Array.newInstance(this.clazz, newSize);\n</pre> can be:<pre>\nT[] newObjs = getArray(getNewSize());\n</pre> to remove duplication and eliminate a variable.</li>\n<li>Minor (insignificant) optimization, in the constructor change:<pre>\nthis.nulls = getArray(this.buffer);</pre> to:<pre>\nthis.nulls = getArray(buff)</pre> as referencing a local variable uses a shorter bytecode than referencing a class-scoped variable.</li>\n<li>Remove the following code:<pre>\nelse if (this.index == this.open) {\n// return empty buffer\n}</pre> by commenting the return statement as:<pre>\n// retBuff will be empty if index == open.</pre></li>\n</ol>\n\n<p>I, personally, prefer <code>result</code> over <code>retBuff</code>; return statement is read as \"return the result\" vs. \"return the return buffer.\" Throughout my code, the <code>result</code> variable, invariably, is the variable that contains the value returned from a function.</p>\n\n<p>For extensibility, a <code>private getArray(int)</code> method prevents subclasses from adding injecting custom <code>Array</code> behaviour. Also, a <code>get</code> method name prefix is typically reserved for accessing a member attribute; a <code>create</code> method name prefix is typical for methods that simply perform instantiation. Thus you could have a <code>protected</code> method called <code>createArray(int)</code> and another helper method of <code>protected createArray(Class&lt;T&gt;, int)</code> that subclasses could override.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T08:13:15.963", "Id": "35525", "ParentId": "31388", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T21:12:30.140", "Id": "31388", "Score": "3", "Tags": [ "java", "performance", "thread-safety", "circular-list" ], "Title": "Unbounded, High-performance(?), Generic, Thread-Safe(?), BatchedCircularQueue" }
31388
<p>This is a program I made to bounce the letter a across the screen. I made a few others, but this one I made with a recursive <code>bounce()</code> method. I know <code>main()</code> is a bit empty, but I intend to make an input menu that main refrences, so it seemed better to put the code in another method. </p> <p>Is my code clean (probably far from it)? Easy to read? Am I overdoing the comments, or not specifing the code well enough?<br> Is it a bad idea using a recursive method for this as it has to keep memory for 80 recursions? It seemed like a good idea, because I was condensing so much more code into a smaller space. </p> <pre><code>/** * This code is designed for use with CMD with an 80 * ASCII character width space. * It adds and subtracts a space to a string and out prints * the line. * It uses recursion to create one full Right-Left cycle, * then uses an infinite while loop to repeat. */ class Wave8 { static String spaces = ""; // Holds the spaces static boolean direction = true; // True is right, false is left // Bouncing loop public static void bounce() { if (spaces.length() == (80 - 1)) { // Width minus the string after lead System.out.print(spaces + "a"); direction = false; // Change direction } else System.out.println(spaces + "a"); if (direction) { // If going right spaces += " "; bounce(); // Recursion } if (!direction) { // If going left spaces = spaces.substring(1); if (spaces.isEmpty()) { direction = true; return; } else System.out.println(spaces + "a"); // Normal routine } } public static void main(String args[]) { while (true) { bounce(); } } } </code></pre> <p>Also, is there a way to test for efficiency? That would help greatly.</p>
[]
[ { "body": "<p>Before explaining why I think recursion might be a bad idea here, let me show you the solution I came up with. </p>\n\n<pre><code>class Wave8 {\n\n public static void bounce() {\n String spaces = \"\";\n for (int i=0; i&lt;80; i++, spaces += \" \")\n {\n System.out.println(spaces + \"a\");\n }\n for (int i=0; i&lt;80; i++, spaces = spaces.substring(1))\n {\n System.out.println(spaces + \"a\");\n }\n }\n\n public static void main(String args[]) {\n bounce();\n }\n}\n</code></pre>\n\n<p>The advantage of this solution against the recursive one :</p>\n\n<ul>\n<li><p>clarity : one can clearly see what was intended.</p></li>\n<li><p>termination : there is no doubt on the fact that this solution will eventually return</p></li>\n<li><p>no use of object members : if I call <code>bounce()</code> twice, I expect it to behave the same way twice.</p></li>\n<li><p>performance : I'd expect this solution to be much faster.</p></li>\n</ul>\n\n<p>On the other hand, many functions are much better when written in a recursive way. This is the case when it's easy to see that we call the function on a \"smaller\" problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T23:25:20.530", "Id": "50003", "Score": "0", "body": "on fire today @Josay! keep up!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T23:43:29.240", "Id": "50004", "Score": "0", "body": "To be honest, I've come up with (unintentionally) complicated ways of doing this, seven times. And this beats them all. The kicker is I knew how to do that when I made the first one (that used strings). Thanks (in a non-sarcastic manner)!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T01:15:25.913", "Id": "50007", "Score": "0", "body": "That's basically the same [solution](http://codereview.stackexchange.com/questions/31297/is-my-java-program-efficent-and-does-it-look-clean-and-clear/31306#31306) that I came up with for `Wave6` but with a fixed message, fixed width, and no delay. =)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T23:10:33.523", "Id": "31393", "ParentId": "31392", "Score": "7" } }, { "body": "<p>Recursion is fun as a mind-expanding exercise. However, excessive recursion is a bad idea in Java, because the language does not support <a href=\"http://en.wikipedia.org/wiki/Tail_call\" rel=\"nofollow\">tail recursion</a>. Each time you call a function, a frame is added to the stack for bookkeeping. If the stack grows too large, you will get a <code>StackOverflowError</code>. You can get away with 80 levels, but deep recursion is frowned upon in Java. (In languages such as LISP, which do support tail recursion, recursion is very much a common and viable strategy.)</p>\n\n<p>Usually, when you recurse, you call the function with parameters that vary in an interesting way. The function would test the parameters to see if it has reached a \"base\" case, and decides whether to recurse or return. In your code, you're mutating the state of the object, so there's no point to using recursion.</p>\n\n<p>Here's an effective recursive solution:</p>\n\n<pre><code>public class Wave8 {\n public static void bounce() {\n bounce(\"\", 79);\n }\n\n private static void bounce(String spaces, int remaining) {\n System.out.println(spaces + \"a\");\n if (remaining &gt; 0) {\n bounce(spaces + \" \", remaining - 1);\n if (!spaces.isEmpty()) {\n System.out.println(spaces + \"a\");\n }\n }\n }\n\n public static void main(String[] args) {\n // This still has to be iterative, because Java doesn't\n // support tail recursion, and therefore can't recurse\n // infinitely.\n while (true) {\n bounce();\n }\n }\n}\n</code></pre>\n\n<p>See how short and sweet it is? In particular, notice the complete lack of instance and class variables, and, usually, of local variables too. That's what makes recursion an attractive strategy — all of the state is implicitly stored in the stack.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T16:43:13.567", "Id": "50088", "Score": "0", "body": "Very nice explanation how recursion can be effectively used. As an aside, it's not about tail recursion, it is about optimizations like tail recursion elimination (rewriting to a loop) and/or call stack frame recycling, both of which allow constant-space stacks, but would mess up any stack traces beyond recognition. The JVM has decided this tradeoff in favour of debuggability." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T00:15:09.303", "Id": "31397", "ParentId": "31392", "Score": "4" } } ]
{ "AcceptedAnswerId": "31393", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T22:43:21.903", "Id": "31392", "Score": "4", "Tags": [ "java", "optimization", "recursion" ], "Title": "Is this recursion a bad idea and does it make for clean code?" }
31392
<p>I am trying to open two CSV files, one for reading and one for writing. The script should continue only if both files were successfully opened. My code seems to accomplish that but it seems like it could be improved further.</p> <p>My questions are:</p> <ol> <li>Should I consider a different approach?</li> <li>My code feels a bit bloated inside the try statement (imagine 100 additional lines of code). Is there a "cleaner" approach?</li> <li>If the files were opened successfully, but a different error occurs later on that is not an IOError, this code will not catch it, correct?</li> </ol> <p>Code:</p> <pre><code>input_file = 'in_file.csv' output_file = 'out_file.csv' def main(): try: with open(input_file, 'rb') as in_csv, open(output_file , 'wb') as out_csv: writer = csv.writer(out_csv, delimiter='\t') reader = csv.reader(in_csv, delimiter='\t') for row in reader: # many lines of code... except IOError as e: print "Error: cannot open file" if e.errno == errno.EACCES: print "\tPermission denied." print "\tError message: {0}".format(e) sys.exit() # Not a permission error. print "\tDoes file exist?" print "\tError message: {0}".format(e) sys.exit() if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>You might want to pass the filenames to <code>main()</code> as parameters, to promote code re-use and testing. Then in <code>__main__:</code> you could <code>import sys</code> and check for <code>len(sys.argv) &gt; 1</code> ... setting the input, and output filenames thereby.</p>\n\n<p>(You can preserve the default behavior in the case where your program is called as it, but these changes would also mean that your CSV re-writer could be used as a module for some other program).</p>\n\n<p>In fact it would also be good go rename your current <code>main()</code> to something more reflective of it's function and wrap the argument handling into a newly written <code>main()</code> wrapper around the function you've shown here.</p>\n\n<p>Generalizing further you could add a <code>delimiter=None</code> as a defaulted argument to your function and thus facilitate over-ride of the input and output delimiters inside the function.</p>\n\n<p>All of that depends on how generalized and re-useable you want your code to be. Obviously there's a trade off between the flexible functionality and the additional complexity being introduced there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T20:15:27.620", "Id": "50663", "Score": "0", "body": "Much appreciated. Great explanation!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T00:36:20.433", "Id": "31398", "ParentId": "31395", "Score": "1" } }, { "body": "<p>To answer your questions…</p>\n\n<ol>\n<li>Your approach is fine.</li>\n<li>Move your hundreds of lines into a function, then break down that function into reasonable-sized chunks. If it's still huge and ugly, then pose that as another code review question.</li>\n<li>If an error other an <code>IOError</code> occurred, then the error would not get caught. However, when the <code>with</code> block is exited for any reason, <code>input_file</code> and <code>output_file</code> will get properly closed.</li>\n</ol>\n\n<p>In addition to what @JimDennis said, I would like to point out that it it customary to print error messages to <code>sys.stderr</code>, and exit with a non-zero status when an error occurs.</p>\n\n<pre><code>def process(csv_reader, csv_writer):\n for row in csv_reader:\n # many lines of code...\n\ndef main(input_filename, output_filename):\n try:\n with open(input_filename, 'rb') as in_csv, open(output_filename , 'wb') as out_csv:\n writer = csv.writer(out_csv, delimiter='\\t')\n reader = csv.reader(in_csv, delimiter='\\t')\n process(reader, writer)\n except IOError as e:\n print &gt;&gt; sys.stderr, \"Error: cannot open file\"\n if e.errno == errno.EACCES:\n print &gt;&gt; sys.stderr, \"\\tPermission denied.\"\n print &gt;&gt; sys.stderr, \"\\tError message: {0}\".format(e)\n sys.exit(1)\n # Not a permission error.\n print &gt;&gt; sys.stderr, \"\\tError message: {0}\".format(e)\n sys.exit(1)\n except Exception as other_exception:\n print &gt;&gt; sys.stderr, \"Error: \" + str(other_exception)\n sys.exit(2)\n\nif __name__ == '__main__':\n main('in_file.csv', 'out_file.csv')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T20:16:26.623", "Id": "50664", "Score": "0", "body": "Thanks a lot for answering my questions and providing an example!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T20:45:50.597", "Id": "50665", "Score": "0", "body": "You're welcome. I've added some [minor touches](http://codereview.stackexchange.com/revisions/31411/2). In particular, you shouldn't speculate on the cause of an error, because you could mislead the user. Let the error message speak for itself." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T07:36:03.703", "Id": "31411", "ParentId": "31395", "Score": "4" } } ]
{ "AcceptedAnswerId": "31411", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-16T23:52:41.703", "Id": "31395", "Score": "8", "Tags": [ "python", "csv", "file" ], "Title": "Python: Open Multiple Files" }
31395
<p>I'm working on a simple CMS with the intent of making it as secure as possible (a personal challenge) and the code as clean as possible. I think I've a long way to go so I would appreciate any input, or bug spotting!</p> <p><strong>Common.php</strong></p> <pre><code>&lt;?php // Errors, errors everywhere. Let us display them all! error_reporting(E_ALL); ini_set('display_errors', 1); // These variables define the connection information for your MSSQL database $username = &lt;redacted&gt;; $password = &lt;redacted&gt;; $host = &lt;redacted&gt;; $dbname = &lt;redacted&gt;; // UTF-8 is a character encoding scheme that allows you to conveniently store // a wide varienty of special characters, like ¢ or €, in your database. // By passing the following $options array to the database connection code we // are telling the MSSQL server that we want to communicate with it using UTF-8 // See Wikipedia for more information on UTF-8: // http://en.wikipedia.org/wiki/UTF-8 //$options = array(PDO::MSSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8'); // A try/catch statement is a common method of error handling in object oriented code. // First, PHP executes the code within the try block. If at any time it encounters an // error while executing that code, it stops immediately and jumps down to the // catch block. For more detailed information on exceptions and try/catch blocks: // http://us2.php.net/manual/en/language.exceptions.php try { // This statement opens a connection to your database using the PDO library // PDO is designed to provide a flexible interface between PHP and many // different types of database servers. For more information on PDO: // http://us2.php.net/manual/en/class.pdo.php //$db = new PDO("mssql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); //$db = new PDO('sqlsrv:Server=$host;Database=$dbname','$username','$password'); $db = new PDO ("sqlsrv:server = tcp:$host,1433; Database = $dbname", "$username", "$password"); $db-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch(PDOException $ex) { // If an error occurs while opening a connection to your database, it will // be trapped here. The script will output an error and stop executing. // Note: On a production website, you should not output $ex-&gt;getMessage(). // It may provide an attacker with helpful information about your code // (like your database username and password). die("Failed to connect to the database: " . $ex-&gt;getMessage()); } // This statement configures PDO to throw an exception when it encounters // an error. This allows us to use try/catch blocks to trap database errors. $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // This statement configures PDO to return database rows from your database using an associative // array. This means the array will have string indexes, where the string value // represents the name of the column in your database. $db-&gt;setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // This block of code is used to undo magic quotes. Magic quotes are a terrible // feature that was removed from PHP as of PHP 5.4. However, older installations // of PHP may still have magic quotes enabled and this code is necessary to // prevent them from causing problems. For more information on magic quotes: // http://php.net/manual/en/security.magicquotes.php if(function_exists('get_magic_quotes_gpc') &amp;&amp; get_magic_quotes_gpc()) { function undo_magic_quotes_gpc(&amp;$array) { foreach($array as &amp;$value) { if(is_array($value)) { undo_magic_quotes_gpc($value); } else { $value = stripslashes($value); } } } undo_magic_quotes_gpc($_POST); undo_magic_quotes_gpc($_GET); undo_magic_quotes_gpc($_COOKIE); } // This tells the web browser that your content is encoded using UTF-8 // and that it should submit content back to you using UTF-8 header('Content-Type: text/html; charset=utf-8'); // This initializes a session. Sessions are used to store information about // a visitor from one web page visit to the next. Unlike a cookie, the information is // stored on the server-side and cannot be modified by the visitor. However, // note that in most cases sessions do still use cookies and require the visitor // to have cookies enabled. For more information about sessions: // http://us.php.net/manual/en/book.session.php session_start(); // Note that it is a good practice to NOT end your PHP files with a closing PHP tag. // This prevents trailing newlines on the file from being included in your output, // which can cause problems with redirecting users. </code></pre> <p><strong>Login.php</strong> (this one likely can be done a <em>LOT</em> better)</p> <pre><code>&lt;?php // First we execute our common code to connection to the database and start the session require("common.php"); // This variable will be used to re-display the user's username to them in the // login form if they fail to enter the correct password. It is initialized here // to an empty value, which will be shown if the user has not submitted the form. $submitted_username = ''; // This if statement checks to determine whether the login form has been submitted // If it has, then the login code is run, otherwise the form is displayed if(!empty($_POST) || isset($_COOKIE["qcore"])) { // set the parameter values as if the form has been filled out if(!empty($_POST)) { // This query retreives the user's information from the database using // their username. SELECT TOP 1 prevents people from being able to edit // their HTTP POST to fetch the entire table. $query = " SELECT TOP 1 * FROM dbo.[User] WHERE Username = :username "; $query_params = array( ':username' =&gt; $_POST['username'] ); } // if it hasn't, let's use the cooooooooooooookie! Woo! else if (isset($_COOKIE["qcore"])) { $query = " SELECT TOP 1 u.* FROM dbo.[User] AS u INNER JOIN dbo.UserSession AS us ON us.UserId = u.UserId WHERE us.SessionId = :sessiontoken"; // The parameter values $query_params = array( ':sessiontoken' =&gt; $_COOKIE["qcore"] ); } try { // Execute the query against the database $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch(PDOException $ex) { // Note: On a production website, you should not output $ex-&gt;getMessage(). // It may provide an attacker with helpful information about your code. die("Failed to run query: " . $ex-&gt;getMessage()); } // This variable tells us whether the user has successfully logged in or not. // We initialize it to false, assuming they have not. // If we determine that they have entered the right details, then we switch it to true. $login_ok = false; // Retrieve the user data from the database. If $row is false, then the username // they entered is not registered. $row = $stmt-&gt;fetch(); if($row &amp;&amp; !isset($_COOKIE["qcore"])) { // Using the password submitted by the user and the salt stored in the database, // we now check to see whether the passwords match by hashing the submitted password // and comparing it to the hashed version already stored in the database. $check_password = hash('sha256', $_POST['password'] . $row['Salt']); for($round = 0; $round &lt; 65536; $round++) { $check_password = hash('sha256', $check_password . $row['Salt']); } if($check_password === $row['Password']) { // If they do, then we flip this to true $login_ok = true; } } elseif (isset($_COOKIE["qcore"])) { $login_ok = true; } // If the user logged in successfully, then we send them to the private members-only page // Otherwise, we display a login failed message and show the login form again if($login_ok) { // Here I am preparing to store the $row array into the $_SESSION by // removing the salt and password values from it. Although $_SESSION is // stored on the server-side, there is no reason to store sensitive values // in it unless you have to. Thus, it is best practice to remove these // sensitive values first. if(!empty($_POST)) { unset($row['Salt']); unset($row['Password']); } // This stores the user's data into the session at the index 'user'. // We will check this index on the private members-only page to determine whether // or not the user is logged in. We can also use it to retrieve // the user's details. $_SESSION['user'] = $row; // Generate a session token which is used locally as a key between the users cookie // and their UserID, this prevents the user from being able to edit their cookie // to login as another user. $sessiontoken = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); // Save our cookie 'qcore' with the users session id setcookie("qcore", $sessiontoken); // Insert a new session ID record, or update if one already exists. $query = " DECLARE @userid AS INTEGER = :userid DECLARE @sessionid AS varchar(500) = :sessionid IF EXISTS ( SELECT TOP 1 * FROM dbo.UserSession WHERE UserId = @userid ) UPDATE dbo.UserSession SET SessionId = @sessionid WHERE UserId = @userid ELSE INSERT INTO dbo.UserSession ( UserId , SessionId ) VALUES ( @userid , @sessionid)"; $query_params = array( ':userid' =&gt; $row['UserId'], ':sessionid' =&gt; $sessiontoken ); try { // Execute the query to insert a new user session or update // an existing one $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch(PDOException $ex) { // Note: On a production website, you should not output $ex-&gt;getMessage(). // It may provide an attacker with helpful information about your code. // die("Failed to run query: " . $ex-&gt;getMessage()); die("Failed to run query: " . $ex-&gt;getMessage()); } // Redirect the user to the private members-only page. // This will need to be changed once we have the QUEST logic flow sorted out // to be the landing quest page. header("Location: private.php"); die("Redirecting to: private.php"); } else { // Tell the user they failed print("Login Failed."); // Show them their username again so all they have to do is enter a new // password. The use of htmlentities prevents XSS attacks. You should // always use htmlentities on user submitted values before displaying them // to any users (including the user that submitted them). For more information: // http://en.wikipedia.org/wiki/XSS_attack $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); } } ?&gt; &lt;h1&gt;Login&lt;/h1&gt; &lt;form action="login.php" method="post"&gt; Username:&lt;br /&gt; &lt;input type="text" name="username" value="&lt;?php echo $submitted_username; ?&gt;" /&gt; &lt;br /&gt;&lt;br /&gt; Password:&lt;br /&gt; &lt;input type="password" name="password" value="" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;input type="submit" value="Login" /&gt; &lt;/form&gt; &lt;a href="register.php"&gt;Register&lt;/a&gt; </code></pre> <p><strong>Logout.php</strong></p> <pre><code>&lt;?php // First we execute our common code to connection to the database and start the session require("common.php"); // We remove the user's data from the session unset($_SESSION['user']); // set the cookie expiration date to one hour ago setcookie("qcore", "", time()-3600); // We redirect them to the login page header("Location: login.php"); die("Redirecting to: login.php"); </code></pre> <p><strong>Private.php</strong></p> <pre><code>&lt;?php // *** IMPORTANT *** // This file will lock a page down to logged in users only. If you would like to secure // the page to administrators only then include private_administrator.php instead! // First we execute our common code to connection to the database and start the session require("common.php"); // At the top of the page we check to see whether the user is logged in or not if(empty($_SESSION['user'])) { // If they are not, we redirect them to the login page. header("Location: login.php"); // Remember that this die statement is absolutely critical. Without it, // people can view your members-only content without logging in. die("Redirecting to login.php"); } // Everything below this point in the file is secured by the login system // We can display the user's username to them by reading it from the session array. Remember that because // a username is user submitted content we must use htmlentities on it before displaying it to the user. ?&gt; Hello &lt;?php echo htmlentities($_SESSION['user']['Username'], ENT_QUOTES, 'UTF-8'); ?&gt;, secret content!&lt;br /&gt; &lt;a href="memberlist.php"&gt;Memberlist&lt;/a&gt;&lt;br /&gt; &lt;a href="edit_account.php"&gt;Edit Account&lt;/a&gt;&lt;br /&gt; &lt;a href="logout.php"&gt;Logout&lt;/a&gt; </code></pre> <p><strong>Register.php</strong></p> <pre><code>&lt;?php // First we execute our common code to connection to the database and start the session require("common.php"); // This if statement checks to determine whether the registration form has been submitted // If it has, then the registration code is run, otherwise the form is displayed if(!empty($_POST)) { // Ensure that the user has entered a non-empty username if(empty($_POST['username'])) { // Note that die() is generally a terrible way of handling user errors // like this. It is much better to display the error with the form // and allow the user to correct their mistake. However, that is an // exercise for you to implement yourself. die("Please enter a username."); } // Ensure that the user has entered a non-empty password if(empty($_POST['password'])) { die("Please enter a password."); } // Make sure the user entered a valid E-Mail address // filter_var is a useful PHP function for validating form input, see: // http://us.php.net/manual/en/function.filter-var.php // http://us.php.net/manual/en/filter.filters.php if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { die("Invalid E-Mail Address"); } // We will use this SQL query to see whether the username entered by the // user is already in use. A SELECT query is used to retrieve data from the database. // :username is a special token, we will substitute a real value in its place when // we execute the query. $query = " SELECT 1 FROM dbo.[User] WHERE Username = :username "; // This contains the definitions for any special tokens that we place in // our SQL query. In this case, we are defining a value for the token // :username. It is possible to insert $_POST['username'] directly into // your $query string; however doing so is very insecure and opens your // code up to SQL injection exploits. Using tokens prevents this. // For more information on SQL injections, see Wikipedia: // http://en.wikipedia.org/wiki/SQL_Injection $query_params = array( ':username' =&gt; $_POST['username'] ); try { // These two statements run the query against your database table. $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch(PDOException $ex) { // Note: On a production website, you should not output $ex-&gt;getMessage(). // It may provide an attacker with helpful information about your code. die("Failed to run query: " . $ex-&gt;getMessage()); } // The fetch() method returns an array representing the "next" row from // the selected results, or false if there are no more rows to fetch. $row = $stmt-&gt;fetch(); // If a row was returned, then we know a matching username was found in // the database already and we should not allow the user to continue. if($row) { die("This username is already in use"); } // Now we perform the same type of check for the email address, in order // to ensure that it is unique. $query = " SELECT 1 FROM dbo.[User] WHERE Email = :email "; $query_params = array( ':email' =&gt; $_POST['email'] ); try { $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch(PDOException $ex) { die("Failed to run query: " . $ex-&gt;getMessage()); } $row = $stmt-&gt;fetch(); if($row) { die("This email address is already registered"); } // An INSERT query is used to add new rows to a database table. // Again, we are using special tokens (technically called parameters) to // protect against SQL injection attacks. $query = " INSERT INTO dbo.[User] ( Username, Password, Salt, Email ) VALUES ( :username, :password, :salt, :email ) "; // A salt is randomly generated here to protect again brute force attacks // and rainbow table attacks. The following statement generates a hex // representation of an 8 byte salt. Representing this in hex provides // no additional security, but makes it easier for humans to read. // For more information: // http://en.wikipedia.org/wiki/Salt_%28cryptography%29 // http://en.wikipedia.org/wiki/Brute-force_attack // http://en.wikipedia.org/wiki/Rainbow_table $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); // This hashes the password with the salt so that it can be stored securely // in your database. The output of this next statement is a 64 byte hex // string representing the 32 byte sha256 hash of the password. The original // password cannot be recovered from the hash. For more information: // http://en.wikipedia.org/wiki/Cryptographic_hash_function $password = hash('sha256', $_POST['password'] . $salt); // Next we hash the hash value 65536 more times. The purpose of this is to // protect against brute force attacks. Now an attacker must compute the hash 65537 // times for each guess they make against a password, whereas if the password // were hashed only once the attacker would have been able to make 65537 different // guesses in the same amount of time instead of only one. for($round = 0; $round &lt; 65536; $round++) { $password = hash('sha256', $password . $salt); } // Here we prepare our tokens for insertion into the SQL query. We do not // store the original password; only the hashed version of it. We do store // the salt (in its plaintext form; this is not a security risk). $query_params = array( ':username' =&gt; $_POST['username'], ':password' =&gt; $password, ':salt' =&gt; $salt, ':email' =&gt; $_POST['email'] ); try { // Execute the query to create the user $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch(PDOException $ex) { // Note: On a production website, you should not output $ex-&gt;getMessage(). // It may provide an attacker with helpful information about your code. die("Failed to run query: " . $ex-&gt;getMessage()); } // This redirects the user back to the login page after they register header("Location: login.php"); // Calling die or exit after performing a redirect using the header function // is critical. The rest of your PHP script will continue to execute and // will be sent to the user if you do not die or exit. die("Redirecting to login.php"); } ?&gt; &lt;h1&gt;Register&lt;/h1&gt; &lt;form action="register.php" method="post"&gt; Username:&lt;br /&gt; &lt;input type="text" name="username" value="" /&gt; &lt;br /&gt;&lt;br /&gt; E-Mail:&lt;br /&gt; &lt;input type="text" name="email" value="" /&gt; &lt;br /&gt;&lt;br /&gt; Password:&lt;br /&gt; &lt;input type="password" name="password" value="" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;input type="submit" value="Register" /&gt; &lt;/form&gt; </code></pre> <p><strong>User table</strong></p> <pre><code>CREATE TABLE [dbo].[User]( [UserId] [int] IDENTITY(1,1) NOT NULL, [Title] [varchar](50) NULL, [FirstName] [varchar](100) NULL, [MiddleName] [varchar](100) NULL, [LastName] [varchar](100) NULL, [Gender] [varchar](20) NULL, [DOB] [date] NULL, [Email] [varchar](200) NULL, [Phone] [varchar](50) NULL, [Mobile] [varchar](50) NULL, [ResidentialAddress] [varchar](100) NULL, [ResidentialPostCode] [varchar](10) NULL, [ResidentialSuburb] [varchar](50) NULL, [ResidentialState] [varchar](20) NULL, [ResidentialCountry] [varchar](200) NULL, [PostalAddress] [varchar](100) NULL, [PostalPostCode] [varchar](10) NULL, [PostalSuburb] [varchar](50) NULL, [PostalState] [varchar](20) NULL, [PostalCountry] [varchar](200) NULL, [BrowserDetails] [varchar](500) NULL, [IsActive] [bit] NULL, [Password] [varchar](500) NULL, [Salt] [varchar](50) NULL, [LastLogin] [datetime] NULL, [CompanyID] [int] NULL, [Created] [datetime] NULL, [CreatedBy] [varchar](50) NULL, [LastModified] [datetime] NULL, [LastModifiedBy] [varchar](50) NULL ) SET ANSI_PADDING OFF ALTER TABLE [dbo].[User] ADD [Username] [varchar](50) NULL SET ANSI_PADDING ON ALTER TABLE [dbo].[User] ADD [UserRole] [varchar](30) NULL CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ( [UserId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[User] ADD DEFAULT ('User') FOR [UserRole] GO </code></pre> <p><strong>UserSession Table</strong></p> <pre><code>CREATE TABLE [dbo].[UserSession]( [UserId] [int] NOT NULL, [SessionId] [varchar](500) NOT NULL, [Created] [datetime] NOT NULL, [CreatedBy] [varchar](50) NOT NULL, [LastModifed] [datetime] NULL, [LastModifiedBy] [varchar](50) NULL, CONSTRAINT [PK_SessionID] PRIMARY KEY CLUSTERED ( [SessionId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ) GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[UserSession] ADD DEFAULT (getdate()) FOR [Created] GO ALTER TABLE [dbo].[UserSession] ADD DEFAULT (user_name()) FOR [CreatedBy] GO </code></pre>
[]
[ { "body": "<p>You talk security, but you make some really bad mistakes.</p>\n\n<p>To start with the error_reporting. NEVER, simply NEVER have E_ALL as error_reporting level on a production enviroment.</p>\n\n<p>You are catching Exceptions, that is good. But what about E_NOTICE? and E_WARNING? you can catch these by registering an error report function using <a href=\"http://php.net/manual/en/function.set-error-handler.php\" rel=\"nofollow noreferrer\">set_error_handler();</a>\nThen to be sure you can also add an <a href=\"http://php.net/manual/en/function.set-exception-handler.php\" rel=\"nofollow noreferrer\">exception handler</a> in case a uncaught exception bubbles up to the root.</p>\n\n<p>Then, on to your password hashing. <a href=\"http://en.wikipedia.org/wiki/PBKDF2\" rel=\"nofollow noreferrer\">Don't</a> <a href=\"http://www.openwall.com/phpass/\" rel=\"nofollow noreferrer\">reinvent</a> <a href=\"https://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords\">the</a> <a href=\"https://crackstation.net/hashing-security.htm\" rel=\"nofollow noreferrer\">wheel</a>\nPersonally I prefer PBKDF2, but the stach overflow answer on 'the' sums it up.</p>\n\n<p>Then, why are you generating a session_token? Ok, to be more secure. But you use mt_rand and then simply convert it to hexadecimal. How is this secure? </p>\n\n<p>The next thing I noticed was all those horrible die(); calls. Yuck, they simply ask for a hard time debugging that code. NEVER display an error using die('my error'); If an error happens, throw an exception or what ever and let the error-reporting function do iets job (i.e. loging, mailing the webmaster, ...). This also gives you more control on the output of the application instead of simply sending a HTTP 200 OK message with only 1 string (the error).</p>\n\n<p>Apart from that I have some overall remarks: seperation of concern. Personally I tend to chuck code away without even looking at it if there is business logic and html in the same file. Seperate them. And while your at it. Create one entry point that decides what to do (i.e. the controller / router).</p>\n\n<p>Then there are some small things.</p>\n\n<pre><code>$row = $stmt-&gt;fetch();\nif ( $row ) ...\n</code></pre>\n\n<p>Is weird code. What are you doing with $row? nothing...</p>\n\n<pre><code>if ( $stmt-&gt;rowCount() === 1 ) ...\n</code></pre>\n\n<p>Does the job and its easier and more fun to read.</p>\n\n<p>You save the entire user in the $_SESSION and rely on that being set. But this will make scalability very hard. $_SESSION data is stored in a file on the server itself. If you simply store the session data in the database instead of $_SESSION you give yourself much more flexibility. Just my 5 cents</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T13:17:32.540", "Id": "50063", "Score": "0", "body": "I disagree with your saying catching errors is good. If the catch-block only contains a `die` satement, `catch` is just dead-weight, and will bypass any exception handlers registered. If something your app needs throws an exception, don't catch it 'till the very end (exception handler)... BTW `$row` is used in some cases, though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T14:03:49.880", "Id": "50069", "Score": "0", "body": "Personally I think depending on the situation some exceptions need to be catched and others not. It also depends on what programming style you are using. Are you returning a boolean success? or are you throwing an exception? Do you throw exception for every little problem (i.e. no an int)? And as I also pointed out, heshouldnt simply die. But I do get what you mean. Overall try-catch will be dead weight" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T14:21:31.080", "Id": "50071", "Score": "0", "body": "Of course, some exceptions have to be caught, just like I pointed out in my example: an insert fails -> rollback the transaction, this should be done using `try-catch`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:44:59.127", "Id": "31416", "ParentId": "31396", "Score": "2" } }, { "body": "<p>You want to make your code as secure as possible. Good. You want your code to be as clean as possible: Great. How are you doing? Well, there's some work left to be done, I'm affraid.</p>\n<p><em>Magic quotes</em><Br/>\nI have very little to say about this, except for: <a href=\"http://www.php.net/manual/en/security.magicquotes.php\" rel=\"noreferrer\">RTFM</a> (it's in the security section BTW):</p>\n<blockquote>\n<p>This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.</p>\n</blockquote>\n<p>Just replace the code that deals with magic quotes with a couple of <code>ini_set</code>'s, that ammount to:</p>\n<pre><code>magic_quotes_gpc = Off\nmagic_quotes_runtime = Off\nmagic_quotes_sybase = Off\n</code></pre>\n<p><em>PDO</em><br/>\nAfter connecting, in the pointless try-catch block (more on that later), you set the error-mode:</p>\n<pre><code>$db-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );\n</code></pre>\n<p>Only to repeat this call <em>after the try-catch again</em>. That's not clean code, that's clutter. Besides, wouldn't it be cleaner to connect like this:</p>\n<pre><code>$pdo = new PDO( 'sqlsrv:server=tcp:'.$host.',1433;Database='.$dbname,\n (string) $username,\n (string) $password,\n array(\n PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC\n )\n );\n</code></pre>\n<p>Setting your attributes in one fell swoop? this way, I can see what attributes are being set and what server is being connected to. Why, then, am I not catching an exception, that might be thrown here? Simply because your <code>catch</code> block is a <code>die</code>: if the connection fails, your app fails, why <em>catch</em> what cannot be saved?</p>\n<p><em>Other niggles:</em><br/></p>\n<p>Redundat queries: You're preparing a stmt, to check if the email is taken. If it isn't, you proceed to query to check the existance of the username. Why not do this in one go?</p>\n<pre><code>SELECT Email FROM tbl WHERE Email = :email OR username = :username\n</code></pre>\n<p>This does <em>exactly</em> the same thing, but requires only <em>one</em> query.</p>\n<p>Redirecting: <code>header(&quot;Location: login.php&quot;); </code> is not standard, it'll redirect to the <code>login.php</code> script in your pwd (present working directory). The best way to redirect still is:</p>\n<pre><code>header(&quot;Location: http://yourdomain.com/login.php&quot;, true, 301);//redirect permanently\nreturn;//or exit... I hate die\n</code></pre>\n<p>Wrapping your selects in a <code>try-catch=&gt;die</code> is just a waste of space, just select, if it throws an exception, let the app crash, and get to debugging. When <code>INSERT INTO</code> fails, however, that's a different story. You <em>have</em> to use <code>try-catch</code> there, if you want your code to be as safe as it possibly can be, but you'll have to use transactions, and rollback in case of an exception:</p>\n<pre><code>try\n{\n $pdo-&gt;beginTransaction();\n $pdo-&gt;exec($insertStmt);\n $pdo-&gt;commit();\n}\ncatch(PDOException $e)\n{\n $pdo-&gt;rollBack();//revert any changes made during last transaction\n throw $e;//rethrow exception, let it go... don't call die\n}\n</code></pre>\n<p><em><code>require</code> is not safe</em><br/>\nWell, it's not the safest option available to you. <code>require_once</code> is. They do exactly the same thing, except for one thing: <code>require_once</code> (as its name suggests) will make sure the file wasn't included already. That makes it a tad slower, but a whole lot safer. Use <code>require_once</code>, then!</p>\n<p><em>globals are bad</em><br/>\nglobal variables are not safe. Ever. Period. Use functions, classes, namespaces and all that, to avoid name-conflicts.</p>\n<p><em>error settings</em><br/>\nIf this were production code, I hope you'd set <code>display_errors</code> to 0, right? clients shouldn't be able to see what errors your code contains, that's not safe. setting the <code>error_reporting(E_ALL);</code> is good, but consider: <code>error_reporting(E_STRICT|E_ALL);</code> or <code>error_reporting(-1);</code>, and <em>&quot;go for zero&quot;</em> (as in no notices, warnings or errors)</p>\n<p>Now, I've saved best for last:</p>\n<h2>Silly hash!</h2>\n<p>You're using <code>sha256</code> with salt as a hash. That's <em>enough</em>. Honestly! When looping, and hashing the hash <em>65536 times!!</em>, you're just slowing your code down, not making it extra secure. If anything, however unlikely they are (<a href=\"http://en.wikipedia.org/wiki/SHA-2\" rel=\"noreferrer\">none found to this date</a>, in fact), this will increase the possibility of collisions, not reduce them! Anyway, sha256 is, to this date, perfectly safe:<br/>\nIf you were to have a machine, dedicated to cracking a sha256 hash, it'd take ~= 10^64 years!. If 10^64 is meaningless, here's the number in full:</p>\n<blockquote>\n<p>100.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000</p>\n</blockquote>\n<p>That's <em>years</em>, not tries, <em>years</em>!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T13:24:19.370", "Id": "50064", "Score": "0", "body": "I assume `sha256` is being called repeatedly as a form of key-strengthening. If your goal is to prevent an external user from hacking, a delay will work just as well, yet will avoid burning CPU. If your goal is to make it more painful to crack your database (i.e., if someone manages to steal your password database and you want to slow down their efforts to extract plain-text passwords), then key-strengthening will help. That being said, I agree with [Pinoniq](http://codereview.stackexchange.com/a/31416/8243) that it's better to use an existing key-strengthening function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T13:38:22.823", "Id": "50067", "Score": "0", "body": "@Brian: My point is: sha256 is secure enough... there's other things you'd want secure _first_. You're not going to spend time applying sealant around your bath tub when your roof is leaking, are you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T14:07:18.893", "Id": "50070", "Score": "0", "body": "Good thing to point out that sha256 multiple times won't help as you pointed out. It will make it weaker because of a bigger chance of collisions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T14:28:08.450", "Id": "50072", "Score": "0", "body": "@Pinoniq: _\"this will increase the possibility of collisions, not reduce them\"_... already pointed that out... though the increase of probability _is ≃ 0%_, but about twice as big a chance of a natural collision. Ah well... there is a _some_ increased risk of collision" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T14:41:25.303", "Id": "50074", "Score": "0", "body": "@EliasVanOotegem: Maybe not, but you're also not going to start ripping off existing sealant from your bath tub while your roof is leaking. The OP's use repeated calls to sha256 *is* accomplishing something. Whether it is important to protect the database after it has been stolen is a decision the OP can make. It's good practice to do so (mitigates attacks on your users' passwords, since they are probably using the same password everywhere). I admit this particular protection is low priority, but that isn't justification to remove it if it is already in place." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T12:26:56.217", "Id": "31423", "ParentId": "31396", "Score": "6" } }, { "body": "<p>Since there are multiple answers about the security aspect of your code, I'll comment on the \"cleanliness\" and generally about architecture.</p>\n\n<ol>\n<li><p>Connecting to the database with each HTTP request can expose your application and database to a Distributed Denial Of Service Attack.</p>\n\n<pre><code>// First we execute our common code to connection to the database and start the session\nrequire(\"common.php\");\n</code></pre>\n\n<p>With this at the top of every file, one HTTP request corresponds to one connection to the database. Imagine a botnet throwing tsunami after tsunami of requests at your server. It takes down your server, application AND database. Yow.</p>\n\n<p><strong>Don't connect to the database unless you need to.</strong></p></li>\n<li><p>Comments should explain why something is done, not what is being done. Read <a href=\"http://blog.codinghorror.com/coding-without-comments/\" rel=\"nofollow\">Coding Without Comments</a> for some inspiration. Don't comment the obvious.</p>\n\n<pre><code>// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.\n// This prevents trailing newlines on the file from being included in your output,\n// which can cause problems with redirecting users.\n</code></pre>\n\n<p>While this explains <em>why</em> the trailing closing PHP tag was omitted, you don't need to say this. PHP developers are going to know this, or learn this quickly. You don't need to comment about commonly known facts about a language or design pattern.</p></li>\n</ol>\n\n<p>The rest of your code, while it works, basically breaks every programming best practice I can think of. You've got business logic mixed in with data access code, mixed in with view logic, mixed in with user interaction code, mixed in with user input validation code. These all should be in their own classes. This is really where object oriented code starts to shine.</p>\n\n<h2>Utilizing Object Oriented Programming</h2>\n\n<p>The key here is to \"separate your concerns.\" What \"concerns\" are there?</p>\n\n<ul>\n<li>Data access</li>\n<li>Business logic</li>\n<li>Form validation</li>\n<li>HTTP request handling</li>\n<li>Rendering a view</li>\n</ul>\n\n<h3>Separating HTTP Request Handling From the View</h3>\n\n<p>For example, Login.php should be split into two files. Login.php should just contain PHP code and no HTML. It should include LoginForm.php, which would have the HTML code. This separates the HTTP request handling from rendering the view. Now you can make changes in either file with minimal impact on the other. Furthermore, you want to re-render the Login form if there are validation errors instead of calling <code>die</code>. Show the user the validation messages:</p>\n\n<pre><code>if (empty($_POST['username'])) {\n $_POST['username_error'] = 'Username is required';\n}\n</code></pre>\n\n<p>Where your Login.php file ended with:</p>\n\n<pre><code>?&gt;\n&lt;h1&gt;Login&lt;/h1&gt;\n</code></pre>\n\n<p>It should end with:</p>\n\n<pre><code>include('path/to/LoginForm.php');\n</code></pre>\n\n<p>And LoginForm.php would be:</p>\n\n<pre><code>&lt;h1&gt;Register&lt;/h1&gt;\n&lt;form action=\"register.php\" method=\"post\"&gt;\n Username:&lt;br /&gt;\n &lt;input type=\"text\" name=\"username\" value=\"&lt;?php echo $_POST['username']; ?&gt;\" /&gt;\n &lt;span&gt;&lt;?php echo $_POST['username_error']; ?&gt;&lt;/span&gt;\n &lt;br /&gt;&lt;br /&gt;\n E-Mail:&lt;br /&gt;\n &lt;input type=\"text\" name=\"email\" value=\"&lt;?php echo $_POST['email']; ?&gt;\" /&gt;\n &lt;span&gt;&lt;?php echo $_POST['email_error']; ?&gt;&lt;/span&gt;\n &lt;br /&gt;&lt;br /&gt;\n Password:&lt;br /&gt;\n &lt;input type=\"password\" name=\"password\" value=\"&lt;?php echo $_POST['password']; ?&gt;\" /&gt;\n &lt;span&gt;&lt;?php echo $_POST['password_error']; ?&gt;&lt;/span&gt;\n &lt;br /&gt;&lt;br /&gt;\n &lt;input type=\"submit\" value=\"Register\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>The last two items are separating your data access from business logic.</p>\n\n<h2>Separating Data Access From Business Logic</h2>\n\n<p>Since you have two tables in the database, create Domain Models for each table. A Domain Model is a class that represents a row from a particular table. You have a table called \"Users\" so create a class in PHP called <code>User</code> (the singular form of the table name). After that you need another class to perform CRUD operations on the Users table in the database (<strong>C</strong>reate, <strong>R</strong>ead, <strong>U</strong>pdate, <strong>D</strong>elete). For this data access layer, we can utilize the <a href=\"http://code.tutsplus.com/tutorials/the-repository-design-pattern--net-35804\" rel=\"nofollow\">Repository Pattern</a> to really clean things up.</p>\n\n<h3>Creating the <code>User</code> Domain Model</h3>\n\n<p>First things first. Let's create the Domain Model for the \"Users\" table called <code>User</code>:</p>\n\n<pre><code>class User\n{\n private $id;\n private $username;\n private $title;\n private $first_name;\n private $middle_name;\n private $last_name;\n private $gender;\n private $birth_date;\n private $email;\n private $phone;\n private $mobile_phone;\n private $residential_address;\n private $postal_address;\n private $browser_details;\n private $active;\n private $password;\n private $salt;\n private $last_login_date;\n private $company_id;\n private $date_created;\n private $created_by;\n private $date_modified;\n private $modified_by;\n\n public __construct($salt, $password, $username, $id = 0)\n {\n $this-&gt;username = $username;\n $this-&gt;id = $id;\n $this-&gt;salt = $salt;\n $this-&gt;password = $password;\n }\n\n // Getters\n\n public function getId()\n {\n return $this-&gt;id;\n }\n\n public function getUsername()\n {\n return $this-&gt;username;\n }\n\n public function getTitle()\n {\n return $this-&gt;title;\n }\n\n public function getFirstName()\n {\n return $this-&gt;first_name;\n }\n\n public function getMiddleName()\n {\n return $this-&gt;middle_name;\n }\n\n public function getLastName()\n {\n return $this-&gt;last_name;\n }\n\n public function getFullName()\n {\n return $this-&gt;first_name . ' ' . $this-&gt;middle_name . ' ' . $this-&gt;last_name;\n }\n\n public function getGender()\n {\n return $this-&gt;gender;\n }\n\n public function getBirthDate()\n {\n return $this-&gt;birth_date;\n }\n\n public function getEmail()\n {\n return $this-&gt;email;\n }\n\n public function getPhone()\n {\n return $this-&gt;phone;\n }\n\n public function getMobilePhone()\n {\n return $this-&gt;mobile_phone;\n }\n\n public function getResidentialAddress()\n {\n return $this-&gt;residential_address;\n }\n\n public function getPostalAddress()\n {\n return $this-&gt;postal_address;\n }\n\n public function getBrowserDetails()\n {\n return $this-&gt;browser_details;\n }\n\n public function getLastLoginDate()\n {\n return $this-&gt;last_login_date;\n }\n\n public function getCompanyId()\n {\n return $this-&gt;company_id;\n }\n\n public function getDateCreated()\n {\n return $this-&gt;date_created;\n }\n\n public function getCreatedBy()\n {\n return $this-&gt;created_by;\n }\n\n public function getDateModified()\n {\n return $this-&gt;date_modified;\n }\n\n public function getModifiedBy()\n {\n return $this-&gt;modified_by;\n }\n\n // Setters\n\n public function setId($value)\n {\n $this-&gt;id = $value;\n }\n\n public function setTitle($value)\n {\n $this-&gt;title = $value;\n }\n\n public function setFirstName($value)\n {\n $this-&gt;first_name = $value;\n }\n\n public function setMiddleName($value)\n {\n $this-&gt;middle_name = $value;\n }\n\n public function setLastName($value)\n {\n $this-&gt;last_name = $value;\n }\n\n public function setGender($value)\n {\n $this-&gt;gender = $value;\n }\n\n public function setBirthDate($value)\n {\n if ($value &gt; now()) {\n throw new Exception(\"Birth date cannot be in the future\");\n }\n\n $this-&gt;birth_date = $value;\n }\n\n public function setEmail($value)\n {\n $this-&gt;email = $value;\n }\n\n public function setPhone($value)\n {\n $this-&gt;phone = $value;\n }\n\n public function setMobilePhone($value)\n {\n $this-&gt;mobile_phone = $value;\n }\n\n public function setResidentialAddress(Address $value)\n {\n $this-&gt;residential_address = $value;\n }\n\n public function setPostalAddress(Address $value)\n {\n $this-&gt;postal_address = $value;\n }\n\n public function setBrowserDetails($value)\n {\n $this-&gt;browser_details = $value;\n }\n\n public function setPassword($value)\n {\n $this-&gt;password = $value;\n }\n\n public function setLastLoginDate($value)\n {\n $this-&gt;last_login_date = $value;\n }\n\n public function setCompanyId($value)\n {\n $this-&gt;company_id = $value;\n }\n\n public function setDateCreated($value)\n {\n $this-&gt;date_created = $value;\n }\n\n public function setCreatedBy($value)\n {\n $this-&gt;created_by = $value;\n }\n\n public function setDateModified($value)\n {\n $this-&gt;date_modified = $value;\n }\n\n public function setModifiedBy($value)\n {\n $this-&gt;modified_by = $value;\n }\n\n // Actions\n\n public function activate()\n {\n $this-&gt;active = true;\n }\n\n public function changePassword($old_password_raw, $new_password_raw)\n {\n $password_changed = false;\n $old_password = // Encrypt $old_password_raw using $this-&gt;salt\n $new_password = // Encrypt $old_password_raw $this-&gt;salt\n\n if (/* $old_password equals $this-&gt;password */) {\n $this-&gt;password = $new_password;\n $password_changed = true;\n }\n\n return $password_changed;\n }\n\n public function deactivate()\n {\n $this-&gt;active = false;\n }\n\n public function isActive()\n {\n return $this-&gt;active;\n }\n\n public function logIn($password)\n {\n // Use $this-&gt;salt to encrypt $password and compare it to $this-&gt;password\n }\n}\n</code></pre>\n\n<p>There's a lot going on here. First, create <code>private</code> properties for each column in the Users table. We create getter and setter methods for each property, except a few key properties:</p>\n\n<ul>\n<li>username: This is required just to have a <code>User</code> object, and should get supplied in the constructor.</li>\n<li>salt: This is security related and should be provided in the constructor. Code outside the <code>User</code> class should not ever need to know the <code>salt</code>. Any code requiring the <code>salt</code> should be a method in the <code>User</code> class.</li>\n<li>password: This should be provided in the constructor and never accessed outside of the <code>User</code> object for the same reasons as the <code>salt</code>.</li>\n</ul>\n\n<p>We have additional \"actions\" that can be performed on a user. For instance, activating and deactivating a user, or changing their password:</p>\n\n<pre><code>class User\n{\n // ...\n\n // Actions\n\n public function activate()\n {\n $this-&gt;active = true;\n }\n\n public function changePassword($old_password_raw, $new_password_raw)\n {\n $password_changed = false;\n $old_password = // Encrypt $old_password_raw using $this-&gt;salt\n $new_password = // Encrypt $old_password_raw $this-&gt;salt\n\n if (/* $old_password equals $this-&gt;password */) {\n $this-&gt;password = $new_password;\n $password_changed = true;\n }\n\n return $password_changed;\n }\n\n public function deactivate()\n {\n $this-&gt;active = false;\n }\n\n public function isActive()\n {\n return $this-&gt;active;\n }\n\n public function logIn($password)\n {\n // Use $this-&gt;salt to encrypt $password and compare it to $this-&gt;password\n }\n}\n</code></pre>\n\n<p>These \"actions\" are the Business Logic of a <code>User</code>. Bundling data (private properties) with methods that operate on those properties is an advantage of creating Domain Models. This Business Logic becomes very portable. Everywhere you have a <code>User</code> object, you have all the necessary business logic for users.</p>\n\n<p>You'll also notice that the <code>set_residential_address</code> and <code>set_postal_address</code> methods have a PHP Type Hint requiring you to pass in an <code>Address</code> object:</p>\n\n<pre><code>class Address\n{\n private $address;\n private $postal_code;\n private $suburb;\n private $state;\n private $country;\n\n public __construct($address, $postal_code, $suburb, $state, $country)\n {\n $this-&gt;address = $address;\n $this-&gt;postal_code = $postal_code;\n $this-&gt;suburb = $suburb;\n $this-&gt;state = $state;\n $this-&gt;country = $country;\n }\n\n public function getAddress()\n {\n return $this-&gt;address;\n }\n\n public function getPostalCode()\n {\n return $this-&gt;postal_code;\n }\n\n public function getSuburb()\n {\n return $this-&gt;suburb;\n }\n\n public function getState()\n {\n return $this-&gt;state;\n }\n\n public function getCountry()\n {\n return $this-&gt;country;\n }\n}\n</code></pre>\n\n<p>Why create an <code>Address</code> class? You have two sets of columns on the Users table with similar sounding names. Creating an <code>Address</code> class allows you to follow the \"Don't Repeat Yourself\" guideline (DRY up your code).</p>\n\n<ul>\n<li>Residential<strong>Address</strong></li>\n<li>Residential<strong>PostCode</strong></li>\n<li>Residential<strong>Suburb</strong></li>\n<li>Residential<strong>State</strong></li>\n<li>Residential<strong>Country</strong></li>\n<li>Postal<strong>Address</strong></li>\n<li>Postal<strong>PostCode</strong></li>\n<li>Postal<strong>Suburb</strong></li>\n<li>Postal<strong>State</strong></li>\n<li>Postal<strong>Country</strong></li>\n</ul>\n\n<p>This means your <code>User</code> class needs only two properties to represent these two similar pieces of information, rather than 10.</p>\n\n<h3>Creating the Data Access Layer</h3>\n\n<p>For the data access layer, we will use the <a href=\"http://code.tutsplus.com/tutorials/the-repository-design-pattern--net-35804\" rel=\"nofollow\">Repository Design Pattern</a>. This is where you will use the <code>PDO</code> class to connect to the database. We will create a parent class called <code>DatabaseRepository</code> and then create a <code>UserRepository</code> class that provides methods allowing you to perform CRUD operations on the Users table.</p>\n\n<p>The DatabaseRepository class:</p>\n\n<pre><code>class DatabaseRepository\n{\n private $db;\n private $connection_string;\n\n public __construct()\n {\n $this-&gt;connection_string = // Get connection string from a config file\n $this-&gt;db = new PDO($this-&gt;connection_string);\n }\n\n protected function executeQuery($sql, $params)\n {\n $statement = $this-&gt;db-&gt;prepare($sql);\n\n return $statement-&gt;execute($params);\n }\n}\n</code></pre>\n\n<p>This doesn't contain much. There are a couple of keys to this class:</p>\n\n<ol>\n<li><p>The <code>$db</code> property is <code>private</code>. Anytime code needs to use the <code>$db</code> object, you must define a <code>protected</code> method in this class so child classes have controlled access to the database. This will make refactoring code later much easier since no child classes directly access <code>$this-&gt;db</code>.</p></li>\n<li><p>The connection string to the database should be read from a config file. Don't hard code this in PHP. Putting this in a config file allows you to define multiple \"environments\" for your application: Dev, Test and Production, for instance, should all connect to different databases.</p></li>\n</ol>\n\n<p>Now let's see the <code>UserRepostory</code> class, which inherits from <code>DatabaseRepository</code>:</p>\n\n<pre><code>class UserRepository extends DatabaseRepository\n{\n private static $table_name = 'dbo.[User]';\n private static $sql_find_by_username = \"SELECT TOP 1 * FROM {UserRepository::$table_name} WHERE Username = :username\";\n\n public function findByUsername($username)\n {\n $params = array(':username' =&gt; $username);\n $data = $this-&gt;executeQuery(self::$sql_find_by_username, $params);\n\n if (empty($data)) {\n return null;\n }\n\n return $this-&gt;mapToUser($data);\n }\n\n private function mapToUser($data)\n {\n $user = new User($data['Salt'], $data['Password'], $data['Username'], $data['UserID']);\n\n $user-&gt;set_first_name($data['FirstName']);\n $user-&gt;set_middle_name($data['MiddleName']);\n\n // Call more setters...\n\n // Map a complex property...\n $residential_address = new Address(\n $data['ResidentialAddress'],\n $data['ResidentialPostCode'],\n $data['ResidentialSuburb'],\n $data['ResidentialState'],\n $data['ResidentialCountry']\n );\n\n // Set the complex property\n $user-&gt;setResidentialAddress($residential_address);\n\n return $user;\n }\n}\n</code></pre>\n\n<p>Some things to note:</p>\n\n<ul>\n<li>The table name is a static (class level) property</li>\n<li>Any hard coded SQL should also be kept in constants or static properties</li>\n<li>The <code>findByUsername</code> method takes a username and returns a fully populated <code>User</code> object</li>\n<li>The <code>map_to_user</code> method takes an array of data directly from the database and calls the appropriate methods on the <code>User</code> object.</li>\n</ul>\n\n<h2>Cleaning up Login.php</h2>\n\n<p>Now that we have our view, business logic and data access separated out, we can really shorten up Login.php:</p>\n\n<pre><code>&lt;?php\n\n// Login.php\n\nif (isset($_POST)) {\n // Display the form with a GET request\n include('path/to/LoginForm.php');\n}\nelse {\n if (empty($_POST['username'])) {\n $_POST['username_error'] = 'Username is required';\n\n // Redisplay the form if a POST results in validation errors\n include('path/to/LoginForm.php');\n } elseif (empty($_POST['password'])) {\n $_POST['password_error'] = 'Password is required';\n\n // Redisplay the form if a POST results in validation errors\n include('path/to/LoginForm.php');\n } else {\n // Now we connect to the database on a POST request\n $repository = new UserRepository();\n $user = $repository.findByUsername($_POST['username']);\n\n if (!isset($user)) {\n header('location: register.php');\n die();\n }\n\n if (!$user-&gt;logIn($_POST['password'])) {\n $_POST['password_error'] = 'Username or Password is incorrect';\n }\n\n // Set the user on the session\n // Get/create the session data from the database\n\n // User successfully logged in\n header('location: private.php');\n }\n}\n</code></pre>\n\n<p>Login.php gets reduced to the bare minimum code required to handle the HTTP request and validate user input. The rendering of the view is delegated to LoginForm.php. Data access is delegated to <code>UserRepository</code> and the business logic of logging in is delegated to <code>User</code>. I intentionally left out finding and mapping the <code>UserSession</code> as an exercise for you (and because this answer is already long enough).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T16:56:42.907", "Id": "200838", "Score": "0", "body": "Since this post focusses on the cleanliness of the OP's code: it might best to follow the [PHP-FIG coding standards](http://php-fig.org): opening `{` for methods and classes go on a separate line, method names are preferable camelCased instead of undercore_names, and `isset($_POST['someKey'])` is to be preferred over `empty($_POST['someKey'])` [see this post](http://kunststube.net/isset/) for details on that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T18:22:19.180", "Id": "200856", "Score": "0", "body": "@EliasVanOotegem: Very true. It's been a while since I did much PHP programming. I'll see if I can edit my answer to reflect this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T18:35:26.180", "Id": "200859", "Score": "0", "body": "@EliasVanOotegem: I don't see any recommendation to use `isset` instead of `empty` for checking post values. I actually _do_ want to check for null or empty strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T23:06:26.610", "Id": "200920", "Score": "0", "body": "This code is all the way back from 2013 - certainly wouldn't have approached it the way I did originally. SO should really lock these over time!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-30T00:45:27.017", "Id": "200938", "Score": "0", "body": "Yeah, I noticed the date after I posted my answer. Maybe I'll get some sort of silly badge for this? Either way the joke's on me for posting an answer to such an old code review. :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T14:25:17.257", "Id": "109118", "ParentId": "31396", "Score": "0" } } ]
{ "AcceptedAnswerId": "31423", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T00:09:12.127", "Id": "31396", "Score": "3", "Tags": [ "php", "sql", "security", "sql-server" ], "Title": "Simple CMS system" }
31396
<p>What is the general design pattern for declaring variables in a class?</p> <p>I have a homework assignment to create a simple Java program which asks the user for a range of two variables. The program then creates a random variable from within this range and prompts the user to guess the number.</p> <p>I'm having trouble understanding how to declare my variables. I'm not sure if I should declare variables as <code>public</code> or <code>private</code>, and <code>static</code> or non-<code>static</code>. When is it correct to use a <code>public</code>/<code>private</code> variable?</p> <p>Also, how much code should I include in my <code>main()</code> method? What is generally placed into the <code>main()</code> method? </p> <pre><code>import java.util.Scanner; import java.util.Random; public class HiLo { static int guess, guessCount, randomNumber, startRange, endRange; static Scanner scan = new Scanner(System.in); static Random random = new Random(); public static void main(String[] args) { getRange(); playGame(); } public static void getRange() { System.out.println("Welcome! Enter integer for start of range (must be &gt; 0)"); startRange = scan.nextInt(); System.out.println("Enter integer for end of range (must be &gt;0)"); endRange = scan.nextInt(); randomNumber = random.nextInt(endRange - startRange + 1) + startRange; System.out.println(randomNumber); } public static void playGame() { guessCount = 0; System.out.println("Enter guess or 0 to quit: "); guess = scan.nextInt(); while (randomNumber != guess) { if (guess == 0) { break; } else if (randomNumber &gt; guess) { guessCount++; System.out.println("Too Low"); System.out.println("Enter guess or 0 to quit: "); guess = scan.nextInt(); } else if (randomNumber &lt; guess) { guessCount++; System.out.println("Too High"); System.out.println("Enter guess or 0 to quit: "); guess = scan.nextInt(); } } if (randomNumber == guess) { guessCount++; System.out.println("Correct! That took you " + guessCount + " guesses."); } } } </code></pre>
[]
[ { "body": "<p>You can read <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html\" rel=\"nofollow\">this</a> to understand scope of variables or method.</p>\n\n<p>In short:</p>\n\n<ol>\n<li><code>public</code> - Any member of a class declared as public can be accessed outside of the class. So declare public when you want to give client code access to methods/variables of a class.</li>\n<li><code>private</code> - A private method or field is invisible and inaccessible to other classes, and can be used only within the class in which the field or method is declared.</li>\n<li><code>protected</code> - Protected variables and methods allow the class itself to access them, classes inside of the same package to access them, and subclasses of that class to access them.</li>\n<li><code>static</code> - In general when a number of objects created from the same class, they all have their distinct copies of instance variables stored in different location. Sometimes we want to have variables that are common to all objects. To accomplish this use static. <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html\" rel=\"nofollow\">Read this</a>.</li>\n</ol>\n\n<p>Think of the <code>main</code> method as a place where you can write code to test your class. No design / logic should be placed in <code>main</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>public class Hilo {\n public Hilo() {}\n //other methods...\n\npublic static void main(String[] args) {\n Hilo hilo = new Hilo();\n hilo.getRange();\n hilo.playGame();\n }\n}\n</code></pre>\n\n<p>I would prefer to remove all the <code>static</code> variables used in your class and make those <code>private</code>. The two methods <code>getRange</code> and <code>playGame</code> can be <code>public</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T04:20:37.640", "Id": "31406", "ParentId": "31400", "Score": "3" } } ]
{ "AcceptedAnswerId": "31406", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T01:36:04.420", "Id": "31400", "Score": "2", "Tags": [ "java", "random", "homework", "interval", "number-guessing-game" ], "Title": "Guessing a random number between a range of numbers" }
31400
<p>Just getting into functional programming and F# with the most appropriately titled <a href="http://rads.stackoverflow.com/amzn/click/1107684064" rel="nofollow">Functional Programming Using F#</a>. I wrote the following function definition for problem 2.4 but I'm thinking there's most likely a more elegant and/or idiomatic solution:</p> <pre><code>let rec occurrencesFromIth = let bool2int x = if x then 1 else 0 function | str:string, i, _ when i &gt;= str.Length -&gt; 0 | str, i, ch -&gt; isIthChar (str,i,ch ) |&gt; bool2int |&gt; (+) (occurrencesFromIth (str,i+1,ch )) </code></pre> <p><code>isIthChar</code> is defined as:</p> <pre><code>let isIthChar ( str:string, i, ch ) = str.[i] = ch </code></pre> <p>The actual problem description is:</p> <blockquote> <p>Declare the F# function <code>occFromIth</code>:</p> <p><code>string * int * char -&gt; int</code> where <code>occFromIth(str,i,ch)</code> = the number of occurrences of character <code>ch</code> in positions <code>j</code> in the string <code>str</code> with <code>j &gt;= i</code>.</p> <p>Hint: the value should be 0 for <code>i &gt;= size str</code>.</p> </blockquote>
[]
[ { "body": "<p>First of all, I think that your <code>isIthChar</code> function is an overkill: it usually doesn't make sense to write a function that's <em>that</em> short.</p>\n\n<p>To write the <code>occurrencesFromIth</code> itself, I would use sequence expression to generate the indexes to test and then use <code>Seq.sumBy</code> to count the matching characters:</p>\n\n<pre><code>let occurrencesFromIth (str : string, start, ch) =\n seq { start .. str.Length - 1 } |&gt;\n Seq.sumBy (fun i -&gt; if str.[i] = ch then 1 else 0)\n</code></pre>\n\n<p>I would prefer to use something like <code>Seq.count</code> even more, but there is no such method. You <em>could</em> use <code>Count()</code> from LINQ, which makes the code shorter, but I guess that is less idiomatic (and means you can't use <code>|&gt;</code>):</p>\n\n<pre><code>let occurrencesFromIth (str : string, start, ch) =\n let indexes = seq { start .. str.Length - 1 }\n indexes.Count (fun i -&gt; str.[i] = ch)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:21:48.883", "Id": "50081", "Score": "0", "body": "You could use `Seq.sumBy (fun i -> if str.[i] = ch then 1 else 0)` in place of `fold`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:38:49.700", "Id": "50082", "Score": "0", "body": "@Daniel Yeah, that's better, edited in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T02:29:13.237", "Id": "50127", "Score": "0", "body": "if could check two answers would check this one also. More functional/declarative in my novice opinion. Gotta learn me some Seq but that is in a few more chapters. (The reason for the isIthChar function is that it was the answer to the previous exercise so reuse was implied - but that doesn't matter, your criticism is valid in general)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:06:52.320", "Id": "31427", "ParentId": "31401", "Score": "1" } }, { "body": "<p>A simple recursive function would be:</p>\n\n<pre><code>let rec occFromIth s i ch = \n if i &gt;= String.length s then 0\n else (if s.[i] = ch then 1 else 0) + occFromIth s (i + 1) ch\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:43:16.470", "Id": "50083", "Score": "0", "body": "Ooh, you can use `String.length` instead of `string.Length` to avoid specifying the type, nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T02:24:19.903", "Id": "50126", "Score": "0", "body": "first answer, simpler than mine, and uses recursion which is in the spirit of the current book chapter and exercises so gets the answer check." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:18:25.223", "Id": "31429", "ParentId": "31401", "Score": "2" } } ]
{ "AcceptedAnswerId": "31429", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T02:11:49.240", "Id": "31401", "Score": "2", "Tags": [ "recursion", "f#" ], "Title": "Recursive function refactoring help: occurrences of char in string starting at ith char" }
31401
<p>This code can be found in the <a href="http://webEbenezer.net/build_integration.html" rel="nofollow noreferrer">archive here</a>. Usually I have a .cc file, but in this case it's all in a header. Am wondering about that. It needs to work in VS12. If possible I'll post more code from the archive for review. I started with this because it's used a lot. Tia.</p> <pre><code>#ifndef CMW_ErrorWords_hh #define CMW_ErrorWords_hh #include &lt;exception&gt; #include &lt;string&gt; namespace cmw { class failure : public ::std::exception { ::std::string whatStr; public: explicit failure (char const* what_) : whatStr(what_) {} explicit failure (::std::string what_) : whatStr(::std::move(what_)) {} ~failure () throw() {} char const* what () const throw() { return whatStr.c_str(); } failure&amp; operator&lt;&lt; (char* s) { whatStr.append(s); return *this; } failure&amp; operator&lt;&lt; (char const* s) { whatStr.append(s); return *this; } failure&amp; operator&lt;&lt; (::std::string const&amp; s) { whatStr.append(s); return *this; } template &lt;class T&gt; failure&amp; operator&lt;&lt; (T const&amp; val) { whatStr.append(::std::to_string(val)); return *this; } }; class eof : public failure { public: explicit eof (char const* what_) : failure(what_) {} ~eof () throw() {} template &lt;class T&gt; eof&amp; operator&lt;&lt; (T val) { failure::operator&lt;&lt;(val); return *this; } }; } #endif </code></pre> <p>Edit - @Loki Astari</p> <p>I have compile problems on both clang and gcc if I remove the non const version of that function. Clang says there's &quot;no matching function for call to to_string.&quot;</p> <pre><code>whatStr.append(::std::to_string(val)); </code></pre> <p>IIuc it goes on to say it doesn't like this line:</p> <pre><code>raise(failure(&quot;Blah blah &quot;) &lt;&lt; yytext); </code></pre> <p>I ran across that a few months ago and found that adding the non-const version got the compilers to accept it. I'm not sure what the problem is really. I'm using flex and that's where yytext comes from.</p> <p>Oo Tiib suggested the raise function as a help for debugging -- a central function where you could put a breakpoint to see the stack. It may be something used in some large projects. That made some sense so I decided to try it. I believe I need both versions of raise to avoid slicing.</p> <p>Edit 2:</p> <p>Removed raise functions from above code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T02:56:47.950", "Id": "50011", "Score": "1", "body": "Is this code from your archive, or someone else's?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T03:21:27.617", "Id": "50013", "Score": "0", "body": "@Jamal It's part of my archive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T03:26:55.437", "Id": "50014", "Score": "0", "body": "Okay, just making sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T20:37:06.333", "Id": "50107", "Score": "0", "body": "I think there's a typo for the `std::to_string()`. The `::` in front of it shouldn't be there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T22:09:04.600", "Id": "50116", "Score": "1", "body": "If you inherit form std::exception then you can put the break point in std::exception::exception that's a nice central place to catch exceptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T15:37:55.480", "Id": "50208", "Score": "0", "body": "@LokiAstari I decided to drop the raise functions. Clang likes it with significant drop in size, but gcc doesn't with significant increase in size." } ]
[ { "body": "<p>Though std::exception does not have a constructor for taking an error message; the other standard excretions do. So you can make your exception class simpler by inheriting from one of these.</p>\n\n<pre><code>class failure : public ::std::runtime_error {\n\n public:\n failure (std::string const&amp; msg) : ::std::runtime_error(msg)\n</code></pre>\n\n<p>I understand you are trying to make your exceptions easier to use by adding a couple of stream operator to the class. But you can achieve the same affect with greater flexibility using std::stringstream.</p>\n\n<pre><code> // Your way:\n failure x(\"Hi there\");\n x &lt;&lt; \": More info:\" &lt;&lt; 5 &lt;&lt; \" At night:\" &lt;&lt; 22;\n\n // using string stream (works with all stream-able types)\n std::stringstream msg;\n msg &lt;&lt; \"Hi there\" &lt;&lt; \": More info:\" &lt;&lt; 5 &lt;&lt; \" At night:\" &lt;&lt; 22;\n failure y(msg.str());\n</code></pre>\n\n<p>If the only difference between a methods is the constness of their parameters. Then the const version is all you need. As it will accept normal values and promise not to change them.</p>\n\n<pre><code>// This method is not needed\nfailure&amp; operator&lt;&lt; (char* s)\n{\n whatStr.append(s);\n return *this;\n}\n\n// This method will handle both\n// `char*` and `char const*` perfectly well.\n// if you remove the first method above.\nfailure&amp; operator&lt;&lt; (char const* s)\n{\n whatStr.append(s);\n return *this;\n}\n</code></pre>\n\n<p>I don't like your raise (and why two different version. Why not raise on the base class of std::exception (that will cover you for all exceptions)).</p>\n\n<pre><code>inline void raise (failure const&amp; ex)\n</code></pre>\n\n<p>In my opinion (so its perfectly valid to believe differently) this buys you nothing and makes the code less readable.</p>\n\n<pre><code>raise(failure(\"hi\"));\n\n// Vs\n\nthrow failure(\"Hi\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T19:57:21.347", "Id": "50104", "Score": "0", "body": "I edited the original post. Am adding a comment here because I'm not sure you'll be notified otherwise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:31:12.063", "Id": "31414", "ParentId": "31404", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T02:53:58.140", "Id": "31404", "Score": "4", "Tags": [ "c++" ], "Title": "Exception classes" }
31404
<p>Just looking for some pointers on how I could improve the code. This is my first game ever and python is my first language so it's bit messy but I'll be happy to explain stuff if needed. I'm kinda frustrated cause some bits look really ugly and I hope you guys can help me out. Here it is:</p> <p><strong>EDIT</strong>: cleaned up the code and added some new stuff.</p> <p><strong>objects.py</strong></p> <pre><code>import pygame import math import random from Vec2D import Vec2D from constants import * from pygame.locals import * class Text(object): def __init__(self, value, size, color, left_orientation=False, font=None, x=0, y=0, top=None, bottom=None, left=None, right=None, centerx=None, centery=None): self._size = size self._color = color self._value = value self._font = pygame.font.Font(font, self._size) self.width, self.height = self._font.size(self._value) self._left_orientation = left_orientation self.image = self._create_surface() self.rect = self.image.get_rect() if x: self.rect.x = x if y: self.rect.y = y if top: self.rect.top = top if bottom: self.rect.bottom = bottom if left: self.rect.left = left if right: self.rect.right = right if centerx: self.rect.centerx = centerx if centery: self.rect.centery = centery def _create_surface(self): return self._font.render(self._value, True, self._color) def set_value(self, new_value): if new_value != self._value: self._value = new_value self.image = self._create_surface() new_rect = self.image.get_rect(x = self.rect.x, y = self.rect.y) if self._left_orientation: width_diff = new_rect.width - self.rect.width new_rect.x = self.rect.x - width_diff self.rect = new_rect class Ball(pygame.sprite.Sprite): def __init__(self, game, vector=Vec2D()): super(Ball, self).__init__() self.image = pygame.Surface((BALL_RADIUS*2, BALL_RADIUS*2)) self.rect = self.image.get_rect() self._draw_ball() screen = pygame.display.get_surface() self.area = screen.get_rect().inflate(-GAP*2, 0) self.vector = vector self.game = game self.start_to_the = 'left' self.reinit() def _draw_ball(self): self.image.fill(BLACK) self.image.set_colorkey(BLACK, RLEACCEL) pygame.draw.circle(self.image, WHITE, (self.rect.centerx, self.rect.centery), BALL_RADIUS) def reinit(self): self.rect.centerx = self.area.centerx self.rect.centery = self.area.centery if self.start_to_the == 'left': self.vector = Vec2D(-BALL_SPEED, 0) else: self.vector = Vec2D(BALL_SPEED, 0) def update(self, dt): self.rect = self.calcnewpos(dt) self.handle_collision() def calcnewpos(self, dt): (dx, dy) = self.vector.get_xy() return self.rect.move(dx, dy) def handle_collision(self): (dx, dy) = self.vector.get_xy() if not self.area.contains(self.rect): if self._hit_topbottom(): dy = -dy elif self._hit_leftright(): side = self._hit_leftright() self.game.increase_score(side) if side == 'left': self.start_to_the = 'right' elif side == 'right': self.start_to_the = 'left' self.reinit() return else: if self.hit_paddle(): paddle = self.hit_paddle() if paddle.side == 'left': self.rect.left = GAP + PADDLE_WIDTH elif paddle.side == 'right': self.rect.right = SCREEN_WIDTH - (GAP + PADDLE_WIDTH) dx = -dx dy = (self.rect.centery - paddle.rect.centery) if dy &lt;= -32: dy = -32 elif -32 &lt; dy &lt;= -16: dy = -16 elif -16 &lt; dy &lt; 16: dy = 0 elif 16 &lt;= dy &lt; 32: dy = 16 elif dy &gt;= 32: dy = 32 dy /= 4 paddle.collided = True self.vector = Vec2D(dx, dy) def _hit_topbottom(self): return self.rect.top &lt; 0 or self.rect.bottom &gt; SCREEN_HEIGHT def _hit_leftright(self): if self.rect.left &lt; self.area.left: return 'left' elif self.rect.right &gt; self.area.right: return 'right' def hit_paddle(self): player = self.game.player enemy = self.game.enemy paddles = [player, enemy] for paddle in paddles: if self.rect.colliderect(paddle.rect): return paddle class Paddle(pygame.sprite.Sprite): def __init__(self): super(Paddle, self).__init__() self.image = pygame.Surface(PADDLE_SIZE) self.rect = self.image.get_rect() self._draw_paddle() screen = pygame.display.get_surface() self.area = screen.get_rect() self.collided = False def _draw_paddle(self): self.image.fill(WHITE) def reinit(self): self.state = 'still' self.movepos = [0, 0] self.rect.centery = self.area.centery def update(self): new_rect = self.rect.move(self.movepos) if self.area.contains(new_rect): self.rect = new_rect pygame.event.pump() class Player(Paddle): def __init__(self, side): super(Player, self).__init__() self.side = side self.speed = PLAYER_SPEED self.score = 0 self.reinit() def update(self, dt): keys = pygame.key.get_pressed() if keys[K_UP]: self.movepos[1] = -self.speed * dt if keys[K_DOWN]: self.movepos[1] = self.speed * dt super(Player, self).update() def reinit(self): super(Player, self).reinit() if self.side == 'left': self.rect.left = GAP elif self.side == 'right': self.rect.right = SCREEN_WIDTH - GAP self.score = 0 class Enemy(Paddle): def __init__(self, game): super(Enemy, self).__init__() self.game = game self.speed = ENEMY_SPEED self.side = 'right' if PLAYER_SIDE == 'left' else 'left' self.hitpos = 0 self.score = 0 self.reinit() def update(self, dt): super(Enemy, self).update() ball = self.game.ball hitspot_ypos = self.rect.centery + self.hitpos if (hitspot_ypos - ball.rect.centery) not in range(-5, 5): if hitspot_ypos &gt; ball.rect.centery: self.movepos[1] = -self.speed * dt if hitspot_ypos &lt; ball.rect.centery: self.movepos[1] = self.speed * dt else: self.movepos[1] = 0 if self.collided: self.hitpos = random.randrange(-40, 40) self.collided = False def reinit(self): super(Enemy, self).reinit() if self.side == 'left': self.rect.left = GAP elif self.side == 'right': self.rect.right = SCREEN_WIDTH - GAP self.score = 0 </code></pre> <p><strong>game.py</strong></p> <pre><code>#!python3 import pygame import sys import random import math from Vec2D import Vec2D from constants import * from pygame.locals import * from objects import Text, Ball, Player, Enemy class Game(object): def __init__(self): self.ball = Ball(self, Vec2D(random.choice([-BALL_SPEED, BALL_SPEED]), 0)) self.enemy = Enemy(self) self.player = Player(PLAYER_SIDE) self.game_sprites = pygame.sprite.Group(self.ball, self.enemy, self.player) screen = pygame.display.get_surface() self.background = pygame.Surface(screen.get_size()) self.reinit() def reinit(self): for sprite in self.game_sprites: sprite.reinit() self._draw_background() self.player_score = 0 self.enemy_score = 0 self.highest_score = 0 self.winner = None def main(self): left_score = Text('0', 32, WHITE, True, right = SCREEN_WIDTH/2 - 20, top = 10) right_score = Text('0', 32, WHITE, left = SCREEN_WIDTH/2 + 20, top = 10) pause_text = Text('PAUSE', 64, RED, centerx = SCREEN_WIDTH/2, centery = SCREEN_HEIGHT/2) theme_music = pygame.mixer.music.load('theme.mp3') clock = pygame.time.Clock() paused = False self.countdown_animation() screen.blit(self.background, [0, 0]) pygame.mixer.music.play(-1) while 1: dt = clock.tick(FPS) / 1000 for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): pygame.quit() sys.exit() elif event.type == KEYUP: if event.key == K_UP or event.key == K_DOWN: self.player.movepos = [0, 0] self.player.state = 'still' elif event.type == KEYDOWN: if event.key == K_p: if not paused: pygame.mixer.music.pause() paused = True else: pygame.mixer.music.unpause() paused = False if not paused: self.game_sprites.clear(screen, self.background) screen.blit(self.background, left_score.rect, left_score.rect) screen.blit(self.background, right_score.rect, right_score.rect) screen.blit(self.background, pause_text.rect, pause_text.rect) self.game_sprites.update(dt) self.player_score = self.player.score self.enemy_score = self.enemy.score left_score.set_value(str(self.player.score)) right_score.set_value(str(self.enemy.score)) if self.player.side != 'left': left_score.set_value(str(self.enemy.score)) right_score.set_value(str(self.player.score)) self.game_sprites.draw(screen) screen.blit(left_score.image, left_score.rect) screen.blit(right_score.image, right_score.rect) self.highest_score = max(self.player_score, self.enemy_score) if self.highest_score == TOP_SCORE: if self.player.score &gt; self.enemy.score: self.winner = 'player' elif self.enemy.score &gt; self.player.score: self.winner = 'enemy' pygame.mixer.music.stop() self.game_won_animation() self.reinit() self.countdown_animation() screen.blit(self.background, [0, 0]) pygame.mixer.music.play(-1) else: screen.blit(pause_text.image, pause_text.rect) pygame.display.flip() def countdown_animation(self): font = pygame.font.Font(None, 100) beep = pygame.mixer.Sound('beep1.wav') count = COUNTDOWN while count &gt; 0: screen.fill(BLACK) font_size = font.size(str(count)) # calculate text position so that its center = screen center textpos = [SCREEN_WIDTH/2 - font_size[0]/2, SCREEN_HEIGHT/2 - font_size[1]/2] screen.blit(font.render(str(count), True, WHITE, BGCOLOR), textpos) pygame.display.flip() beep.play() count -= 1 pygame.time.delay(1000) def game_won_animation(self): screen.blit(self.background, self.ball.rect, self.ball.rect) if self.winner == 'player': message = 'You won!' endgame_sound = pygame.mixer.Sound('won.wav') color = BLUE elif self.winner == 'enemy': message = 'You suck!' endgame_sound = pygame.mixer.Sound('lost.wav') color = RED winner_text = Text(message, 128, color, centerx = SCREEN_WIDTH/2, centery = SCREEN_HEIGHT/2) screen.blit(winner_text.image, winner_text.rect) pygame.display.flip() endgame_sound.play() pygame.time.delay(5000) screen.blit(self.background, winner_text.rect, winner_text.rect) def increase_score(self, side): if self.player.side == side: self.enemy.score += 1 self.winner = self.enemy.side else: self.player.score += 1 self.winner = self.player.side def _draw_background(self): self.background.fill(BGCOLOR) leftcolor = BLUE rightcolor = RED if self.player.side != 'left': leftcolor = RED rightcolor = BLUE # draw left line pygame.draw.line(self.background, leftcolor, (GAP, 0), (GAP, SCREEN_HEIGHT), 2) # draw right line pygame.draw.line(self.background, rightcolor, (SCREEN_WIDTH - GAP, 0), (SCREEN_WIDTH - GAP, SCREEN_HEIGHT), 2) # draw middle line pygame.draw.line(self.background, WHITE, (SCREEN_WIDTH/2, 0), (SCREEN_WIDTH/2, SCREEN_HEIGHT), 2) if __name__ == '__main__': pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption('Pong!') pong = Game() pong.main() </code></pre> <p><strong>constants.py</strong></p> <pre><code>SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 PADDLE_WIDTH = 20 PADDLE_HEIGHT = 80 BALL_SPEED = 5 BALL_RADIUS = 10 PLAYER_SPEED = 200 ENEMY_SPEED = 200 GAP = 40 # R G B BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) BLUE = ( 0, 0, 255) SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT) PADDLE_SIZE = (PADDLE_WIDTH, PADDLE_HEIGHT) BGCOLOR = BLACK PLAYER_SIDE = 'left' TOP_SCORE = 10 COUNTDOWN = 3 FPS = 30 </code></pre> <p><strong>Vec2D.py</strong></p> <pre><code>import math class Vec2D(object): def __init__(self, x = 0., y = 0.): self.x = x self.y = y self.magnitude = self.get_magnitude() def __str__(self): return "%s, %s" %(self.x, self.y) @classmethod def from_points(cls, P1, P2): return cls(P2[0] - P1[0], P2[1] - P1[1]) @classmethod def from_magn_and_angle(cls, magn, angle): x = magn * math.cos(angle) y = magn * math.sin(angle) return cls(x, y) def get_magnitude(self): return math.sqrt(self.x ** 2 + self.y ** 2) def get_xy(self): return (self.x, self.y) </code></pre> <p><a href="https://docs.google.com/file/d/0B5wwb6AC6QdBZl9LVkx6NzZGWWs/edit" rel="nofollow"><strong>Here</strong></a> is the full program.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T21:23:23.220", "Id": "50236", "Score": "1", "body": "There's no need for a try-except block to surround the imports. You probably don't want to run the script if imports fail, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T14:08:04.107", "Id": "50291", "Score": "0", "body": "This code isn't runnable as-is. Can you post the contents of the `Vec2D` and `constants` modules, please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T16:02:29.420", "Id": "50300", "Score": "0", "body": "Use constants rather than hard coded numbers. Similarly for strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:23:35.773", "Id": "50343", "Score": "0", "body": "@GarethRees Sorry. Its all there now." } ]
[ { "body": "<h2>1. First version</h2>\n\n<ol>\n<li><p>I can't run it:</p>\n\n<pre><code>&gt;&gt;&gt; import game\nImportError: No module named Vec2D\n</code></pre>\n\n<p>There's no <code>Vec2D</code> package available from the <a href=\"https://pypi.python.org/pypi\">Python Package Index</a>. So where does this come from? I guess it must be your own vector package, but if so, you need to post it here.</p>\n\n<p>Similar remarks apply to the <code>constants</code> module.</p></li>\n<li><p>I don't know which version of Python to use to run this. Your parenthesized <code>print</code> statements, and your use of <code>dt = clock.tick(FPS) / 1000</code> suggest that Python 3 is required, but on the other hand your use of <code>super(Ball, self)</code> instead of plain <code>super()</code> suggest that you are thinking about running on Python 2.</p>\n\n<p>It would be sensible to have a comment near the top noting the supported version(s) of Python.</p>\n\n<p>Alternatively, you might consider rewriting the code to be portable between Python 3 and Python 2, by changing</p>\n\n<pre><code>print(\"ImportError:\", message)\n</code></pre>\n\n<p>to something like</p>\n\n<pre><code>print(\"ImportError: {0}\".format(message))\n</code></pre>\n\n<p>and</p>\n\n<pre><code>dt = clock.tick(FPS) / 1000\n</code></pre>\n\n<p>to</p>\n\n<pre><code>dt = clock.tick(FPS) / 1000.0\n</code></pre></li>\n<li><p>You've surrounded your <code>import</code> statements with a <code>try ... except</code> that suppresses the <code>ImportError</code> resulting from a failed import. Why did you do this? If any of these modules can't be imported, the right thing to do is to fail immediately with an <code>ImportError</code>, not to carry on running and fail later with a <code>NameError</code>.</p></li>\n<li><p>You have variables named <code>BLACK</code>, <code>WHITE</code>, <code>RED</code>, <code>BLUE</code> and so on. This seems like a bad idea because it's not clear from the name what those variables are for (which things are coloured black?), and if you want to configure the colours then the names will end up looking silly:</p>\n\n<pre><code>RED = pygame.Color('blue')\n</code></pre>\n\n<p>Better to have names that refer to the <em>purpose</em> of the variable, for example <code>ENEMY_COLOR</code> instead of <code>RED</code> and <code>PLAYER_COLOR</code> instead of <code>BLUE</code>.</p></li>\n<li><p>You use <a href=\"http://docs.python.org/3/tutorial/classes.html#tut-private\">private method names</a> like <code>__draw_ball</code> and <code>__hit_topbottom</code>. Why do you do this? The intended use case is \"letting subclasses override methods without breaking intraclass method calls\" but that doesn't seem to apply to your code. All that private method names achieve in your case is to make the program slightly more difficult to debug:</p>\n\n<pre><code>&gt;&gt;&gt; ball.__hit_leftright()\nAttributeError: 'Ball' object has no attribute '__hit_leftright'\n&gt;&gt;&gt; ball._Ball__hit_leftright()\n'left'\n</code></pre></li>\n</ol>\n\n<h2>2. Second version</h2>\n\n<p>Thank you for providing copies of the <code>constants</code> and <code>Vec2D</code> modules.</p>\n\n<h3>2.1. Major problems</h3>\n\n<ol>\n<li><p>It still doesn't work:</p>\n\n<pre><code>Traceback (most recent call last):\n File \"game.py\", line 142, in &lt;module&gt;\n pong.main()\n File \"game.py\", line 38, in main\n self.theme_music = pygame.mixer.music.load('theme.mp3')\npygame.error: Couldn't open 'theme.mp3'\n</code></pre></li>\n</ol>\n\n<h3>2.2. Vec2D module</h3>\n\n<ol>\n<li><p>There's no documentation: in particular, there are no docstrings. How are people expected to know how to use this module?</p></li>\n<li><p>There are lots of vector libraries already out there. Did you really need to write your own? If your Python installation was built with Tk, then there's one in the standard library:</p>\n\n<pre><code>&gt;&gt;&gt; from turtle import Vec2D\n&gt;&gt;&gt; v = Vec2D(1, 2)\n&gt;&gt;&gt; w = Vec2D(3, 4)\n&gt;&gt;&gt; abs(w) # returns magnitude of the vector\n5.0\n&gt;&gt;&gt; v + w\n(4.00,6.00)\n&gt;&gt;&gt; v * 2\n(2.00,4.00)\n</code></pre>\n\n<p>or if you need more features than <code>turtle.Vec2D</code>, the <a href=\"https://pypi.python.org/pypi\">Python Package Index</a> has several vector libraries (Daniel Pope's <a href=\"https://pypi.python.org/pypi/wasabi.geom\"><code>wasabi.geom</code></a> might be suitable).</p></li>\n<li><p>When a <code>Vec2D</code> object is created, you set its <code>magnitude</code>:</p>\n\n<pre><code>self.magnitude = self.get_magnitude()\n</code></pre>\n\n<p>but your game never uses this property. Consider using the <code>@property</code> decorator instead so that the magnitude only gets computed when you need it:</p>\n\n<pre><code>@property\ndef magnitude(self):\n return math.hypot(self.x, self.y)\n</code></pre>\n\n<p>(Also note the use of <a href=\"http://docs.python.org/3/library/math.html#math.hypot\"><code>math.hypot</code></a> from the standard library.)</p></li>\n<li><p>You have a class method <code>from_magn_and_angle</code> but you only ever call it with <code>angle</code> equal to zero, for example:</p>\n\n<pre><code>self.vector = Vec2D.Vec2D.from_magn_and_angle(BALL_SPEED, 0)\n</code></pre>\n\n<p>which is the same as:</p>\n\n<pre><code>self.vector = Vec2D.Vec2D(BALL_SPEED, 0)\n</code></pre></li>\n</ol>\n\n<h3>2.3. Constants</h3>\n\n<ol>\n<li><p>It would make your code clearer if you used Pygame's colour names. Instead of</p>\n\n<pre><code>BLACK = ( 0, 0, 0)\nBGCOLOR = BLACK\n</code></pre>\n\n<p>consider something like:</p>\n\n<pre><code>BACKGROUND_COLOR = pygame.Color('black')\n</code></pre></li>\n<li><p>There's no explanation of the meaning of the constants. We can guess from the name that <code>SCREEN_HEIGHT = 480</code> gives the height of the screen in pixels, but what about <code>GAP</code>? It's the gap betwen <em>something</em> and <em>something else</em>, but what?</p>\n\n<p>Or consider <code>BALL_SPEED = 5</code>. It's probably the speed of the ball in some units. But what units? Pixels per second? Pixels per frame?</p>\n\n<p>From examining the code it seems that <code>BALL_SPEED</code> is in pixels per frame, but <code>PLAYER_SPEED</code> and <code>ENEMY_SPEED</code> are in pixels per second. This is particularly confusing! It also means that if you change the framerate, then the ball will speed up or slow down. Better to specify all speeds <em>per second</em>, so that you can easily change the framerate.</p></li>\n</ol>\n\n<h3>2.4. Text</h3>\n\n<ol>\n<li><p>The <code>Text._size</code> member is only used to create the font, so there is no need to store it in the instance.</p></li>\n<li><p>Why not make <code>Text</code> a subclass of <code>pygame.sprite.Sprite</code> so that you can draw it using a sprite group?</p></li>\n<li><p>Lots of code is repeated betwen <code>Text.__init__</code> and <code>Text.set_value</code>. Why not have the former call the latter?</p></li>\n<li><p>The <code>Text.__init__</code> constructor takes many keyword arguments, which you then apply to <code>self.rect</code> like this:</p>\n\n<pre><code>if top: self.rect.top = top\n...\n</code></pre>\n\n<p>The first problem is that the test <code>if top:</code> means that you can't set <code>top</code> to zero. You should write something like this:</p>\n\n<pre><code>if top is not None: self.rect.top = top\n</code></pre>\n\n<p>But it would be much simpler to use Python's <code>**</code> keyword argument mechanism to take any number of keyword arguments, and pass them all to <a href=\"http://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect\"><code>Surface.get_rect</code></a>. Like this:</p>\n\n<pre><code>class Text(pygame.sprite.Sprite):\n def __init__(self, text, size, color, font=None, **kwargs):\n super(Text, self).__init__()\n self.color = color\n self.font = pygame.font.Font(font, size)\n self.kwargs = kwargs\n self.set(text)\n\n def set(self, text):\n self.image = self.font.render(str(text), 1, self.color)\n self.rect = self.image.get_rect(**self.kwargs)\n</code></pre></li>\n</ol>\n\n<h3>2.5. Ball class</h3>\n\n<ol>\n<li><p>The <code>Ball</code> class sets a <code>collided</code> flag on a paddle when it collides with it. The purpose of this flag is to communicate to the <code>Enemy</code> class, telling it to select a new value for <code>hitpos</code> the next time that the <code>update</code> method is called. This does not seem very elegant! Why not have a method instead, that can be subclassed? For example, in the <code>Ball</code> class you'd replace:</p>\n\n<pre><code>paddle.collided = True\n</code></pre>\n\n<p>with</p>\n\n<pre><code>paddle.collided()\n</code></pre>\n\n<p>and then in the <code>Paddle</code> class you'd have a base method (that does nothing):</p>\n\n<pre><code>def collided(self):\n \"Handle collision with ball.\"\n pass\n</code></pre>\n\n<p>which you'd override in the <code>Enemy</code> subclass:</p>\n\n<pre><code>def collided(self):\n self.hitpos = random.randrange(-40, 40)\n</code></pre></li>\n<li><p>Your use of black as the transparent colorkey means that you cannot configure the game to have a black ball. An alternative approach would be to use per-pixel alpha, and then you could omit the lines:</p>\n\n<pre><code>self.image.fill(BLACK)\nself.image.set_colorkey(BLACK, RLEACCEL)\n</code></pre></li>\n<li><p>Since <code>_draw_ball</code> is called only from <code>Ball.__init__</code> and is really short (just one line after making the above change), why not inline it there? Similarly for <code>_draw_paddle</code>.</p></li>\n<li><p>There's no point in passing a <code>vector</code> argument to the <code>Ball</code> constructor because it will be immediately overwritten by the call to <code>reinit</code>.</p></li>\n<li><p>The name <code>vector</code> doesn't tell you what the purpose of the vector is: I suggest <code>velocity</code> instead.</p></li>\n<li><p>The <code>calcnewpos</code> and <code>handle_collision</code> methods are only called from one place in <code>update</code>, so I suggest inlining them there. Similarly, the <code>_hit_leftright</code> and <code>_hit_topbottom</code> methods are only called from one place in <code>handle_collision</code>.</p></li>\n<li><p>It's possible for the ball to hits the paddle and the edge of the playing area at the same time, but this case is not handled.</p></li>\n<li><p>If you're going to call <code>_hit_topbottom</code> and <code>_hit_leftright</code>, why also call <code>self.area.contains</code>?</p></li>\n<li><p><code>_hit_topbottom</code> is implemented like this:</p>\n\n<pre><code>return self.rect.top &lt; 0 or self.rect.bottom &gt; SCREEN_HEIGHT\n</code></pre>\n\n<p>but shouldn't it be</p>\n\n<pre><code>return self.rect.top &lt; self.area.top or self.rect.bottom &gt; self.area.bottom\n</code></pre>\n\n<p>so that you can adjust the playing area if you need to?</p></li>\n<li><p>This code</p>\n\n<pre><code>if dy &lt;= -32:\n dy = -32\nelif -32 &lt; dy &lt;= -16:\n dy = -16\nelif -16 &lt; dy &lt; 16:\n dy = 0\nelif 16 &lt;= dy &lt; 32:\n dy = 16\nelif dy &gt;= 32:\n dy = 32\n</code></pre>\n\n<p>looks suspicious because there's no <code>else:</code> clause at the end of the chain of <code>if: ... elif: ...</code> statements. Also, these could be combined into one line, perhaps like this:</p>\n\n<pre><code>dy = math.copysign(min(abs(dy) // 16 * 16, 32), dy)\n</code></pre>\n\n<p>It also seems very unsatisfactory to me that the ball can only travel at five angles. Wouldn't the game be more interesting (and require more skill to play) if the ball had a wider range of behaviour? You could try something like this:</p>\n\n<pre><code>dy = math.copysign(min(abs(dy), 32), dy)\n</code></pre></li>\n</ol>\n\n<h3>2.6. Paddle, Player, and Enemy classes</h3>\n\n<ol>\n<li><p>There seems to be a lot of shared code between the <code>Player</code> and <code>Enemy</code> classes. For example, both classes have the following setup in their <code>__init__</code> methods:</p>\n\n<pre><code>self.ball = ball\nself.side = ???\nself.speed = ???\nself.score = 0\nself.reinit()\n</code></pre>\n\n<p>Why not put this shared code into <code>Paddle.__init__</code>?</p></li>\n<li><p>Similarly, <code>Player.reinit</code> and <code>Enemy.reinit</code> are identical. Why not put this shared code into <code>Paddle.reinit</code>?</p></li>\n<li><p>Code like this looks suspicious:</p>\n\n<pre><code>if self.side == 'left': self.rect.left = GAP\nelif self.side == 'right': self.rect.right = SCREEN_WIDTH - GAP\n</code></pre>\n\n<p>because there's no <code>else:</code> clause. What happens if <code>self.side</code> is neither <code>'left'</code> or <code>'right'</code>? You could raise an error:</p>\n\n<pre><code>if self.side == 'left': self.rect.left = GAP\nelif self.side == 'right': self.rect.right = SCREEN_WIDTH - GAP\nelse:\n raise ValueError(\"self.side = '{0}': must be 'left' or 'right'\"\n .format(self.side))\n</code></pre>\n\n<p>Or you could assert that <code>self.side</code> is correct:</p>\n\n<pre><code>assert(self.side in {'left', 'right'})\nif self.side == 'left': self.rect.left = GAP\nelse: self.rect.right = SCREEN_WIDTH - GAP\n</code></pre>\n\n<p>But really I think that this is eveidence that the \"side\" mechanism needs rethinking. I would consider specifying <code>self.rect</code> directly instead of <code>self.side</code>.</p></li>\n<li><p><code>Player.update</code> has code for updating <code>self.hitpos</code>, but this is never used.</p></li>\n<li><p>This line of code:</p>\n\n<pre><code> if (spot - self.ball.rect.centery) not in range(-5, 5):\n</code></pre>\n\n<p>has a couple of problems. First, it only works so long as <code>spot</code> and <code>self.ball.rect.centery</code> are integers. Should you ever change the code so that either is floating-point, then this code would break. Second, each time you visit this line you construct a new <code>range</code> object which you then throw away. Third, <code>range(-5, 5)</code> only goes up to 4, which might not be what you meant. Instead, write something like:</p>\n\n<pre><code>if abs(spot - self.ball.rect.centery) &gt; 5:\n</code></pre></li>\n<li><p>In code like this:</p>\n\n<pre><code>if spot &gt; self.ball.rect.centery:\n self.movepos[1] = -self.speed * dt\nif spot &lt; self.ball.rect.centery:\n self.movepos[1] = self.speed * dt\n</code></pre>\n\n<p>you could make use of <a href=\"http://docs.python.org/3/library/math.html#math.copysign\"><code>math.copysign</code></a>:</p>\n\n<pre><code>self.movepos[1] = math.copysign(self.speed * dt, self.ball.rect.centery - spot)\n</code></pre>\n\n<p>but see below for a different suggestion. </p></li>\n<li><p>The remaining code in the <code>update</code> methods of the <code>Player</code> and <code>Enemy</code> classes, consists of determining which direction to move (up or down?) and then calling the superclass method. It would be simpler to turn this around and have a method (<code>move</code>, say) which determines the direction to move.</p>\n\n<p>So <code>Paddle.update</code> would look like this:</p>\n\n<pre><code>def update(self, dt):\n new_rect = self.rect.move([0, self.move(dt)])\n if self.area.contains(new_rect):\n self.rect = new_rect\n pygame.event.pump()\n</code></pre>\n\n<p>and then the <code>Player</code> class would look like this:</p>\n\n<pre><code>class Player(Paddle):\n def move(self, dt):\n keys = pygame.key.get_pressed()\n if keys[K_UP]: return -self.speed * dt\n elif keys[K_DOWN]: return self.speed * dt\n else: return 0\n</code></pre>\n\n<p>and the <code>Enemy</code> class like this:</p>\n\n<pre><code>class Enemy(Paddle):\n def reinit(self):\n super().reinit()\n self.hitpos = 0\n\n def move(self, dt):\n dy = self.rect.centery + self.hitpos - self.ball.rect.centery\n if abs(dy) &lt;= 5: return 0\n return math.copysign(self.speed * dt, dy)\n\n def collided(self):\n self.hitpos = random.randrange(-40, 40)\n</code></pre></li>\n<li><p>The <code>Player.movepos</code> member is only used to transfer a value from <code>Player.move</code> to <code>Player.update</code>. When the return value is use instead, this member has no further use and can be removed.</p></li>\n<li><p>The <code>Enemy</code> behaviour results in jittery motion because it can only move full speed, so if it is trying to track a ball whose vertical component of velocity is less than <code>enemy.speed * dt</code> then it will alternate between frames of motion and frames of no motion. It would be yield a more pleasing result if the speed tapered off gracefully:</p>\n\n<pre><code>def move(self, dt):\n dy = self.ball.rect.centery - self.rect.centery + self.hitpos \n return math.copysign(min(abs(dy), self.speed * dt), dy)\n</code></pre></li>\n<li><p>There seems to be no use for the <code>Player.state</code> variable.</p></li>\n<li><p>Instead of</p>\n\n<pre><code>(self.rect.centerx, self.rect.centery)\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>self.rect.center\n</code></pre>\n\n<p>And instead of</p>\n\n<pre><code>self.rect.centerx = self.area.centerx\nself.rect.centery = self.area.centery\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>self.rect.center = self.area.center\n</code></pre></li>\n<li><p>What is the purpose of calling <a href=\"http://www.pygame.org/docs/ref/event.html#pygame.event.pump\"><code>pygame.event.pump</code></a> in <code>Paddle.update</code>? The documentation says, \"This function is not necessary if your program is consistently processing events on the queue through the other <code>pygame.event</code> functions.\"</p></li>\n</ol>\n\n<h3>2.7. Game class</h3>\n\n<ol>\n<li><p>It's conventional to write</p>\n\n<pre><code>while True:\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>while 1:\n</code></pre></li>\n<li><p>Comments that merely document what happens in the next line are pretty useless:</p>\n\n<pre><code># initialize clock\nclock = pygame.time.Clock()\n</code></pre>\n\n<p>Any reader could guess, from its capitalized name, that <code>Clock</code> is a constructor; and if they want to know what it does then they can read the documentation. It's generally best to use comments to explain <em>why</em> you're doing something, not <em>what</em> you're doing (if that's obvious from reading the code).</p></li>\n<li><p>You have a complicated drawing operation where you erase all the sprites and text at their old positions, update their positions, and then draw them at their new positions. This approach works here where you have a static unchanging background, but it won't work at all when the background moves or animates in any way.</p>\n\n<p>At the moment your main loop looks like this:</p>\n\n<pre><code># erase sprites\nscreen.blit(self.background, self.ball.rect, self.ball.rect)\nscreen.blit(self.background, self.player.rect, self.player.rect)\nscreen.blit(self.background, self.enemy.rect, self.enemy.rect)\n\n# erase scores\nscreen.blit(self.background, self.left_score.rect, self.left_score.rect)\nscreen.blit(self.background, self.right_score.rect, self.right_score.rect)\n\n# erase pause text\nscreen.blit(self.background, self.pause_text.rect, self.pause_text.rect)\n\n# update ...\n\n# draw sprites ...\n\n# draw scores ...\n</code></pre>\n\n<p>But if you just draw the whole screen every frame, there will no longer be any need to erase the sprites, and the main loop will look something like this:</p>\n\n<pre><code># update ...\n\n# draw background\nscreen.blit(self.background, screen.get_rect())\n\n# draw sprites ...\n\n# draw scores ...\n</code></pre></li>\n<li><p>When the game is paused, you arrange not to draw the screen. But that means that there is no flip, and so no wait for the next frame. You compensate for this by adding a delay when the game is paused:</p>\n\n<pre><code>pygame.time.delay(150)\n</code></pre>\n\n<p>But if you just draw the frame normally when the game is paused, then there will be a flip as usual, and you won't need these <code>delay</code> calls.</p></li>\n</ol>\n\n<h2>3. Third version</h2>\n\n<p>It's not fair to ask us to review a moving target like this. It's best to finish writing your code <em>before</em> you ask people to review it.</p>\n\n<p>Tom Gilb and Dorothy Graham, in their book <em>Software Inspection</em>, have a section (§4.4) about entry criteria for the inspection process. If a product is inspected at too early a stage, then there is a risk of wasting inspection effect:</p>\n\n<blockquote>\n <p>checkers will find a large number of defects which can be found very easily by one individual alone, even the author. Inspections are cost-effective when the combined skills of a number of checkers are concentrated on a [program] which seems superficially all right, but actually has a number of major defects in it which will only be found by the intensive Inspection process, not by the author checking the product.</p>\n</blockquote>\n\n<p>So in a professional context, it's important not to start inspection until the author has made the product as good as possible. (Here at Code Review we are a bit more relaxed.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T05:04:57.773", "Id": "50358", "Score": "0", "body": "A little thing. parenthized `print` doesn't necessarily mean Python3. Try `print(\"abcd\")` in Python2. It will work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:57:31.970", "Id": "50381", "Score": "0", "body": "@AseemBansal: The OP's code originally said `print(\"ImportError:\", message)`. In Python 2 this prints a tuple, which doesn't seem likely to be what the OP intended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-25T23:23:18.440", "Id": "50748", "Score": "0", "body": "What do you mean by '*The code will become much simpler if you just draw the whole screen every frame.*' in **2.7.3**?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T12:07:58.023", "Id": "50769", "Score": "0", "body": "@Jovito: see revised answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T14:47:04.243", "Id": "50785", "Score": "0", "body": "@GarethRees I also didn't understand what you meant by 'inlining' the methods in **2.5.3**. Could you give an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T14:49:56.353", "Id": "50786", "Score": "1", "body": "@Jovito: See Wikipedia for the meaning of [inline expansion](http://en.wikipedia.org/wiki/Inline_expansion) (\"inlining\" for short). But all I'm saying here is that if a method is called from only one place and doesn't have obvious \"standalone\" functionality, then it may not be worth making it into a separate method in the first place. But this is a matter of personal taste and judgement." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T14:49:51.500", "Id": "31539", "ParentId": "31408", "Score": "13" } } ]
{ "AcceptedAnswerId": "31539", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T06:35:54.527", "Id": "31408", "Score": "10", "Tags": [ "python", "game", "pygame" ], "Title": "Pong with Pygame" }
31408
<p>I have a <code>Task</code> model in Django which looks like the following:</p> <pre><code>class Task(TimeStampedModel): project = models.ForeignKey(Project, related_name='tasks') date = models.DateField(_('date')) task = models.TextField(_('what\'s the task?')) status = models.CharField( _('what\'s the status'), default=constants.TASK_STATUS_EMPTY, max_length=40, choices=constants.TASK_STATUS_CHOICES) status_note = models.TextField(_('write a note about status'), blank=True) created_by = models.ForeignKey(User, related_name='created_tasks') modified_by = models.ForeignKey(User, related_name='modified_tasks') class Meta: ordering = ('-created', '-modified') def __unicode__(self): return self.task </code></pre> <p>Here is a screenshot of the final implementation:</p> <p><img src="https://i.stack.imgur.com/YM7Zg.png" alt="Task Management System Dashboard"></p> <p>I have exposed this <code>Task</code> model using <code>django-tastypie</code> as a RESTful api.</p> <p>On client side, I have used AngularJS for editing/adding tasks.</p> <p>I need to group tasks by project and date for rendering them properly. I have used _.groupBy method of <a href="http://lodash.com/" rel="nofollow noreferrer">lodash.js</a> for this.</p> <p>I wanted to know if there is a better approach to implement same interface.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T06:46:15.670", "Id": "50138", "Score": "1", "body": "I think grouping on the client side is fine, given the list is limited. I am currently building stuff which lets you do some processing in the client itself. I see that performance for 1000 - 2000 entries is reasonable in that case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T07:27:56.020", "Id": "50141", "Score": "0", "body": "I thought grouping of tasks in `django-tastypie` may be a pain. Further, API could have been complicated if I moved this to server side. Lodash has reasonable performance. Anyway, as per our use case, no. of tasks to be rendered on a page will be always less than 2000." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T07:34:43.270", "Id": "31410", "Score": "3", "Tags": [ "python", "datetime", "django", "angular.js", "lodash.js" ], "Title": "Implementing \"day wise task management\" system using Django and AngularJS" }
31410
<p>I'm supplying a HashMap with data in the following way:</p> <pre><code>HashMap&lt;String,MyClass&gt; myHashMap = new HashMap&lt;String,MyClass&gt;(); myHashMap.put( "foo", new MyClass(2,4) ); myHashMap.put( "bar", new MyClass(0,10) ); myHashMap.put( "a", new MyClass(0,0) ); myHashMap.put( "b", new MyClass(0,1) ); myHashMap.put( "c", new MyClass(0,0) ); myHashMap.put( "d", new MyClass(0,42) ); // ... </code></pre> <p>There's around 20 lines, but a lot is duplicated text. The only interesting information in every line is foo,2,4, bar,0,10, a,0,0 and so on. How can I make this code neater?</p> <p>If only the strings differed, I'd do it this way:</p> <pre><code>List&lt;String&gt; names = Arrays.aslist("foo","bar","a","b","c","d"); for ( String name : names ) myHashMap.put( name, new MyClass(0,0) ); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T10:33:06.877", "Id": "50046", "Score": "1", "body": "I don't think that there is enough information to offer a good alternative. What are the values \"foo\", 2, 4, etc? Where does the data originate (for both keys and values)? How are keys and values related (if at all)? How will the Map be used after it is created?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T10:47:15.670", "Id": "50049", "Score": "0", "body": "The data is hard-coded business logic. Each instance of MyClass represents a parameter with scaling factors and maximum values. Since the class doesn't do much except collect them, it makes more sense to put those values there than in a separate file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T12:47:16.530", "Id": "50057", "Score": "0", "body": "i feel the first set of code is ok, because it is readable, understandable to any coder in team(or future members), and maintainable. [which does not need extra documentation for the code!]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T13:12:20.133", "Id": "50062", "Score": "1", "body": "The first set of code is fine, but it does not lend itself to optimization as it is not clear why it is doing what it is doing. For example, are the keys arbitrary - is a Map needed at all or could a Set be used? Would the Key be better represented as a property of `MyClass`? If reading the values from an external source, would an iterator be preferable? Will the map be modified post creation (is it static?)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:09:22.437", "Id": "50079", "Score": "1", "body": "You considered putting these into easily-editable configuration files? That does add another class to parse that file and create a HashMap, but might leader to better abstraction (easy to swap them out at runtime is a bonus)." } ]
[ { "body": "<p>A simple way (but maybe not the best looking one), is this:</p>\n\n<pre><code>String[] names = new String[]{\"foo\",\"bar\",\"a\",\"b\",\"c\",\"d\"};\nint[] parameter1 = new int[]{2,0,0,0,0,0};\nint[] parameter2 = new int[]{4,10,0,1,0,42};\n\nfor (int i=0; names.length&gt;i; i++)\n myHashMap.put( names[i], new MyClass(parameter1[i],parameter2[i]) );\n</code></pre>\n\n<p>If they are a lot of entries, you should consider to put the names and the parameters in an external file and read that instead of putting this information in your source code. [<strong>Putting the data to a file is my recommendation</strong>]</p>\n\n<p>or also a bit ugly:</p>\n\n<pre><code>Object[] data = new String[]{\"foo\", 2, 4, // \n \"bar\", 0,10, // \n \"a\", 0,0, // \n \"b\", 0,1, // \n \"c\", 0,0, // \n \"d\" 0,42,\n };\nint i=0;\nwhile (data.length&gt;i)\n myHashMap.put( (String)data[i++], new MyClass((Integer)data[i++],(Integer)data[i++]) );\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T10:28:04.757", "Id": "50044", "Score": "0", "body": "I think it would be difficult to see e.g. that (b,0,1) belong together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T11:21:07.110", "Id": "50050", "Score": "0", "body": "@Andreas: I added another possibility which allows better to see, what belongs together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T11:37:20.633", "Id": "50052", "Score": "1", "body": "Wouldn't using a new line instead of `/**/` be a better way of formatting?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T12:10:52.557", "Id": "50053", "Score": "0", "body": "@Bobby: Yes, but my impression was that Andreas wanted less lines of code than his initial approach. Formatting is most times a matter of taste." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T12:51:09.113", "Id": "50058", "Score": "0", "body": "I'm not looking for less lines, but rather less cruft and text that doesn't add anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T14:32:11.390", "Id": "50073", "Score": "1", "body": "@Bobby: I changed the second variant of my answer to a easier to read formatting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:06:18.423", "Id": "50078", "Score": "0", "body": "@MrSmith42: May I suggest a small tweak? Remove the `//` and start with the data on a new line, indented by one step [like this](http://pastebin.com/YRnUrrSG). This way the array creates a \"visual block\" of it's own (similar to if/for-blocks). The declaration is also incorrect, it should be Object, not String, and the last line has messed up commas." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T08:06:47.783", "Id": "50150", "Score": "0", "body": "@Bobby: The `//` avoids my IDE (eclipse) to merge the line together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T08:12:56.470", "Id": "50151", "Score": "0", "body": "@MrSmith42: Oh, that one. It's one of these thing I need to remember to turn off when using Eclipse." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T10:16:22.090", "Id": "31418", "ParentId": "31417", "Score": "0" } }, { "body": "<p>Create a custom class?</p>\n\n<pre><code>class MyHashMapCreator {\n private HashMap&lt;String, MyClass&gt; myHashMap = new HashMap&lt;String,MyClass&gt;();\n public MyBuilder add(String x, int y, int z) {\n myHashMap.add(x, new MyClass(y, z));\n }\n public HashMap&lt;String, MyClass&gt; getHashMap() {\n return myHashMap;\n }\n}\n</code></pre>\n\n<p>And use it like...</p>\n\n<pre><code>HashMap&lt;String,MyClass&gt; hashmap = new MyHashMapCreator().\n add(\"foo\", 2, 4).\n add(\"bar\", 0, 10).\n add(\"a\", 0, 0).\n add(\"b\", 0, 1).\n add(\"c\", 0, 0).\n add(\"d\", 0, 42).getHashMap();\n</code></pre>\n\n<p>Although its odd that you have the data in your class and from an external source (service? database?) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T10:46:52.560", "Id": "50048", "Score": "0", "body": "The data is business logic. Each instance of MyClass represents a parameter with scaling factors and maximum values. Since the class doesn't do much except collect them, it makes more sense to put those values there than in a separate file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T12:54:57.047", "Id": "50059", "Score": "1", "body": "@Andreas, except that now you need a developer to change that file, if the data was external then an analyst could change it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T17:34:08.277", "Id": "50089", "Score": "0", "body": "Will not the new class create extra overhead? in any case the \"add\" is going to to be repeated..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T10:27:32.230", "Id": "31419", "ParentId": "31417", "Score": "0" } }, { "body": "<p>Then I would use a static method to put the entries in the map:</p>\n\n<pre><code>HashMap&lt;String,MyClass&gt; myHashMap = new HashMap&lt;String,MyClass&gt;();\naddEntry(myHashMap, \"foo\",2,4);\naddEntry(myHashMap, \"bar\", 0,10);\naddEntry(myHashMap, \"a\", 0,0);\naddEntry(myHashMap, \"b\", 0,1);\naddEntry(myHashMap, \"c\", 0,0);\naddEntry(myHashMap, \"d\", 0,42);\n// ...\n\nprivate static //\nvoid addEntry(HashMap&lt;String,MyClass&gt; map, String name, int arg1, int arg2){\n map.put( name, new MyClass(arg1,arg2) );\n}\n</code></pre>\n\n<p>I recommend reading the data from a file and call <code>addEntry(myHashMap, ...);</code> in a loop until end of file is reached.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T14:29:43.880", "Id": "31425", "ParentId": "31417", "Score": "1" } }, { "body": "<p>So, I'm not sure how to answer because I don't understand the use case, but here are a couple of thoughts.</p>\n\n<p>If you are defining some data that will never change and is well understood then you could consider using an enum:</p>\n\n<pre><code>public enum ParamterScale {\n X(2, 4),\n Y(2, 4),\n LENGTH(0, 10);\n\n private int scale;\n private int maximum;\n\n private ParameterScale(int scale, int maximum) {\n this.scale = scale;\n this.maximum = maximum;\n }\n\n //getters\n}\n</code></pre>\n\n<p>By using an enum you clearly enumerate all the supported cases and encapsulate your data without resorting to data structures that do not fit your purpose.</p>\n\n<p>If your data is not clearly defined, or is dynamic or extensible in anyway then the enum approach will not work. At this point I would need to understand the relationship between the key and value in your map. If the key describes the parameter and the two values encapsulate the behavior then the key should be a part of the <code>MyClass</code> object (if this is the case you are using <code>MyClass</code> as a tuple). In this case you should begin by modifying <code>MyClass</code> to include a parameterName member variable and then override <code>equals</code> and <code>hashCode</code> so that you can use <code>MyClass</code> in a set. How you chose to override the methods will depend on whether you can have multiple instances of a parameter with different values or whether each parameter name should be unique.</p>\n\n<p>If your data is hardcoded today, but might not be tomorrow, don't worry about it. If your data is hardcoded today and won't be tomorrow you could define an interface, say <code>ParameterValueProvider</code>. This interface can expose whatever maethods might be useful to you - size, iterator, next... Create a single implementation for today say <code>StaticParameterDataProvider</code> or <code>MockParameterDataProvider</code> - whatever accurately describes the data you will be feeding back. This means that in the future you could add a <code>CSVParameterDataProvider</code> or <code>XMLParameterDataProvider</code> or whatever. </p>\n\n<p>Now, inside your <code>StaticParameterDataProvider</code> you could create an enum as described above. If you need to iterate over the values to convert them into another structure you can use the <code>.values</code> method:</p>\n\n<pre><code>for (ParameterScale ps : ParameterScale.values()) {\n //then for each value you can access it's fields like so.\n ps.name(); //or ps.toString() if you want to customise the parameter name\n ps.getScale();\n ps.getMaximum();\n}\n</code></pre>\n\n<p>If the HashMap is important, you can use a static initialiser within an enum like this:</p>\n\n<pre><code>public enum ParameterScale {\n\n //enum values\n ...\n\n public static Map&lt;String, MyClass&gt; params;\n\n static {\n params = new HashMap&lt;String, MyClass&gt;();\n for (ParameterScale ps : ParameterScale.values()) {\n params.put(ps.name(), new MyClass(ps.getScale(), ps.getMaximum()));\n }\n }\n\n}\n</code></pre>\n\n<p>This is publicly accessible using <code>ParameterScale.params</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T15:07:34.200", "Id": "31428", "ParentId": "31417", "Score": "0" } }, { "body": "<p>I can't get any solution that will reduce you code drastically... but try <a href=\"http://c2.com/cgi/wiki?DoubleBraceInitialization\" rel=\"nofollow\">Double Brace Initialization</a>.</p>\n\n<pre><code>HashMap&lt;String,MyClass&gt; myHashMap = new HashMap&lt;String,MyClass&gt;(){{\n put( \"foo\", new MyClass(2,4) );\n put( \"bar\", new MyClass(0,10) );\n put( \"a\" , new MyClass(0,0) );\n put( \"b\" , new MyClass(0,1) );\n put( \"c\" , new MyClass(0,0) );\n put( \"d\" , new MyClass(0,42) );\n}};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T18:19:05.957", "Id": "50095", "Score": "1", "body": "Use it, or don't use it, but if you do, make sure you understand what it is doing and why it is better than the other options. One day someone will say WTF are all those braces up to :) This was a really interesting question on SO (don't worry about the efficiency angle, proably), http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T22:37:35.857", "Id": "59373", "Score": "1", "body": "Double Brace Initialization is clever, but a bit deceptive: it doesn't create a normal HashMap, but rather an anonymous inner class that extends HashMap." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T18:02:06.690", "Id": "31442", "ParentId": "31417", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:55:35.193", "Id": "31417", "Score": "3", "Tags": [ "java" ], "Title": "How to fill in this HashMap neatly without code duplication?" }
31417
<p>I have an array of objects that each have a name/value property. The array can contain multiple objects with the same name property. I want to serialize this array into the form: </p> <pre><code>name:value,value|name:value|name:value,value,value </code></pre> <p>So basically each property is separated by a <code>|</code> and each value by a <code>,</code>. The above example is not exactly how I want it to look, just an example of the syntax, results will vary based upon input.</p> <p>Here is an example of the array:</p> <pre><code>var objs = [ {name:"name1", value: "value1"}, {name:"name4", value: "value4"}, {name:"name3", value: "value3"}, {name:"name2", value: "value2"}, {name:"name2", value: "value2"}, {name:"name2", value: "value3"} ]; </code></pre> <p>I wrote some code to perform this serialization, but I wanted to see if anyone could suggest improvements to this code, I know there are some Javascript experts on this site and wanted to get their opinion:</p> <pre><code>function serialize(objs){ var out = ""; for(var i = 0; i &lt; objs.length; i++){ var propKey = objs[i].name + ":"; if (out.indexOf(propKey) == -1){ out += "|" + propKey; } var position = out.indexOf(propKey) + propKey.length; out = out.substring(0, position) + objs[i].value + "," + out.substring(position); } return out.substring(1,out.length-1).replace(/\,\|/g,"|"); } </code></pre> <p>JS Fiddle: <a href="http://jsfiddle.net/BHsuM/" rel="nofollow">http://jsfiddle.net/BHsuM/</a></p> <p>BTW jQuery is acceptable.</p>
[]
[ { "body": "<p>Why do you want it serialized specifically in that form? Just use the universal, built-in JSON serialization:</p>\n\n<pre><code>var serialized = JSON.stringify(myvar);\nvar reconstituted = JSON.parse(serialized);\n</code></pre>\n\n<p>Done, <code>reconstituted</code> is a normal object again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T17:18:06.063", "Id": "31421", "ParentId": "31420", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T16:02:14.720", "Id": "31420", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Serialize name/value pairs" }
31420
<p>I have two different ways of populating a <code>List</code> with querying another <code>List</code>. They are:</p> <pre><code>var list = _surveyList.Where(x =&gt; x.Date == selectedDate).Select(s =&gt; s.Joint).ToList(); </code></pre> <p>And:</p> <pre><code>var list = from s in _surveyList where s.Date.Equals(selectedDate) select s.Joint; </code></pre> <p>They functionally do the same thing. My question is which is better in terms of readability, and function? Does one have more overhead than the other? Is one way more preferred than the other?</p>
[]
[ { "body": "<p>These aren't completely the same. The first will return a <code>List&lt;T&gt;</code> and the second will return an <code>IEnumerable&lt;T&gt;</code>.</p>\n\n<p>You would need to make this change in order for these to be equivalent.</p>\n\n<pre><code>var list = (from s in _surveyList\n where s.Date.Equals(selectedDate)\n select s.Joint).ToList();\n</code></pre>\n\n<p>But to answer your question it really comes down to personal preference. What do you feel more comfortable with? What has your team agreed on? </p>\n\n<p>There are cases where you have to use Method Syntax over Query Syntax. And there are some cases when one will be more readable then others. You will have to make that determination yourself.</p>\n\n<p>Check out this question over on Stack Overflow.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/8037677/linq-query-syntax-vs-method-chains-lambda\">https://stackoverflow.com/questions/8037677/linq-query-syntax-vs-method-chains-lambda</a></p>\n\n<p>That question was ultimately closed as being not constructive (opinion related) as I'm sure this one will be also.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T16:23:35.237", "Id": "31435", "ParentId": "31431", "Score": "7" } }, { "body": "<p>There is absolutely <strong>no overhead</strong> as they both produce the exact same IL code once edited to use same comparison (<code>s.Date.Equals(selectedDate)</code>) and result type (<code>IEnumerable&lt;T&gt;</code>).</p>\n\n<p><strong>Lambda expression</strong> (complete example)</p>\n\n<pre><code>using System;\nusing System.Linq;\n\npublic class C {\n public void M() {\n DateTime selectedDate = DateTime.Now;\n S[] _surveyList = {};\n\n var list = _surveyList\n .Where(s =&gt; s.Date.Equals(selectedDate))\n .Select(s =&gt; s.Joint);\n }\n\n private class S{\n public DateTime Date {get;set;}\n public String Joint {get;set;}\n }\n}\n</code></pre>\n\n<p><strong>Query expression</strong> (equivalent complete example)</p>\n\n<pre><code>using System;\nusing System.Linq;\n\npublic class C {\n public void M() {\n DateTime selectedDate = DateTime.Now;\n S[] _surveyList = {};\n\n var list = from s in _surveyList\n where s.Date.Equals(selectedDate)\n select s.Joint;\n }\n\n private class S{\n public DateTime Date {get;set;}\n public String Joint {get;set;}\n }\n}\n</code></pre>\n\n<p>You can generate the IL result using an online tool like <a href=\"http://sharplab.io\" rel=\"nofollow noreferrer\">sharplab.io</a> and then compare both using a file diff tool like <a href=\"https://www.diffnow.com/\" rel=\"nofollow noreferrer\">diffnow.com</a>.</p>\n\n<p>So as @nickles80 mentionned, it's up to your preference regarding the readability</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-12T14:18:19.700", "Id": "201512", "ParentId": "31431", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T16:03:31.937", "Id": "31431", "Score": "1", "Tags": [ "c#" ], "Title": "Which of these two is better in terms of readability and function?" }
31431
<p>I am creating my models manually. I have five tables in my database as follows:</p> <ol> <li><code>Members</code></li> <li><code>MemberTypeMasters</code></li> <li><code>Payments</code></li> <li><code>Relationships</code></li> <li><code>StatusMasters</code></li> </ol> <p>My database looks like this:</p> <p><img src="https://i.stack.imgur.com/eZXLu.jpg" alt="enter image description here"></p> <p>So far I have 6 files containing auto-implemented properties as below:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Models |-- DBCS.cs |-- Member.cs |-- MemberTypeMaster.cs |-- Payment.cs |-- Relationship.cs |-- StatusMaster.cs </code></pre> </blockquote> <p><strong>DBCS.cs</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Data.Entity; namespace Munim_File_Sharing.Models { public class DBCS : DbContext { public DbSet&lt;Member&gt; Members { get; set; } public DbSet&lt;MemberTypeMaster&gt; MemberTypeMasters { get; set; } public DbSet&lt;Payment&gt; Payments { get; set; } public DbSet&lt;Relationship&gt; RelationShips { get; set; } public DbSet&lt;StatusMaster&gt; StatusMasters { get; set; } } } </code></pre> <p><strong>Member.cs</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Munim_File_Sharing.Models { public class Member { [Key] public int MemberID { get; set; } public string Name { get; set; } public string Password { get; set; } public string MobileNo { get; set; } public string FileName { get; set; } public Nullable&lt;DateTime&gt; MemberSince { get; set; } public int MemberTypeID { get; set; } public virtual MemberTypeMaster MemberTypeMaster { get; set; } public virtual ICollection&lt;Payment&gt; Payments { get; set; } public virtual ICollection&lt;Relationship&gt; RelationshipSenders { get; set; } public virtual ICollection&lt;Relationship&gt; RelationshipReceivers { get; set; } } } </code></pre> <p><strong>MemberTypeMaster.cs</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Munim_File_Sharing.Models { public class MemberTypeMaster { [Key] public int MemberTypeID { get; set; } public string MemberType { get; set; } public ICollection&lt;Member&gt; Members { get; set; } } } </code></pre> <p><strong>Payment.cs</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Munim_File_Sharing.Models { public class Payment { [Key] public int PaymentID { get; set; } public decimal Amount { get; set; } public DateTime DateOfReceipt { get; set; } public int MemberID { get; set; } public virtual Member Member { get; set; } } } </code></pre> <p><strong>Relationship.cs</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Munim_File_Sharing.Models { public class Relationship { [Key] public int RelationshipID { get; set; } public int RequestSenderID { get; set; } public int RequestReceiverID { get; set; } public int StatusID { get; set; } public virtual Member RequestSender { get; set; } public virtual Member RequestReciever { get; set; } public virtual StatusMaster Status { get; set; } } } </code></pre> <p><strong>StatusMaster.cs</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Munim_File_Sharing.Models { public class StatusMaster { [Key] public int StatusID { get; set; } public string Status { get; set; } public virtual ICollection&lt;Relationship&gt; Relationships { get; set; } } } </code></pre> <p><code>connectionString</code> in web.Config:</p> <pre class="lang-xml prettyprint-override"><code>&lt;connectionStrings&gt; &lt;add name="DBCS" connectionString="server=.; database=FileSharingDB; Integrated Security = SSPI" providerName="System.Data.SqlClient" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>Is there any problem in my above classes? Am I forgetting anything in Models?</p>
[]
[ { "body": "<p>The above classes are used by entity framework for persistance, don't confuse these with the Models in MVC. While its possible to use them directly in MVC, its considered bad practise to so tightly couple your presentation layer to your persistance layer.</p>\n\n<p>Look at tools like AutoMapper that can help you map from the above classes to your actual View Models. Try and have one view model per page and populate them with properties that make sense to the presentation of the data, not its storage.</p>\n\n<p>ie: </p>\n\n<pre><code>public class User\n{\n [Key]\n public int ID { get; set; }\n public string FirstName { get; set; }\n public string LastName { get; set; }\n}\n\npublic class UserModel\n {\n public string Name { get; set; }\n }\n\nMapper.CreateMap&lt;User,UsersModel&gt;()\n .ForMember(dst =&gt; dst.Name, m =&gt; m.MapFrom(src =&gt; src.FirstName + \" \" + src.LastName))\n</code></pre>\n\n<p>and</p>\n\n<pre><code>var userModel = Mapper.Map&lt;User, UserModel&gt;(user);\n</code></pre>\n\n<p>Then use the userModel in your view.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-04T06:10:20.790", "Id": "32225", "ParentId": "31432", "Score": "2" } } ]
{ "AcceptedAnswerId": "32225", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T16:05:27.020", "Id": "31432", "Score": "1", "Tags": [ "c#", "entity-framework", "asp.net-mvc-4" ], "Title": "Creating models manually in MVC" }
31432
<p>This is a typical bouncing ball program. I'm looking to improve and perhaps add to the program. For example, is it possible to be able to click on a ball and have it pause? </p> <pre><code>import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; public class BouncingBalls extends JPanel implements MouseListener { protected List&lt;Ball&gt; balls = new ArrayList&lt;Ball&gt;(20); private Container container; private DrawCanvas canvas; private int canvasWidth; private int canvasHeight; public static final int UPDATE_RATE = 30; int x = random(480); int y = random(480); int speedX = random(30); int speedY = random(30); int radius = random(20); int red = random(255); int green = random(255); int blue = random(255); int count = 0; public static int random(int maxRange) { return (int) Math.round((Math.random() * maxRange)); } public BouncingBalls(int width, int height) { canvasWidth = width; canvasHeight = height; container = new Container(); canvas = new DrawCanvas(); this.setLayout(new BorderLayout()); this.add(canvas, BorderLayout.CENTER); this.addMouseListener(this); start(); } public void start() { Thread t = new Thread() { public void run() { while (true) { update(); repaint(); try { Thread.sleep(1000 / UPDATE_RATE); } catch (InterruptedException e) { } } } }; t.start(); } public void update() { for (Ball ball : balls) { ball.move(container); } } class DrawCanvas extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); container.draw(g); for (Ball ball : balls) { ball.draw(g); } } public Dimension getPreferredSize() { return (new Dimension(canvasWidth, canvasHeight)); } } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame f = new JFrame("Bouncing Balls"); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setContentPane(new BouncingBalls(500, 500)); f.pack(); f.setVisible(true); } }); } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { count++; balls.add(new Ball()); } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } public static class Ball { public int random(int maxRange) { return (int) Math.round(Math.random() * maxRange); } int x = random(480); int y = random(480); int speedX = random(30); int speedY = random(30); int radius = random(20); int red = random(255); int green = random(255); int blue = random(255); int i = 0; public void draw(Graphics g) { g.setColor(new Color(red, green, blue)); g.fillOval((int) (x - radius), (int) (y - radius), (int) (2 * radius), (int) (2 * radius)); } public void move(Container container) { x += speedX; y += speedY; if (x - radius &lt; 0) { speedX = -speedX; x = radius; } else if (x + radius &gt; 500) { speedX = -speedX; x = 500 - radius; } if (y - radius &lt; 0) { speedY = -speedY; y = radius; } else if (y + radius &gt; 500) { speedY = -speedY; y = 500 - radius; } } } public static class Container { private static final int HEIGHT = 500; private static final int WIDTH = 500; private static final Color COLOR = Color.WHITE; public void draw(Graphics g) { g.setColor(COLOR); g.fillRect(0, 0, WIDTH, HEIGHT); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T18:10:12.813", "Id": "50093", "Score": "4", "body": "“For example, is it possible to be able to click on a ball and have it pause?” This site is about reviewing and improving your code, but it's not here to write your code for you, so this part of the question is off topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T23:42:01.560", "Id": "50246", "Score": "0", "body": "@user2692751: What svick means to say is that your question is better suited for http://StackOverflow.com than here." } ]
[ { "body": "<p>when I was looking through your code I noticed that you have some Variables that you defined Globally</p>\n\n<pre><code>int x = random(480);\nint y = random(480);\nint speedX = random(30);\nint speedY = random(30);\nint radius = random(20);\nint red = random(255);\nint green = random(255);\nint blue = random(255);\nint count = 0;\n</code></pre>\n\n<p>and then you defined these variables again in <code>public static class Ball</code></p>\n\n<p>I am thinking that you wouldn't need to define these variables twice, but that you could define them once and use them throughout the code. I am not entirely familiar with the way that Java works (syntax-wise) but I would imagine that you only need to define these Variables once and then use them throughout the code. </p>\n\n<p>I know that the <code>Ball</code> class is created inside of the <code>BouncingBalls</code> class</p>\n\n<p><strong>Additional</strong></p>\n\n<p>to have the ball pause when it is clicked, just make the <code>speed = 0</code> {no movement} and then when it is unclicked resume the previous speed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T20:07:05.343", "Id": "31504", "ParentId": "31434", "Score": "2" } }, { "body": "<p>I only looked at the code briefly, but it seems alright. </p>\n\n<p>However, when you call <code>repaint()</code> in the secondary thread you started, you should probably run that UI repaint call on the UI thread. See for example <a href=\"https://stackoverflow.com/questions/4921009/swing-how-to-properly-update-the-ui#4921271\">this stackoverflow answer</a>. Also, running a continuous <code>while</code>-loop might be overkill, you might just want to update the UI every few milliseconds (maybe aim for 60 fps). You could do it by hand, or look at <a href=\"http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html\" rel=\"nofollow noreferrer\">javax.swing.Timer</a>.</p>\n\n<p>And some minor points:</p>\n\n<ol>\n<li><p>Instead of <code>MouseListener</code>, look into <code>MouseAdapter</code>. It's the same, but it avoids having to define empty methods. On the other hand, you would now have to make it a separate class (likely an inner class) from <code>BouncingBalls</code>. </p></li>\n<li><p>For <code>random(maxRange)</code>, look instead at <code>java.util.Random.nextInt(Int)</code>.</p></li>\n<li><p>In <code>move(container)</code>, the argument is unnecessary. I guess it used to have some use, but you forgot to remove the argument after some changes.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T01:40:28.980", "Id": "31519", "ParentId": "31434", "Score": "1" } }, { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li><p>You have a lot of magic numbers:</p>\n\n<pre><code>int x = random(480);\nint y = random(480);\nint speedX = random(30);\n</code></pre>\n\n<p>I'd suggest extracting these numbers to constants to explain what they are.</p></li>\n<li><p>The <code>Ball</code> class seems unnecessarily tightly coupled to <code>Container</code>. It also is coupled to <code>Graphics</code> in the <code>draw</code> method. It feels like that is not a responsibility of <code>Ball</code>. </p></li>\n<li><p>There are lots of instance variables at the top-level <code>BouncingBalls</code> class; many of them, such as <code>red</code> and <code>blue</code> are only used in Ball, so I'd suggest moving them there.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:22:55.340", "Id": "31536", "ParentId": "31434", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T16:20:18.027", "Id": "31434", "Score": "1", "Tags": [ "java", "multithreading" ], "Title": "Bouncing ball program" }
31434
<p>I have written Java code that finds the frequency of the occurrence of a word in a sentence. It is working fine. The only thing I want to do is to optimize this code.</p> <pre><code>String str = "I am a Boy I am a"; String[] splitStr = str.split(" "); int count = 0; List&lt;String&gt; list = new ArrayList&lt;&gt;(); for(String s:splitStr){ if(!list.contains(s)){ list.add(s); } } for(int i=0;i&lt;list.size();i++){ for(int j=0;j&lt;splitStr.length;j++){ if(list.get(i).equals(splitStr[j])){ count++; } } System.out.println("Occurrence of " + list.get(i) + " is " + count + " times."); count=0; } </code></pre>
[]
[ { "body": "<p>You can simplify your code to a great extent by using a <code>Map&lt;String, Integer&gt;</code> instead of <code>List&lt;String&gt;</code>. The map would store the mapping from each word to it's count in the array. </p>\n\n<p>You can modify your code like so:</p>\n\n<pre><code>String str = \"I am a Boy I am a\";\nString[] splitStr = str.split(\" \");\n\nMap&lt;String, Integer&gt; wordCount = new HashMap&lt;&gt;();\nfor (String word: splitStr) {\n if (wordCount.containsKey(word)) {\n // Map already contains the word key. Just increment it's count by 1\n wordCount.put(word, wordCount.get(word) + 1);\n } else {\n // Map doesn't have mapping for word. Add one with count = 1\n wordCount.put(word, 1);\n }\n}\n</code></pre>\n\n<p>And then simply iterate over the map, and print the key: value pair:</p>\n\n<pre><code>for (Entry&lt;String, Integer&gt; entry: map.entrySet()) {\n System.out.println(\"Count of : \" + entry.getKey() + \n \" in sentence = \" + entry.getValue());\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T17:52:17.293", "Id": "50091", "Score": "1", "body": "Consider using `TreeMap` to get your output in alphabetical rather than an arbitrary order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T17:53:44.460", "Id": "50092", "Score": "0", "body": "@200_success. Of course if that is the requirement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T17:47:26.270", "Id": "31441", "ParentId": "31440", "Score": "9" } } ]
{ "AcceptedAnswerId": "31441", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T17:40:17.820", "Id": "31440", "Score": "6", "Tags": [ "java", "optimization", "strings" ], "Title": "Occurrence of a word in a sentence" }
31440
<p>I've just written my first angularjs directive, and I was hoping to get some feedback. I already have two doubts myself.</p> <ul> <li>Why is it that I must use <code>tElement.append()</code> to append the canvas element? <code>tElement.html()</code> doesn't work, at all. That just returns <code>[[object HTMLCanvasElement]]</code> in plain text inside of the element.</li> <li>Should I be accessing <code>canvasElement[0]</code>? It feels wrong, but it might not be.</li> </ul> <p>Here's the code:</p> <pre class="lang-js prettyprint-override"><code>angular.module('yupDraw', []) .directive('yupCanvas', function factory() { // Create elements (templates) in vars here var canvasTemplate = '&lt;canvas&gt;&lt;/canvas&gt;'; return { restrict: 'E', compile: function compile(tElement, tAttrs, transclude) { var canvasElement = angular.element(canvasTemplate); tElement.append(canvasElement); return function link(scope, element, attrs) { var canvas = new fabric.Canvas(canvasElement[0], { isDrawingMode: true }); } } }; }); </code></pre> <p>And I'm simply calling the directive like so: <code>&lt;yup-canvas&gt;&lt;/yup-canvas&gt;</code></p> <p>Fire away! :)</p>
[]
[ { "body": "<p>Angular includes a tiny subset of jQuery called <code>jqLite</code> which is what you get with <code>angular.element</code>. The <code>html()</code> <a href=\"https://github.com/angular/angular.js/blob/v1.2.0-rc.3/src/jqLite.js#L523\" rel=\"nofollow\">method</a> on it specifically only accepts a string, not an array of jqLite objects like jQuery normally does I think (unless it's a bug).</p>\n\n<p>One solution would be to use jquery. If you include jquery before angular, angular will use your jquery instead of the embedded jqlite. Swap the script tags in <a href=\"http://jsfiddle.net/uCwCd/\" rel=\"nofollow\"><strong><em>this fiddle</em></strong></a> to see it toggle between working and not.</p>\n\n<p>Another solution would be to use the outerHTML of your canvas element's html node like in <a href=\"http://jsfiddle.net/JBnXP/\" rel=\"nofollow\"><strong><em>this fiddle</em></strong></a>:</p>\n\n<pre><code>tElement.html(canvasElement[0].outerHTML);\n</code></pre>\n\n<p>I think using canvasElement[0] is fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T21:58:21.820", "Id": "33418", "ParentId": "31444", "Score": "3" } }, { "body": "<p>I never used <code>compile:</code> so I am not sure what you use it for but.. I think there is a template property in directives and you can easily access the canvas with <code>.children[0]</code></p>\n\n<pre><code>app.directive('yupCanvas', function factory() {\n\n return {\n\n restrict: 'E',\n template: '&lt;canvas&gt;&lt;/canvas&gt;',\n link: function(scope, element, attrs) {\n var canvas = new fabric.Canvas(element.children[0], {\n isDrawingMode: true\n });\n\n }\n };\n});\n</code></pre>\n\n<p>Maybe I am not understanding what you are trying to do though...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-05T21:59:54.460", "Id": "43557", "ParentId": "31444", "Score": "1" } } ]
{ "AcceptedAnswerId": "33418", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T19:08:10.420", "Id": "31444", "Score": "3", "Tags": [ "javascript", "angular.js" ], "Title": "First angularjs directive" }
31444
<p>I'm new to Go, and as a learning project I've been implementing RC4, attempting to follow pseudo-code in the <a href="http://en.wikipedia.org/wiki/RC4" rel="nofollow">Wikipedia</a> <a href="http://web.archive.org/web/20080404222417/http://cypherpunks.venona.com/date/1994/09/msg00304.html" rel="nofollow">links</a> (and trying not to look at the far-superior version in the <a href="http://golang.org/pkg/crypto/rc4/" rel="nofollow">crypto</a> package).</p> <p>Some questions:</p> <ul> <li>Wikipedia suggests computing new array indexes using mod 256 at several points throughout the implementation. However, mod 256 results in index out of bound errors or "constant 256 overflows byte". What am I missing?</li> <li>The crypto package returns a custom "Cipher" type, which has the rc4 function implemented on it. Is this idiomatic Go (returning an objecty type) or something specific for the rc4 implementation?</li> <li>any suggestions to improve clarity/speed/accuracy?</li> </ul> <p>Source:</p> <pre><code>package main import "fmt" func ksa(keystring string) ([256]byte) { var key = []byte(keystring) var s [256]byte var j byte for i := 0; i &lt; 255; i++ { s[i] = byte(i) } for i := 0; i &lt; 255; i++ { j = (j + s[byte(i)] + key[i % len(key)]) % 255 s[j], s[i] = s[i], s[j] } return s } func rc4(bufferstring string, key [256]byte) ([]byte) { buffer := []byte(bufferstring) res := make([]byte, len(buffer)) var x, y, k, r byte = 0, 0, 0, 0 for i, b := range(buffer) { x = (x + 1) % 255 y = (y + key[x] % 255) y, x = x, y k = key[(key[x] + key[y]) % 255] r = b ^ k fmt.Printf("i: %d, b: %c, x: %#X, y: %#X, k: %#X, r: %#X \n", i, b, x, y, k, r) res[i] = r } return res } func main() { keystring := "Secret" plaintext := "Attack at dawn" key := ksa(keystring) encrypted := rc4(plaintext, key) unencrypted := rc4(string(encrypted), key) fmt.Println("Encrypted") fmt.Printf("hex: %#X\n", string(encrypted)) fmt.Printf("string: %s\n", string(encrypted)) fmt.Println("Un-Encrypted") fmt.Printf("hex: %#X\n", string(unencrypted)) fmt.Printf("string: %s\n", string(unencrypted)) } </code></pre>
[]
[ { "body": "<p>Here is a simple translation of the Wikipedia RC4 key-scheduling algorithm (KSA) and pseudo-random generation algorithm (PRGA) into Go.</p>\n\n<pre><code>package main\n\nimport \"fmt\"\n\n// Key-scheduling algorithm (KSA)\nfunc ksa(key []byte) []byte {\n s := make([]byte, 256)\n for i := range s {\n s[i] = byte(i)\n }\n j := byte(0)\n for i := range s {\n j += s[i] + key[i%len(key)]\n s[i], s[j] = s[j], s[i]\n }\n return s\n}\n\n// Pseudo-random generation algorithm (PRGA)\nfunc prga(message, s []byte) []byte {\n text := make([]byte, len(message))\n i, j := byte(0), byte(0)\n for m := range message {\n i++\n j += s[i]\n s[i], s[j] = s[j], s[i]\n k := s[s[i]+s[j]]\n text[m] = message[m] ^ k\n }\n return text\n}\n\n// RC4 stream cipher\n// http://en.wikipedia.org/wiki/RC4\nfunc rc4(message, key []byte) []byte {\n return prga(message, ksa(key))\n}\n\nfunc main() {\n testRC4 := []struct {\n key, plain []byte\n }{\n {[]byte(\"Key\"), []byte(\"Plaintext\")},\n {[]byte(\"Wiki\"), []byte(\"pedia\")},\n {[]byte(\"Secret\"), []byte(\"Attack at dawn\")},\n }\n for _, test := range testRC4 {\n cipher := rc4(test.plain, test.key)\n fmt.Printf(\"%s\\n\", string(test.key))\n fmt.Printf(\"%s\\n\", string(test.plain))\n fmt.Printf(\"%X\\n\", cipher)\n fmt.Println(string(rc4(cipher, test.key)) == string(test.plain))\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Key\nPlaintext\nBBF316E8D940AF0AD3\ntrue\nWiki\npedia\n1021BF0420\ntrue\nSecret\nAttack at dawn\n45A01F645FC35B383552544B9BF5\ntrue\n</code></pre>\n\n<p><strong>References:</strong></p>\n\n<p><a href=\"http://golang.org/ref/spec\" rel=\"nofollow\">The Go Programming Language Specification</a></p>\n\n<p><a href=\"http://golang.org/ref/spec#Integer_overflow\" rel=\"nofollow\">Integer overflow</a></p>\n\n<p><a href=\"http://golang.org/ref/spec#Conversions\" rel=\"nofollow\">Conversions</a></p>\n\n<p><strong>Mod 256 error:</strong></p>\n\n<blockquote>\n <p><a href=\"http://golang.org/ref/spec#Constants\" rel=\"nofollow\">Constants</a></p>\n \n <p>There are boolean constants, rune constants, integer constants,\n floating-point constants, complex constants, and string constants.\n Character, integer, floating-point, and complex constants are\n collectively called numeric constants.</p>\n \n <p>A constant value is represented by a rune, integer, floating-point,\n imaginary, or string literal, an identifier denoting a constant, a\n constant expression, a conversion with a result that is a constant, or\n the result value of some built-in functions such as unsafe. The\n boolean truth values are represented by the predeclared constants <code>true</code>\n and <code>false</code>. The predeclared identifier <code>iota</code> denotes an integer\n constant.</p>\n \n <p>Numeric constants represent values of arbitrary precision and do not\n overflow.</p>\n \n <p>Constants may be typed or untyped. Literal constants, <code>true</code>, <code>false</code>,\n <code>iota</code>, and certain constant expressions containing only untyped\n constant operands are untyped.</p>\n \n <p>A constant may be given a type explicitly by a constant declaration or\n conversion, or implicitly when used in a variable declaration or an\n assignment or as an operand in an expression. It is an error if the\n constant value cannot be represented as a value of the respective\n type.</p>\n \n <p><a href=\"http://golang.org/ref/spec#Operators\" rel=\"nofollow\">Operators</a></p>\n \n <p>Operators combine operands into expressions.</p>\n\n<pre><code>Expression = UnaryExpr | Expression binary_op UnaryExpr .\nUnaryExpr = PrimaryExpr | unary_op UnaryExpr .\n\nbinary_op = \"||\" | \"&amp;&amp;\" | rel_op | add_op | mul_op .\nrel_op = \"==\" | \"!=\" | \"&lt;\" | \"&lt;=\" | \"&gt;\" | \"&gt;=\" .\nadd_op = \"+\" | \"-\" | \"|\" | \"^\" .\nmul_op = \"*\" | \"/\" | \"%\" | \"&lt;&lt;\" | \"&gt;&gt;\" | \"&amp;\" | \"&amp;^\" .\n\nunary_op = \"+\" | \"-\" | \"!\" | \"^\" | \"*\" | \"&amp;\" | \"&lt;-\" .\n</code></pre>\n \n <p>Comparisons are discussed elsewhere. For other binary operators, the\n operand types must be identical unless the operation involves shifts\n or untyped constants. For operations involving constants only, see the\n section on constant expressions.</p>\n \n <p>Except for shift operations, if one operand is an untyped constant and\n the other operand is not, the constant is converted to the type of the\n other operand.</p>\n</blockquote>\n\n<p>For example, the compile error \"constant 256 overflows byte\" can occur as follows:</p>\n\n<pre><code>b := byte(42)\n// constant 256 overflows byte\nm := b % 256\n</code></pre>\n\n<p>The integer literal <code>256</code> is an untyped numeric constant. In the expression <code>b % 256</code>, it takes the type (<code>byte</code>) of the other operand <code>b</code>. A <code>byte</code> is an eight-bit unsigned integer that can represent the integers 0 to 255. Therefore, it's an error that the constant value <code>256</code> cannot be represented as a value of type <code>byte</code>: \"constant 256 overflows byte.\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T17:57:50.247", "Id": "50575", "Score": "0", "body": "Thanks, any idea why mod 255 was failing in my case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T18:03:32.340", "Id": "50576", "Score": "0", "body": "Ahh just noticed your links" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T20:00:19.490", "Id": "50587", "Score": "0", "body": "I've revised my answer to include an explanation of the mod 256 error: \"constant 256 overflows byte.\" Mod 255 does not fail." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T12:37:53.337", "Id": "31683", "ParentId": "31446", "Score": "2" } } ]
{ "AcceptedAnswerId": "31683", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T21:47:17.420", "Id": "31446", "Score": "3", "Tags": [ "go", "cryptography" ], "Title": "RC4 implementation in Go" }
31446
<p>I am updating some old reports that are using <code>mysql_</code> statements and trying to use the MySQL PDO stuff. I was told that PDO is far better since I was running into runtime issues with some of my reports. My old report took 91 seconds to run, and my PDO version takes 106 seconds. While 15 seconds may not seem like a big deal, this report is dealing with 1 week's worth of data, and other reports deal with a month up to a year. Additionally, my <code>$cart_total</code> doesn't seem to work in the PDO version.</p> <p>I would appreciate any help optimizing my queries (though I think they are pretty solid), and my PHP/PDO code.</p> <pre><code>&lt;?php $start_time = time(); require_once('db_configuration.php'); $db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_username, $db_password, array(PDO::ATTR_EMULATE_PREPARES =&gt; false, PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION)); $key_query_raw = "SELECT configuration_key, configuration_value FROM configuration WHERE configuration_group_id = 6501 AND configuration_key IN('RCS_BASE_DAYS', 'RCS_EMAIL_TTL', 'RCS_SKIP_DAYS') ORDER BY configuration_key ASC;"; try { $key_query = $db-&gt;query($key_query_raw); } catch(PDOException $ex) { echo "An Error occured! &lt;br&gt;&lt;br&gt;" . $ex; } while($key = $key_query-&gt;fetch(PDO::FETCH_ASSOC)) { if ($key['configuration_key'] == 'RCS_BASE_DAYS') { $base_days = $key['configuration_value']; } elseif ($key['configuration_key'] == 'RCS_EMAIL_TTL') { $ttl_days = $key['configuration_value']; } elseif ($key['configuration_key'] == 'RCS_SKIP_DAYS') { $skip_days = $key['configuration_value']; } } $key_query-&gt;closeCursor(); $skip_date = date('Ymd',strtotime('-'.$skip_days.' day',time())); $base_date = date('Ymd',strtotime('-'.$base_days.' day',time())); $ttl_date = date('Ymd',strtotime('-'.$ttl_days.' day',time())); ?&gt; &lt;html&gt; &lt;style type="text/css"&gt; .row { padding-left:5px; padding-right:5px; border-style:solid; border-color:black; border-width:1px; border-width:0 0 1 0; } .header { background-color:#C8C8C8; text-align:left; font-weight:bold; padding-left:5px; padding-right:5px; border-style:solid; border-color:black; border-width:0 0 3 0; } &lt;/style&gt; &lt;head&gt; &lt;title&gt;Recover Cart Sales Test&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="reports.css" /&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;/head&gt; &lt;body&gt; &lt;table style="border-collapse:collapse;" width=100%&gt; &lt;tr&gt; &lt;td class="header"&gt;Contacted&lt;/td&gt; &lt;td class="header"&gt;Date&lt;/td&gt; &lt;td class="header"&gt;Customer Name&lt;/td&gt; &lt;td class="header" colspan=2&gt;Email&lt;/td&gt; &lt;td class="header"&gt;Phone&lt;/td&gt; &lt;td class="header"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="header"&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="header"&gt;Item&lt;/td&gt; &lt;td class="header" colspan=2&gt;Description&lt;/td&gt; &lt;td class="header" width=20&gt;Qty&lt;/td&gt; &lt;td class="header" width=20&gt;Price&lt;/td&gt; &lt;td class="header" width=20&gt;Total&lt;/td&gt; &lt;/tr&gt; &lt;? $customer_query_raw = "SELECT DISTINCT cb.customers_id, cb.customers_basket_date_added, c.customers_firstname, c.customers_lastname, c.customers_email_address, c.customers_telephone, sc.datemodified AS last_contacted FROM customers_basket cb INNER JOIN customers c ON c.customers_id = cb.customers_id LEFT JOIN scart sc ON cb.customers_id = sc.customers_id WHERE cb.customers_basket_date_added &lt; " . $skip_date . " AND cb.customers_basket_date_added &gt; " . $base_date . " AND cb.customers_id NOT IN (SELECT sc.customers_id FROM scart sc WHERE sc.datemodified &gt; " . $ttl_date . ") ORDER BY cb.customers_basket_date_added DESC;"; try { $customer_query = $db-&gt;query($customer_query_raw); } catch(PDOException $ex) { echo "An Error occured! &lt;br&gt;&lt;br&gt;" . $ex; } $customer_row_count = $customer_query-&gt;rowCount(); while($customer = $customer_query-&gt;fetch(PDO::FETCH_ASSOC)) { $product_query_raw = "SELECT cb.customers_id, cb.products_id, p.products_model, pd.products_name, cb.customers_basket_quantity, p.products_price, (p.products_price * cb.customers_basket_quantity) AS product_total FROM customers_basket cb, products p, products_description pd WHERE cb.customers_id = " . $customer['customers_id'] . " AND cb.products_id = pd.products_id AND p.products_id = pd.products_id"; try { $product_query = $db-&gt;query($product_query_raw); } catch(PDOException $ex) { echo "An Error occured! &lt;br&gt;&lt;br&gt;" . $ex; } $cart_total_query_raw = "SELECT SUM( p.products_price * cb.customers_basket_quantity ) AS cart_total FROM customers_basket cb, products p WHERE cb.customers_id = " . $customer['customers_id'] . " AND cb.products_id = p.products_id;"; try { $cart_total_query = $db-&gt;query($cart_total_query_raw); } catch(PDOException $ex) { echo "An Error occured! &lt;br&gt;&lt;br&gt;" . $ex; } $result = $cart_total_query-&gt;fetchAll(PDO::FETCH_ASSOC); $cart_total = $result['cart_total']; $cart_total_query-&gt;closeCursor(); $last_contacted = ($customer['last_contacted'] &lt; $ttl_date || $customer['last_contacted'] == NULL) ? 'Uncontacted' : date('Y-m-d', strtotime($customer['last_contacted'])); ?&gt; &lt;tr&gt; &lt;td class="row"&gt;&lt;?= $last_contacted; ?&gt;&lt;/td&gt; &lt;td class="row"&gt;&lt;?= date('Y-m-d', strtotime($customer['customers_basket_date_added'])); ?&gt;&lt;/td&gt; &lt;td class="row"&gt;&lt;?= $customer['customers_firstname'] . ' ' . $customer['customers_lastname']; ?&gt;&lt;/td&gt; &lt;td class="row" colspan=2&gt;&lt;?= $customer['customers_email_address']; ?&gt;&lt;/td&gt; &lt;td class="row"&gt;&lt;?= $customer['customers_telephone']; ?&gt;&lt;/td&gt; &lt;td class="row"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;? while($product = $product_query-&gt;fetch(PDO::FETCH_ASSOC)) { ?&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="row"&gt;&lt;?= $product['products_model']; ?&gt;&lt;/td&gt; &lt;td class="row" colspan=2&gt;&lt;?= $product['products_name']; ?&gt;&lt;/td&gt; &lt;td class="row" width=20&gt;&lt;?= $product['customers_basket_quantity']; ?&gt;x &lt;/td&gt; &lt;td class="row" width=20&gt;&lt;?= $product['products_price']; ?&gt;&lt;/td&gt; &lt;td class="row" width=20&gt;&lt;?= $product['product_total']; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;? } ?&gt; &lt;tr&gt; &lt;td colspan=7 style="font-weight:bold; text-align:right;"&gt;Cart Total: &lt;?= $cart_total; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;? $product_query-&gt;closeCursor(); } // End While $customer_query-&gt;closeCursor(); $db = NULL; ?&gt; &lt;/table&gt; &lt;br&gt;&lt;br&gt; &lt;? $end_time = time(); echo "Number of Records: " . $customer_row_count . "&lt;br&gt;"; echo "Start: " . $start_time . "&lt;br&gt;"; echo "End: " . $end_time . "&lt;br&gt;"; echo "Time Elapsed: " . ($end_time - $start_time); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T02:19:23.217", "Id": "50125", "Score": "0", "body": "Fixed my non-working $cart_total by using fetch vs fetchALL (not sure why I had fetchAll)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T08:56:29.527", "Id": "50153", "Score": "1", "body": "if speed is what you're after, forget about `PDO`, and go for `mysqli_*`. It's the fastest of the two. And don't forget the classic DNS bottleneck, in case you're passing the host-name as a string, and not IP... And don't, for the love of God do this: `catch(PDOException $ex) { echo \"An Error occured! <br><br>\" . $ex; }`. Not only is `$ex` an object, you're not stopping the rest of the script, it'll still continue to run as though the error _never_ occurred. That's just plain wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T11:07:46.227", "Id": "50159", "Score": "0", "body": "I also noticed you're using the short-tag quite a few times. Now this is probably down to the code being legacy and all that, but when mixing PHP in with markup the `<?` tag isn't a great idea. It never is, really, because `<?xml`<--: having short-tags enabled, enables PHP parsing on what, essentially, is XML" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T16:21:08.000", "Id": "50301", "Score": "0", "body": "@Elias Thank you for your comments, they were very useful. What would be a better approach for the error? For now, I want it to print the error on-screen for debugging. Once complete, it will write to a logfile (which I know how to do). I should probably use $ex->getMessage() vs just $ex though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-04T06:10:39.827", "Id": "250080", "Score": "0", "body": "I'd like to refer this question to my answer [here](http://codereview.stackexchange.com/questions/26581/mysql-vs-pdo-execution-time/26818#26818). Basically, PDO has some trouble resolving a hostname, so use the IP address of the server instead of 'localhost' or 'mydb.com', etc." } ]
[ { "body": "<p>If I were you, I would try to add some sort of index to your MySQL database for this fields:</p>\n\n<pre><code>cb.customers_basket_date_added\ncb.customers_id\n</code></pre>\n\n<p>when this is done I would make changes your SQL, something similar to this:</p>\n\n<pre><code>SELECT DISTINCT \n cb.customers_id, \n cb.customers_basket_date_added, \n c.customers_firstname, \n c.customers_lastname, \n c.customers_email_address, \n c.customers_telephone, \n sc.datemodified AS last_contacted\nFROM \n customers_basket cb \n INNER JOIN customers c ON c.customers_id = cb.customers_id\n LEFT JOIN scart sc ON cb.customers_id = sc.customers_id\nWHERE \n ( cb.customers_basket_date_added BETWEEN '{start-date}' AND '{end-date}' ) AND\n NOT EXISTS (\n SELECT \n sc.customers_id \n FROM \n scart sc \n WHERE\n sc.datemodified &gt; '{date-modified}' AND\n sc.{customerId-field} = cb.customers_id )\n ORDER BY \n cb.customers_basket_date_added DESC\n</code></pre>\n\n<p>I changed your <code>NOT IN</code> function to <code>NOT EXISTS</code>, and changed a lot more.</p>\n\n<p>Why are you using distinct and not group by function?</p>\n\n<p>when this SQL performs fast we can go to next step, the SQL inside your loop. </p>\n\n<p>Is it posible to make a SQL dump so that I can download it and help you out more?</p>\n\n<p>I think you have a big mistake in your 3rd block of SQL, maybe it can be done with only 1 SQL select and not 1 select * 2 select each loop run, this mean if you got 90 rows out you make 181 selects, I am sure that you can do it with less select statements being run against the SQL Server.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T16:26:17.587", "Id": "50302", "Score": "0", "body": "Thank you for your response, it was very useful. While I think I could ultimately combine the 'customer' query and the 'product' query, I could not figure out how to combine the 'cart total' query. Which is faster, performing a query that would return the 1 record with the SUM, or to add the products as I loop through them via PHP $cart_total =+ $cart_total + $product['product_total']" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T06:38:14.710", "Id": "31456", "ParentId": "31449", "Score": "1" } } ]
{ "AcceptedAnswerId": "31456", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T23:46:53.167", "Id": "31449", "Score": "1", "Tags": [ "php", "mysql", "pdo" ], "Title": "Optimize PHP and MySQL with PDO" }
31449
<p>This draws scanline of the image to <code>System.Drawing.Graphics</code>. It's quite simple and it's optimized in order to merge neigbour samples with the same color into single rectangle (instead of drawing sample-by-sample in 1x1 rectangles).</p> <p>I don't like the duplication of this code inside and outside the loop:</p> <pre><code>updateAlpha(brush, previousColor); graphics.FillRectangle(brush, previousIndex + positionX, y, i - previousIndex, 1); </code></pre> <p>Do you know the good way how to follow DRY principle here and to keep code easy to understand? Or this is a kind of perfectionism and all is already fine?</p> <pre><code>private static void drawGlyphRowToGraphics(int rowIndex, FT_Bitmap glyphBitmap, Graphics graphics, float positionX, float positionY, SolidBrush brush) { float y = rowIndex + positionY; byte previousColor = 0; int previousIndex = 0; for (int i = 0; i &lt; glyphBitmap.Width; ++i) { byte color = (byte)(255 - glyphBitmap.Buffer[i + rowIndex * glyphBitmap.Width]); if (i == 0) previousColor = color; if (color != previousColor) { updateAlpha(brush, previousColor); graphics.FillRectangle(brush, previousIndex + positionX, y, i - previousIndex, 1); previousColor = color; previousIndex = i; } } if (glyphBitmap.Width &gt; 0) { updateAlpha(brush, previousColor); graphics.FillRectangle(brush, previousIndex + positionX, y, glyphBitmap.Width - previousIndex, 1); } } private static void updateAlpha(SolidBrush brush, byte gray) { brush.Color = Color.FromArgb(255 - gray, brush.Color.R, brush.Color.G, brush.Color.B); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T02:43:17.160", "Id": "50128", "Score": "0", "body": "My first thought is to pull out updateAlpha and your FillRectangle methods into a method with a single parameter that would replace (i|glyphBitmap.Width) Then you could just call that single method. Granted it is still twice, but without putting your code into a test of mine I can't determine if I would break anything. Maybe you could consider using a do/while loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T00:27:17.043", "Id": "50255", "Score": "1", "body": "Simple extraction of common method for updateAlpha and FillRectangle was the first thought, but such method doesn't look well-designed. We should pass many different arguments there and also it has not single clean goal. So I'd rather prefer to refactor method to avoid calling these methods in two places." } ]
[ { "body": "<p>First off I have to say I found this code very hard to understand. It took me quite some time to finally understand what this code actually does.</p>\n\n<p>First off the function takes 6 arguments. That's way too many. Clearly the positionX and positionY should be combined into one Point object.</p>\n\n<p>But the larger problem is, that you seem to be working at the wrong level of abstraction. The function is supposed to deal with one single row of a FT_Bitmap, but because there is no abstraction of such a single row, it ends up dealing with the whole FT_Bitmap, doing confusing offset calculations all over the place.</p>\n\n<p>What I would do first, is to create a separate GlyphRow class:</p>\n\n<pre><code>public class GlyphRow\n{\n private FT_Bitmap bitmap;\n private int offset;\n\n public int Width;\n\n public GlyphRow(FT_Bitmap bitmap, int rowIndex)\n {\n this.bitmap = bitmap;\n this.offset = rowIndex * bitmap.Width;\n this.Width = bitmap.Width;\n }\n\n // Returns the transparency value of a point in position x of our row\n public byte Alpha(x)\n {\n return bitmap.Buffer[offset + x];\n }\n\n}\n</code></pre>\n\n<p>This will allow us to work with a single row at a time.</p>\n\n<p>Now our function can take just the following arguments:</p>\n\n<pre><code>private static void drawGlyphRowToGraphics(\n GlyphRow row, Graphics graphics, Point position, SolidBrush brush)\n</code></pre>\n\n<p>And when calling it, we initialize Point and GlyphRow objects:</p>\n\n<pre><code>GlyphRow row = new GlyphRow(glyphBitmap, rowIndex);\nPoint position = new Point(positionX, rowIndex + positionY);\ndrawGlyphRowToGraphics(row, graphics, position, brush);\n</code></pre>\n\n<p>Note that the <code>position</code> is now exactly the position where this <code>GlyphRow</code> should be painted, already offset with <code>rowIndex</code>.</p>\n\n<p>So here's the new simplified <code>drawGlyphRowToGraphics</code>:</p>\n\n<pre><code>private static void drawGlyphRowToGraphics(\n GlyphRow row, Graphics graphics, Point position, SolidBrush brush)\n{\n int i = 0;\n while (i &lt; row.Width)\n {\n int length = sameAlphaLength(row, i);\n brush.Color = cloneColorWithAlpha(brush.Color, row.Alpha(i));\n graphics.FillRectangle(brush, position.X + i, position.Y, length, 1);\n i += length;\n }\n}\n</code></pre>\n\n<p>I found the algorithm in original implementation very hard to grasp, so using divide-and-conquer strategy, I created a separate function to calculate the length of a section that has the same transparency value:</p>\n\n<pre><code>private static int sameAlphaLength(GlyphRow row, int start)\n{\n byte alpha = row.Alpha(start);\n int length = 1;\n while (start + length &lt; row.Width)\n {\n if (alpha != row.Alpha(start + length))\n {\n return length;\n }\n length++;\n }\n return length;\n}\n</code></pre>\n\n<p>In the original code, at first the gray value was calculated with <code>(255 - alpha)</code>, and then passed to <code>updateAlpha</code>, where it was again transformed with <code>(255 - gray)</code>. Pretty redundant IMHO. So I'm skipping this whole double-conversion. I also find it better to work with functions without side-effects, so I replaced <code>updateAlpha</code> with a function that creates a new color value from an existing one, which I can then assign to brush:</p>\n\n<pre><code>private static Color cloneColorWithAlpha(Color color, byte alpha)\n{\n return Color.FromArgb(alpha, color.R, color.G, color.B);\n}\n</code></pre>\n\n<p><strong>Disclaimer:</strong> I've never written a single line of C# before. It probably doesn't compile, not to mention other possible bugs. But hoping to get the general point across.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T16:01:02.890", "Id": "50212", "Score": "1", "body": "+1 for (working at the wrong level of) _abstraction_ and gathering all the bits into a `GlyphRow` _abstraction_. Abstracting fundamental problem-domain stuff seems to naturally [engender](http://dictionary.reference.com/browse/engender?s=t) object oriented goodness throughout the rest of the program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T00:22:46.837", "Id": "50253", "Score": "0", "body": "Thank you for perfect refactoring example. Wrong level of abstraction here is a very good point. I will check this suggestion, but in general it looks correct and should improve code clarity." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T11:47:19.227", "Id": "31473", "ParentId": "31450", "Score": "6" } } ]
{ "AcceptedAnswerId": "31473", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T00:18:27.800", "Id": "31450", "Score": "6", "Tags": [ "c#", "image" ], "Title": "Drawing scanline of an image" }
31450
<p>I'm developing a small craps game in C++, and my C++ skills are a bit rusty. I really need someone to review my code to ensure that I have correctly implemented the game according to the rules. </p> <p><strong>Game rules:</strong></p> <blockquote> <ol> <li>The player or shooter rolls a pair of standard dice <ol> <li>If the sum is 7 or 11 the game is won</li> <li>If the sum is 2, 3 or 12 the game is lost</li> <li>If the sum is any other value, this value is called the shooter’s point and he continues rolling until he rolls a 7 and loses or he rolls the point again in which case he wins</li> </ol></li> <li>If a game is won the shooter plays another game and continues playing until he loses a game, at which time the next player around the Craps table becomes the shooter</li> </ol> </blockquote> <p><strong>My code:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;ctime&gt; using namespace std; bool checkWinning(int roll); int main(int argc, const char * argv[]) { //create player aka shooter //create pair of dice unsigned int dice1=0; unsigned int dice2 = 0; //create roll unsigned int roll = 0; //create game loop while(checkWinning(roll) == true) { dice1 = rand() % 6 + 1; dice2 = rand() % 6 + 1; roll = dice1 + dice2; cout&lt;&lt; dice1&lt;&lt;" +"&lt;&lt; dice2&lt;&lt;" = "&lt;&lt; roll &lt;&lt; endl; //cout&lt;&lt; checkWinning(2) &lt;&lt;endl; } return 0; } bool checkWinning(int roll) { bool winner = true; if( roll == 2 || roll == 3 || roll == 12) return winner= false; else if(roll == 7 || roll == 11 ) return winner; else return winner; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T14:13:15.953", "Id": "50172", "Score": "2", "body": "The shooter loses his turn if a 7 is rolled after there is a point." } ]
[ { "body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try not to use <code>using namespace std</code></a>.</p></li>\n<li><p>The parameters in <code>main()</code> are only necessary if you're executing from the command line.</p></li>\n<li><p>You're not calling <a href=\"http://en.cppreference.com/w/cpp/numeric/random/srand\" rel=\"nofollow noreferrer\"><code>std::srand()</code></a> nor including <a href=\"http://en.cppreference.com/w/cpp/header/cstdlib\" rel=\"nofollow noreferrer\"><code>&lt;cstdlib&gt;</code></a>. However, if you're using C++11, both <code>std::srand</code> and <code>std::rand</code> are not recommended due to certain computational complications (the C++11 pseudo-random number generators can be found under <a href=\"http://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\"><code>&lt;random&gt;</code></a>). But, for a simple program, it may not matter.</p>\n\n<p>In general, here's how to call <code>std::srand()</code>:</p>\n\n<pre><code>// casting may just be necessary if warnings are generated\n// that will alert you if there's a possible loss of data\n// prefer nullptr to NULL if using C++11\nstd::srand(static_cast&lt;unsigned int&gt;(std::time(NULL)));\n</code></pre>\n\n<p><em>Only</em> include this <em>once</em>, preferably at the top of <code>main()</code>. This is preferred because</p>\n\n<ol>\n<li>It'll help you keep track of it, especially if it'll need to be removed at some point.</li>\n<li>If called repeatedly, you'll receive the \"same random number\" each time.</li>\n</ol></li>\n<li><p>It's best to keep variables as close in scope as possible. Here, <code>dice1</code> and <code>dice2</code> can be initialized in the <code>while</code>-loop:</p>\n\n<pre><code>unsigned int dice1 = rand() % 6 + 1;\nunsigned int dice2 = rand() % 6 + 1;\n</code></pre>\n\n<p><code>roll</code>, however, will need to stay where it is so that the loop will work.</p></li>\n<li><p>The <code>bool</code>-checking can be shortened:</p>\n\n<pre><code>// these are similar\nwhile (checkWinning(roll) == true)\nwhile (checkWinning(roll))\n</code></pre>\n\n<p></p>\n\n<pre><code>// these are also similar\nwhile (checkWinning(roll) == false)\nwhile (!checkWinning(roll))\n</code></pre></li>\n<li><p><code>checkWinning()</code> takes <code>int roll</code>, but <code>roll</code> is already <code>unsigned int</code>. They should match.</p></li>\n<li><p><code>checkWinning()</code>'s closing curly brace shouldn't have a <code>;</code>. It's not a type.</p></li>\n<li><p><code>bool winner</code> seems redundant; just return <code>true</code> or <code>false</code>. Also, the conditions seem a little unclear. If the sum constitutes a win or a re-roll, how do you specifically distinguish the two? They both return <code>true</code>. I'd at least rename the function for clarification. There's also a <a href=\"https://codereview.stackexchange.com/questions/11300/boolean-enums-improved-clarity-or-just-overkill\">Boolean enum</a>, but that <em>may</em> be overkill here (or even unnecessary as there are only two ending outcomes).</p></li>\n<li><p>There should be a final outcome message, indicating a win or a loss. Also, you're not giving the player the option to play another game if victorious (and until loss).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T05:42:21.613", "Id": "50131", "Score": "2", "body": "Good points, but two nit picks: The parameters to main have nothing to do with if you're *compiling* from the command line, but rather how you're *running* (creating) it. And for `if using C++11, use nullptr instead`... You should also mention that if you're using C++11, run the hell away from srand()/rand(). rand() has terrible range, is a pain in the ass to clamp to a range without bias, and a 32 bit seed limit is rather meh (half of `std::time()` gets truncated for example). Doesn't matter for a basic card game program, but CR brings out my inner pedant :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T05:43:43.713", "Id": "50132", "Score": "0", "body": "@Corbin: Good points. I'll put those in with my current edits." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T06:33:45.953", "Id": "50136", "Score": "0", "body": "@Corbin: Also, I had no idea about `std::srand()` in this case. I did happen to come across [`std::uniform_int_distribution`](http://www.cplusplus.com/reference/random/uniform_int_distribution/) not too long ago. Would this be a valid solution for here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T00:47:54.287", "Id": "50257", "Score": "2", "body": "Yeah. You would use a `std::uniform_int_distribution<int>(1, 6)` to achieve the same functionality as what he's done. A full (conviently dice oriented) example is here: http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T01:15:21.043", "Id": "50258", "Score": "1", "body": "@Corbin: Awesome! It appears to work with my old compiler, too. Looks like I can toss out `rand()` from my own stuff." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T05:16:54.957", "Id": "31452", "ParentId": "31451", "Score": "9" } }, { "body": "<p>In addition to what @Jamal said…</p>\n\n<p>The singular for \"dice\" is \"die\", so name your variables accordingly. It's C++, so Die deserves to be a class, with a <code>Die.roll()</code> method. The constructor could call <code>std::srand()</code>.</p>\n\n<p>You should use a do-while loop. Then you could avoid having to artificially initialize all of your values to illegal 0 values.</p>\n\n<p>Your <code>checkWinning()</code> function could just be a <code>switch</code> statement. It doesn't need a <code>winner</code> variable, and can just return the result immediately. I see where you implemented rules 1.1 and 1.2, but I don't see any of your other game rules expressed anywhere in your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T05:37:25.153", "Id": "31454", "ParentId": "31451", "Score": "4" } }, { "body": "<p>Using % with rand is wrong.</p>\n\n<p>Assuming your RAND_MAX is the same as mine <code>2147483647</code> then the probabilities for each number are:</p>\n\n<pre><code>dice1 = rand() % 6 + 1;\n\n1: 357913942/2147483647 Notice a slightly higher probability for a 1.\n2: 357913941/2147483647\n3: 357913941/2147483647\n4: 357913941/2147483647\n5: 357913941/2147483647\n6: 357913941/2147483647\n</code></pre>\n\n<p>The solution use <a href=\"https://stackoverflow.com/a/14009676/14065\">C++11 random</a> functionality.<br>\nCorrect for the skew in C++03's rand()</p>\n\n<p>Unfortunately I can't find a correct answer on SO for using rand().</p>\n\n<pre><code>int dieRoll() // return a number between 1 and 6\n{\n static int maxRange = RAND_MAX / 6 * 6; // note static so calculated once.\n\n int result;\n do\n {\n result = rand();\n }\n while(result &gt; maxRange); // Anything outside the range will skew the result\n return result % 6 + 1; // So throw away the answer and try again.\n}\n</code></pre>\n\n<p>Note:</p>\n\n<pre><code>int result = rand() * 1.0 / range; // does not help with distribution\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T15:22:22.650", "Id": "31499", "ParentId": "31451", "Score": "8" } } ]
{ "AcceptedAnswerId": "31452", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T04:54:46.500", "Id": "31451", "Score": "11", "Tags": [ "c++", "algorithm", "game", "random", "dice" ], "Title": "Craps game rules and code" }
31451
<p><code>get_item_count</code> calls to an API and gets a count. There are several pages to get this count from until there are no more results.</p> <p>How do I improve this code to remove all of the extra variables and make it easier to read?</p> <pre><code>final_count = 0 page = 1 final_count = individual_count = get_item_count(config, page) while individual_count &gt; 20 page = page + 1 individual_count = get_item_count(config,page) final_count = individual_count + final_count end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T05:54:37.423", "Id": "50133", "Score": "2", "body": "Do you want get_item_count() to be executed only once, that is, for page = 1 ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T07:36:01.317", "Id": "50146", "Score": "1", "body": "Yes I do. I would prefer to only call it in once but in a loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T09:31:52.270", "Id": "50156", "Score": "0", "body": "Yay, I almost forgot how is it to have a feeling that it can't be cleaned, but can't come with solution in less, than 5 minutes )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T19:33:23.933", "Id": "50229", "Score": "0", "body": "Within the loop you call get_items(), but I assume you mean get_item_count(). (?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T02:29:19.807", "Id": "50261", "Score": "0", "body": "I updated the question with the error." } ]
[ { "body": "<p>Cryptic but cool way with ruby 2.0 lazy enumerators :</p>\n\n<pre><code>(2..Float::INFINITY).lazy\n .map {|page| get_items(config, page) }\n .take_while {|count| count &gt; 20 }\n .reduce( get_item_count(config, 1), :+ )\n# =&gt; returns final count\n</code></pre>\n\n<p>if @toto2 is right and you really mean <code>get_item_count</code> inside the loop :</p>\n\n<pre><code>(1..Float::INFINITY).lazy\n .map {|page| get_item_count(config, page) }\n .take_while {|count| count &gt; 20 }\n .reduce( :+ )\n# =&gt; returns final count\n</code></pre>\n\n<p>(I don't have a ruby 2 env at hand now, so didn't try but it should work) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T08:30:24.103", "Id": "50267", "Score": "0", "body": "I thought about this, but the OP seems to want the last count greater than 20, so we'd need a take_while that takes the last value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T08:33:09.007", "Id": "50268", "Score": "0", "body": "oh, did not see that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T08:41:13.377", "Id": "50269", "Score": "0", "body": "dang. I wish `take_while` had an :inclusive option. Some guy suggested a `take_until` that would do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T09:05:23.873", "Id": "50273", "Score": "0", "body": ":-) In my answer I was to suggest exactly this, either have an option or a new method. But once you have to monkeypatch the solution loses glamour. I deleted my answer because of this very thing, I couldn't get the last value without making things a lot ugglier." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T20:59:22.510", "Id": "31508", "ParentId": "31453", "Score": "0" } }, { "body": "<p>Use a do-while loop, so the loop body gets always executed at least once:</p>\n\n<pre><code>final_count = 0\npage = 1\nbegin\n individual_count = get_item_count(config, page)\n final_count += individual_count\n page += 1\nend while individual_count &gt; 20\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T08:16:46.550", "Id": "50367", "Score": "0", "body": "+1, still ugly and verbose, but in imperative style that's as good as it gets." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T08:30:55.730", "Id": "31526", "ParentId": "31453", "Score": "2" } }, { "body": "<p>Another way to optimize is to keep the individual counts in an array and sum it up at the end.</p>\n\n<pre><code>count = []\nuntil count.any? {|c| c &lt;= 20 }\n count &lt;&lt; get_items(config, page)\nend\ncount.reduce(&amp;:+)\n# =&gt; returns full count\n</code></pre>\n\n<p>The whole array will be checked at each iteration. But this should not be a performance hit, especially when API communication is involved.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T10:20:32.487", "Id": "51139", "Score": "0", "body": "This wouldn't work as the `page` variable is nowhere incremented. Also, an array of counts would be better named `counts` not `count`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T16:32:15.020", "Id": "31625", "ParentId": "31453", "Score": "0" } }, { "body": "<pre><code>def final_count(config)\n fc = 0\n (1..1.0/0).each do |page|\n ic = get_item_count(config, page)\n fc += ic\n return fc if ic &gt; 20\n end\nend\n</code></pre>\n\n<p>Uncomfortable with <code>1.0/0</code>? Then use <code>Float::INFINITY</code>. (Edited to correct error spotted by @Rene. Thanks, @Rene.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T10:25:34.297", "Id": "51140", "Score": "0", "body": "The returned final count will be incorrect, as it doesn't take into account the number of items on the last page. And I'd say this solution is pushing too much towards a one-liner at the cost of readability - for example I find it weird to see a return statement inside the tertiary-operator." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T05:25:59.677", "Id": "32012", "ParentId": "31453", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T05:36:02.280", "Id": "31453", "Score": "6", "Tags": [ "ruby" ], "Title": "Get individual item count" }
31453
<p>Please help me optimize this bubble sort code. It's working fine otherwise.</p> <pre><code>int[] randomIntegers = {2,3,1,1,4,5,8,-2,0}; for(int i=0;i&lt;randomIntegers.length;i++){ for(int j=i;j&lt;(randomIntegers.length-1);j++){ if(randomIntegers[i]&gt;randomIntegers[j+1]){ randomIntegers[i] += randomIntegers[j+1]; randomIntegers[j+1] = randomIntegers[i] - randomIntegers[j+1]; randomIntegers[i] = randomIntegers[i] - randomIntegers[j+1]; } } } for(int i:randomIntegers){ System.out.print(i+","); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T12:52:57.563", "Id": "50162", "Score": "0", "body": "As pointed out by @Guffa, this is not bubble sort (see [wikipedia](http://en.wikipedia.org/wiki/Bubble_sort), or Guffa's answer). Also it is quite odd to swap the elements by adding and subtracting bits of them; they are usually swapped using some temporary variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T21:34:32.457", "Id": "60438", "Score": "0", "body": "Here's the best implementation of bubble sort I've ever seen. It's very fast and efficient. https://github.com/mirrors/linux-2.6/blob/b3a3a9c441e2c8f6b6760de9331023a7906a4ac6/drivers/media/common/saa7146/saa7146_hlp.c#L308" } ]
[ { "body": "<p>If you need to optimize bubble sort, you're doing it wrong. It's not really worth optimizing something that's inherently slow. You should just use a better sorting algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T08:59:38.197", "Id": "50154", "Score": "3", "body": "my sentiments exactly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:11:17.113", "Id": "50164", "Score": "2", "body": "You feel so strongly about bubble sort that you did not even read the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:42:53.443", "Id": "50170", "Score": "0", "body": "True :) Doesn't really make much difference if it's a selection sort or insertion sort instead. The first step in optimizing any code is to use a better algorithm." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T07:49:03.167", "Id": "31463", "ParentId": "31460", "Score": "12" } }, { "body": "<p>Well, first of all, that's not bubble sort at all.</p>\n\n<p>Here's bubble sort:</p>\n\n<pre><code>bool swapped = true;\nwhile (swapped) {\n swapped = false;\n for (int i = 0; i &lt; randomIntegers.length - 1; i++){\n if (randomIntegers[i] &gt; randomIntegers[i + 1]) {\n swapped = true;\n int temp = randomIntegers[i];\n randomIntegers[i] = randomIntegers[i + 1];\n randomIntegers[i + 1] = temp;\n }\n }\n}\n</code></pre>\n\n<p>Here's an improved version of bubble sort, where the items known to be sorted are excluded:</p>\n\n<pre><code>bool swapped = true;\nfor (int i = randomIntegers.length - 1; swapped &amp;&amp; i &gt;= 0; i--){\n swapped = false;\n for (int j = 0; j &lt; i; j++){\n if (randomIntegers[j] &gt; randomIntegers[j + 1]) {\n int temp = randomIntegers[j];\n randomIntegers[j] = randomIntegers[j + 1];\n randomIntegers[j + 1] = temp;\n }\n }\n}\n</code></pre>\n\n<p>On the subject of optimising the code that you have, whatever algorithm that is, you can let <code>j</code> loop from <code>i + 1</code> instead of <code>i</code>, so that you don't need to use <code>j + 1</code> everywhere. Also, use a temporary variable to swap the items:</p>\n\n<pre><code>for (int i = 0; i &lt; randomIntegers.length; i++) {\n for (int j = i + 1; j &lt; randomIntegers.length; j++) {\n if (randomIntegers[i] &gt; randomIntegers[j]) {\n int temp = randomIntegers[i];\n randomIntegers[i] = randomIntegers[j];\n randomIntegers[j] = temp;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T16:32:04.483", "Id": "50217", "Score": "0", "body": "Umair is using a variant of the [XOR swap](http://en.wikipedia.org/wiki/XOR_swap_algorithm#Variations) technique to swap values without using a local temporary variable. I could tolerate it if he actually used XOR, since it would be easier to recognize, but using the subtraction variation makes it cryptic, as evidenced by your confusion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T17:29:19.737", "Id": "50220", "Score": "0", "body": "@200_success: Yes, I regocnise it, and I'm not confused by it. (I actually suggested a variation of it in an SQL query a few days ago.) There is just no reason to use it here, using a local variable as temporary storage is shorter and more efficient." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T11:45:14.293", "Id": "31472", "ParentId": "31460", "Score": "7" } }, { "body": "<p>Your algorithm is nearly \"selection sort\" (see the <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm\" rel=\"nofollow\">wikipedia entry on sorting algorithms</a>). </p>\n\n<p>You could make it more efficient by doing the true selection sort: during the <code>j</code>-loop, you do not swap every time you find a value smaller than the <code>i</code>-value, but rather you just use the loop to find the minimal value to the right of the <code>i</code>-value and only after the <code>j</code>-loop is done do you swap, if needed.</p>\n\n<p>Also, for efficiency, you should just swap the values by using a temporary variable (see Guffa's code for example) instead adding and subtracting bits of the numbers in-place.</p>\n\n<p>But it would even better to implement the true bubble sort, or some inherently faster algorithm. Again, take a look at the wikipedia link.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:10:13.343", "Id": "31475", "ParentId": "31460", "Score": "1" } } ]
{ "AcceptedAnswerId": "31463", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-18T07:42:37.853", "Id": "31460", "Score": "1", "Tags": [ "java", "performance", "sorting" ], "Title": "Optimizing bubble sort code" }
31460
<p>What the code does is convert an image to a bitmap without having to create 3 arrays to make the conversion. It basically uses 1/3rd of the memory that it would normally use.</p> <p>I'm trying to refactor this method to make it shorter, less complex and more readable. So far, I've been unsuccessful in the 4 attempts I've made. Every time I try to extract something it says that there are ambiguous return statements.</p> <pre><code>private Bitmap decodeBitmapFromFile(File file, boolean preview) { byte[] byteArr = new byte[0]; byte[] buffer = new byte[1024]; int count = 0; int len; InputStream inputStream = null; try { inputStream = new FileInputStream(file); while ((len = inputStream.read(buffer)) &gt; -1) { if (len != 0) { if (count + len &gt; byteArr.length) { byte[] newBuf = new byte[(count + len) * 2]; System.arraycopy(byteArr, 0, newBuf, 0, count); byteArr = newBuf; } System.arraycopy(buffer, 0, byteArr, count, len); count += len; } } final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(byteArr, 0, count, options); options.inPurgeable = true; options.inInputShareable = true; options.inJustDecodeBounds = false; if (preview) { options.inSampleSize = getInSampleSize(); } options.inPreferredConfig = Bitmap.Config.ARGB_8888; return BitmapFactory.decodeByteArray(byteArr, 0, count, options); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (Exception e) { } } return null; } </code></pre>
[]
[ { "body": "<p>Half of the code deals with reading a file into a byte array, which is a very generic operation. Split the code into two functions, one accepting a file and another accepting a byte array. The former can call the latter.</p>\n\n<pre><code>private static Bitmap decodeBitmap(File file, boolean preview)\n throws IOException {\n // Read file fully into byteArr, then...\n return decodeBitmap(byteArr, preview);\n}\n\nprivate static Bitmap decodeBitmap(byte[] byteArr, boolean preview) {\n BitmapFactory.Options options = new BitmapFactory.Options();\n // etc.\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T09:12:55.117", "Id": "31464", "ParentId": "31462", "Score": "0" } }, { "body": "<p>A couple of thoughts.</p>\n\n<ol>\n<li>Always think about breaking your code into discrete units of work, this will make it more logical, more readable and importantly, more testable. In your case, separate out the reading of the data from the creation of the bitmap.</li>\n<li>The ambiguous return will either be because you are modifying multiple local properties (<code>count, len, buffer</code>) or because you return a new Bitmap or <code>null</code> from different points in your code. By needing to use <code>count</code> in your Bitmap creation you make it harder to refactor.</li>\n<li>If you are concerned about <code>0</code> length returns from <code>inputStream.read()</code> consider adding a handbrake to avoid infinite loops - I have never encountered this in real life though.</li>\n<li>Does your code perform better than using <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html\" rel=\"nofollow\"><code>ByteArrayOutputStream</code></a>, something like the below.</li>\n</ol>\n\n<p>Code:</p>\n\n<pre><code>//add throws or try/catch as suits your code.\n\nprivate byte[] readBitmapData() {\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n byte[] inputBuffer = new byte[16384]; //16K default buffer size\n int nRead;\n\n while ((nRead = is.read(inputBuffer, 0, data.length)) != -1) {\n buffer.write(inputBuffer, 0, nRead);\n }\n\n return buffer.toByteArray();\n}\n</code></pre>\n\n<p>You can check out the OpenJDK code for ByteArrayOutputStream on <a href=\"http://www.docjar.com/html/api/java/io/ByteArrayOutputStream.java.html\" rel=\"nofollow\">docjar</a>. Note their code for <code>grow</code> and <code>ensureCapacity</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T09:25:58.447", "Id": "31465", "ParentId": "31462", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T07:44:53.187", "Id": "31462", "Score": "1", "Tags": [ "java", "converting", "image" ], "Title": "Converting an image to a bitmap" }
31462
<p>I'm looking for remarks on pretty much anything. This has been my first project that's meant for use by others and I'd like to have it as clean as possible. I will post the main source code here but because of the size you might prefer reading it on <a href="https://github.com/Vannevelj/TVDBSharp">Github</a> instead.</p> <p>The code should be adequately documented so I don't think a lot of explanation is needed. The project itself is a wrapper for an API to translate XML requests and responses into simple C# objects.</p> <p>Any advice is welcome!</p> <p><strong>TVDB</strong></p> <pre><code>namespace TVDBSharp { /// &lt;summary&gt; /// The main class which will handle all user interaction. /// &lt;/summary&gt; public class TVDB { private readonly IDataProvider _dataProvider; /// &lt;summary&gt; /// Creates a new instance with the provided API key and dataProvider. /// &lt;/summary&gt; /// &lt;param name="apiKey"&gt;The API key provided by TVDB.&lt;/param&gt; /// &lt;param name="dataProvider"&gt;Specify your own &lt;see cref="IDataProvider"/&gt; instance.&lt;/param&gt; public TVDB(string apiKey, IDataProvider dataProvider) { _dataProvider = dataProvider; _dataProvider.ApiKey = apiKey; } /// &lt;summary&gt; /// Creates a new instance with the provided API key and standard &lt;see cref="IDataProvider"/&gt;. /// &lt;/summary&gt; /// &lt;param name="apiKey"&gt;The API key provided by TVDB.&lt;/param&gt; public TVDB(string apiKey) { _dataProvider = new DataProvider { ApiKey = apiKey }; } /// &lt;summary&gt; /// Search for a show in the database. /// &lt;/summary&gt; /// &lt;param name="query"&gt;Query that identifies the show.&lt;/param&gt; /// &lt;param name="results"&gt;Maximal amount of results in the returning set. Default is 5.&lt;/param&gt; /// &lt;returns&gt;Returns a list of shows.&lt;/returns&gt; public List&lt;Show&gt; Search(string query, int results = 5) { return new Builder(_dataProvider).Search(query, results); } /// &lt;summary&gt; /// Get a specific show based on its ID. /// &lt;/summary&gt; /// &lt;param name="showId"&gt;ID of the show.&lt;/param&gt; /// &lt;returns&gt;Returns the corresponding show.&lt;/returns&gt; public Show GetShow(string showId) { return new Builder(_dataProvider).BuildShow(showId); } } } </code></pre> <p><strong>Models.DAO.IDataProvider</strong></p> <pre><code>namespace TVDBSharp.Models.DAO { /// &lt;summary&gt; /// Defines a Dataprovider API. /// &lt;/summary&gt; public interface IDataProvider { /// &lt;summary&gt; /// The API key provided by TVDB. /// &lt;/summary&gt; string ApiKey { get; set; } /// &lt;summary&gt; /// Retrieves the show with the given id and returns the corresponding XML tree. /// &lt;/summary&gt; /// &lt;param name="showID"&gt;ID of the show you wish to lookup.&lt;/param&gt; /// &lt;returns&gt;Returns an XML tree of the show object.&lt;/returns&gt; XDocument GetShow(string showID); /// &lt;summary&gt; /// Returns an XML tree representing a search query for the given parameter. /// &lt;/summary&gt; /// &lt;param name="query"&gt;Query to perform the search with.&lt;/param&gt; /// &lt;returns&gt;Returns an XML tree of a search result.&lt;/returns&gt; XDocument Search(string query); } } </code></pre> <p><strong>Models.DAO.DataProvider</strong></p> <pre><code>namespace TVDBSharp.Models.DAO { /// &lt;summary&gt; /// Standard implementation of the &lt;see cref="IDataProvider"/&gt; interface. /// &lt;/summary&gt; public class DataProvider : IDataProvider { public string ApiKey { get; set; } public XDocument GetShow(string showID) { var web = new WebClient(); var response = web.DownloadString(new StringBuilder("http://thetvdb.com/api/").Append(ApiKey).Append("/series/").Append(showID).Append("/all/").ToString()); return XDocument.Parse(response); } public XDocument Search(string query) { var web = new WebClient(); var response = web.DownloadString(new StringBuilder("http://thetvdb.com/api/GetSeries.php?seriesname=").Append(query).ToString()); return XDocument.Parse(response); } } } </code></pre> <p><strong>Models.Builder</strong></p> <pre><code>namespace TVDBSharp.Models { /// &lt;summary&gt; /// Provides builder classes for complex entities. /// &lt;/summary&gt; public class Builder { private readonly IDataProvider _dataProvider; /// &lt;summary&gt; /// Initializes a new Builder object with the given &lt;see cref="IDataProvider"/&gt;. /// &lt;/summary&gt; /// &lt;param name="dataProvider"&gt;The DataProvider used to retrieve XML responses.&lt;/param&gt; public Builder(IDataProvider dataProvider) { _dataProvider = dataProvider; } /// &lt;summary&gt; /// Builds a show object from the given show ID. /// &lt;/summary&gt; /// &lt;param name="showID"&gt;ID of the show to serialize into a &lt;see cref="Show"/&gt; object.&lt;/param&gt; /// &lt;returns&gt;Returns the Show object.&lt;/returns&gt; public Show BuildShow(string showID) { var builder = new ShowBuilder(_dataProvider.GetShow(showID)); return builder.GetResult(); } /// &lt;summary&gt; /// Returns a list of &lt;see cref="Show"/&gt; objects that match the given query. /// &lt;/summary&gt; /// &lt;param name="query"&gt;Query the search is performed with.&lt;/param&gt; /// &lt;param name="results"&gt;Maximal amount of shows the resultset should return.&lt;/param&gt; /// &lt;returns&gt;Returns a list of show objects.&lt;/returns&gt; public List&lt;Show&gt; Search(string query, int results) { var shows = new List&lt;Show&gt;(results); var doc = _dataProvider.Search(query); foreach (var element in doc.Descendants("Series").Take(results)) { var id = element.GetXmlData("seriesid"); var response = _dataProvider.GetShow(id); shows.Add(new ShowBuilder(response).GetResult()); } return shows; } private class ShowBuilder { private Show _show; public ShowBuilder(XDocument doc) { _show = new Show(); _show.ID = doc.GetSeriesData("id"); _show.ImdbID = doc.GetSeriesData("IMDB_ID"); _show.Name = doc.GetSeriesData("SeriesName"); _show.Language = doc.GetSeriesData("Language"); _show.Network = doc.GetSeriesData("Network"); _show.Description = doc.GetSeriesData("Overview"); _show.Rating = string.IsNullOrWhiteSpace(doc.GetSeriesData("Rating")) ? (double?) null : Convert.ToDouble(doc.GetSeriesData("Rating"), System.Globalization.CultureInfo.InvariantCulture); _show.RatingCount = string.IsNullOrWhiteSpace(doc.GetSeriesData("RatingCount")) ? (int?) null : Convert.ToInt32(doc.GetSeriesData("RatingCount")); _show.Runtime = string.IsNullOrWhiteSpace(doc.GetSeriesData("Runtime")) ? (int?) null : Convert.ToInt32(doc.GetSeriesData("Runtime")); _show.Banner = doc.GetSeriesData("banner"); _show.Fanart = doc.GetSeriesData("fanart"); _show.LastUpdated = string.IsNullOrWhiteSpace(doc.GetSeriesData("lastupdated")) ? 0L : Convert.ToInt64(doc.GetSeriesData("lastupdated")); _show.Poster = doc.GetSeriesData("poster"); _show.Zap2ItID = doc.GetSeriesData("zap2it_id"); _show.FirstAired = Utils.ParseDate(doc.GetSeriesData("FirstAired")); _show.AirTime = string.IsNullOrWhiteSpace(doc.GetSeriesData("Airs_Time")) ? (TimeSpan?) null : Utils.ParseTime(doc.GetSeriesData("Airs_Time")); _show.AirDay = string.IsNullOrWhiteSpace(doc.GetSeriesData("Airs_DayOfWeek")) ? (DayOfWeek?) null : (DayOfWeek) Enum.Parse(typeof(DayOfWeek), doc.GetSeriesData("Airs_DayOfWeek")); _show.Status = string.IsNullOrWhiteSpace(doc.GetSeriesData("Status")) ? (Status?) null : (Status) Enum.Parse(typeof(Status), doc.GetSeriesData("Status")); _show.ContentRating = Utils.GetContentRating(doc.GetSeriesData("ContentRating")); _show.Genres = new List&lt;string&gt;(doc.GetSeriesData("Genre").Split('|')); _show.Actors = new List&lt;string&gt;(doc.GetSeriesData("Actors").Split('|')); _show.Episodes = new EpisodeBuilder(doc).BuildEpisodes(); } public Show GetResult() { return _show; } } private class EpisodeBuilder { private XDocument _doc; public EpisodeBuilder(XDocument doc) { _doc = doc; } public List&lt;Episode&gt; BuildEpisodes() { var result = new List&lt;Episode&gt;(); foreach (var episode in _doc.Descendants("Episode")) { var ep = new Episode { ID = episode.GetXmlData("id"), Title = episode.GetXmlData("EpisodeName"), Description = episode.GetXmlData("Overview"), EpisodeNumber = string.IsNullOrWhiteSpace(episode.GetXmlData("EpisodeNumber")) ? (int?) null : Convert.ToInt32(episode.GetXmlData("EpisodeNumber")), Director = episode.GetXmlData("Director"), FileName = episode.GetXmlData("filename"), FirstAired = string.IsNullOrWhiteSpace(episode.GetXmlData("FirstAired")) ? (DateTime?) null : Utils.ParseDate(episode.GetXmlData("FirstAired")), GuestStars = new List&lt;string&gt;(episode.GetXmlData("GuestStars").Split('|')), ImdbID = episode.GetXmlData("IMDB_ID"), Language = episode.GetXmlData("Language"), LastUpdated = string.IsNullOrWhiteSpace(episode.GetXmlData("lastupdated")) ? 0L : Convert.ToInt64(episode.GetXmlData("lastupdated")), Rating = string.IsNullOrWhiteSpace(episode.GetXmlData("Rating")) ? (double?) null : Convert.ToDouble(episode.GetXmlData("Rating"), System.Globalization.CultureInfo.InvariantCulture), RatingCount = string.IsNullOrWhiteSpace(episode.GetXmlData("RatingCount")) ? (int?) null : Convert.ToInt32(episode.GetXmlData("RatingCount")), SeasonID = episode.GetXmlData("seasonid"), SeasonNumber = string.IsNullOrWhiteSpace(episode.GetXmlData("SeasonNumber")) ? (int?) null : Convert.ToInt32(episode.GetXmlData("SeasonNumber")), SeriesID = episode.GetXmlData("seriesid"), ThumbHeight = string.IsNullOrWhiteSpace(episode.GetXmlData("thumb_height")) ? (int?) null : Convert.ToInt32(episode.GetXmlData("thumb_height")), ThumbWidth = string.IsNullOrWhiteSpace(episode.GetXmlData("thumb_width")) ? (int?) null : Convert.ToInt32(episode.GetXmlData("thumb_width")), TmsExport = episode.GetXmlData("tms_export"), Writers = new List&lt;string&gt;(episode.GetXmlData("Writer").Split('|')) }; result.Add(ep); } return result; } } } } </code></pre> <p><strong>Utilities.Extensions</strong></p> <pre><code>namespace TVDBSharp.Utilities { /// &lt;summary&gt; /// Extension methods used to simplify data extraction. /// &lt;/summary&gt; public static class Extensions { /// &lt;summary&gt; /// Retrieves a value from an XML tree representing a show. /// &lt;/summary&gt; /// &lt;param name="doc"&gt;XML tree representing a show.&lt;/param&gt; /// &lt;param name="element"&gt;Name of the element with the data.&lt;/param&gt; /// &lt;returns&gt;Returns the value corresponding to the given element name.&lt;/returns&gt; /// &lt;exception cref="XmlSchemaException"&gt;Thrown when the element doesn't exist or the XML tree is incorrect.&lt;/exception&gt; public static string GetSeriesData(this XDocument doc, string element) { var root = doc.Element("Data"); if (root != null) { var xElement = root.Element("Series"); if (xElement != null) { var result = xElement.Element(element); if (result != null) { return result.Value; } throw new XmlSchemaException("Could not find element &lt;" + element + "&gt;"); } throw new XmlSchemaException("Could not find element &lt;Series&gt;"); } throw new XmlSchemaException("Could not find element &lt;Data&gt;"); } /// &lt;summary&gt; /// Retrieves a value from an XML tree. /// &lt;/summary&gt; /// &lt;param name="xmlObject"&gt;The given XML (sub)tree.&lt;/param&gt; /// &lt;param name="element"&gt;Name of the element with the data.&lt;/param&gt; /// &lt;returns&gt;Returns the value corresponding to the given element name;&lt;/returns&gt; /// &lt;exception cref="XmlSchemaException"&gt;Thrown when the element doesn't exist.&lt;/exception&gt; public static string GetXmlData(this XElement xmlObject, string element) { var result = xmlObject.Element(element); if (result != null) { return result.Value; } throw new XmlSchemaException("Element &lt;" + element + "&gt; could not be found."); } } } </code></pre> <p><strong>Utilities.Utils</strong></p> <pre><code>namespace TVDBSharp.Utilities { /// &lt;summary&gt; /// Provides static utility methods. /// &lt;/summary&gt; public static class Utils { /// &lt;summary&gt; /// Parses a string of format yyyy-mm-dd to a &lt;see cref="DateTime"/&gt; object. /// &lt;/summary&gt; /// &lt;param name="value"&gt;String to be parsed.&lt;/param&gt; /// &lt;returns&gt;Returns a &lt;see cref="DateTime"/&gt; representation.&lt;/returns&gt; public static DateTime ParseDate(string value) { var date = value.Split('-'); return new DateTime(Convert.ToInt32(date[0]), Convert.ToInt32(date[1]), Convert.ToInt32(date[2])); } /// &lt;summary&gt; /// Parses a string of format hh:mm tt to a &lt;see cref="TimeSpan"/&gt; object. /// &lt;/summary&gt; /// &lt;param name="value"&gt;String to be parsed.&lt;/param&gt; /// &lt;returns&gt;Returns a &lt;see cref="TimeSpan"/&gt; representation.&lt;/returns&gt; public static TimeSpan ParseTime(string value) { var hour = Convert.ToInt32(value.Substring(0, value.IndexOf(':'))); var minute = Convert.ToInt32(value.Substring(value.IndexOf(':') + 1, 2)); var daypart = value.Substring(value.Length - 2); if (daypart == "PM") { hour += 12; } return new TimeSpan(hour, minute, 0); } /// &lt;summary&gt; /// Translates the incoming string to a &lt;see cref="ContentRating"/&gt; enum, if applicable. /// &lt;/summary&gt; /// &lt;param name="rating"&gt;The rating in string format.&lt;/param&gt; /// &lt;returns&gt;Returns the appropriate &lt;see cref="ContentRating"/&gt; value.&lt;/returns&gt; /// &lt;exception cref="ArgumentException"&gt;Throws an exception if no conversion could be applied.&lt;/exception&gt; public static ContentRating GetContentRating(string rating) { switch (rating) { case "TV-14": return ContentRating.TV14; case "TV-PG": return ContentRating.TVPG; case "TV-Y": return ContentRating.TVY; case "TV-Y7": return ContentRating.TVY7; case "TV-G": return ContentRating.TVG; case "TV-MA": return ContentRating.TVMA; default: return ContentRating.Unknown; } } } } </code></pre> <p>If you've made it this far, here is the entire test setup to review as well!</p> <p><strong>Models.Conversion</strong></p> <pre><code>namespace Tests.Models { /// &lt;summary&gt; /// A helper class to translate an object to its XML value and vice versa. /// &lt;/summary&gt; public class Conversion { /// &lt;summary&gt; /// The XML representation for either an element tag or a value. /// &lt;/summary&gt; public string XmlValue { get; set; } /// &lt;summary&gt; /// The object representation for either a property or a value. /// &lt;/summary&gt; public string ObjValue { get; set; } /// &lt;summary&gt; /// Constructs a new object with the given values. /// &lt;/summary&gt; /// &lt;param name="xmlValue"&gt;XML Value (see &lt;see cref="XmlValue"/&gt;).&lt;/param&gt; /// &lt;param name="objValue"&gt;Object Value (see &lt;see cref="ObjValue"/&gt;).&lt;/param&gt; public Conversion(string xmlValue, string objValue) { XmlValue = xmlValue; ObjValue = objValue; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Conversion) obj); } protected bool Equals(Conversion other) { return string.Equals(XmlValue, other.XmlValue) &amp;&amp; string.Equals(ObjValue, other.ObjValue); } public override int GetHashCode() { unchecked { return ((XmlValue != null ? XmlValue.GetHashCode() : 0) * 397) ^ (ObjValue != null ? ObjValue.GetHashCode() : 0); } } } } </code></pre> <p><strong>Models.Data</strong></p> <pre><code>namespace Tests.Models { /// &lt;summary&gt; /// Simulation of the real XML tree. /// &lt;/summary&gt; [XmlRoot("Data")] public class Data { /// &lt;summary&gt; /// The XML tree's show object. /// &lt;/summary&gt; [XmlElement("Series")] public TestShow TestShow { get; set; } } } </code></pre> <p><strong>TestDataProvider</strong></p> <pre><code>namespace Tests { /// &lt;summary&gt; /// Dataprovider used for testing. This class generates XML trees to be used for parsing tests. /// &lt;/summary&gt; public class TestDataProvider : IDataProvider { private readonly TestData _data; public string ApiKey { get; set; } /// &lt;summary&gt; /// Initializes a new instance with the provided testing data. /// &lt;/summary&gt; /// &lt;param name="data"&gt;Mocking data of type &lt;see cref="TestData"/&gt;.&lt;/param&gt; public TestDataProvider(TestData data) { _data = data; } public XDocument GetShow(string showID) { var showData = _data.GetShowData(); var episodeData = _data.GetEpisodeData(); var show = new Data { TestShow = new TestShow() }; // Dynamically create the show object foreach (var key in showData.Keys) { var prop = show.TestShow.GetType().GetProperty(key.XmlValue); prop.SetValue(show.TestShow, showData[key].XmlValue, null); } // Add episodes to the show object show.TestShow.Episodes = new List&lt;TestEpisode&gt;(); foreach (var ep in episodeData) { var newEpisode = new TestEpisode(); foreach (var key in ep.Keys) { var prop = newEpisode.GetType().GetProperty(key.XmlValue); prop.SetValue(newEpisode, ep[key].XmlValue, null); } show.TestShow.Episodes.Add(newEpisode); } // Pull the created object trough an XML serializer var serializer = new XmlSerializer(show.GetType()); string xml; using (var writer = new StringWriter()) { serializer.Serialize(writer, show); xml = writer.ToString(); } return XDocument.Parse(xml); } public XDocument Search(string query) { throw new NotImplementedException(); } } } </code></pre> <p><strong>MainTests</strong></p> <pre><code>namespace Tests { /// &lt;summary&gt; /// A collection of the most important tests which test the complete workflow excluding connecting to the web service. /// &lt;/summary&gt; [TestClass] public class MainTests { private TestData _data; private IDataProvider _dataProvider; /// &lt;summary&gt; /// Initializes the test with mock data. See &lt;see cref="TestData"/&gt; for more information. /// &lt;/summary&gt; [TestInitialize] public void Initialize() { _data = new TestData(); _dataProvider = new TestDataProvider(_data); } /// &lt;summary&gt; /// Test the retrieval of a show. A &lt;see cref="TestShow"/&gt; object is created /// to accurately represent the XML tree of a show. /// /// Afterwards the &lt;see cref="TVDBSharp.Models.Builder"/&gt; is called /// to parse this into a &lt;see cref="TVDBSharp.Models.Show"/&gt; object. /// /// This process includes creating &lt;see cref="TVDBSharp.Models.Episode"/&gt; objects. /// Finally every property is being tested to have the expected outcome a /// as detailed in &lt;see cref="TestData"/&gt;. /// &lt;/summary&gt; [TestMethod] public void GetShow() { // Pull XML tree trough the show builder var builder = new Builder(_dataProvider); var result = builder.BuildShow(_data.GetShowData().Keys.FirstOrDefault(x =&gt; x.XmlValue == "id").XmlValue); var showData = _data.GetShowData(); var episodeData = _data.GetEpisodeData(); // Assert equality between value conversions for show data foreach (var key in showData.Keys) { var prop = result.GetType().GetProperty(key.ObjValue); Assert.IsTrue(prop.GetValue(result).ToString() == showData[key].ObjValue, "!Show object! Property: " + prop.Name + " ;Actual object value: " + prop.GetValue(result) + " ;Expected value: " + showData[key].ObjValue); } // Assert equality between value conversion for episode data for (var i = 0; i &lt; result.Episodes.Count; i++) { var currentEpisode = result.Episodes[i]; var dic = episodeData[i]; foreach (var key in dic.Keys) { var prop = currentEpisode.GetType().GetProperty(key.ObjValue); // Checks whether or not we're dealing with a list // ToString() method on lists will not show the values and are therefore not suited for comparison // That's why we manually check the entries if (new List&lt;string&gt; { "Actors", "Genres", "GuestStars", "Writers" }.Contains(key.ObjValue)) { foreach (var entry in dic[key].XmlValue.Split('|')) { Assert.IsTrue(((List&lt;string&gt;) prop.GetValue(currentEpisode)).Contains(entry), "!List object! Property: " + prop.Name + " ;Actual object value: " + string.Join(", ", (List&lt;string&gt;) prop.GetValue(currentEpisode)) + ";Expected value: " + dic[key].XmlValue); } } var value = prop.GetValue(currentEpisode).ToString(); var expected = dic[key].ObjValue; Assert.IsTrue(value == expected, "!Episode object! Property: " + prop.Name + " ;Actual object value: " + prop.GetValue(currentEpisode) + " ;Expected value: " + dic[key].ObjValue); } } } } } </code></pre> <p>A few helper classes that are just property classes or encapsulate testing data are left out, you can view those on the github page.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T18:55:37.690", "Id": "50227", "Score": "3", "body": "IMO there's way too much comments, it really slows down the reading. Things like builders don't need comments or even your unit tests. They should be straightforward enough so the code can speak for itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T19:27:50.327", "Id": "50228", "Score": "1", "body": "@Pierre-LucPineault: the XML comments are there for intellisense usage by external developers. Surely that's a good reason, no? The unit test was pretty complex which is why I added comments to clarify it." } ]
[ { "body": "<p>Some minor stuff for now:</p>\n\n<ol>\n<li><p>Any specific reason to use <code>StringBuilder</code> rather than <code>string.Format()</code>? I personally find</p>\n\n<pre><code>string.Format(\"http://thetvdb.com/api/{0}/series/{1}/all/\", ApiKey, showID)\n</code></pre>\n\n<p>easier to read than</p>\n\n<pre><code>new StringBuilder(\"http://thetvdb.com/api/\").Append(ApiKey).Append(\"/series/\").Append(showID).Append(\"/all/\").ToString()\n</code></pre>\n\n<p>The structure of the resulting string is much easier to see with <code>string.Format</code> (and it's also less code).</p></li>\n<li><p>You do something like this fairly often:</p>\n\n<pre><code>string.IsNullOrWhiteSpace(doc.GetSeriesData(\"Runtime\"))\n ? (int?) null\n : Convert.ToInt32(doc.GetSeriesData(\"Runtime\"));\n</code></pre>\n\n<p>You could look at encapsulating this in an extension method like this</p>\n\n<pre><code>T GetSeriesData(this XDocument doc, string key, Func&lt;string, T&gt; converter);\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T13:27:02.500", "Id": "58775", "Score": "0", "body": "Again a very spot on answer! I'll accept it as well because I don't expect there to be any traction for this question anymore. Thank you for the time to look over these two programs!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T10:20:28.007", "Id": "36006", "ParentId": "31468", "Score": "6" } } ]
{ "AcceptedAnswerId": "36006", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T10:17:09.227", "Id": "31468", "Score": "6", "Tags": [ "c#", "unit-testing", "xml", "api" ], "Title": "API wrapper for translating XML requests and responses into objects" }
31468
<p>I have written this code to find second largest element in an array of random integers. If it needs to be optimized, then do comment on it. First of all I'm populating all the elements into the list which does not have any repeating value, then sorting, then in <code>list.size()-2</code> I have second largest element.</p> <p>This is one way of doing this:</p> <pre><code>int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9}; int max = Integer.MIN_VALUE; int secMax = Integer.MIN_VALUE; List&lt;Integer&gt; list = new ArrayList&lt;&gt;(); for(int i:randomIntegers) { if(!(list.contains(i))){ list.add(i); } } Collections.sort(list); System.out.println(list.get(list.size()-2)); </code></pre> <p>If you are not allowed to sort that list then you can do the following to find the second-largest element:</p> <pre><code>int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9}; int max = Integer.MIN_VALUE; int secMax = Integer.MIN_VALUE; List&lt;Integer&gt; list = new ArrayList&lt;&gt;(); for(int i:randomIntegers) { if(!(list.contains(i))){ list.add(i); } } for(int i:list) { if(max &lt; i) { secMax = max; max = i; } else if(secMax &lt; i){ secMax = i; } } System.out.println("Second Largest Number is :" + secMax); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T20:40:13.507", "Id": "50231", "Score": "1", "body": "Just for your information, if you want to generalise this, you can have a look at http://en.wikipedia.org/wiki/Selection_algorithm ." } ]
[ { "body": "<p>After sorting </p>\n\n<pre><code>int highestElementIndex = list.indexOf(Collections.max(list)); \nSystem.out.println(\"Second highest element is : \" + list.get(highestElementIndex - 1));\n</code></pre>\n\n<p>Without sorting I think your code is all right.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:36:52.827", "Id": "50168", "Score": "1", "body": "if you look at my code. i have also use same thing to the sorted list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T15:29:39.813", "Id": "50206", "Score": "0", "body": "@Umair sorry I didn't look closely. You are doing the same thing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:11:18.707", "Id": "31476", "ParentId": "31470", "Score": "0" } }, { "body": "<p><code>ArrayList</code> is not the right tool. Since <code>ArrayList</code> makes no attempt to arrange its elements, <code>ArrayList.contains(...)</code> is inefficient — it has to examine every previously added element to see whether it is present. Then, at the end, you still have to sort the entire list. If you're adding <em>n</em> numbers, and adding each number takes O(<em>n</em>) time, then your entire solution is O(<em>n</em><sup>2</sup>), which is horrible for such a simple problem.</p>\n\n<p>If you want to use a Java Collections data structure, why not use <code>SortedSet</code> instead? The advantages of <code>SortedSet</code> are:</p>\n\n<ul>\n<li>It maintains the order of elements as it adds them</li>\n<li>It automatically deduplicates (<code>TreeSet</code> does it in O(log <em>n</em>) time)</li>\n<li>You don't have to sort the elements again at the end</li>\n</ul>\n\n<p>Here's a solution (that works in O(<em>n</em> log <em>n</em>) time):</p>\n\n<pre><code>int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9 };\nSortedSet&lt;Integer&gt; set = new TreeSet&lt;Integer&gt;();\nfor (int i: randomIntegers) {\n set.add(i);\n}\n// Remove the maximum value; print the largest remaining item\nset.remove(set.last());\nSystem.out.println(set.last());\n</code></pre>\n\n<p>A more efficient and minimalist solution wouldn't use any data structure. You just keep track of the two largest numbers you have encountered as you walk along the input array. See this <a href=\"https://codereview.stackexchange.com/questions/31339\">related question</a>. That approach hardly uses any space and works in O(<em>n</em>) time, which is as good as it gets.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T20:33:14.460", "Id": "31506", "ParentId": "31470", "Score": "7" } }, { "body": "<p>The code is not complete. What will happen if the array is like this (9 and 8 are interchanged)?</p>\n\n<pre><code>int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 9, 8};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T01:59:21.023", "Id": "48096", "ParentId": "31470", "Score": "1" } }, { "body": "<p>TreeSet/SortedSet and Collections.sort essentially rely on ordering array and then use DS properties to obtain Second Largest / Second Smallest key.</p>\n\n<p>While same can be done using some of the recursive magic while carrying along Satellite data.</p>\n\n<p>Here is what implementation looks like : </p>\n\n<blockquote>\n <p>nlog(n) implementation.</p>\n</blockquote>\n\n<pre><code>public class Test {\n public static void main(String...args){\n int arr[] = new int[]{1,2,2,3,3,4,9,5, 100 , 101, 1, 2, 1000, 102, 2,2,2};\n System.out.println(getMax(arr, 0, 16));\n }\n\n public static Holder getMax(int[] arr, int start, int end){\n if (start == end)\n return new Holder(arr[start], Integer.MIN_VALUE);\n else {\n int mid = ( start + end ) / 2;\n Holder l = getMax(arr, start, mid);\n Holder r = getMax(arr, mid + 1, end);\n\n if (l.compareTo(r) &gt; 0 )\n return new Holder(l.high(), r.high() &gt; l.low() ? r.high() : l.low());\n else\n return new Holder(r.high(), l.high() &gt; r.low() ? l.high(): r.low());\n }\n }\n\n static class Holder implements Comparable&lt;Holder&gt; {\n private int low, high;\n public Holder(int r, int l){low = l; high = r;}\n\n public String toString(){\n return String.format(\"Max: %d, SecMax: %d\", high, low);\n }\n\n public int compareTo(Holder data){\n if (high == data.high)\n return 0;\n\n if (high &gt; data.high)\n return 1;\n else\n return -1;\n }\n\n public int high(){\n return high;\n }\n public int low(){\n return low;\n }\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-26T11:43:01.990", "Id": "55316", "ParentId": "31470", "Score": "1" } } ]
{ "AcceptedAnswerId": "31506", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T10:58:39.543", "Id": "31470", "Score": "3", "Tags": [ "java", "optimization", "array" ], "Title": "Find the second-largest number in an array of elements" }
31470
<p>At first it was like this:</p> <pre><code>public abstract class TicTacToeViewAbstract implements TicTacToeView { private final List&lt;OnCellClickListener&gt; onCellClickListeners; private boolean movesBlocked; private boolean gameFinished; private TicTacToeModel model; protected TicTacToeViewAbstract(TicTacToeModel model) { onCellClickListeners = new ArrayList&lt;OnCellClickListener&gt;(); gameFinished = false; movesBlocked = false; plugModel(model); } protected TicTacToeViewAbstract(TicTacToeModel model, TicTacToeViewAbstract toRestore) { this.onCellClickListeners = toRestore.onCellClickListeners; this.gameFinished = toRestore.gameFinished; this.movesBlocked = toRestore.movesBlocked; this.plugModel(model); toRestore.unplugModel(); } // other methods ... } </code></pre> <p>Then I tried to remove duplication in both constructors:</p> <pre><code>public abstract class TicTacToeViewAbstract implements TicTacToeView { private final List&lt;OnCellClickListener&gt; onCellClickListeners; private boolean gameFinished; private boolean movesBlocked; private TicTacToeModel model; private TicTacToeViewAbstract(List&lt;OnCellClickListener&gt; onCellClickListeners, boolean gameFinished, boolean movesBlocked, TicTacToeModel model) { this.onCellClickListeners = onCellClickListeners; this.gameFinished = gameFinished; this.movesBlocked = movesBlocked; this.plugModel(model); } protected TicTacToeViewAbstract(TicTacToeModel model) { this(new ArrayList&lt;OnCellClickListener&gt;(), false, false, model); } protected TicTacToeViewAbstract(TicTacToeModel model, TicTacToeViewAbstract toRestore) { this(toRestore.onCellClickListeners, toRestore.gameFinished, toRestore.movesBlocked, model); toRestore.unplugModel(); } // ... } </code></pre> <p>Which one looks better, and why?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T12:48:47.750", "Id": "50161", "Score": "2", "body": "I'm a bit puzzled why you would need to create a view based on a view. Since you pass toRestore in the constructor, I don't see why you need to also pass the model since I would guess it is already included in toRestore. I hope you are not recreating a new view every time there is a move." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T15:23:33.003", "Id": "50204", "Score": "0", "body": "This code is from Android application. In Android, every time when the screen orientation is changed - the current Activity is recreated.\nReally there is no need to pass model in the second constructor - thank you for the comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T15:45:54.150", "Id": "50211", "Score": "1", "body": "You should probably use more usual Android patterns then. When you change the orientation, the Activity is completely destroyed, so the previous View will have been destroyed too." } ]
[ { "body": "<p>I would vote for the second, i.e. the one with a basic constructor called by others.</p>\n\n<p>But what is important is how to decide. The criteria that come to mind are:</p>\n\n<ul>\n<li>what if you should refactor later?</li>\n<li>which is the most clear when using this class?</li>\n</ul>\n\n<p>In your case, you want to offer different constructors for different usages, with default values in some case.</p>\n\n<p>There are two types of refactoring impacting a constructor: </p>\n\n<ul>\n<li>fields change</li>\n<li>usage changes</li>\n</ul>\n\n<p><strong>Refactoring fields</strong></p>\n\n<p>If the fields change, then you do not have to update 2 (or more) constructors by hand. You first update the lowest level constructor. You can handle the default setting of this field once. If you use an argument and forget to update other constructors, the compiler will let you know.</p>\n\n<p>While if you picked the first option, you will notice you forgot to update all constructors at execution (or test if you have good tests) time.</p>\n\n<p><strong>Refactoring usage</strong></p>\n\n<p>If the usage change, you want to add a new constructor with different arguments. Then you will call another constructor, and all fields will be set since your constructors were correct at first implementation.</p>\n\n<p>Again, if you picked the first option, you would have to set the fields one by one, and there are chances you would not set a field correctly, the compiler would not help you on that.</p>\n\n<p><strong>Clarity</strong></p>\n\n<p>Now let's consider how clear it looks to a user. If you set correctly the visibility (as you did), no option is particularly preferable. Some javadoc would help though, so that the user does not need to open your file. But when reading your file, unless the javadoc is clear, the second option is more confusing, as one should read the whole code to figure what best to use, and what each constructor does, jumping to another method, ...</p>\n\n<p>There might be other criteria that I missed. But from a basic check, the second option seems easier to maintain and be clear enough if some documentation is added. But based on those two criteria, you might conclude differently (you might find clarity more important than later refactoring)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:01:31.230", "Id": "31474", "ParentId": "31471", "Score": "1" } }, { "body": "<p>Contrary to Vince, <strong>I would vote for the first version.</strong></p>\n\n<p>Guided from the principle of <strong>You Ain't Gonna Need It</strong>, I would argue that the duplication here is very minimal and eliminating it is not really worth the cost of losing the clarity.</p>\n\n<p>I would even say there's <strong>no real duplication</strong> here at all. No program logic is duplicated. It's only that both constructors know about these three fields and this one method. But they're constructors - one kind'a expects that they initialize these fields. And when they instead call some other method, then I'm a bit puzzled, as this goes against my expectations of what constructors do.</p>\n\n<p>In the second version there's this <strong>new constructor with 4 arguments</strong>, and that's too much for most methods. One needs to do spend additional mental effort to understand which arguments in here <code>(new ArrayList&lt;OnCellClickListener&gt;(), false, false, model)</code> map to which parameters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:24:23.937", "Id": "31480", "ParentId": "31471", "Score": "1" } } ]
{ "AcceptedAnswerId": "31480", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T11:24:42.573", "Id": "31471", "Score": "1", "Tags": [ "java", "comparative-review", "tic-tac-toe" ], "Title": "Multiple independent or layered constructors for TicTacToe?" }
31471
<p>I ran a sonar analysis on my code and it told me the cyclomatic complexity is too high (sonar's limit is ten branches).</p> <p>Here is my code:</p> <pre><code>public void myMethod(){ try{ // do something catch(SomeException e){ throw new WrappingException("issue when doing something " + e.getMessage(), e); } catch(AnotherException e){ throw new WrappingException("issue when doing something " + e.getMessage(), e); } // lots of other Exceptions } </code></pre> <p>Basically, I want to catch a large set of Exceptions, (maybe always processing the same behaviour). I read the question <a href="https://codereview.stackexchange.com/questions/12767/when-to-catch-a-general-exception">Catching multiple types of exceptions when writing JSON</a> but I don't use Java 7 (with which I could have all Exceptions in one catch statement) and I do not really want to catch ALL Exceptions, since I want my code to fail in a case I did not expect.</p> <p>Is there any alternative that would involve fewer branches?</p> <p>NOTE: What I want to achieve here is not to recover from any Exception, but to categorize the Exceptions. An upper layer is in charge of handling Exceptions, but for this purpose, Exceptions need to be properly categorized.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:28:30.283", "Id": "50166", "Score": "3", "body": "If the Exceptions that you are interested in catching share common super classes (but not as far up the ancestor stack as `Exception`) then you **could** catch the super class rather than each subclass. If they don't, is your method doing too much?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:34:59.937", "Id": "50167", "Score": "0", "body": "I call a constructor by reflection. That gives me already 6 Exceptions to catch. But I agree, I should maybe split the rest of my method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:39:39.427", "Id": "50169", "Score": "2", "body": "Shame it is Java 6, as if you look at what they added (fixed, was silly not to have this before) here http://docs.oracle.com/javase/7/docs/api/java/lang/ReflectiveOperationException.html that would have cut down your necessary catch blocks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:45:44.693", "Id": "50171", "Score": "0", "body": "ah indeed it's cool that they decided to use inheritance on Exceptions. Indeed, if we switch to Java 7, I'll update the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T08:59:57.410", "Id": "50272", "Score": "1", "body": "@JohnMark13 I found a way to split my method, it looks nicer now. Thanks, you can actually post your comments as an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-04T15:41:06.310", "Id": "51505", "Score": "0", "body": "What does `myMethod` throw in its signature?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T18:00:33.597", "Id": "52208", "Score": "0", "body": "@Duncan Jones nothing necessarily. in that case let's assume WrappingException is an unchecked exception." } ]
[ { "body": "<p>As JohnMark13 stated in the comments above, if the exceptions you want to catch share a common supertype (possibly besides the basic <code>Exception</code> class), then you could catch the supertype instead of all the subtypes. If you have created the <code>SomeException</code> and <code>AnotherException</code> classes yourself, then I strongly suggest that you make them extend a common custom exception type.</p>\n\n<p>Also, I think that since you <strong>rethrow</strong> the exceptions (or at least most of them), then catching the general <code>Exception</code> is OK. Or, you could first catch all <code>RuntimeException</code>s, rethrow them directly, and then check the rest and possibly throw your <code>WrappingException</code>. Consider this:</p>\n\n<pre><code>public void myMethod() {\n try {\n // do something\n }\n catch (RuntimeException e) {\n // We don't need to wrap these, so we just throw the same exception again\n throw e;\n }\n catch (YourCommonSuperException e) {\n throw new WrappingException(\"issue when doing something \" + e.getMessage(), e);\n }\n catch (Exception e) {\n // All other excpetions, such as `IOException` and stuff will be caught and wrapped and throwed here.\n throw new WrappingException(\"issue when doing something \" + e.getMessage(), e);\n }\n // No need for any other Exceptions\n}\n</code></pre>\n\n<p>Perhaps you get some extra cyclomatic complexity from the <code>// do something</code> part. If so, then you could split that part into multiple methods and possibly declaring to throw the exception from the method if needed so that it will get caught in this <code>myMethod()</code> (or catch within the method and throw some kind of <code>YourCommonSuperException</code>.</p>\n\n<p>Depending on the specific <code>// do something</code> part, you might want to overlook which kind of exceptions that are thrown there. If you throw them yourself, it might be possible to change to <code>IllegalArgumentException</code>, <code>IllegalStateException</code> (which both extend <code>RuntimeException</code>) or some exception that extends <code>YourCommonSuperException</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T14:23:14.110", "Id": "35534", "ParentId": "31477", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:18:12.020", "Id": "31477", "Score": "7", "Tags": [ "java", "exception-handling" ], "Title": "Reducing cyclomatic complexity" }
31477
<p>Originally I submitted a question here: <a href="https://codereview.stackexchange.com/questions/29807/better-approach-to-using-the-c-serialport-class">SerialPort class for a library</a></p> <p>I cleaned up my code a bit and rewrote a few things. I've had a number of problems along the way and I've still not gotten to test this class, but I'd like to ask if there's anything major I can do to improve it.</p> <pre><code>using System; using System.IO.Ports; using System.Text; using System.Threading; namespace SerialPortSharp { public sealed class SerialPortConn : IDisposable { private readonly SerialPort serialPort; private readonly string returnToken; private readonly string hookOpen; private readonly string hookClose; private bool disposed; public SerialPortConn( string comPort = "Com1", int baud = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One, string returnToken = "&gt; ", string hookOpen = "", string hookClose = "" ) { this.serialPort = new SerialPort(comPort, baud, parity, dataBits, stopBits) { ReadTimeout = 1000, RtsEnable = true, DtrEnable = true }; this.returnToken = returnToken; if (hookOpen == "") this.hookOpen = null; else this.hookOpen = hookOpen; if (hookClose == "") this.hookClose = null; else this.hookClose = hookClose; } public bool OpenConnection() { if (this.disposed) { throw new ObjectDisposedException(this.GetType().Name, "Cannot use a disposed object."); } try { this.serialPort.Open(); this.serialPort.DiscardInBuffer(); bool hooked = false; if (hookOpen != null) { hooked = this.Hook(); } else { hooked = true; } if (hooked) { return true; } else { return false; } } catch { return false; } } public bool CloseConnection() { if (this.disposed) { throw new ObjectDisposedException(this.GetType().Name, "Cannot use a disposed object."); } try { bool unhooked = false; if (hookClose != null) { unhooked = this.UnHook(); } else { unhooked = true; } if (unhooked) { Thread.Sleep(100); this.serialPort.ReadLine(); this.serialPort.DiscardInBuffer(); this.serialPort.Close(); this.serialPort.Dispose(); return true; } else { return false; } } catch { return false; } } public void Dispose() { if (this.disposed) { throw new ObjectDisposedException(this.GetType().Name, "Cannot dispose of a disposed object."); } var closed = this.CloseConnection(); if (closed) { this.disposed = true; } else { throw new Exception("Error! Could not close port!"); } } private bool Hook() { if (this.disposed) { throw new ObjectDisposedException(this.GetType().Name, "Cannot use a disposed object."); } try { this.serialPort.Write(hookOpen + "\r"); Thread.Sleep(100); this.serialPort.DiscardInBuffer(); return true; } catch { return false; } } private bool UnHook() { if (this.disposed) { throw new ObjectDisposedException(this.GetType().Name, "Cannot use a disposed object."); } try { this.serialPort.Write(hookClose + "\r"); Thread.Sleep(100); this.serialPort.DiscardInBuffer(); return true; } catch { return false; } } private string HookTest(string serialCommand) { if (this.disposed) { throw new ObjectDisposedException(this.GetType().Name, "Cannot use a disposed object."); } try { this.serialPort.Write(serialCommand + "\r"); Thread.Sleep(100); bool loop = true; string output = ""; while (loop) { output += this.serialPort.ReadExisting(); if (output.EndsWith(this.returnToken)) { break; } } return output; } catch (TimeoutException e) { throw new Exception("Connection failed. Read timed out."); } } public string WriteConnection(string serialCommand, bool isSafe = false) { if (this.disposed) { throw new ObjectDisposedException(this.GetType().Name, "Cannot use a disposed object."); } if (isSafe) { var output = this.HookTest(serialCommand); return output; } else { try { this.serialPort.Write(serialCommand + "\r"); Thread.Sleep(100); return this.serialPort.ReadExisting(); } catch (Exception e) { throw new Exception("Connection failed. Timed out."); } } } } } </code></pre> <p><del>As a note, a couple returned strings contain "#!". I want to return the entire exception instead of just returning false (signifying the write failed). I just added something that easily differentiates it from the default strings returned by reading whatever's returned by the SerialPort()</del></p> <p><strong>Edit:</strong> I tried to implement svick's recommendation and changed Open/CloseConnection to check if hook/unhook is successful.</p> <p><strong>EDIT 2:</strong> I've changed the code about lately. I finally freed up a device for testing purposes and it works. I tested 400+ queries and only gotten several errors related to a device quirk I had to work out in the commands I was submitting. I'd love to hear any further suggestions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T15:38:08.863", "Id": "50209", "Score": "1", "body": "“I want to return the entire exception” You really shouldn't do that. If you can't handle an exception, let it bubble up. In general `catch (Exception ex)` or just `catch` (with no exception specified) is a big code smell. You should always catch only the specific exceptions that you know how to handle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T16:23:18.263", "Id": "50215", "Score": "0", "body": "@svick I've made an edit. I'd like to clarify that the most common exception is a `TimeoutException` which occurs when the read fails out. These really shouldn't be fatal. I'm just returning the strings with an identifier so I can throw them in a log at this point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T16:27:49.357", "Id": "50216", "Score": "0", "body": "@svick So it's not that they're unhandled, I'm just expecting Timeouts so I catch them, spit them out as a string, and throw them in a log. Is that a bad idea?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T16:35:39.440", "Id": "50218", "Score": "1", "body": "I think so. It should be up to the method that calls `WriteConnection()` to decide what to do with normal output and what to do with an error, it shouldn't be up to `HookTest()`. A reasonable solution would be to catch the `TimeoutException` and then throw a new exception of some specific type, so that the caller doesn't need to know about implementation details." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T16:54:19.757", "Id": "50219", "Score": "0", "body": "@svick I tried editing the code to reflect what you recommended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T20:47:19.130", "Id": "50433", "Score": "0", "body": "Made another major edit. Quite a bit has changed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T16:16:39.467", "Id": "50937", "Score": "0", "body": "you can use virtual serial port emulators to test code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T16:23:55.407", "Id": "50940", "Score": "0", "body": "@ZachSmith I need to have another look at this with fresh eyes, but it seems a little overcomplicated. If I get time over the weekend, I'll write a little answer. I have some serial port code I have written in vb.. which is similar enough.. I don't have the energy to rewrite it into c# - what do u think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T16:25:55.793", "Id": "50941", "Score": "0", "body": "@ThinksALot I'd greatly appreciate that. I would like to note that a lot of the bulk comes from implementing IDisposable and the \"Hook\" methods just initialize the devices I work with. A command is required to put them in \"Remote\" mode so they'll listen for commands from the RS232 port." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T16:36:00.380", "Id": "50943", "Score": "0", "body": "@ZachSmith I have a hectic weekend.. if I haven't posted over the next 2 days ping me to remind me, if u still need some feedback" } ]
[ { "body": "<p>Not sure if still relevant, but here you go:</p>\n\n<ol>\n<li><p>Consider refactoring <code>if (this.disposed) { }</code> into a method like <code>ThrowIfDisposed()</code>. If you ever want to change the dispose method or add logging or whatnot then you have to change only one place. Code duplication should be avoided even for trivial things like that.</p></li>\n<li><p>You swallow exceptions in <code>Hook</code> and <code>Unhook</code> and return a <code>bool</code> which tells you nothing except that it went wrong. Same in <code>OpenConnection</code> and <code>CloseConnetion</code>. A lot of information is thrown away which will be useful for troubleshooting should the need arise. In general I would consider that a bad idea.</p></li>\n<li><p>Replace the magic constant <code>Thread.Sleep(100);</code> either with a <code>const</code> definition or even a setting you can tweak. If you make it a setting please make it a <code>TimeStamp</code> - I personally find all that code which scatters around <code>int</code>s with implicit units very annoying. I often have to look up what it means because it's not always that obvious - seconds, milliseconds, ..?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-07T08:39:25.233", "Id": "32368", "ParentId": "31483", "Score": "3" } }, { "body": "<h1>Usability / Testability</h1>\n\n<p>The problem of this class is it has a dependency on <code>SerialPort</code>. This is very hard to test. You'd either need a serial port or a USB-2-Serial-Converter. Also note that these converters react differently on connection issues than a serial port. </p>\n\n<p>The solution is to create an interface <code>IStreamResource</code> that provides all the methods you need.</p>\n\n<pre><code>public interface IStreamResource : IDisposable\n{\n void Open();\n void DiscardInBuffer();\n string ReadLine();\n void Write(string buffer);\n // ..\n}\n</code></pre>\n\n<p>You can create an adapter/bridge for <code>SerialPort</code>.</p>\n\n<pre><code>public class SerialPortAdapter : IStreamResource\n{\n public SerialPort Source { get; }\n public SerialPortAdapter(SerialPort source) =&gt; SerialPort = source; // check not null..\n\n // IStreamResource impl ..\n}\n</code></pre>\n\n<p>Havig done this, you could also make adapters for <code>TcpClient</code>, <code>UdpClient</code>, <code>UnitTestAdapter</code>, or any other stream resource.</p>\n\n<p>You could then change your class to use the interface.</p>\n\n<pre><code>public SerialPortConn(IStreamResource streamResource)\n{\n StreamResource = streamResource; // check not null ..\n}\n</code></pre>\n\n<p>You could allow for overloads for common stream resources.</p>\n\n<pre><code>public SerialPortConn(SerialPort serialPort)\n : this (new SerialPortAdapter(serialPort)\n{\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T19:55:01.117", "Id": "222824", "ParentId": "31483", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T14:16:49.923", "Id": "31483", "Score": "7", "Tags": [ "c#", "serial-port" ], "Title": "SerialPort C# Class" }
31483
<p>I wrote this small test, i would love to know if it's possible to achieve the same result in a more "efficient" way, before any moderator closes this question, it's not subjective because my defention of efficient here means less lines of code, and less memory usage.</p> <p>Here is a Demo : <a href="http://jsfiddle.net/YsjLp/" rel="nofollow">http://jsfiddle.net/YsjLp/</a></p> <p>and here is the JS code : </p> <pre><code>var position = 0; var divToEdit = document.getElementById('here'); function executeIt(){ setInterval(function(){moveIt()},300); } function moveIt(){ var textToInsert = ''; var textLength = 10; for (var i = 0; i &lt;= textLength; i++) { if(i == position){ textToInsert += '[-]'; }else{ textToInsert += '-'; } }; if(position == textLength){ position = 0; }else{ position += 1; } divToEdit.innerHTML = textToInsert; } executeIt(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T05:36:28.570", "Id": "50175", "Score": "0", "body": "Is there even a question here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T05:38:30.097", "Id": "50176", "Score": "0", "body": "@remyabel yes, the question is, could the above code be rewritten in a more efficient way, efficient defined in the question body." } ]
[ { "body": "<p>As you define efficient to be \"less lines of code\", here it is:</p>\n\n<pre><code>function moveIt(){\n var textToInsert = '';\n var textLength = 10;\n\n for (var i = 0; i &lt;= textLength; i++)\n textToInsert+= (i==position)?'[-]':'-';\n (position==textLength)?position=0:position++;\n divToEdit.innerHTML = textToInsert;\n}\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/YsjLp/3/\" rel=\"nofollow\">http://jsfiddle.net/YsjLp/3/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T21:07:09.360", "Id": "50177", "Score": "0", "body": "Fair enough, a good use of ternary operators, i would love to see both benchmarked, i'll check and see, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T05:54:56.300", "Id": "31486", "ParentId": "31485", "Score": "1" } } ]
{ "AcceptedAnswerId": "31486", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T05:30:49.530", "Id": "31485", "Score": "0", "Tags": [ "javascript" ], "Title": "Efficient text scroller" }
31485
<p>A serial port is a physical interface through which data is transferred (uni- or bidirectionally) one bit at a time. Largely superseded in the consumer market by USB, serial connections are still commonly used in many other specialist applications. Typical applications include scientific/medical instruments, industrial controllers and server diagnostics.</p> <p>More information at <a href="http://en.wikipedia.org/wiki/Serial_port" rel="nofollow">http://en.wikipedia.org/wiki/Serial_port</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T15:06:50.733", "Id": "31497", "Score": "0", "Tags": null, "Title": null }
31497
A serial port is a physical interface through which data is transferred (uni- or bidirectionally) one bit at a time. Largely superseded in the consumer market by USB, serial connections are still commonly used in many other specialist applications. Typical applications include scientific/medical instruments, industrial controllers and server diagnostics...
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T15:06:50.733", "Id": "31498", "Score": "0", "Tags": null, "Title": null }
31498
<p>I'm using Twitter Bootstrap's navbar. While testing different screen resolutions, I noticed that on lower resolutions, sometimes the submenu would get cut off by the right side of the page.</p> <p>In the code below, when a dropdown is opened, I'm getting the width of the dropdown menu and dropdown submenu, adding those together and checking them against the width of the window. If the width is greater than the window width, I add the class <code>pull-right</code> so the dropdown menu and/or dropdown submenu will extend to the left and not get cut off by the right side of the page.</p> <p>In this <a href="http://jsfiddle.net/Qu4WN/"><strong>jsFiddle</strong></a>, you can see what I'm talking about by increasing/decreasing the width of the <em>Results</em> section. When you increase the width of the Results section far enough, the submenu for 'Dropdown 2' will open to the right. When you decrease the size of the Results section enough that the submenu would get cut off, the 'pull-right' class is applied and it extends to the left.</p> <p>For the most part, this code is doing what it should, but does anyone have any suggestions on how to improve it?</p> <p><strong>JavaScript</strong></p> <pre><code>$('.dropdown-toggle').click(function() { var dropdownList = $('.dropdown-menu'); var dropdownOffset = $(this).offset(); var offsetLeft = dropdownOffset.left; var dropdownWidth = dropdownList.width(); var docWidth = $(window).width(); var subDropdown = $('.dropdown-menu').eq(1); var subDropdownWidth = subDropdown.width(); var isDropdownVisible = (offsetLeft + dropdownWidth &lt;= docWidth); var isSubDropdownVisible = (offsetLeft + dropdownWidth + subDropdownWidth &lt;= docWidth); if (!isDropdownVisible || !isSubDropdownVisible) { $('.dropdown-menu').addClass('pull-right'); } else { $('.dropdown-menu').removeClass('pull-right'); } }); </code></pre> <p>Please let me know if I need to better my explanation or if any other details are needed.</p>
[]
[ { "body": "<p>A couple things you can do:</p>\n\n<p>Use <code>.on()</code> to save a few function calls:</p>\n\n<pre><code>$('.dropdown-toggle').on('click', function() { ... });\n</code></pre>\n\n<p>You can also actually use the cache you save called <code>dropdownList</code>:</p>\n\n<pre><code>var subDropdown = dropdownList.eq(1);\n//...\ndropdownList.addClass('pull-right');\n//...\ndropdownList.removeClass('pull-right');\n</code></pre>\n\n<p>From what I can tell, this is only a problem on small width screens. I suggest you replace the <code>nav</code> bar with a <code>select</code> list when the screen is too small. You can use media-queries for this or even jQuery. You should just hide/show the <code>nav</code> and <code>dropdown</code> to suit your specific needs. I didn't include that part in the fiddle but something like this should do the trick:\n<a href=\"http://jsfiddle.net/bloqhead/Kq43X\" rel=\"nofollow\">jsfiddle.net/bloqhead/Kq43X</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T19:05:15.007", "Id": "50335", "Score": "0", "body": "thanks for taking a look at it and for the suggestion. Bootstrap does have similar functionality (and look) to the dropdown list when the screen width is less than a certain number of pixels (I don't remember the exact number). Before adding my code I noticed it because the page title in my last submenu is very long (can't shorten it either) so it actually needs to change direction at 1280x800 no matter what. Using .on() and cache seem good though. I'll leave this open for a day or so to see if anyone else chimes in with anything, if not I'll mark this as answer. Thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:46:57.453", "Id": "31555", "ParentId": "31501", "Score": "4" } }, { "body": "<p>I came across this post searching for a fix to a slightly different problem. I have long entries in a drop-down menu that get cut off on small screen sizes.\nI found that if I allow the content in the dropdown to wrap it automatically gets adjusted to the page width:</p>\n\n<pre><code>.dropdown-menu &gt; li &gt; a {\n white-space: normal;\n}\n</code></pre>\n\n<p>If you don't want it to wrap if there is enough space, add no-wrap back in with a media query. Because it is so simple I figured I leave this here for others, even though it does not directly apply to the cascading dropdown in your example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-19T05:39:45.207", "Id": "39580", "ParentId": "31501", "Score": "5" } }, { "body": "<p>Adding a little bit to what Jonny Sooter said. I would suggest to also use a little best practice where you don't call the reserved keyword \"var\" every time you create a variable.</p>\n\n<p>Like:</p>\n\n<pre><code>$('.dropdown-toggle').on(\"click\", function() {\n var dropdownList = $('.dropdown-menu'),\n dropdownOffset = $(this).offset(),\n offsetLeft = dropdownOffset.left,\n dropdownWidth = dropdownList.width(),\n docWidth = $(window).width(),\n\n subDropdown = dropdownList.eq(1),\n subDropdownWidth = subDropdown.width(),\n\n isDropdownVisible = (offsetLeft + dropdownWidth &lt;= docWidth),\n isSubDropdownVisible = (offsetLeft + dropdownWidth + subDropdownWidth &lt;= docWidth);\n\n if (!isDropdownVisible || !isSubDropdownVisible) {\n dropdownList.addClass('pull-right');\n } else {\n dropdownList.removeClass('pull-right');\n }\n});\n</code></pre>\n\n<p>Hope that helps.</p>\n\n<p>EDIT:</p>\n\n<p>As apparently someone did not like my answer for some reason... I'm going to explain why I said what I said.</p>\n\n<p>As I can see, the code is using a lot of \"var\"s to declare variables. The thing is, that you might not see a performance issue in the client in a few lines like in this case, but I assume that if the code was written this way, a lot more code could be written the same way, and if the question was \"how to improve it?\" not \"in specifically this _____ way how could I improve it\", my answer was according to performance (client side). We should always assume that the internet is as slow as it could be, the less info, the better.</p>\n\n<p>I have seen a lot of people debate on rather it actually helps or not, the thing is, it does help (maybe just a little, but it does), and this might even add up to a lot. The reason why; is because at the end, your code is downloaded to the client, the less bytes you have to download, the best. Even, a lot of minifiers do this (point is, if they do it for performance, why shouldn't we for our own code?)</p>\n\n<p>And I got the reference out of the book \"Secrets of the JavaScript Ninja\" written by: John Resig (creator of jQuery and lots more) and Bear Bibeault. I encourage you to read this book.</p>\n\n<p>Also: an older <a href=\"https://stackoverflow.com/questions/3781406/javascript-variable-definition-commas-vs-semicolons\">question</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T08:27:04.357", "Id": "45133", "ParentId": "31501", "Score": "1" } } ]
{ "AcceptedAnswerId": "31555", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T19:13:24.580", "Id": "31501", "Score": "7", "Tags": [ "javascript", "jquery" ], "Title": "Adjust bootstrap dropdown menu based on page width" }
31501
<p>I am using the DatabaseHelper class to execute SQL statements e.g. ExecuteDataReader, ExecuteDataTable etc. The signature for ExecuteReader is:</p> <pre class="lang-vb prettyprint-override"><code>Public Overloads Shared Function ExecuteReader(ByVal connectionString As String, _ ByVal commandType As CommandType, _ ByVal commandText As String, _ ByVal ParamArray commandParameters() As DbParameter) As DbDataReader </code></pre> <p>Therefore it is expecing some parameters. I have created the class below:</p> <pre class="lang-vb prettyprint-override"><code>Public Class clsParameterValues 'Implements IDisposable Private paramValues(0) As DbParameter Public Function AssignParameterValues(ByVal strParameterName As String, ByVal strParameterValue As String, ByVal intDatabaseType As Integer) As Integer Dim intArrayBound As Integer intArrayBound = UBound(paramValues) 'If intArrayBound &gt; 0 Then If paramValues(0) Is Nothing = False Then intArrayBound = intArrayBound + 1 ReDim Preserve paramValues(intArrayBound) End If If intDatabaseType = 1 Then paramValues(intArrayBound) = New SqlParameter(strParameterName, strParameterValue) ElseIf intDatabaseType = 2 Then paramValues(intArrayBound) = New OracleParameter(strParameterName, strParameterValue) 'paramValues(intArrayBound) = New OracleParameter(":" &amp; strParameterName, OracleType.Int32) 'paramValues(intArrayBound).Value = strParameterValue End If Return intArrayBound End Function Public Function AssignParameterValues(ByVal strParameterName As String, ByVal strParameterValue As Date, ByVal intDatabaseType As Integer) As Integer Dim intArrayBound As Integer intArrayBound = UBound(paramValues) 'If intArrayBound &gt; 0 Then If paramValues(0) Is Nothing = False Then intArrayBound = intArrayBound + 1 ReDim Preserve paramValues(intArrayBound) End If If intDatabaseType = 1 Then 'paramValues(intArrayBound) = New SqlParameter(strParameterName, DateValue(strParameterValue)) paramValues(intArrayBound) = New SqlParameter(strParameterName, strParameterValue) ElseIf intDatabaseType = 2 Then paramValues(intArrayBound) = New OracleParameter(strParameterName, DateValue(strParameterValue)) 'paramValues(intArrayBound) = New OracleParameter(":" &amp; strParameterName, OracleType.Int32) 'paramValues(intArrayBound).Value = strParameterValue End If Return intArrayBound End Function Public Function AssignParameterValues(ByVal strParameterName As String, ByVal strParameterValue As Decimal, ByVal intDatabaseType As Integer) As Integer Dim intArrayBound As Integer intArrayBound = UBound(paramValues) 'If intArrayBound &gt; 0 Then' If paramValues(0) Is Nothing = False Then intArrayBound = intArrayBound + 1 ReDim Preserve paramValues(intArrayBound) End If If intDatabaseType = 1 Then paramValues(intArrayBound) = New SqlParameter(strParameterName, strParameterValue) ElseIf intDatabaseType = 2 Then paramValues(intArrayBound) = New OracleParameter(strParameterName, strParameterValue) 'paramValues(intArrayBound) = New OracleParameter(":" &amp; strParameterName, OracleType.Int32) 'paramValues(intArrayBound).Value = strParameterValue End If Return intArrayBound End Function Public Function AssignParameterValues(ByVal strParameterName As String, ByVal strParameterValue As Boolean, ByVal intDatabaseType As Integer) As Integer Dim intArrayBound As Integer intArrayBound = UBound(paramValues) 'If intArrayBound &gt; 0 Then If paramValues(0) Is Nothing = False Then intArrayBound = intArrayBound + 1 ReDim Preserve paramValues(intArrayBound) End If If intDatabaseType = 1 Then paramValues(intArrayBound) = New SqlParameter(strParameterName, strParameterValue) ElseIf intDatabaseType = 2 Then paramValues(intArrayBound) = New OracleParameter(strParameterName, strParameterValue) 'paramValues(intArrayBound) = New OracleParameter(":" &amp; strParameterName, OracleType.Int32) 'paramValues(intArrayBound).Value = strParameterValue End If Return intArrayBound End Function Public Function getParameterValues() As DbParameter() Return paramValues End Function 'Public Sub Dispose() Implements IDisposable.Dispose ' Erase paramValues ' paramValues = Nothing 'End Sub' End Class </code></pre> <p>The app can use this class to create the parameter collection and then get the parameter collection before supplying it to ExecuteReader. The intDatabaseType allows this to work with SQL Server and Oracle.</p> <p>Is this a reasonable approach or is there a better approach?</p>
[]
[ { "body": "<h3>Potential issues</h3>\n\n<ul>\n<li><p><code>intDatabaseType</code> should be promoted to an instance variable instead of being supplied in every call to <code>AssignParameterValues</code> - the way you have it, <strong>you can build an 5-items array with 2 parameters for SQL Server and 3 parameters for Oracle</strong>. Not sure that's the way it was intended...</p></li>\n<li><p>Your \"database type\" is a magic number. What tells client code to pass a <code>1</code> for a SQL Server database and a <code>2</code> for an Oracle database? Nothing. Not even an exception. That parameter is literally <strong>begging to be an enum type</strong>.</p></li>\n<li><p>If <code>ExecuteReader</code> is ultimately taking in the return value from <code>getParameterValues</code>, then there's no need for <code>ParamArray</code> here; consider changing it to take any <code>IEnumerable(Of DbParameter)</code>.</p></li>\n<li><p><code>AssignParameterValues</code> will resize the array even if <code>intDataBaseType</code> is an invalid value, so <strong>the return value is meaningless</strong>. Why are you returning the array's upper bound? Why not make it a <code>Sub</code> that can either succeed or throw an exception?</p></li>\n<li><p>Instead of an array of <code>DbParameter</code>, consider using a <code>List(Of DbParameter)</code>. That alone would <strong>make all of that <code>ReDim Preserve</code> and <code>UBound</code> stuff go away</strong>!</p></li>\n</ul>\n\n<hr>\n\n<h3>Naming issues</h3>\n\n<ul>\n<li><strong>Hungarian notation</strong> is outdated, ugly at best and misleading at worst. Do yourself a favor and rename those variables!\n<ul>\n<li><code>clsParameterValues</code> => <code>ParameterValues</code></li>\n<li><code>intArrayBound</code> => <code>arrayUpperBound</code></li>\n<li><code>intDatabaseType</code> => <code>databaseType</code></li>\n<li><code>strParameterName</code> => <code>name</code></li>\n<li><code>strParameterValue</code> => <code>value</code></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<h3>Other nitpicks</h3>\n\n<ul>\n<li><p><code>intArrayBound = intArrayBound + 1</code> can be shortened to <code>intArrayBound += 1</code>.</p></li>\n<li><p>Prefer <code>If Not SomeBooleanExpression Then</code> for negation and <code>If SomeBooleanExpression Then</code> for the opposite, instead of the redundant <code>If SomeBooleanExpression = True Then</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T00:26:30.330", "Id": "33203", "ParentId": "31502", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T19:44:09.920", "Id": "31502", "Score": "3", "Tags": [ "design-patterns", "vb.net" ], "Title": "Encapsulation with a dbParameter class" }
31502
<p>In C# I can use </p> <pre><code>DateTime dt = DateTime.Now.Date; </code></pre> <p>This will give the current date, without the TimeSpan value (<strong><em>'00:00:00'</em></strong>). In JavaScript I did this:</p> <pre><code>var dt = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()); </code></pre> <p>But is so "ugly" that there must be a better, easier and clean way to do it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T20:47:06.377", "Id": "50232", "Score": "1", "body": "That is ugly, why would you call `new Date(...)` 4 times?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T21:04:39.397", "Id": "50233", "Score": "2", "body": "Also, DateTime.Now is usually used in C# (as it's static property, no need to create new object)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:56:07.110", "Id": "50290", "Score": "0", "body": "@Jesse Thanks, I was in a hurry and didn't use copy and paste. Thanks a lot for correct this silly mistake ^_^" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T14:29:02.013", "Id": "50293", "Score": "1", "body": "do you want that date format on any machine, any browser, or do you want your date format when you view the page, what are you using the date for? if you are filling something in, then how it looks on a browser isn't going to matter, you just use the properties of the object to fill in....whatever" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T15:28:59.990", "Id": "50296", "Score": "2", "body": "Note: The `Date` method doesn't return a `DateTime` value without the time part, it returns one where the time is actually `00:00:00`. A `DateTime` value doesn't exist without the time part. Note also that using `new Date()` multiple times is not just ugly, it could give a completely wrong result if you run the code right at midnight so that the date changes from one call to the next. Given, that is extremely unlikely to happen, but it's better to write it so that it can never happen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T15:54:35.623", "Id": "50299", "Score": "1", "body": "@Guffa As I put in parentheses, I just use the expression `without` to mean the value 00:00:00" } ]
[ { "body": "<p><a href=\"http://www.w3schools.com/js/js_obj_date.asp\" rel=\"nofollow noreferrer\">JavaScript Date Object</a></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString\" rel=\"nofollow noreferrer\">Mozilla Documentation on <code>toLocalDateString</code></a></p>\n<p>this code will give you the date in the format <code>mm/dd/yyyy</code> (at least that is what it gave me, because that is my locale convention)</p>\n<pre><code>var today = new Date(); \ndocument.write(today.toLocaleDateString());\n</code></pre>\n<p><em>Note</em>: <code>var today = new Date();</code> is a Date object that has <code>ToString</code> Methods for displaying it's <code>properties</code></p>\n<p>if your local conventions are to give you <code>yyyy/mm/dd</code> then it should give you what you want. as w3schools says</p>\n<blockquote>\n<p><code>toLocaleDateString</code> --&gt; Returns the date portion of a Date object as a string, using locale conventions</p>\n</blockquote>\n<p><strong>Code and Result of another answer doesn't look right to me</strong></p>\n<pre><code>var today = new Date();\ntoday.setHours(0); // or today.toUTCString(0) due to timezone differences\ntoday.setMinutes(0);\ntoday.setSeconds(0); document.write(today);\n</code></pre>\n<p>This code gives the result of</p>\n<blockquote>\n<p>Thu Sep 19 2013 00:00:00 GMT-0500 (Central Daylight Time)</p>\n</blockquote>\n<p>in Chrome</p>\n<p>my answer gives</p>\n<blockquote>\n<p>9/19/2013</p>\n</blockquote>\n<p>because that is my Locale Convention, if the OP wanted <code>yyyy/mm/dd</code> because that is the locale convention then my answer would be correct.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T21:52:00.287", "Id": "50240", "Score": "3", "body": "Note that the OP wants a `Date` object, not a string. And he wants a code shorter than his (even if yours is prettier)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T00:32:30.640", "Id": "50256", "Score": "2", "body": "It's again a string. If I understand right, the OP wants today's date with the time set to 00:00:00." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:06:42.540", "Id": "50277", "Score": "3", "body": "quote from the Original Post `This will give the current date, without the TimeSpan value ('00:00:00').`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:25:50.793", "Id": "58163", "Score": "3", "body": "Referencing to w3schools on StackOverflow is like begging for downvotes. There are better sources, for example the [Official Mozilla Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T17:33:00.497", "Id": "58167", "Score": "0", "body": "@SimonAndréForsberg, I know, but I also provided code and explanation to show that the information was correct, and that it worked the way I said it did. I will add a link from that page as well" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T21:36:08.667", "Id": "31511", "ParentId": "31503", "Score": "0" } }, { "body": "<p>It is not ideal, but you can do it this way...</p>\n\n<pre><code>var today = new Date();\nvar dateWithoutTime = new Date(today.getFullYear() , today.getMonth(), today.getDate());\n</code></pre>\n\n<p>There are multiple ways to make Dates in javascript. The format above will create a new Date based on \"today\"'s year, month, and date (think day of the month).</p>\n\n<p>Technically you could also do this with a DateString, however \"new Date(dateString)\" is implementation dependent, and may have inconsistent behavior across different browsers.</p>\n\n<p>And if making 2 Date objects makes you uncomfortable, you could always do the following:</p>\n\n<pre><code>var today = new Date();\ntoday.setHours(0); // or today.toUTCString(0) due to timezone differences\ntoday.setMinutes(0);\ntoday.setSeconds(0);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:50:12.520", "Id": "50287", "Score": "0", "body": "I liked the idea of setting hours min and sec to 0" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T00:46:56.170", "Id": "31516", "ParentId": "31503", "Score": "6" } }, { "body": "<p>Your solution can be slightly improved by using a variable:</p>\n\n<pre><code>var now = new Date();\nvar dt = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n</code></pre>\n\n<p>However, you can use <a href=\"http://www.datejs.com/\" rel=\"nofollow\">Date.js</a>, in which case your solution is simple:</p>\n\n<pre><code>var dt = Date.today();\n</code></pre>\n\n<p>Read more about it in the <a href=\"http://code.google.com/p/datejs/wiki/APIDocumentation#today\" rel=\"nofollow\">Date.js documentation</a>, or try it <a href=\"http://jsfiddle.net/s9guc/\" rel=\"nofollow\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:53:33.550", "Id": "50288", "Score": "0", "body": "Good link, but I don't want to use a plugging for this task" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T00:49:58.017", "Id": "31517", "ParentId": "31503", "Score": "3" } } ]
{ "AcceptedAnswerId": "31516", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T19:59:18.950", "Id": "31503", "Score": "4", "Tags": [ "javascript", "datetime" ], "Title": "How could I do DateTime.Now.Date (from C#) in JavaScript?" }
31503
<h2>Abstract</h2> <p>I'd like to have advice on how to :</p> <ul> <li>implement <strong>methods that rely on a state</strong>, </li> <li>when the <strong>instance is mutable and may be in an inconsistent state</strong>, </li> <li>in such a way that the methods <strong>either silently fail or return nil</strong>,</li> <li>without having to <strong>nil guard / coerce state to meaningful values</strong> everywhere.</li> </ul> <p>Anyway, if my design is wrong itself, let me know.</p> <h2>Context</h2> <p>I have an <code>ActiveRecord</code> class. It is pretty simple, but has <strong>lots and lots</strong> of methods that require the whole instance to be <code>valid?</code> to work correctly.</p> <p>The class in question handles a complex tax calculation, but for the sake of clarity, let's boil it down to this :</p> <pre><code>class Foo &lt; ActiveRecord::Base validates :a, :b, :c, :d, :e, numericality: {inclusion: 0..100} validates :f, :g, :h, numericality: {greater_than: 0} def some_method a * b / c end def other_method d + e * (g / f) end def yet_another_method some_method - other_method * f end def this_is_getting_really_complex yet_another_method * other_method - some_method end # and so on, with piles of methods calling each other end </code></pre> <p>Moreover, i have subclasses for this class that override these methods (different tax calculation rules, etc.)</p> <p>The thing is, as long as an instance is in a <strong>consistent</strong> state (all a, b, c... fields are present and valid), all the methods work fine. But <code>ActiveRecord</code> instances <em>must</em> be able to be in an <strong>inconsistent</strong> state, because...well, we want to be able to validate them. So raising <code>ArgumentError</code> during <code>initialize</code> when the params are meaningless is out of the question.</p> <p>In this case, let's say <code>a, b, c</code> are filled with junk strings or <code>nil</code> instead of <em>meaningful values</em> : all of our methods will raise various errors, or even worse - thanks to duck typing it <em>will</em> work in a crazy, unintended way ( <code>"junk" * 300_000</code>, anyone? ).</p> <h2>Trying to solve this problem</h2> <h3>first try : nil guards</h3> <p>this is getting ugly pretty quick :</p> <pre><code>def some_method return nil unless [a, b, c].all? &amp;:present? a * b / c end </code></pre> <p>... ugh, nil guarding isn't enough, what if i have strings instead of numbers ? I admit for a while i was tempted with heresy :</p> <pre><code>def some_method a * b / c rescue TypeError, NoMethodError nil end </code></pre> <p>This is too bad. Wait, what if i simply check for validity ?</p> <pre><code>def some_method return nil unless valid? a * b / c end </code></pre> <p>A bit better, but now the whole validation process kicks in every time i call a method. This is silly. OO to the rescue ?</p> <h3>second try : OO refactoring</h3> <p>My first thought was : well, we have a behavior that varies according to state - this is textbook example for a <strong>state machine</strong>. But how would i hook this on <code>AR</code>'s validation cycle ? Did not figured it out.</p> <p>Then I proceeded to try and extract those methods into a variety of <strong>immutable decorator classes</strong>, with a <strong>factory method</strong> that accepted one instance from my <code>Foo</code> class :</p> <pre><code> class FooDecorator def self.factory( foo ) # NullDecorator has methods that always return nil return NullDecorator.new( foo ) if foo.invalid? case foo when Foo:Bar then BarDecorator.new( foo ) when Foo:Baz then BazDecorator.new( foo ) else raise ArgumentError end end def initialize( foo ) @foo = foo.dup.freeze.readonly! end def some_method @foo.a * @foo.b / @foo.c end def yet_another_method some_method - other_method * @foo.f end end </code></pre> <p>I promptly stopped because it felt <strong>ridiculously overengineered</strong>, and smelled like <em>feature envy</em> over the top. </p> <p>I also considered using the <code>Maybe</code> <strong>monad</strong>, or create a monad of my own like "MaybeAValidNumber" to coerce everything to meaningful values. That felt not much better than nil guards and again, overengineered.</p> <h3>third try : don't care</h3> <p>Thinking about this, i wondered if i should nil guard at all : after all, these methods are only relevant if the instance is in a consistent state. As far as i understand it, <strong>design by contract</strong> goes this way : if you do not ensure state prerequistes are met before calling the methods, you break the contract, so you are at fault.</p> <p>Problem is, as you can easily guess, these methods are likely to be called in the views to display the results of calculations. I don't find having to throw a bunch of conditionals in my views entirely satisfying... </p> <h3>Thoughts ?</h3>
[]
[ { "body": "<p>Looks like your class has two separate responsibilities:</p>\n\n<ul>\n<li>validating a set of fields (fields can be in an inconsistent state)</li>\n<li>performing calculations on these fields (fields must be valid)</li>\n</ul>\n\n<p>Therefore I would split it up into two classes:</p>\n\n<ul>\n<li>The ActiveRecord could still take care of the validation and other ActiveRecord stuff.</li>\n<li>All the tax calculations though would happen in say TaxCalculator, which initializes all its fields from a validated ActiveRecord that's passed in from a constructor, so all the methods of it can blindly assume that the fields are OK.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T10:45:39.070", "Id": "50274", "Score": "0", "body": "that's more or less what i did with the decorator class. I guess it's a valid approach, but it quickly became really complex as my class has multiple subclasses with different calculations rules - i ended up having one decorator class for each of my classes, plus null decorator classes. That felt a bit too much... And the fact is that i want the thing to be dynamic, i.e. when i call a method it should retrurn the actual calculation result from up-to-date state values - i would have to create a decorator every time i call a method, calling valid? ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T10:46:01.713", "Id": "50275", "Score": "0", "body": "I'm currently exploring the Maybe monad option, seems easier and cleaner than expected, i'll let you know. thanks for the input anyway" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:54:44.267", "Id": "50289", "Score": "0", "body": "I assumed you can first validate the values and then do the calculations. But when you need to modify the values in the middle of these calculations, my approach starts to fall apart." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T10:13:56.183", "Id": "31530", "ParentId": "31505", "Score": "1" } }, { "body": "<p>Accepted an answer because it is a valid solution, but i'd like to explain an approach that seemed interesting (<strong>not functional as is</strong>): coercion plus a <code>NullObject</code>, in the spirit of the <code>Maybe</code>monad used by <a href=\"http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/\" rel=\"nofollow\">Avdi Grimm</a>.</p>\n\n<pre><code> class NonFloat\n\n include Comparable\n\n # allows arithmetic operations to take place with non-null values\n def coerce( other )\n [self, self]\n end\n\n def to_f\n self\n end\n\n def coerce( other )\n [self, self]\n end\n\n # did the same thing for various operators\n def *( other )\n self\n end\n\n def to_s\n \"\"\n end\n\n def &lt;=&gt;( other )\n # yuck, could not find anything meaningful to return from here :/\n end\n end\n\n def MaybeFloat( value )\n return value if value.kind_of?( NonFloat )\n Float( value )\n rescue TypeError # coercion failed\n NonFloat.new\n end\n</code></pre>\n\n<p>... Looks oddly like a <code>NaN</code> ;). What i like about this solution is that it allows to perform arithmetic operations, even with potentially non-float coercible values : </p>\n\n<pre><code> MaybeFloat( value ) * MaybeFloat( other_value )\n</code></pre>\n\n<p>but more important, this behavior can propagate :</p>\n\n<pre><code> def some_value\n MaybeFloat( @value )\n end\n\n def some_calculations\n some_value * 4 + other_value\n end\n\n def other_calculations\n some_calculations / yet_another_value # may return a NonFloat\n end\n</code></pre>\n\n<p>what s*cks is that you can't really compare <code>NonFloat</code> with other types because <code>&lt;=&gt;</code> is not expected to return anything other than 1,0 and -1 (no way to tell \"it doesn't make sense to compare these values\")... so <code>Array#min</code>, for instance, can't be used.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T17:48:51.810", "Id": "31755", "ParentId": "31505", "Score": "0" } } ]
{ "AcceptedAnswerId": "31530", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T20:17:09.193", "Id": "31505", "Score": "0", "Tags": [ "ruby", "state", "active-record" ], "Title": "Ruby OO design : how to handle inconsistent state in a mutable class?" }
31505
<p>I recently decided to make a <code>LinkedList</code> and binary search tree using JavaScript. I wanted to reach out to a wider audience and see how I did, and where could I improve.</p> <p><a href="https://gist.github.com/TheIronDeveloper/6604756" rel="nofollow"><strong>Linked List:</strong></a></p> <pre><code>var Node = function(value) { this.value = value; this.next=null; return this; }; var LinkedList = function(node){ this.head = node; return this; }; LinkedList.prototype.insertEnd = function(newNode, currentNode) { var currentNode = currentNode || this.head; if(currentNode.next !== null) { return this.insertEnd(newNode, currentNode.next); } else { currentNode.next = newNode; } }; LinkedList.prototype.insertBeginning = function(newNode) { newNode.next = this.head; this.head = newNode; }; LinkedList.prototype.search = function(searchValue, currentNode) { var currentNode = currentNode || this.head; if(currentNode.value == searchValue) { console.log("true"); return true; } else if(currentNode.next !== null) { return this.search(searchValue, currentNode.next); } console.log("not found"); return false; }; LinkedList.prototype.remove = function(deleteValue, currentNode, parentNode) { currentNode = currentNode || this.head; if(currentNode.value === deleteValue) { if(currentNode.next !== null) { parentNode.next = currentNode.next; } else { parentNode.next = null; } } else if(currentNode.next !== null) { return this.remove(deleteValue, currentNode.next, currentNode); } }; LinkedList.prototype.size = function(currentNode, size) { var currentNode = currentNode || this.head; var size = size || 1; if(currentNode.next !== null) { return this.size(currentNode.next, size+1); } else { console.log(size); return size; } }; (function(){ // LinkedList Example var linkedList = new LinkedList(new Node("oldHead")); linkedList.insertEnd(new Node(2)); linkedList.insertEnd(new Node("cat")); linkedList.insertEnd(new Node("dog")); linkedList.insertEnd(new Node(100)); linkedList.search("cat"); linkedList.size(); linkedList.remove("cat"); linkedList.size(); linkedList.search("cat"); console.log("current head: "+linkedList.head.value); linkedList.insertBeginning(new Node("testBeginningInsert")); console.log("current head: "+linkedList.head.value); linkedList.size(); })(); </code></pre> <p><a href="https://gist.github.com/TheIronDeveloper/6604713" rel="nofollow"><strong>Binary Search Tree:</strong></a></p> <pre><code>var Node = function(value) { this.value = value; this.left = null; this.right = null; return this; }; Node.prototype.insert = function(newNode) { if(newNode.value &lt; this.value) { if(this.left === null) { this.left = newNode; } else { this.left.insert(newNode); } } else if(newNode.value &gt; this.value) { if(this.right === null) { this.right = newNode; } else { this.right.insert(newNode); } } else { return true; } }; Node.prototype.depthFirstSearch = function(searchValue) { console.log(searchValue+": "+this.value); if(this.value === searchValue) { console.log("search item found"); return true; } else if(searchValue &lt; this.value &amp;&amp; this.left !== null) { return this.left.depthFirstSearch(searchValue); } else if(searchValue &gt; this.value &amp;&amp; this.right !== null) { return this.right.depthFirstSearch(searchValue); } else { console.log("could not find "+searchValue); return false; } }; Node.prototype.inorderTraversal = function() { if(this.left !== null) { this.left.inorderTraversal(); } console.log(this.value); if(this.right !== null) { this.right.inorderTraversal(); } }; Node.prototype.preOrderTraversal = function() { console.log(this.value); if(this.left !== null) { this.left.preOrderTraversal(); } if(this.right !== null) { this.right.preOrderTraversal(); } }; Node.prototype.postOrderTraversal = function() { if(this.left !== null) { this.left.postOrderTraversal(); } if(this.right !== null) { this.right.postOrderTraversal(); } console.log(this.value); }; var BinarySearchTree = function(insertNode) { if(insertNode instanceof Node) { this.root = insertNode; } else { this.root = new Node(insertNode); } return this; }; BinarySearchTree.prototype.insert = function(insert) { if(insert instanceof Node) { this.root.insert(insert); } else { this.root.insert(new Node(insert)); } }; BinarySearchTree.prototype.depthFirstSearch = function(searchValue) { this.root.depthFirstSearch(searchValue); }; BinarySearchTree.prototype.breadthFirstTraversal = function() { console.log("Breadth First Traversal"); // For our intensive purposes, // our array is acting as a queue for us. var queue = [], current = this.root; if(current !== null) { queue.push(current); } // start off enqueing root while(queue.length &gt; 0) { var tempNode = queue.shift(); console.log(tempNode.value); // Visit current node if(tempNode.left !== null) { queue.push(tempNode.left); } if(tempNode.right !== null) { queue.push(tempNode.right); } } }; BinarySearchTree.prototype.inOrderTraversal = function(){ this.root.inorderTraversal(); }; BinarySearchTree.prototype.preOrderTraversal = function(){ this.root.preOrderTraversal(); }; BinarySearchTree.prototype.postOrderTraversal = function(){ this.root.postOrderTraversal(); }; // Gotta not hurt dat global namespace (function(){ // Example BinBinarySearchTree var bst = new BinarySearchTree(50); bst.insert(25);bst.insert(75);bst.insert(12);bst.insert(37);bst.insert(87);bst.insert(63); console.log("Inorder Traversal"); bst.inOrderTraversal(); console.log("Preorder Traversal"); bst.preOrderTraversal(); console.log("Postorder Traversal"); bst.postOrderTraversal(); console.log("Search for valid (63)"); bst.depthFirstSearch(63); console.log("Search for invalid (19)"); bst.depthFirstSearch(19); bst.breadthFirstTraversal(); })(); </code></pre>
[]
[ { "body": "<p>Most of your code looks like textbook code.</p>\n\n<p>Your <code>size</code> function shouldn't have to take a second argument.</p>\n\n<pre><code>LinkedList.prototype.size = function(currentNode /* optional */) {\n // var currentNode, shadowing the currentNode param, is weird\n var node = currentNode || this.head;\n // I prefer to put the base case first\n if (node.next == null) {\n return 1;\n } else {\n return 1 + this.size(node.next);\n }\n};\n</code></pre>\n\n<p>Your traversal functions should not hard-code <code>console.log()</code> as the action. For flexibility, they should take a <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\">visitor</a> function as a callback.</p>\n\n<pre><code>// Fixed capitalization of \"inOrderTraversal\"\nNode.prototype.inOrderTraversal = function(visitor) { \n if (this.left !== null) {\n this.left.inOrderTraversal(visitor);\n }\n visitor(this.value);\n if(this.right !== null) {\n this.right.inOrderTraversal(visitor);\n }\n};\n\n// Elsewhere...\ntree.inOrderTraversal(console.log);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T03:43:15.650", "Id": "50263", "Score": "0", "body": "\"Most of your code looks like textbook code.\"\nWelp, I wrote this from scratch; it was intended as an educational refresher, so if it looks close to textbook... great!\n\n\n\nI have one inconsistency with my implementation of LinkedList and BST. The LinkedList implementation makes recursive calls to itself.\n\nFor the BST, the traversals are delegated to the Node object, which it will then make recursive calls to other Node elements.\n\nWhich was done closer to the \"right\" way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T04:32:24.737", "Id": "50264", "Score": "0", "body": "I think you've done the right thing in each case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T02:37:46.620", "Id": "31522", "ParentId": "31513", "Score": "6" } }, { "body": "<p>For LinkedList remove function, if the deleteValue is same as head's, the function should be failed, here is a modified version:</p>\n\n<pre><code>LinkedList.prototype.remove = function(deleteValue, currentNode, parentNode) {\n currentNode = currentNode || this.head;\n if (currentNode.value === deleteValue) {\n if (currentNode.value === this.head.value) {\n this.head = currentNode.next;\n } else if (currentNode.value === this.tail.value) {\n parentNode.next = null;\n this.tail = parentNode;\n } else {\n parentNode.next = currentNode.next;\n }\n } else if (currentNode.next !== null) {\n return this.remove(deleteValue, currentNode.next, currentNode);\n }\n};\n</code></pre>\n\n<p>Besides, I prefer to keep a tail to make insertEnd faster, like:</p>\n\n<pre><code>var LinkedList = function(newNode) {\n this.head = newNode || null;\n this.tail = newNode || null; // storing a reference to the end of the list\n return this;\n};\n</code></pre>\n\n<p>Then insertEnd should not need a recursive, like:</p>\n\n<pre><code>LinkedList.prototype.insertEnd = function (newNode) {\n if (!(newNode instanceof Node)) {\n newNode = new Node(newNode);\n }\n\n if(!this.head) {\n this.head = newNode;\n this.tail = this.head;\n } else {\n // Switch to use tail for good performance\n this.tail.next = newNode;\n this.tail = this.tail.next;\n }\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-08T16:34:24.307", "Id": "90180", "ParentId": "31513", "Score": "3" } } ]
{ "AcceptedAnswerId": "31522", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T23:16:00.187", "Id": "31513", "Score": "9", "Tags": [ "javascript", "linked-list", "tree" ], "Title": "LinkedList and binary search tree in JavaScript" }
31513
<p>I'm pretty new to coding and I want to get an opinion on my coding. I am learning Python and I made a really simple heads and tails guessing game.</p> <pre><code>import random import time import easygui import sys while True: rand = random.choice(["Heads", "Tails"]) firstguess = raw_input("Guess Heads or Tails: ") if firstguess == rand: print "Wow you win" else: print "That is wrong you suck so bad lol." time.sleep(2) answer = easygui.buttonbox("Play again?", choices=["Yes","No"]) if answer == "Yes": easygui.msgbox("Ok") else: break easygui.msgbox("Ok, see you later!") sys.exit(0) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-06T08:12:45.827", "Id": "238721", "Score": "0", "body": "You are doing fine. My first program ever was a guessing game like this. Keep it up." } ]
[ { "body": "<p>Why are you mixing <code>raw_input()</code> with <code>easygui</code>? That's a suboptimal user experience.</p>\n\n<p><code>sys.exit(0)</code> at the end is superfluous, but harmless.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T00:01:36.803", "Id": "31515", "ParentId": "31514", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T23:33:12.043", "Id": "31514", "Score": "5", "Tags": [ "python", "beginner", "game", "python-2.x" ], "Title": "\"Heads or Tails?\" guessing game in Python" }
31514
<p>I am new to the OOP world I have been reading as much as I can about it and have never been more confused. I understand that its great for organizing code and making it more maintainable, etc. I have written some OOP code but I am unsure if its proper, it works fine though.</p> <p>I am confused about public private functions along with extends and constructors. I haven't used them yet in my code and do not see where I would use them in a real life example. The more I read and try to understand it the more confused I get. I have included my code and was wondering if someone could point out mistakes, improvements, proper usage, organization. I feel it would help me better understand if someone with a lot of experience was to look at my code and give me pointers.</p> <pre><code>class userFunctions { const SALT_LENGTH = 9; //Retrieves encrypted password from database returns in variable $salt public function retrievePassword($conn,$username) { try{ $stmt = $conn-&gt;prepare('SELECT `password` FROM `users` WHERE `userName`= :userName'); $stmt-&gt;bindValue(':userName', $username); $stmt-&gt;execute(); $salt = $stmt-&gt;fetchColumn(); } catch (PDOException $e){ echo 'Connection failed: ' . $e-&gt;getMessage(); } return $salt; } //Generate an encrypted password method public function generateHash($password, $salt = null) { if ($salt === null) { $salt = substr(md5(uniqid(rand(), true)), 0, self::SALT_LENGTH); } else { $salt = substr($salt, 0, SALT_LENGTH); } return $salt . sha1($salt . $password); } //Check database for duplicate username public function userCheck($conn,$userName) { try{ $stmt = $conn-&gt;prepare('SELECT COUNT(*) FROM `users` WHERE `userName` LIKE CONCAT("%",:userName)'); $stmt-&gt;bindValue(':userName', $userName); $stmt-&gt;execute(); $count = $stmt-&gt;fetchColumn(); return $count; } catch (PDOException $e){ echo 'Connection failed: ' . $e-&gt;getMessage(); } } //Add user to database public function Register($conn,$userName,$encryptedPass) { try{ $stmt = $conn-&gt;prepare('INSERT INTO users (userName, password) VALUES (:userName, :password)'); $stmt-&gt;execute(array(':userName' =&gt; strip_tags($userName), ':password' =&gt; $encryptedPass)); } catch (PDOException $e){ echo 'Connection failed: ' . $e-&gt;getMessage(); } } } </code></pre>
[]
[ { "body": "<p>What you're really doing here, is using a class as a container for bunch of functions. It's a perfectly fine thing to do, but it's not really object-oriented programming. Even the name of your class <code>userFunctions</code> confirms it.</p>\n\n<p>An object should be something that binds together some state and a group of methods which operate on this state. In your case most of the methods need a database connection object and a username to do their work, so this should be your shared state:</p>\n\n<pre><code>class User {\n private $db;\n private $username;\n\n function __construct($db_connection, $username) {\n $this-&gt;db = $db_connection;\n $this-&gt;username = $username;\n }\n\n public function exists() {\n ...\n }\n\n public function register($pass) {\n ...\n }\n}\n</code></pre>\n\n<p>So here we have a User class. We instantiate it with a database connection and a username, and then we have an object that represents one particular user, and we can call the various methods without having to pass in the connection and username to each one of them.</p>\n\n<p>We also can then work at a higher level, having a concept of a User, we can tell it to do various tasks:</p>\n\n<pre><code>$user = new User($db_connection, $_POST[\"user\"]);\nif (!$user-&gt;exists()) {\n $user-&gt;register($_POST[\"pass\"]);\n}\n</code></pre>\n\n<p>Additional tips:</p>\n\n<ul>\n<li>Indent your source code properly.</li>\n<li>Follow PHP naming convention of starting class names with uppercase letter and method names with downcase letter.</li>\n<li>Drop the <code>/////////////</code> separators - whitespace is enough.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T08:00:05.960", "Id": "31524", "ParentId": "31520", "Score": "2" } }, { "body": "<p>Right, your object is, like Rene said, just a container of functions. Though, in theory, that's what objects are for (group functionality together), the way you went about this, you're actually using classes as modules. It's not what you call <a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"nofollow noreferrer\"><em>SOLID</em> code</a>. </p>\n\n<p><em>Edit:</em><Br/>\nPerhaps you might want to scroll down first, because throughout the answer I've used rather messy examples to explain things, but at the bottom I've added a <em>really</em> simple example that might help you to understand the access modifiers and inheritance better.</p>\n\n<p>Anyhow, I'm not going into details on how you should refactor this to be SOLID compliant, that's part of the learning curve. The simple fact of the matter is that, yes OOP <em>is</em> confusing at first, and <em>at first</em> you might not even need constructors, access modifiers (public, protected or private), let alone destructors. Especially if you haven't come to terms with inheritance. But let me explain a few things that, hopefully, will clarify one or two things. </p>\n\n<p>Class methods share state:<br/>\nThat's just a fancy way of saying that class methods have access to variables, without having them passed as arguments. Of course, not just any variable will do: it's the properties of the class that are accessible. In your snippet, you're passing <code>$conn</code> to various methods, like you would if they were functions. The difference is, that classes can be assigned properties, too.</p>\n\n<pre><code>class RefactoredFunctions\n{\n private $conn = null;\n public function setConn($conn)\n {\n $this-&gt;conn = $conn;\n }\n public function retrievePassword($userNAme)\n {\n //your code here, but replace $conn with $this-&gt;conn\n }\n}\n</code></pre>\n\n<p>Now you can call the <code>retrievePassword</code> method, without having to pass the <code>$conn</code> param over and over again. Though, this code <em>would</em> fail, if <code>$conn</code> wasn't set prior to calling <code>retrievePassword</code>. How can we fix that?<br/>\nEnter constructors. A constructor is a method, like any other, except for the fact that it can't be called manually. It's called automatically, when an instance of the class is created. You could define a constructor that expects an argument, and pass the connection to it, ensuring the <code>$conn</code> property will be set:</p>\n\n<pre><code>public function __constructor($conn)\n{\n $this-&gt;conn = $conn;\n}\n//using this class:\n$instance = new RefactoredFunctions($conn);\n$instance-&gt;retrievePassword('userFoo');//conn is set through constructor!\n</code></pre>\n\n<p>That's all a constructor does (9/10 times): setting properties your class requires to work properly. These properties are sometimes called <em>the dependencies</em> of that class. The class <em>depends</em> on them.<br/>\nNow, an argument that is called <code>$conn</code> is clearly supposed to be a DB connection in your case, but how do we make sure nobody passes a string? Simple: we use <em>type-hinting</em>, another benefit of OOP:</p>\n\n<pre><code>public function __construct(PDO $conn)\n{\n $this-&gt;conn = $conn;\n}\n//usage\n$instance= new RefactoredFunctions(new PDO());//works fine\n$error = new RefactoredFunctions('foobar');//fatal error string is not PDO instance\n</code></pre>\n\n<p>This makes your code more failsafe. Use type-hints to avoid bugs. That's an order!<br/>\nNow, all this time, I've been using <code>$this-&gt;conn</code> which is a property declared as private. Why? Simple. I've used type-hints to ensure the value of <code>$this-&gt;conn</code> is guaranteed to be an instance of <code>PDO</code>, but if I would have declared <code>public $conn</code>, I'm able to access the property (and thus assign it a new value) simply bypassing the setter/constructor:</p>\n\n<pre><code>//assume public $conn\n$instance= new RefactoredFunctions(new PDO());//works fine\n$instance-&gt;retrievePassword('userFoo');//still OK\n$instance-&gt;conn = 'reassign conn';\n$instance-&gt;retrievePassword('userFoo');//ERROR!\n</code></pre>\n\n<p>Now, with private properties:</p>\n\n<pre><code>$instance= new RefactoredFunctions(new PDO());//works fine\n$instance-&gt;conn = 'reassign conn';//ERROR!!\n$instance-&gt;retrievePassword('userFoo');//will never get this far\n</code></pre>\n\n<p>What's the benefit of this? Simple: the bug is easy to find. Imagine if I would've reassinged the <code>conn</code> property by accident, and then call a method 50 lines further down the script, or pass an instance to another class (defined in another file), and call the method there. I'd get an error, with a file &amp; line number that contains the call, not the cause (reassignment statement).</p>\n\n<p>OK, you got this far, and this is still making sense? On to <code>protected</code>... Where does that tie in?<br/>\nWell, the more objects you have, chances are some of them share functionality. Rather than writing the same methods several times, we <em>extend</em> classes from each other. So far, we have:</p>\n\n<pre><code>class RefactoredFunctions\n{\n private $conn = null;\n public function __construct(PDO $conn)\n {\n $this-&gt;conn = $conn;\n }\n public function setConn(PDO $conn)\n {\n $this-&gt;conn = $conn;\n return $this;\n }\n public function retrievePassword($userNAme)\n {\n //your code here, but replace $conn with $this-&gt;conn\n }\n}\n</code></pre>\n\n<p>Now, suppose I wanted a DB class per table (quite common). I have this base class, that holds a connection instance, and some methods to query a DB. What if I moved the constructor, <code>$conn</code> property and <code>setConnection</code> method to a generic class, and create child classes per table? that would save me 2 methods/class to write. If I have 10 tables, that's 20 methods. Of course I'll do that:</p>\n\n<pre><code>class BaseTable\n{\n private $conn = null;\n private $tblName = null;//to hold the table their linked to\n\n public function __construct(PDO $conn)\n {\n $this-&gt;conn = $conn;\n }\n\n public function setConn(PDO $conn)\n {\n $this-&gt;conn = $conn;\n return $this;\n }\n\n public function setTable($tblName)\n {//set table name for each instance\n $this-&gt;tblName = $tblName;\n return $this;\n }\n}\n//a child\nclass UserTbl extends BaseTable\n{\n public function getUsers()\n {\n $this-&gt;conn-&gt;prepare('SELECT * FROM '.$this-&gt;table);\n //etc...\n }\n}\n//usage:\n$users = new UserTbl(new PDO());\n$users-&gt;getUsers();\n</code></pre>\n\n<p>Ok, so I didn't have to write those properties and methods, but the code above won't work! Why? because <code>private</code> means the properties/methods are only visible to the class in which they were defined, in this case <code>BaseTable</code>, not the child class. <code>protected</code> means that properties/methods can be accessed in both the class that defined them, and its children. So, would you make the <code>$conn</code> property protected? Of course <em>NOT</em>.<br/>\nThere's a number of reasons why you wouldn't do this, but I might go into those in a future edit. ATM, we have some more important things to focus on.</p>\n\n<p>Have you noticed how the connection is <em>guaranteed</em> to be available thanks to the constructor, but the tablename isn't? yet, we're using the table name in our queries. How do we fix that? You have 3 options:</p>\n\n<ol>\n<li>Make <code>$tblName</code> protected and assign it a value in the child's definition, and <em>remove</em> the <code>setTable</code> method</li>\n<li>override the parent constructor (less secure)</li>\n<li>A combination of the first two</li>\n</ol>\n\n<p>So, if in the base class, we now have <code>protected $tblName = null;</code> you can write this, in the child:</p>\n\n<pre><code>protected $tblName = 'users';\n</code></pre>\n\n<p>Job done. The second approach would look like this:</p>\n\n<pre><code>//in child\npublic function __construct(PDO $connection, $tblName)\n{\n $this-&gt;tblName = $tblName;\n parent::__construct($connection);//explicit call required\n}\n</code></pre>\n\n<p>To combine the two would require <a href=\"https://codereview.stackexchange.com/questions/28921/fake-covariance-in-php-type-hinting\">using <code>abstract</code>, <code>final</code> and all that</a>, here's an example of this, but I'm not going into all that now.</p>\n\n<p>All this time, we still have to deal with the <code>private $conn</code> being invisible to the child classes. How would you deal with that? The answer to that question is surprizingly simple:</p>\n\n<pre><code>//in BaseTable\nprotected function getConnection()\n{\n return $this-&gt;conn;\n}\n</code></pre>\n\n<p>This protected method is visible to the children, and returns the connection, so all we have to do now is write:</p>\n\n<pre><code>$this-&gt;getConnection()-&gt;prepare('SELECT ...');\n</code></pre>\n\n<p>instead of <code>$this-&gt;conn</code>. There we are, problem solved, you should be able to get these classes working now.<br/>\nNote that there's a lot of things left to be done. For example the <code>getUsers</code> methods is nothing but a <code>select * from tbl</code> query. We could just as well have written that in our <code>BaseTable</code> class, but using another name and access modifier:</p>\n\n<pre><code>protected function getAll()\n{//protected: it's for internal use only\n $res = $this-&gt;conn('SELECT * FROM '.$this-&gt;tblName);\n return $res-&gt;fetchAll();\n}\n</code></pre>\n\n<p>Then, in each child class:</p>\n\n<pre><code>//UsersTable:\npublic function getUsers()\n{\n return $this-&gt;getAll();\n}\n//LogsTable\npublic function getLogs()\n{\n return $this-&gt;getAll();\n}\n</code></pre>\n\n<p>You could even add arguments in the child methods, and process the return value of the <code>getAll</code> method accordingly:</p>\n\n<pre><code>protected function getAll()\n{\n return $this-&gt;conn-&gt;query('SELECT * FROM '.$this-&gt;table);\n}\n//UsersTable:\npublic function getUsers($asArray = false)\n{\n $asArray = $asArray ? PDO::FETCH_ASSOC : PDO::FETCH_OBJ;\n return $this-&gt;getAll()-&gt;fetchAll($asArray);\n}\n</code></pre>\n\n<p>One last thought on inheritance: Assume the classes <code>BasteTable</code> and <code>UserTable extends BaseTable</code>. When using type-hinting, this is good to know:</p>\n\n<pre><code>$base = new BaseTable();\n$user = new UserTable();\nif ($base instanceof BaseTable) echo 'Yes';//will echo, of course\nif ($user instanceof UserTable) echo 'Duh';//of course, this is true\n</code></pre>\n\n<p>That's as you'd expect it, but:</p>\n\n<pre><code>if ($base instanceof UserTable) echo 'WTF';//You won't see this\nif ($user instanceof BaseTable) echo 'Yes';//will echo!!\n</code></pre>\n\n<p>So all instances of <code>UserTable</code> are instances of <code>BaseTable</code>, too, but not all instances of <code>BaseTable</code> are instances of <code>UserTable</code>. Now this might seem odd, at first but think of it like this:</p>\n\n<pre><code>class Room\n{\n public $door;//can be opened from outside\n protected $window;//can only be opened from within ANY room, all rooms have to access this\n}\nclass Bathroom extends Room\n{\n private $mirror;//this room has a mirror, can only be accessed in a bathroom\n}\nclass Bedroom extends Room\n{\n private $bed;//this one has a bed, can only be used when inside a bedroom\n}\n</code></pre>\n\n<p>Now you see: both a bedroom and a bathroom are rooms, but a bedroom is no bathroom, hence:</p>\n\n<pre><code>$bath = new Bathroom;//instanceof Room, not instanceof Bedroom\n$bed = new Bedroom;//instanceof Room, not instanceof Bathroom\n$genericRoom = new Room;//instanceof Room\n//not specified which, so no mirror or bed, so not instance of any child\n</code></pre>\n\n<p>I hope this clears one or two things up for you. If you have a follow up question, don't hesitate to ask. I'm not going to add any more info, as this is quite a lot to deal with already</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:43:10.540", "Id": "50347", "Score": "0", "body": "thank you so much this helped me a lot especially the example of the rooms at the end." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T11:39:12.303", "Id": "31531", "ParentId": "31520", "Score": "3" } } ]
{ "AcceptedAnswerId": "31531", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T02:03:06.807", "Id": "31520", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "Proper usage of OOP PHP" }
31520
<p>According to shootout.alioth.debian.org, Racket is not much slower than C#, at least in the same order of magnitude due to its JIT compiler.</p> <p>However, I'm seeing at least <strong>two degrees of magnitude</strong> slowdown in my implementation of the RC4 cipher in C# vs. Racket. </p> <p>(Disclaimer: I am not using RC4, in this case a hilariously puny 16-bit version, to ensure any type of confidentiality. It is only used as a fast traffic obfuscating layer - that's why I need it to be fast!)</p> <p>My (Typed) Racket code is here: <a href="https://github.com/quantum1423/Kirisurf-Official/blob/master/src/arcfour.rkt" rel="nofollow">https://github.com/quantum1423/Kirisurf-Official/blob/master/src/arcfour.rkt</a></p> <p>The relevant portion:</p> <pre><code>;Returns a stateful function which encrypts one byte of data with the given key (define (make-rc4 keyd) (define key keyd) (define S (make-bytes 256 0)) (for ([i 256]) (bytes-set! S i i)) (define j 0) (for ([i 256]) (set! j (unsafe-fxmodulo (unsafe-fx+ j (unsafe-fx+ (bytes-ref S i) (bytes-ref key (unsafe-fxmodulo i (unsafe-bytes-length key))))) 256)) (define tmp (unsafe-bytes-ref S i)) (unsafe-bytes-set! S i (bytes-ref S j)) (unsafe-bytes-set! S j tmp)) (set! j 0) (define i 0) (: Sr (Integer -&gt; Integer)) (define (Sr x) (unsafe-bytes-ref S x)) (: toret (Integer -&gt; Integer)) (define (toret c) (set! i (unsafe-fxmodulo (unsafe-fx+ 1 i) 256)) (set! j (unsafe-fxmodulo (unsafe-fx+ j (Sr i)) 256)) (define temp (Sr i)) (unsafe-bytes-set! S i (Sr j)) (unsafe-bytes-set! S j temp) (bitwise-xor (Sr (unsafe-fxmodulo (unsafe-fx+ (Sr i) (Sr j)) 256)) c)) toret) </code></pre> <p>My old C# code is here: <a href="https://github.com/quantum1423/Kirisurf-Official/blob/a04136569025f046872c3cf7fd07955f60bf49dc/Tunnel.cs" rel="nofollow">https://github.com/quantum1423/Kirisurf-Official/blob/a04136569025f046872c3cf7fd07955f60bf49dc/Tunnel.cs</a> (scroll to line 398 for the RC4State object)</p> <p>To put things in perspective, my C# code is always I/O-bound and uses imperceptible CPU. My Racket code vrooms my CPU full and pulls an incredibly slow 700 KiB each second.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T02:48:45.217", "Id": "50262", "Score": "3", "body": "As per the FAQ, please embed the code you'd like to have reviewed. You may keep the link as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T15:18:57.190", "Id": "50294", "Score": "0", "body": "I added the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T22:36:42.523", "Id": "50957", "Score": "0", "body": "please post the Relevant C# Code in your question, or lose the C# tag." } ]
[ { "body": "<p>I was looking at the C# code in your link and found something that made me stop for a minute\nthis may be a dumb question, I couldn't put it into a comment</p>\n\n<pre><code>while(true)\n {\n int ky = 0;\n restart:\n if (ky % 256 == 0) \n {\n Console.Error.WriteLine(\n \"[\" +\n repeatchar('|', (ky*100)/(256*256)) +\n repeatchar(' ', (((256*256)-ky)*100)/(256*256)) +\n \"]\"\n );\n }\n byte[] test = new byte[2];\n test[0] = (byte)(ky/(256));\n test[1] = (byte)(ky%256);\n stt.Reinitialize(test);\n for (int i = 0; i &lt; 256; i++)\n {\n if (stt.Dencode(0) != reference[i]) {ky++; goto restart;}\n }\n found = test;\n break;\n }\n</code></pre>\n\n<p>Why do you need to put this into a <code>While</code> loop? </p>\n\n<p>and instead of this</p>\n\n<blockquote>\n<pre><code>while (timer &gt; 0) \n{\n Thread.Sleep (500);\n timer--;\n}\n</code></pre>\n</blockquote>\n\n<p>Just do this instead</p>\n\n<pre><code>Thread.Sleep(50000);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-28T02:05:23.300", "Id": "50993", "Score": "0", "body": "The above is for bruteforcing. It is unrelated to the RC4State object. The second one is used because timer may be reset to 100 by another thread, thus resetting the timeout. Thread.Sleep(50000); would be uninterruptible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T13:24:09.217", "Id": "51159", "Score": "0", "body": "that was about all I had. and it looks like you have good reason for the way it was written." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T22:34:17.057", "Id": "31918", "ParentId": "31521", "Score": "1" } }, { "body": "<p>Here are some tips that may help. Note that these are collected from feedback on #racket on irc.freenode.net (which you may find helpful too).</p>\n\n<ul>\n<li>The length of the bytestring is counted inside the loop, but it's a loop invariant that you can hoist out of the loop.</li>\n<li>Folding over <code>j</code> may be faster than mutating it as you are doing. See <a href=\"http://www.cs.utah.edu/plt/snapshots/current/doc/guide/performance.html#%28part._.Mutation_and_.Performance%29\" rel=\"nofollow\">Mutation and Performance</a> in the Guide for more details.</li>\n<li>Your <code>for</code> loops use generic sequences. Using specialized sequences like <code>in-range</code> would be faster.</li>\n</ul>\n\n<hr>\n\n<p>You might also benefit from trying the <a href=\"https://github.com/stamourv/optimization-coach/tree/master\" rel=\"nofollow\">Optimization Coach</a> plugin for DrRacket. It's a tool that identifies performance pitfalls in your program along with possible solutions. For Typed Racket, it can also find when the type-driven optimizer was not able to optimize the program but could potentially do so with some changes.</p>\n\n<p>Also try the Racket mailing list: <a href=\"http://www.racket-lang.org/community.html\" rel=\"nofollow\">http://www.racket-lang.org/community.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T19:21:35.243", "Id": "39018", "ParentId": "31521", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T02:27:49.713", "Id": "31521", "Score": "4", "Tags": [ "c#", "scheme", "racket" ], "Title": "Why is this RC4 code in Racket so slow?" }
31521
<p>I am working on an HTML document to which I need to add certain classes to some elements. In the following code, I am adding class <code>img-responsive</code>.</p> <pre><code>def add_img_class1(img_tag): try: img_tag['class'] = img_tag['class']+' img-responsive' except KeyError: img_tag['class'] = 'img-responsive' return img_tag def add_img_class2(img_tag): if img_tag.has_attr('class'): img_tag['class'] = img_tag['class']+' img-responsive' else: img_tag['class'] = 'img-responsive' return img_tag soup = BeautifulSoup(myhtml) for img_tag in soup.find_all('img'): img_tag = add_img_class1(img_tag) #or img_tag = add_img_class2(img_tag) html = soup.prettify(soup.original_encoding) with open("edited.html","wb") as file: file.write(html) </code></pre> <ol> <li>Both functions do same, however one uses exceptions and another has_attr from BS4. Which is better and why?</li> <li>Am I doing the right way of writing back to HTML? Or shall convert entire soup to UTF-8 (by <code>string.encode('UTF-8')</code>) and write it?</li> </ol>
[]
[ { "body": "<p>The second option is better, because the possible error is explicit. However, in lots of case in Python, you should follow <a href=\"http://docs.python.org/2/glossary.html#term-eafp\" rel=\"noreferrer\">EAFP</a> and go for the <code>try</code> statement. However, we can do better.</p>\n\n<h2>get(value, default)</h2>\n\n<p>In BeautifulSoup, attributes behave like dictionaries. This means you can write <code>img_tag.get('class', '')</code> to get the class if it exists, or the empty string if it doesn't.</p>\n\n<pre><code>def add_img_class(img_tag):\n img_tag = img_tag.get('class', '') + ' img-responsive'\n</code></pre>\n\n<p>You don't need to return the new <code>img_tag</code> as it is passed by reference. Now that your function is a one-liner, you might as well use the one-liner directly.</p>\n\n<h2>Multi-valued attributes</h2>\n\n<p>Note that the above code doesn't work! <code>class</code> is a multi-valued attribute in HTML4 and HTML5, so at least BeautifulSoup 4 returns a list instead of a string. The correct code becomes:</p>\n\n<pre><code>img_tag['class'] = img_tag.get('class', []) + ['img-responsive']\n</code></pre>\n\n<p>Wich is nicer as you don't have to worry about the extra space between the two values.</p>\n\n<h2>Encoding</h2>\n\n<p>You don't need to convert to UTF-8 before writing the file back. What's wrong with <code>&amp;nbsp;</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-29T09:11:59.320", "Id": "159904", "Score": "0", "body": "Using `img['class'] = img.get('class', []) + ['img-responsive']`\nresults in *TypeError: coercing to Unicode: need string or buffer, list found* but `img['class'] = img.get('class', []) + ' img-responsive` does the trick." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-29T13:16:40.793", "Id": "159909", "Score": "0", "body": "FredCampos, did you use BeautifulSoup4? Did you parse your document as HTML? The BeautifulSoup 4 docs mentions that `img[class]` should always return a list: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#multi-valued-attributes" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T20:09:18.280", "Id": "41426", "ParentId": "31523", "Score": "13" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T07:01:33.673", "Id": "31523", "Score": "12", "Tags": [ "python", "html", "html5", "beautifulsoup" ], "Title": "Adding a new class to HTML tag and writing it back with Beautiful Soup" }
31523
<p>Each row in the table has a delete and duplicate operation. The input values are passed to the new section based on the <code>id</code>s of each input on the row which changes dynamically based on the user's actions. The function for recreating the id's of the rows is not so good. I am not to sure how change it.</p> <p><strong>HTML</strong></p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Package&lt;/th&gt; &lt;th&gt;Weight&lt;/th&gt; &lt;th&gt;Height&lt;/th&gt; &lt;th&gt;Width&lt;/th&gt; &lt;th&gt;Length&lt;/th&gt; &lt;th&gt;Duplicate&lt;/th&gt; &lt;th&gt;Delete&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody id="added-parcels"&gt; &lt;tr id="1"&gt; &lt;td&gt;&lt;span&gt;1&lt;/span&gt;&lt;/td&gt; &lt;td&gt; &lt;div id="weighting-1" class="package-value"&gt; &lt;input type="text" onkeypress="return isNumber(event)"&gt; kgs &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div id="heighting-1" class="package-value"&gt; &lt;input type="text" onkeypress="return isNumber(event)"&gt; cm &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div id="widthing-1" class="package-value"&gt; &lt;input type="text" onkeypress="return isNumber(event)"&gt; cm&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div id="lengthing-1" class="package-value"&gt; &lt;input type="text" onkeypress="return isNumber(event)"&gt; cm&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;button id="1" class="package-dup package-add-dup-1" title="Add Duplicate Parcel"&gt;&lt;/button&gt; &lt;/td&gt; &lt;td&gt;&lt;div class="package-delete package-button" title="Delete"&gt;&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr id="2"&gt; &lt;td&gt; &lt;span&gt;2&lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;div id="weighting-2" class="package-value" onkeypress="return isNumber(event)"&gt; &lt;input type="text"&gt; Kg's &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div id="heighting-2" class="package-value" onkeypress="return isNumber(event)"&gt; &lt;input type="text"&gt; cm &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div id="widthing-2" class="package-value" onkeypress="return isNumber(event)"&gt; &lt;input type="text"&gt; cm &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div id="lengthing-2" class="package-value" onkeypress="return isNumber(event)"&gt; &lt;input type="text"&gt; cm &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;button id="2" class="package-dup package-add-dup-2" title="Add Duplicate Parcel"&gt;&lt;/button&gt; &lt;/td&gt; &lt;td&gt; &lt;div class="package-delete package-button" title="Delete"&gt;&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>And the JS that handles the delete function that keeps the order of the values that are being dynamically generated:</p> <pre><code>//&lt;!-- Recreate numbers on parcels function reNumber() { $('#added-parcels tr td:first-child span').empty() $('#added-parcels tr').each(function () { $(this).attr('id',newNum++) }); newNum = 1; $('#added-parcels tr td:first-child span').each(function () { $(this).text(newNum++); }); newNum = 1; $('#added-parcels tr td:nth-child(2) div').each(function () { $(this).attr('id','weighting-' + newNum++); }); newNum = 1; $('#added-parcels tr td:nth-child(3) div').each(function () { $(this).attr('id', 'heighting-' + newNum++); }); newNum = 1; $('#added-parcels tr td:nth-child(4) div').each(function () { $(this).attr('id', 'widthing-' + newNum++); }); newNum = 1; $('#added-parcels tr td:nth-child(5) div').each(function () { $(this).attr('id', 'lengthing-' + newNum++); }); newNum = 1; } </code></pre> <p>I don't think I can change the HTML. It is dependent on too many other operations to consider, but maybe just a more effective way to code the recreation of the <code>id</code>s when the <code>reNumber()</code> function is called.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T12:22:23.353", "Id": "50276", "Score": "0", "body": "Can you create a fiddle and also try to explain precisely what you are trying to do? Sorry, I couldn't understand your question very well." } ]
[ { "body": "<p>Probably the most important thing you should be focusing on is the idea that ID's are unique. There can't be more than one element with the same ID. If you're trying to select several elements, jQuery will stop looking as soon as it hits the first element that mathces the ID. You should use classes instead. That said, it's up to you to make that change. I cannot determine how to do this, or the implications it will have on your site, just based off the code you posted.</p>\n\n<p>Second most important thing is you should cache your jQuery selections. If you use a selection more than once, you should cache it. This way jQuery doesn't have to go looking for that element(s) every time. You then simply reference the variable you saved the selection in.</p>\n\n<p>I've also replace your variable <code>newNum</code> inside the <code>.each()</code> callbacks to use <code>i</code> instead. This is the index. It counts how many times you've gone through this callback and is more appropriate for what you're trying to do. I would also recommend starting <code>newNum</code> at zero since JS is mostly zero-indexed and will make your life easier if you need to manipulate any of these ID's later.</p>\n\n<p>Anyways, I'm sure there's more you could improve on, but without changing the HTML and while keeping this \"the jQuery way\" there's not much else I could change. Here are the few changes I've made:</p>\n\n<pre><code>function reNumber() {\n var parcelsTR = $(\"#added-parcels tr\"),\n parcelsTRFirst = parcelsTR.find(\"td:first-child span\"),\n newNum = 1;\n\n parcelsTR.each(function (i) {\n $(this).attr('id', newNum+i);\n });\n\n parcelsTRFirst.empty();\n\n parcelsTRFirst.each(function (i) {\n $(this).text(newNum+i);\n });\n\n parcelsTR.find('td:nth-child(2) div').each(function (i) {\n $(this).attr('id','weighting-' + newNum+i);\n });\n\n parcelsTR.find('td:nth-child(3) div').each(function (i) {\n $(this).attr('id', 'heighting-' + newNum+i);\n });\n\n parcelsTR.find('td:nth-child(4) div').each(function (i) {\n $(this).attr('id', 'widthing-' + newNum+i);\n });\n\n parcelsTR.find('td:nth-child(5) div').each(function (i) {\n $(this).attr('id', 'lengthing-' + newNum+i);\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:27:12.237", "Id": "31554", "ParentId": "31525", "Score": "1" } } ]
{ "AcceptedAnswerId": "31554", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T08:27:42.993", "Id": "31525", "Score": "1", "Tags": [ "javascript", "jquery", "html" ], "Title": "Table recreation function" }
31525
<p>Here's an absolutely essential piece of C++ lore, a stack allocator, that will allow you to, say, allocate strings and vectors on the stack. There are 2 stack allocators I know of, <a href="https://stackoverflow.com/questions/783944/how-do-i-allocate-a-stdstring-on-the-stack-using-glibcs-string-implementation">here</a> and <a href="https://stackoverflow.com/questions/11648202/questions-about-hinnants-stack-allocator">here</a>.</p> <p>The trouble was, neither of them were working with gcc-4.8, and both needed fixing. Here's a fixed version of Hinant's allocator. Could there some improvement or fix to still be made?</p> <pre><code>#pragma once #ifndef STACKALLOCATOR_HPP # define STACKALLOCATOR_HPP #include &lt;cassert&gt; #include &lt;cstddef&gt; #include &lt;functional&gt; #include &lt;new&gt; #include &lt;utility&gt; template &lt;std::size_t N&gt; class stack_store { public: stack_store() = default; stack_store(stack_store const&amp;) = delete; stack_store&amp; operator=(stack_store const&amp;) = delete; char* allocate(std::size_t n) { assert(pointer_in_buffer(ptr_) &amp;&amp; "stack_allocator has outlived stack_store"); n = align(n); if (buf_ + N &gt;= ptr_ + n) { auto r(ptr_); ptr_ += n; return r; } else { return static_cast&lt;char*&gt;(::operator new(n)); } } void deallocate(char* const p, std::size_t n) noexcept { assert(pointer_in_buffer(ptr_) &amp;&amp; "stack_allocator has outlived stack_store"); if (pointer_in_buffer(p)) { n = align(n); if (p + n == ptr_) { ptr_ = p; } // else do nothing } else { ::operator delete(p); } } void reset() noexcept { ptr_ = buf_; } static constexpr ::std::size_t size() noexcept { return N; } ::std::size_t used() const { return ::std::size_t(ptr_ - buf_); } private: static constexpr ::std::size_t align(::std::size_t const n) noexcept { return (n + (alignment - 1)) &amp; -alignment; } bool pointer_in_buffer(char* const p) noexcept { return (buf_ &lt;= p) &amp;&amp; (p &lt;= buf_ + N); } private: static constexpr auto const alignment = alignof(::max_align_t); char* ptr_{buf_}; alignas(::max_align_t) char buf_[N]; }; template &lt;class T, std::size_t N&gt; class stack_allocator { public: using store_type = stack_store&lt;N&gt;; using size_type = ::std::size_t; using difference_type = ::std::ptrdiff_t; using pointer = T*; using const_pointer = T const*; using reference = T&amp;; using const_reference = T const&amp;; using value_type = T; template &lt;class U&gt; struct rebind { using other = stack_allocator&lt;U, N&gt;; }; stack_allocator() = default; stack_allocator(stack_store&lt;N&gt;&amp; s) noexcept : store_(&amp;s) { } template &lt;class U&gt; stack_allocator(stack_allocator&lt;U, N&gt; const&amp; other) noexcept : store_(other.store_) { } stack_allocator&amp; operator=(stack_allocator const&amp;) = delete; T* allocate(::std::size_t const n) { return static_cast&lt;T*&gt;(static_cast&lt;void*&gt;( store_-&gt;allocate(n * sizeof(T)))); } void deallocate(T* const p, ::std::size_t const n) noexcept { store_-&gt;deallocate(static_cast&lt;char*&gt;(static_cast&lt;void*&gt;(p)), n * sizeof(T)); } template &lt;class U, class ...A&gt; void construct(U* const p, A&amp;&amp; ...args) { new (p) U(::std::forward&lt;A&gt;(args)...); } template &lt;class U&gt; void destroy(U* const p) { p-&gt;~U(); } template &lt;class U, std::size_t M&gt; inline bool operator==(stack_allocator&lt;U, M&gt; const&amp; rhs) const noexcept { return store_ == rhs.store_; } template &lt;class U, std::size_t M&gt; inline bool operator!=(stack_allocator&lt;U, M&gt; const&amp; rhs) const noexcept { return !(*this == rhs); } private: template &lt;class U, std::size_t M&gt; friend class stack_allocator; store_type* store_{}; }; namespace std { // string template&lt;class CharT&gt; class char_traits; template&lt;class CharT, class Traits, class Allocator&gt; class basic_string; // unordered_map template&lt;class Key, class T, class Hash, class Pred, class Alloc&gt; class unordered_map; // vector template &lt;class T, class Alloc&gt; class vector; } using stack_string = ::std::basic_string&lt;char, ::std::char_traits&lt;char&gt;, stack_allocator&lt;char, 128&gt; &gt;; template &lt;class Key, class T, class Hash = ::std::hash&lt;Key&gt;, class Pred = ::std::equal_to&lt;Key&gt; &gt; using stack_unordered_map = ::std::unordered_map&lt;Key, T, Hash, Pred, stack_allocator&lt;::std::pair&lt;Key const, T&gt;, 256&gt; &gt;; template &lt;typename T&gt; using stack_vector = ::std::vector&lt;T, stack_allocator&lt;T, 256&gt; &gt;; #endif // STACKALLOCATOR_HPP </code></pre> <p>Example usage:</p> <pre><code>#include &lt;iostream&gt; #include "stackallocator.hpp" int main() { ::stack_string::allocator_type::store_type s; ::std::cout &lt;&lt; ::stack_string("blabla", s).c_str() &lt;&lt; std::endl; return 0; } </code></pre> <p>After running the above example under valgrind, it will report:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>==25600== HEAP SUMMARY: ==25600== in use at exit: 0 bytes in 0 blocks ==25600== total heap usage: 0 allocs, 0 frees, 0 bytes allocated ==25600== ==25600== All heap blocks were freed -- no leaks are possible ==25600== ==25600== For counts of detected and suppressed errors, rerun with: -v ==25600== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2) </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:11:54.173", "Id": "50309", "Score": "0", "body": "Why do you use global namespacing operator `::` in example usage?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:56:40.357", "Id": "50332", "Score": "0", "body": "@sasha.sochka It's not really a global operator, it just means outside of the current namespace." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T21:07:05.830", "Id": "50341", "Score": "0", "body": "Ok, but why do you need it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T21:30:16.913", "Id": "50342", "Score": "1", "body": "@sasha.sochka It's slightly more pedantic to use it than not. Programming is conveying meaning to the compiler. If you write `::stack_string`, you mean exactly that, a `::stack_string` type outside the current namespace." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:43:32.797", "Id": "50378", "Score": "0", "body": "Sorry, I have to downvote this because the question lacks enough detail to be answerable. You should rephrase your question by adding more detail what exactly does not work out of the box with Hinnant's allocator, and which uses cases you want to support. It's an interesting problem to consider and I encourage you to spend more effort on it to help potential readers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:00:59.150", "Id": "50383", "Score": "1", "body": "@TemplateRex I think you mistook Code Review for SO. I wasn't asking for help in compiling Hinant's allocator, but for suggestions/fixes for my fix. We're commenting code here, not asking for help in making code work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:18:07.453", "Id": "50387", "Score": "0", "body": "@TemplateRex Here's a little something to prove my point: http://ideone.com/VzzS4I I think you're not providing useful advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:02:46.803", "Id": "50396", "Score": "0", "body": "I understand the difference between code review and answering questions. When you write \"Trouble was neither of them was working with gcc-4.8, both needed fixing.\" and provide a long and renamed implementation of Hinnant's stack allocator, it is hard to see why all those changes were necessary. At the very least you could have provided a summary of the types of errors (simple warnings, missing typedefs / members, missing constructors) that you got without your fixes. Reviewing fixes without a rationale (other than \"was not working\") for those fixes is rather hard, IMO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:10:57.490", "Id": "50400", "Score": "0", "body": "@TemplateRex Hinant himself hinted improvements might be possible here: http://stackoverflow.com/questions/11648202/questions-about-hinnants-stack-allocator , but did not do so. The thing is, I pasted in code - without it my post would have been invalid - and you can suggest improvements based on that alone. You don't need to know about history of the code or anything else. The code compiles and the question was how to improve it. The implementation was not renamed, I gave due credit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:15:38.543", "Id": "50401", "Score": "0", "body": "Look, reasonable people can disagree here, but I am used to reviewing fixes by 3 measures: a) was it broken before, and if so, how? b) does the fix actually correct these problems? and c) is the patch as unintrusive as possible? All these aspects require at least more background about the nature of the problem that you are trying to fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:36:34.003", "Id": "50403", "Score": "0", "body": "@TemplateRex I was asking about the things Hinant hinted of, for example, the fix works for me. I cannot ask that sort of thing on SO. This is the place for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-09T20:52:07.380", "Id": "119620", "Score": "0", "body": "Doesn't the allocator need to use `stack_store<sizeof(T) * N>;` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-11T07:13:14.250", "Id": "190873", "Score": "0", "body": "Don't know, if you are still monitoring this, but your `pointer_in_buffer` function exhibits undefined behavior, if the pointer doesn't point into the buffer. I'd recommend using STL - compare objects and leave a comment in the code, about why you did that. http://stackoverflow.com/questions/27766570/how-do-i-safely-and-sensibly-determine-whether-a-pointer-points-somewhere-into-a" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-15T12:10:45.667", "Id": "191599", "Score": "0", "body": "@MikeMB Thanks! Fortunately the fix is very easy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-15T15:40:47.360", "Id": "191678", "Score": "0", "body": "@user1095108: Appears I was wrong - Sorry for that. I brought up the same topic on TemplateRex's original question about Hinnant's allocator and he explained, that in C++ (contrary to C) it is actually not undefined, but unspecified (read implementation dependent) behavior. So if your are not targeting a particular stange platform, the solution with the standard operators should also be fine" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-25T10:10:13.020", "Id": "219250", "Score": "0", "body": "@user1095108 If you're in nested namespaces and each has the symbol `x` in it, then `::x`will bring you to the global `x`, not the `x` from the closest outside namespace. Compared to filesystem navigation `::` is like `/` not like `..`." } ]
[ { "body": "<h2>Fixes required for a conforming Standard Library</h2>\n\n<p>There is one big issue that will make custom allocators fragile to work with: incomplete C++11 library support. Since C++11, containers are required to go through <code>std::allocator_traits&lt;Allocator&gt;</code> to access <code>construct()</code> and <code>destroy()</code> allocator member functions, as well as to access nested typedefs such as <code>pointer</code> and <code>reference</code>. Furthermore, all containers have a constructor with a single allocator argument. Not every Standard Library implements this for every container.</p>\n\n<p>With the <a href=\"http://coliru.stacked-crooked.com/\" rel=\"nofollow noreferrer\">Coliru online compiler</a>, I can get <a href=\"http://howardhinnant.github.io/short_alloc.h\" rel=\"nofollow noreferrer\">Hinnant's stack allocator</a> working with <code>libstdc++</code> for a <code>std::vector</code> with only 2 minor modifications running </p>\n\n<pre><code>g++ -std=c++11 -O1 -pedantic -Wall -Wconversion -Wsign-conversion -Wsign-promo\n</code></pre>\n\n<p>The first is to put parenthesis around the <code>n + (alignment - 1)</code> operand in the <code>align_up()</code></p>\n\n<pre><code>std::size_t \n align_up(std::size_t n) noexcept\n {return (n + (alignment-1)) &amp; ~(alignment-1);}\n ^ ^\n</code></pre>\n\n<p>The second is to remove the exception specification from the overloaded <code>operator new</code></p>\n\n<pre><code>void* operator new(std::size_t s) // throw(std::bad_alloc)\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/d69fbdac7f2c9b4c\" rel=\"nofollow noreferrer\"><strong>Live Example</strong></a> exactly reproducing <a href=\"http://howardhinnant.github.io/stack_alloc.html\" rel=\"nofollow noreferrer\">Hinnant's first test case</a>.</p>\n\n<p>Note that these 2 warnings are rather innocent and do not affect correctness of the program.</p>\n\n<h2>Fixes required for a non-conforming Standard Library</h2>\n\n<p>Since <code>libstdc++</code> works fine with all containers if a <code>std::allocator</code> is provided (even when the container implementation directly accesses the allocator, rather than through <code>std::allocator_traits</code>) the safest bet is to provide all the nested typedefs and member functions of <code>std::allocator_traits</code> in your own allocator as well. This includes the various pointer and reference types, as well as the rebind templates. You appear to have done so, and this should resolve at least of all those issues. I still would leave the original naming of Hinnant's version in tact, though.</p>\n\n<p>That leaves the issues of constructors taking a single allocator argument. At least for <code>libstdc++</code> for g++ 4.8.1, <a href=\"https://stackoverflow.com/q/18913388/819272\">this constructor is missing</a> for <code>std:unordered_map</code>. Apart from patching the standard library headers yourself (possible, but if you have an automatic package updater, that will require constant monitoring) or <a href=\"http://gcc.gnu.org/onlinedocs/libstdc++/manual/appendix_contributing.html\" rel=\"nofollow noreferrer\">submit a bug report</a>. Microsoft did have many such issues in Visual C++ 2012 November CTP, which have all been fixed in Visual C++ 2013.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T08:43:43.657", "Id": "50369", "Score": "0", "body": "Try making it work with an `unordered_map`. This was the source of major problems. Even so, it did not work out of the box." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T08:50:09.490", "Id": "50371", "Score": "0", "body": "@user1095108 It does work out-of-the-box without `-Wall`. Simply fixing the warnings as I showed above also works. What exactly does not work with `std::unordered_map`? And please indicate how I could improve this answer (if you were the one downvoting it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:31:15.910", "Id": "50374", "Score": "0", "body": "In my case it had a problem with the lack of a default constructor. Even if you added one, the compiler complained about a dangling reference. The problem, I think, had to do with `libstdc++`'s `std::string` implementation. Are you interested in seeing the error? In general you need to adapt the allocator to the situation at hand, sometimes, the STL container is odd itself (for example, does not make use of ::std::allocator_traits). I downvoted because you are not providing fixes/thoughts for improvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:38:39.343", "Id": "50375", "Score": "0", "body": "@user1095108 I think the problems you have with `std::unordered_map` and custom allocators are related to incomplete `libstdc++` support for constructors taking a single allocator argument, and are unrelated to this specific allocator version. FYI, I posed a [question](http://stackoverflow.com/q/18913388/819272) on SO about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:40:50.113", "Id": "50376", "Score": "1", "body": "@user1095108 I think your downvoting is rather harsh. I answered in detail how 2 minor fixes would eliminate the (innocent!) warnings from Hinnant's stack allocator. You then respond by making up 2 use cases that do not appear in your original question. How is one going to answer that without more detail?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:43:08.737", "Id": "50377", "Score": "0", "body": "I did not ask about fixing the Hinant's allocator, since I've fixed it myself. I was asking about fixes to my fix. I don't care if my question gets downvoted to -inf, so why do you care if I downvote your answer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:45:54.680", "Id": "50379", "Score": "0", "body": "@user1095108 My fixes to your fix are detailed in my answer: roll them all back (you are providing way too much, e.g. `construct()` / `destroy()`) and apply the 2 tiny fixes I showed you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:49:18.543", "Id": "50380", "Score": "0", "body": "Your suggestion is wrong, because of the oddities of libstdc++'s implementation of `unordered_map`. I.e. it does not use `::std::allocator_traits` for `construct`/`destroy`. The tiny fixes don't apply to my fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:52:35.033", "Id": "50394", "Score": "0", "body": "@user1095108 I have taken your comments into account, see updated answer. Your fixes are fine, and they will resolve the issue of direct allocator accesses (rather than through `std::allocator_traits`. For missing constructors, you cannot do much except patch the library headers or submitting a bug report (which I would encourage you to do so regardless)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:58:06.217", "Id": "50395", "Score": "0", "body": "I'll remove the downvote, but I won't accept just yet, since I was hoping for some fine hacks on top of those already provided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:04:04.660", "Id": "50398", "Score": "0", "body": "@user1095108 I don't think you can \"hack\" a missing constructor, other than adding it into the libstdc++ source yourself. I feel your pain, having gone through the Visual C++ headers myself this way, last year." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-18T18:45:12.817", "Id": "151850", "Score": "0", "body": "Note Howard's old pages are gone, so you need to update those links: http://howardhinnant.github.io/stack_alloc.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-18T20:45:18.170", "Id": "151882", "Score": "0", "body": "@ShafikYaghmour tnx, updated!" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T08:39:31.350", "Id": "31575", "ParentId": "31528", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T09:10:25.623", "Id": "31528", "Score": "10", "Tags": [ "c++", "c++11", "memory-management", "stack" ], "Title": "A working stack allocator" }
31528
<p><strong>NOTE</strong>: I'm not perfectly sure of some of the parsed data, so any corrections are more than welcome.</p> <p>Parser (cpuid.c):</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;string.h&gt; #include "cpuid.h" enum { CPU_PROC_BRAND_STRING_INTERNAL0 = 0x80000003, CPU_PROC_BRAND_STRING_INTERNAL1 = 0x80000004 }; #ifndef _MSC_VER static void ___cpuid(cpuid_t info, uint32_t *eax, uint32_t *ebx, uint32_t *ecx, uint32_t *edx) { __asm__( "xchg %%ebx, %%edi\n\t" /* 32bit PIC: Don't clobber ebx. */ "cpuid\n\t" "xchg %%ebx, %%edi\n\t" : "=a"(*eax), "=D"(*ebx), "=c"(*ecx), "=d"(*edx) : "0" (info) ); } #else #include &lt;intrin.h&gt; static void ___cpuid(cpuid_t info, uint32_t *eax, uint32_t *ebx, uint32_t *ecx, uint32_t *edx) { uint32_t registers[4]; __cpuid(registers, info); *eax = registers[0]; *ebx = registers[1]; *ecx = registers[2]; *edx = registers[3]; } #endif int highest_ext_func_supported(void) { static int highest; if (!highest) { asm volatile( "cpuid\n\t" : "=a" (highest) : "a" (CPU_HIGHEST_EXTENDED_FUNCTION_SUPPORTED) ); } return highest; } int cpuid_test_feature(cpuid_t feature) { if (feature &gt; CPU_VIRT_PHYS_ADDR_SIZES || feature &lt; CPU_EXTENDED_PROC_INFO_FEATURE_BITS) return 0; return (feature &lt;= highest_ext_func_supported()); } int cpuid_has_feature(cpufeature_t feature) { uint32_t eax, ebx, ecx, edx; ___cpuid(CPU_PROCINFO_AND_FEATUREBITS, &amp;eax, &amp;ebx, &amp;ecx, &amp;edx); switch (feature) { case CF_MMX: case CF_SSE: case CF_SSE2: return (edx &amp; ((int)feature)) != 0; case CF_SSE3: case CF_SSSE3: case CF_SSE41: case CF_SSE42: case CF_AVX: case CF_FMA: return (ecx &amp; ((int)feature)) != 0; } return 0; } int cpuid_has_ext_feature(cpuextfeature_t extfeature) { uint32_t eax, ebx, ecx, edx; if (!cpuid_test_feature(CPU_EXTENDED_PROC_INFO_FEATURE_BITS)) return 0; ___cpuid(CPU_EXTENDED_PROC_INFO_FEATURE_BITS, &amp;eax, &amp;ebx, &amp;ecx, &amp;edx); switch (extfeature) { case CEF_x64: return (edx &amp; ((int)extfeature)) != 0; case CEF_SSE4a: case CEF_FMA4: case CEF_XOP: return (ecx &amp; ((int)extfeature)) != 0; } return 0; } cputype_t get_cpu_type(void) { static cputype_t cputype; static const char *cpuids[] = { "Nooooooooone", "AMDisbetter!", "AuthenticAMD", "CentaurHauls", "CyrixInstead", "GenuineIntel", "TransmetaCPU", "GeniuneTMx86", "Geode by NSC", "NexGenDriven", "RiseRiseRise", "SiS SiS SiS ", "UMC UMC UMC ", "VIA VIA VIA ", "Vortex86 SoC", "KVMKVMKVMKVM" }; if (cputype == CT_NONE) { union { char buf[12]; uint32_t bufu32[3]; } u; uint32_t i; ___cpuid(CPU_VENDORID, &amp;i, &amp;u.bufu32[0], &amp;u.bufu32[2], &amp;u.bufu32[1]); u.buf[12] = '\0'; for (i = 0; i &lt; sizeof(cpuids) / sizeof(cpuids[0]); ++i) { if (strncmp(cpuids[i], u.buf, 12) == 0) { cputype = (cputype_t)i; break; } } } return cputype; } void cpuid(cpuid_t info, void *buf) { /* Sanity checks, make sure we're not trying to do something * invalid or we are trying to get information that isn't supported * by the CPU. */ if (info &gt; CPU_VIRT_PHYS_ADDR_SIZES || (info &gt; CPU_HIGHEST_EXTENDED_FUNCTION_SUPPORTED &amp;&amp; !cpuid_test_feature(info))) return; uint32_t *ubuf = buf; if (info == CPU_PROC_BRAND_STRING) { ___cpuid(CPU_PROC_BRAND_STRING, &amp;ubuf[0], &amp;ubuf[1], &amp;ubuf[2], &amp;ubuf[3]); ___cpuid(CPU_PROC_BRAND_STRING_INTERNAL0, &amp;ubuf[4], &amp;ubuf[5], &amp;ubuf[6], &amp;ubuf[7]); ___cpuid(CPU_PROC_BRAND_STRING_INTERNAL1, &amp;ubuf[8], &amp;ubuf[9], &amp;ubuf[10], &amp;ubuf[11]); return; } else if (info == CPU_HIGHEST_EXTENDED_FUNCTION_SUPPORTED) { *ubuf = highest_ext_func_supported(); return; } uint32_t eax, ebx, ecx, edx; ___cpuid(info, &amp;eax, &amp;ebx, &amp;ecx, &amp;edx); switch (info) { case CPU_VENDORID: ubuf[0] = ebx; ubuf[1] = edx; ubuf[2] = ecx; break; case CPU_PROCINFO_AND_FEATUREBITS: ubuf[0] = eax; /* The so called "signature" of the CPU. */ ubuf[1] = edx; /* Feature flags #1. */ ubuf[2] = ecx; /* Feature flags #2. */ ubuf[3] = ebx; /* Additional feature information. */ break; case CPU_CACHE_AND_TLBD_INFO: ubuf[0] = eax; ubuf[1] = ebx; ubuf[2] = ecx; ubuf[3] = edx; break; case CPU_EXTENDED_PROC_INFO_FEATURE_BITS: ubuf[0] = edx; ubuf[1] = ecx; break; case CPU_L1_CACHE_AND_TLB_IDS: break; case CPU_EXTENDED_L2_CACHE_FEATURES: *ubuf = ecx; break; case CPU_ADV_POWER_MGT_INFO: *ubuf = edx; break; case CPU_VIRT_PHYS_ADDR_SIZES: *ubuf = eax; break; default: *ubuf = 0xbaadf00d; break; } } </code></pre> <p>A full test suite and everything is available <a href="https://github.com/decltype/misccsnippets" rel="nofollow">here</a>.</p> <p>Stuff that I'm not fairly satisfied of:</p> <ul> <li>Processor information and feature bits (Maybe cause not fully tested)</li> <li>Cache and TLBD information.</li> <li>Extended processor information and feature bits</li> <li>Extended L2 Cache features</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T17:21:54.787", "Id": "50801", "Score": "1", "body": "\"GeniuneTMx86\" is probably a typo -> \"GenuineTMx86\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T19:39:27.787", "Id": "58794", "Score": "0", "body": "Your full test suite etc is not at the link provided. Can you fix the link please? Also perhaps add the header cpuid.h to the question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-05T07:53:09.957", "Id": "181620", "Score": "0", "body": "Play it safe and copy the Linux kernel source: http://unix.stackexchange.com/a/219674/32558 :-)" } ]
[ { "body": "<p>Here are some comments on your code.</p>\n\n<p>I think your types <code>cpufeature_t</code> and <code>cpuextfeature_t</code> are probably\nunnecessary as they are just <code>uint32_t</code>. They might be better expressed as\nenums.</p>\n\n<p>Functions that are purely for local use (ie. not part of the public interface)\nshould be <code>static</code>. This prevents polluting the global namespace and allows\nbetter optimisation.</p>\n\n<p>Function <code>___cpuid</code> should be renamed without the underscores (which are\nreserved for use by the implementation). A better name might be <code>get_cpuid</code>.\nThe function also takes a <code>cpuid_t</code> parameter named <code>info</code> that might be\nbetter named <code>request</code>.</p>\n\n<p>In <code>cpuid_has_feature</code> the switch should really have a <code>default</code> case,\nalthough the trailing <code>return 0</code> kind of takes its place. The casts to <code>int</code>\nshould be to <code>uint32_t</code> instead to match the types of <code>eax</code> etc. Note also\nthat</p>\n\n<pre><code>return (edx &amp; ((uint32_t)feature)) != 0;\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>return edx &amp; (uint32_t)feature;\n</code></pre>\n\n<p>In <code>cpuid_has_ext_feature</code>, the initial call to\n<code>cpuid_test_feature(CPU_EXTENDED_PROC_INFO_FEATURE_BITS)</code> is unnecessary\nbecause you already know that <code>CPU_EXTENDED_PROC_INFO_FEATURE_BITS</code> is valid.\nThe switch default is also missing.</p>\n\n<p>In <code>get_cpu_type</code> you return an integer index into your local array of ID\nstrings but that index has no meaning to the caller unless they have exacctly\nthe same list of ID strings. Except for the first entry, your list matches\nthat in Wikipedia, but that is rather weak. I'd prefer to see an enum or #defined constant associated with each array entry. </p>\n\n<p>Also in that function you terminate the string <code>u.buf[12] = '\\0';</code> and in\ndoing so break the stack (<code>u.buf</code> has a size of 12 so you wrote beyond the\nend). You don't actually need to terminate as you use <code>strncmp</code> for your\nstring comparisons - note that the explicit <code>12</code> in the <code>strncmp</code> should really \nbe <code>sizeof cpuids[0]</code>. </p>\n\n<p>In <code>cpuid</code> I don't like the use of a <code>void*</code> parameter to return the various\ntypes of information (strings, integers etc). A better solution would be to\npass a pointer to a structure or a discriminated union that has a field for\neach type of information returned by <code>cpuid</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T02:34:00.363", "Id": "36100", "ParentId": "31532", "Score": "4" } } ]
{ "AcceptedAnswerId": "36100", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T11:45:18.370", "Id": "31532", "Score": "5", "Tags": [ "c", "parsing", "linux", "assembly" ], "Title": "Is this CPUID parser ideal for any usage?" }
31532
<p>I need suggestions.</p> <pre><code>var textarea = document.getElementById("textarea"), filename = prompt("Name this note:", "untitled"); if (filename == null) { window.close(); } else if (filename == "") { filename = "untitled"; }; document.title = filename + ".txt"; function Rename() { // Rename note filename = document.title.substr(0, document.title.lastIndexOf(".")); filename = prompt("Rename this note:", filename); if (filename != null &amp;&amp; filename != "") { document.title = filename + ".txt"; } }; function Save() { // Save note var blob = new Blob([textarea.value], { type: "text/plain;charset=utf-8" }); saveAs(blob, document.title); }; function Email() { // Email note var to = prompt("Enter the recipient\'s email id", "someone@example.com"), link = "mailto:" + to + "?subject=" + document.title + "&amp;body=" + encodeURIComponent(textarea.value); if (to != null &amp;&amp; to != "") { window.open(link); } }; /*function popupWin() { // Open as popup window var data = textarea.value; var popup = window.open(window.location.href, "", "height=480,width=500,resizable=yes,location=no,status=no,toolbar=no"); popup.window.textarea.value = data; }; */ function Open() { // Open a file document.getElementById("selected_file").click(); } function loadFileAsText() { //File loader var selected_file = document.getElementById("selected_file").files[0]; var fileReader = new FileReader(); fileReader.onloadend = function(e) { if (e.target.readyState == FileReader.DONE) { document.title = selected_file.name; textarea.value = e.target.result; textarea.focus(); } }; fileReader.readAsText(selected_file, "utf-8"); } function Help() { //Launch help document.getElementById("help").style.display = "block"; document.getElementById("closeHelp").style.display = "block"; document.getElementById("showHelp").style.display = "none"; textarea.style.opacity = 0.1; }; function closeHelp() { // Close help document.getElementById("help").style.display = "none"; document.getElementById("closeHelp").style.display = "none"; document.getElementById("showHelp").style.display = "block"; textarea.style.opacity = 1; textarea.focus(); }; // Confirm close window.onbeforeunload = function() { if (textarea.value != "") { return "Reloading this page will remove all unsaved changes."; } }; // Keyboard shortcuts var ctrl = "ctrl"; if (navigator.platform.toLowerCase().indexOf("mac") &gt; -1) { ctrl = "command"; }; Mousetrap.bind(ctrl + "+/", function(e) { e.preventDefault(); Help(); }); Mousetrap.bind("esc", function(e) { closeHelp(); }); Mousetrap.bind(ctrl + "+n", function(e) { e.preventDefault(); location.reload(); }); Mousetrap.bind(ctrl + "+o", function(e) { e.preventDefault(); Open(); }); Mousetrap.bind(ctrl + "+s", function(e) { e.preventDefault(); Save(); }); Mousetrap.bind(ctrl + "+e", function(e) { e.preventDefault(); Email(); }); Mousetrap.bind(ctrl + "+r", function(e) { e.preventDefault(); Rename(); }); Mousetrap.bind("tab", function(e) { e.preventDefault(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:25:49.393", "Id": "50279", "Score": "0", "body": "https://dl.dropboxusercontent.com/u/92126558/projects/ntpd/js/main.js is the link to the code btw (had to retrieve it from the page's source...)" } ]
[ { "body": "<h1>Usability</h1>\n\n<ul>\n<li>Horrible user experience. Nobody wants to see a modal prompt popping up right when opening a site.</li>\n<li><code>window.close()</code> when not entering something in that prompt. Not only do most browsers rightfully reject this unless it's a popup window, it's also annoying if it works for some reason.</li>\n<li><code>mailto:</code> URLs are ancient. Don't use them - with most webmail clients (which are VERY popular nowadays) they don't even work.</li>\n<li><em><kbd>Ctrl</kbd> + <kbd>/</kbd> : Help</em> - this does not work on non-US keyboards where <code>/</code> is e.g. on <kbd>SHIFT</kbd>+<kbd>7</kbd>.</li>\n<li>Unconditional <code>onbeforeunload</code> is annoying. Sure, there's no good way to save stuff but anyway, you should really not show that prompt when someone clicked the save button and did not edit the text afterwards.</li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><code>filename = document.title.substr(0, document.title.lastIndexOf(\".\"));</code> - really? using the document title for this? Store it in a variable! Don't pass data between application and presentation layers around for no reason. The title of the page should be considered write-only (even though it's not).</li>\n<li><code>if (to != null &amp;&amp; to != \"\")</code> - that can be simplified to <code>if (to)</code> which is much nicer since it catches all falsy values.</li>\n</ul>\n\n<h1>Misc</h1>\n\n<ul>\n<li>When someone loads a binary file you dump it in the textarea anyway. That's pretty ugly.</li>\n<li>To make this worse, clicking the email button will put the whole file content in the address bar (as part of the mailto URL). At least in Firefox that hangs the browser for a few seconds (tested it with some small-ish jpg file).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:17:48.370", "Id": "31534", "ParentId": "31533", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T13:01:06.167", "Id": "31533", "Score": "1", "Tags": [ "javascript" ], "Title": "text editing app" }
31533
<p>I'd like your thoughts on this basic implementation of MVC. The view outputs a form, and when the page is loaded, the controller checks for a form submission and then updates the model accordingly. Finally, the view outputs the form again, grabbing the new values from the model.</p> <p>One problem with this is that if the user refreshes the page, a submission will still happen because the <code>$_POST['submitted']</code> flag is still sent. Ideally, I'd like to avoid this - is there a suggestion for using AJAX to make this work?</p> <pre><code>&lt;?php class EntryModel { public $date; public $amount; public function update_date($date) { $this-&gt;date = $date; } public function update_amount($amount) { $this-&gt;amount = $amount; } } class EntryController { private $model; public function __construct(EntryModel $model) { $this-&gt;model = $model; } public function get_submission() { if (!isset($_POST['submitted'])) return; foreach ($_POST as $g =&gt; $k) { if ($g == 'form_date') $this-&gt;model-&gt;update_date($k); elseif ($g == 'form_amount') $this-&gt;model-&gt;update_amount($k); } echo ("Sucessful submission"); } } class EntryView { private $model; private $controller; public function __construct(EntryController $controller, EntryModel $model) { $this-&gt;controller = $controller; $this-&gt;model = $model; } public function output() { $form_output = '&lt;form action="index.php" method="POST"&gt; &lt;div&gt;Date: &lt;input type="date" name="form_date" value="' . $this-&gt;model-&gt;date . '"&gt;&lt;/div&gt; &lt;div&gt;Amount: &lt;input type="number" name="form_amount" value="' . $this-&gt;model-&gt;amount . '"&gt;&lt;/div&gt; &lt;input type="hidden" name="submitted" value="yes"&gt; &lt;input type="submit"&gt; &lt;/form&gt;'; return $form_output; } } $model = new EntryModel(); $controller = new EntryController($model); $view = new EntryView($controller, $model); $controller-&gt;get_submission(); echo $view-&gt;output(); ?&gt; </code></pre>
[]
[ { "body": "<h2>Templates</h2>\n\n<p>Your HTML code should be separated out into a template file. You should do your best to avoid mixing HTML into your PHP, as your HTML will inevitably grow, and your PHP will get messier as a result. </p>\n\n<h2>Post/Get/Redirect</h2>\n\n<p>The pattern you are looking for is <a href=\"http://en.wikipedia.org/wiki/Post/Redirect/Get\" rel=\"nofollow\">Post/Get/Redirect</a>. You should always follow this pattern. When a user submits a form using POST, you should process the form, and then if it was successful, redirect them back to some page (possibly the form page again) with an added URL parameter.</p>\n\n<p>E.g. <code>http://example.com/contact-us?submitted=true</code></p>\n\n<p>Then in your form code, you can check if the URL parameter is present, and show a success message.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T16:21:41.967", "Id": "31541", "ParentId": "31538", "Score": "7" } } ]
{ "AcceptedAnswerId": "31541", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T14:35:50.293", "Id": "31538", "Score": "3", "Tags": [ "php", "mvc" ], "Title": "Basic PHP MVC setup for form submissions" }
31538
<p><strong>The background</strong></p> <p>Two beginners without access to an experienced mentor write an ASP .NET MVC application, mostly simple CRUD, using Linq to SQL for the data access layer. Beginner number 1 writes the model part. I, beginner number 2, start writing controllers and views. When using the web and a textbook for learning best practices, I notice that our code differs from the established patterns in some way. Still, I create a way for the user to edit data without changing my coworker's code, and as far as we have tested, it does what it is supposed to do. </p> <p>If our slightly unorthodox approach works, we cannot afford to refactor the whole thing right now. But I am afraid that we can have programmed us into a corner and be too inexperienced to notice it. <strong>So please tell us: what are the potential downsides of our current implementation?</strong> </p> <p><strong>A big picture of the concept</strong></p> <p>We save edits to an entity of type Animal line in the following way: On submitting the form with the edits, the model binder returns a viewmodel to the controller. Every time the controller is initialized, it creates a a new repository instance, initializing it with a new instance of a data context. When the user submits edits, the default model binder returns a new viewmodel object to the controller action. The controller calls the viewmodel's UpdateBaseAnimalLine method, which changes the properties of the entity class. Then the controller calls the repository's Update method on the newly changed entity class. It does nothing more than calling SubmitChanges on the repository's data context. </p> <p><strong>Problems I have seen so far</strong></p> <ul> <li><p>As far as I am aware, the data context is never disposed of in our code. After looking around, it seems that having one data context per repository instance <a href="http://www.west-wind.com/weblog/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management" rel="noreferrer">is good practice</a>, so we probably don't want to change that, but I cannot think of a good place to add a dispose call, what am I overlooking? The examples I found on the web use custom-written factories which provide a datacontext, and I hope there is a simpler way to do it right. </p></li> <li><p>It looks weird to me that we have to change the state of the actual entity object somewhere, and then just call "SubmitChanges" in the repository. Doesn't this open us to potential race conditions? Or is the framework intelligent enough to take care of that behind the scenes? More to the point, does it take care of it in the way we are using it? </p></li> <li><p>Is there a way to get the default model binder to use a viewmodel constructor which takes an int parameter, instead of just initializing all primitive type fields with the values from the form? (I suppose that it is possible if I write a custom one, but as I have a workaround, I don't want to go that deep for now). </p></li> </ul> <p>Please look into the code for further problems, I suppose there must be more than I can find. </p> <p><strong>The code</strong></p> <p>As a shortened example, we have the business entity Animal Line, with the two properties name and database ID. </p> <pre><code> [Table(Name = "AnimalLine")] public class AnimalLine { [Column(Name = "AnimalLine_ID", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)] public int AnimalLineId { get; set; } [Column(Name = "FullName", CanBeNull = false)] public string FullName { get; set; } } </code></pre> <p>There is a class functioning as a repository, called AnimalLineManagement. It can update an existing animal line either from a bunch of properties, or from an existing object. </p> <pre><code>public class AnimalLineManagement { private DataContext dataContext; private Table&lt;AnimalLine&gt; animalLine; public AnimalLineManagement(DataContext dataContext) { // as far as I can see, he has forgotten to dispose of the data context. this.dataContext = dataContext; animalLine = dataContext.GetTable&lt;AnimalLine&gt;(); } // other methods left out for brevity public bool Update(String fullName, int id) { try { var al = animalLine.SingleOrDefault(a =&gt; a.AnimalLineId == id); if (al != null) { if (!String.IsNullOrEmpty(fullName)) { al.fullName= fullName; } } dataContext.SubmitChanges(); return true; } else { return Insert(fullName); } } catch { return Insert(fullName); } } public void Update(AnimalLine al) { dataContext.SubmitChanges(); } } </code></pre> <p>There is also a view model class, which wraps an actual animal line class. It provides the properties of the animal line in a way which will not produce an exception (in the real application, a call like AnimalLine.Species.LatinName produces an exception if Species is not set, and I don't want to catch this in the view in the middle of all the HTML), and packs some more info which would have been stuffed in the ViewBag else (not shown here). </p> <pre><code>public class AnimalLineVM { private AnimalLine animalLine; public string errorMessage = "An error occured while trying to retrieve this information"; private string fullName; //I would have preferred to always initialize the base animal line //in the constructor, but when the instance is created by the model binder, //I don't think I can do this. So I set the base animal line later, //using this variable to ensure that once set, it can't be changed. private bool animalLineAlreadySet; public AnimalLineVM(AnimalLine baseAnimalLine) { this.animalLine = baseAnimalLine; animalLineAlreadySet = true; } public AnimalLineVM() { animalLineAlreadySet = false; } public AnimalLine BaseAnimalLine { get { return animalLine; } set { if (!animalLineAlreadySet) { animalLine = value; animalLineAlreadySet = true; } else { throw new InvalidOperationException("The base animal line has already been set. It is not possible to change it."); } } } [Display(Name = "ID")] public int AnimalLineId { // read only, so we cannot get a discrepancy between the base animal line and the ID in the viewmodel get { if (animalLineAlreadySet) { int id = BaseAnimalLine.AnimalLineId; if (id == null || id &lt; 0) { return -1; } else return id; } else return -1; } } [Display(Name = "Full name")] public string FullName { get { fullName = fullName ?? errorMessage; return fullName; } set { fullName = value; } } public void updateBaseAnimalLine() { BaseAnimalLine.FullName = this.FullName; } } </code></pre> <p>And this is the controller: </p> <pre><code>public class AnimalLineController : Controller { private IAnimalLineManagement animalLineManagement; public TumorModelsController() :base() { animalLineManagement = new AnimalLineManagement(new DataContext(ConfigurationManager.ConnectionStrings["TumorModelsDB"].ConnectionString)); } public ActionResult EditAnimalLine(int animalLineId) { AnimalLine al = animalLineManagement.GetSingleLine(animalLineId); return View("EditAnimalLine", new AnimalLineVM(al)); } //TODO: implement validation of user input [HttpPost] public ActionResult EditAnimalLine(AnimalLineVM animalLine) { int alId; if (int.TryParse(Request.Form["animalLineId"], out alId)) { animalLine.BaseAnimalLine = animalLineManagement.GetSingleLine(alId); animalLine.updateBaseAnimalLine(); } return View("AnimalLine", animalLine); } } </code></pre>
[]
[ { "body": "<p>First of all, your code doesn't compile, you have a poor lonely extra closing bracket in your <code>Update</code> method.</p>\n\n<p>Next, your <code>Update</code> method shouldn't <code>Insert</code> if <code>Update</code> doesn't work. If the entity doesn't exist, you should return false. Otherwise rename your method <code>UpdateOrInsert</code> so that it is clear what you are doing! Also, you shouldn't blindly catch every possible exception. Imagine an <code>SqlException</code> is thrown because the connection cannot be established to the database, you will catch this exception, then try to insert into the \"broken\" database. I don't think you need to catch any exceptions there because you already check if your entity exists. If you need to catch, you might have another problem in your code. </p>\n\n<p>The second <code>Update</code> method is weird, why does it exists?</p>\n\n<p>In your view model, your <code>errorMessage</code> should be marked <code>const</code>. Also, if your application ever needs to offer multiple languages, you should consider putting this message in a resource file.</p>\n\n<p>This code doesn't compile, an <code>int</code> cannot be null, so your if should only check if the <code>id</code> is greater than 0.</p>\n\n<pre><code>int id = BaseAnimalLine.AnimalLineId;\nif (id == null || id &lt; 0)\n</code></pre>\n\n<p>In your <code>FullName</code> getter, I have a suggestion to make it a one liner, (maybe you won't like it but maybe you'll learn something from this!) you can do :</p>\n\n<pre><code>get { return fullName ?? (fullName = errorMessage); }\n</code></pre>\n\n<p><strong>Edit</strong> You could also return <code>fullName ?? errorMessage</code> if you don't need to use <code>fullName</code> with the <code>errorMessage</code> value anywhere else.</p>\n\n<p>For your problem about the intiialization of the base animal line, I would recommend not to validate that it cannot be set more than once. A view model is almost like a DTO, if I decide to mess up its values, it is the problem of the code's user, you don't have to protect your VM from this.</p>\n\n<p>In your controller, the constructor's signature doesn't fit the controller's name, this doesn't compile.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-19T15:53:35.070", "Id": "60480", "ParentId": "31543", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T16:41:48.227", "Id": "31543", "Score": "8", "Tags": [ "c#", "beginner", "linq-to-sql" ], "Title": "Does this unusual data access pattern create any problems?" }
31543
<p>I've been trying to take image pixel data and write it out into printer code and my results are rather slow.</p> <p>Here is a simplified version of what I have so far (image is a PIL Image object of 1200 x 1800 pixels):</p> <pre><code># ~36 seconds on beaglebone f.write(pclhead) pix = image.getdata() for y in xrange(1800): row = '\xff'*72 ### vvv slow code vvv ### for x in xrange(1200): (r,g,b) = pix[y*1200+x] row += chr(g)+chr(b)+chr(r) ### ^^^ slow code ^^^ ### row += '\xff'*72 f.write(row) f.write(pclfoot) </code></pre> <p>I know the loop can be optimized way better, but how?</p> <p>My code is running on a <strong>beaglebone</strong> so speed is slower than you'd expect, but composing the complex images takes about 5 seconds. I wouldn't expect my printer code function (which just reorders the data) to take much longer than about 2 or 3 seconds. My first attempt (with <code>getpixel</code>) took 90 seconds. Now I have it down to <strong>36 seconds</strong>. Surely I can make this quite a bit faster yet.</p> <p>For comparison, just so we can all see where the hold up is, this code runs in <strong>0.1 secs</strong> (but, of course, is lacking the important data):</p> <pre><code># ~0.1 seconds on beaglebone f.write(pclhead) pix = image.getdata() for y in xrange(1800): row = '\xff'*72 ### vvv substituted vvv ### row += '\xff'*3600 ### ^^^ substituted ^^^ ### row += '\xff'*72 f.write(row) f.write(pclfoot) </code></pre> <p>I guess a simplified version of this problem is to rewrite something like the following:</p> <pre><code>[ (1,2,3), (1,2,3) ... 1200 times ] </code></pre> <p>into</p> <pre><code>[ 2, 3, 1, 2, 3, 1, etc... ] </code></pre> <p>but as a string</p> <pre><code>"\x02\x03\x01\x02\x03\x01 ... " </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:06:01.780", "Id": "50305", "Score": "0", "body": "instead of all that string manipulation why not just write it out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:56:51.423", "Id": "50322", "Score": "0", "body": "@cmd, write what out? did you notice the byte order has changed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T19:18:31.560", "Id": "50337", "Score": "0", "body": "is `f` just a simple file object? What do we know about how it buffers writes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T19:25:13.983", "Id": "50338", "Score": "0", "body": "@kojiro, f.write() can be slow, i know, but i just want to optimize the way the loop handles the data" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T19:32:02.307", "Id": "50339", "Score": "1", "body": "That is only fair if your *36 seconds* doesn't include the `f.write`. :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-11T17:33:49.307", "Id": "76325", "Score": "0", "body": "In the code that runs in 0.1 seconds, the compiler is probably using Constant Propagation to optimize the loop. It can't do that with your actual code because the data changes. Hm... didn't realize this was so old, but I'll leave my comment around for others anyway." } ]
[ { "body": "<p>Start with storing the <code>'\\xff' * 72</code> string as a constant; Python strings are immutable, recreating that string each time is not necessary.</p>\n\n<p>Next, use a list to collect all strings, then join at the end; this is cheaper than constant string concatenation.</p>\n\n<p>Last, avoid attribute lookups in critical sections; assign any attribute lookups done more than once to a local name:</p>\n\n<pre><code>from operator import itemgetter\n\nbgr = itemgetter(1,2,0)\n\npix = image.getdata()\nrowstart = '\\xff' * 72\nf_write = f.write\nempty_join = ''.join\nfor y in xrange(1800):\n row = [rowstart]\n r_extend = row.extend\n for x in xrange(1200):\n r_extend(map(chr, bgr(pix[y*1200+x])))\n r.append(rowstart)\n\n f_write(empty_join(row))\n</code></pre>\n\n<p>You can experiment with joining the whole row (including <code>rowstart</code>) or writing out <code>rowstart</code> values separately; the following version might be faster still depending on write speed versus list concatenation speed:</p>\n\n<pre><code>for y in xrange(1800):\n f_write(rowstart)\n row = []\n r_extend = row.extend\n for x in xrange(1200):\n r_extend(map(chr, bgr(pix[y*1200+x])))\n f_write(empty_join(row))\n f_write(rowstart)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:47:56.413", "Id": "50317", "Score": "0", "body": "I tried your code from above and it takes 58 seconds, so actually slower than my code :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:51:45.513", "Id": "50319", "Score": "0", "body": "Could you optimize this further by a single loop over `range(0, 1800*1200+1, 1200)` inserting `'\\xff'*144` every 1200 iterations?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:57:52.280", "Id": "50323", "Score": "0", "body": "(Perhaps even a direct operation on such a slice of `pix` will work if you can solve the byte-swapping problem.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T19:03:45.220", "Id": "50334", "Score": "0", "body": "What if, instead of maintaining a list of strings and doing `chr` on an integer, you just use a `bytearray`?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:04:53.823", "Id": "31546", "ParentId": "31545", "Score": "6" } }, { "body": "<p>First Profile your code to determine what is your bottleneck. </p>\n\n<p>But generally speaking, there are scopes of improvement</p>\n\n<ol>\n<li>Do not generate the strings of HIGH Values inside the Loop</li>\n<li>Use Generators</li>\n<li>Process a 1D List as a 1D list rather than Indexing with two loops</li>\n</ol>\n\n<p>Sample Code</p>\n\n<pre><code>f.write(pclhead)\npix = image.getdata()\nHIGH_VALUES = '\\xff'*72\n#pix_it = (''.join(map(chr, reversed(e))) for e in pix)\n\npix_it = (chr(b)+chr(g)+chr(r) for r,g,b in pix)\nwhile True:\n data = ''.join(islice(pix_it, 1200))\n if not data: break\n f.write(HIGH_VALUES)\n f.write(data)\n f.write(HIGH_VALUES)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:55:47.780", "Id": "50321", "Score": "0", "body": "this took 30 seconds. marginally faster but not significant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:08:25.317", "Id": "50325", "Score": "1", "body": "@Octopus: Profile Your Code and see where the bottleneck is. The above code for me took only 3 secs. Off-course, the data was randomly generated rather than reading from a file through PIL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:27:09.253", "Id": "50328", "Score": "0", "body": "I said my times are coming from a beaglebone so they are expectedly slower, but compare your time to mine" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:28:14.697", "Id": "31549", "ParentId": "31545", "Score": "4" } }, { "body": "<p>Can you use <code>numpy</code>? If you provide a test image it would help (I know most of this answer works, but unsure about <code>tofile</code> doing the right thing here)</p>\n\n<pre><code>import numpy\nf.write(pclhead)\npix = numpy.array(image).astype(numpy.uint8) #Array shape is (x, y, 3)\npix[:,:,[0,1,2]] = pix[:,:,[1,2,0]] #Swap rgb values to gbr, this is a 'view' so is fast\nto_insert = numpy.ones((72, pix.shape[1], 3)).astype(numpy.uint8) * 255\npix = numpy.concatenate((to_insert, pix, to_insert), axis=0).astype(numpy.uint8)\npix.tofile(f)\nf.write(pclfoot)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:34:18.327", "Id": "50344", "Score": "0", "body": "The line that swaps rgb values gives me an error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:36:59.820", "Id": "50346", "Score": "0", "body": "@Octopus Can you tell me what `pix.shape` is immediately before that line? The swap works fine on my machine with a small image loaded through PIL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:51:49.677", "Id": "50348", "Score": "0", "body": "My mistake, i made an error above that. This is faster and has potential, but my pcl file is now 56MB instead of 7MB. ~18 secs" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:58:22.953", "Id": "50349", "Score": "0", "body": "@Octupus That's a shame. Not sure why? Maybe the concatenation, let me have a look." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T23:14:52.913", "Id": "50350", "Score": "0", "body": "@Octupus I'm now ensuring the dtypes for the \"ones\" and the result of the concatenation are `uint8`. The data type may have been mangled in there somewhere in the version you tested." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:13:57.927", "Id": "31565", "ParentId": "31545", "Score": "3" } }, { "body": "<p>I think you can save even more time by keeping to iterables of integers as long as possible, and switching to <code>bytearray</code> at the last possible moment. Also, as tradeoffs usually go, you can save time by keeping more in RAM and saving it all for one final <code>.write</code>. Exactly how well that works will depend on buffering.</p>\n\n<pre><code>from itertools import chain, imap, izip_longest\nfrom operator import itemgetter\n\ndef grouper(iterable, n, fillvalue=None):\n \"\"\"Collect data into fixed-length chunks or blocks\n Copied directly from http://docs.python.org/2/library/itertools.html#recipes\n \"\"\"\n # grouper('ABCDEFG', 3, 'x') --&gt; ABC DEF Gxx\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\npix = chain.from_iterable(imap(itemgetter(1, 2, 0), image.getdata()))\nrows = grouper(pix, 3600)\n# Rows is an iterable of iterables of integers in the range 0-255.\n\nspace = bytearray([255] * 72)\nimg = space + (2 * space).join(map(bytearray, rows)) + space\n# You'll need at least ~6.4M in RAM, but the BeagleBone has 256! :)\nf.write(img)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T04:54:06.193", "Id": "50357", "Score": "0", "body": "This works and is the fastest yet at ~13 secs" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T03:55:28.553", "Id": "31570", "ParentId": "31545", "Score": "3" } }, { "body": "<p>This is the code I finally arrived at. Not only is it way faster (less than 1 second!), but it still maintains good legibility and doesn't rely on additional libraries.</p>\n\n<p>This assumes the image format is raw 'RGB' as was the case in the original scenario. Instead of image.getdata() which returns a set of tuples, I am now using image.getstring() which doesn't need as much coercsion to manipulate its data. Also, by preallocating rpix as a bytearray of known size, you save a lot of memory block copying.</p>\n\n<pre><code># &lt;1 second on beaglebone\nf.write(pclhead)\n\nmgn = '\\xff'*72\npix = image.getstring()\nrpix = bytearray(len(pix))\nrpix[0::3] = pix[1::3]\nrpix[1::3] = pix[2::3]\nrpix[2::3] = pix[0::3]\n\noffs = 0\nfor y in xrange(1800):\n f.write(mgn)\n f.write(str(rpix[offs:offs+3600]))\n f.write(mgn)\n offs += 3600\nf.write(pclfoot)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-25T02:15:50.387", "Id": "31775", "ParentId": "31545", "Score": "3" } } ]
{ "AcceptedAnswerId": "31775", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:01:47.077", "Id": "31545", "Score": "7", "Tags": [ "python", "performance", "strings", "image", "lookup" ], "Title": "Writing image pixel data to printer code" }
31545
<pre><code>/** * Upload has a limit of 10 mb * @param string $dir $_SERVER['DOCUMENT_ROOT'] * @param string $path Path do you want to upload the file * @param string $filetype jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx * @param array $_FILES An associative array of items uploaded to the current script via the HTTP POST method. * @return string ?$fileName:False */ function uploadFiles($dir, $path, $filetype) { $dir_base = "{$dir}{$path}"; $dateadded = date('ynj_Gis-'); $rEFileTypes = "/^\.($filetype){1}$/i"; $MAXIMUM_FILESIZE = 10 * 1024 * 1024; // UPLOAD IMAGES $isFile = is_uploaded_file($_FILES['file']['tmp_name']); if ($isFile) { $safe_filename = $dateadded . preg_replace(array('/\s+/', '/[^-\.\w]+/'), array('_', ''), trim($_FILES['file']['name'])); if ($_FILES['file']['size'] &lt;= $MAXIMUM_FILESIZE &amp;&amp; preg_match($rEFileTypes, strrchr($safe_filename, '.'))) { $isMove = move_uploaded_file($_FILES['file']['tmp_name'], $dir_base . $safe_filename); } } if ($isMove) { return $safe_filename; } else { return false; } } </code></pre> <p>How can I improve the name check part or another things?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:50:44.267", "Id": "50318", "Score": "0", "body": "You should post this to StackOverflow instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:00:44.167", "Id": "50324", "Score": "1", "body": "You're re-assigning/overriding the auto-global variable $_FILES in the function arguments. Since $_FILES is a global, there's no need to pass it as an argument to the function (its accessible from within the function scope)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T23:15:43.117", "Id": "50351", "Score": "0", "body": "@Jamal question edited, it's working now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T23:44:40.973", "Id": "50353", "Score": "1", "body": "Alright, I'll put in my vote." } ]
[ { "body": "<p>I have two minor comments.</p>\n\n<p>First, I prefer having my variables defined in all branches, to avoid the <code>PHP Notice: Undefined variable:...</code> error in logs. So, an initialization</p>\n\n<pre><code>$isMove = false;\n</code></pre>\n\n<p>would be nice. Btw, maybe <code>$isMoved</code> seems a bit more accurate/correct name. This part might also be written like this:</p>\n\n<pre><code>if (!is_uploaded_file($_FILES['file']['tmp_name'])) return false;\n$safe_filename = $dateadded . preg_replace(array('/\\s+/', '/[^-\\.\\w]+/'), array('_', ''), trim($_FILES['file']['name']));\nif ($_FILES['file']['size'] &gt; $MAXIMUM_FILESIZE) return false;\nif (!preg_match($rEFileTypes, strrchr($safe_filename, '.'))) return false;\nif (!move_uploaded_file($_FILES['file']['tmp_name'], $dir_base . $safe_filename)) return false;\nreturn $safe_filename;\n</code></pre>\n\n<p>Depending on your taste, this might be easier to read.</p>\n\n<p>My second comment is related to this:</p>\n\n<pre><code>$rEFileTypes = \"/^\\.($filetype){1}$/i\";\n</code></pre>\n\n<p>What is the purpose of <code>{1}</code> (which means \"repeat once\")? I'd write that regex like this:</p>\n\n<pre><code>$rEFileTypes = \"/\\.($filetype)\\$/i\";\n</code></pre>\n\n<p>and I would replace</p>\n\n<pre><code>preg_match($rEFileTypes, strrchr($safe_filename, '.'))\n</code></pre>\n\n<p>with</p>\n\n<pre><code>preg_match($rEFileTypes, $safe_filename)\n</code></pre>\n\n<p>It seems to me a bit less cluttered this way, and I'd expect such regex to be faster than doing the old one + <code>strrchr</code>, but I have no proof that it really is. However, I don't think this is a kind of code in which speed is very important (upload of a file and moving it around will eat up much more time).</p>\n\n<p>Btw, <code>$filetypes</code> might be a bit better name.</p>\n\n<p>A bit more important comment is regarding the possibility that, given a long enough filename, your safe one will grow too long when you prepend it with a date, and you will lose the file extension (or a part of it). You might want to address that issue by checking the length and trimming the filename part if needed.</p>\n\n<p>Now, for the general approach, there is a question about what you're doing with this. Usually, it is better to keep the original filenames in a database, and to store the uploaded files under a completely generic name (using, for example, an <code>auto_increment</code> primary key from the filenames table). Also, if you don't need filenames at all, you can then just make them generic.</p>\n\n<p>Notice that your <code>$dateadded</code> makes it very likely that your filenames are unique, but it doesn't really guarantee it. Depending on your use and the expected number of users, this might be a potential problem (although I wouldn't expect it).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T17:23:08.083", "Id": "50418", "Score": "0", "body": "What do you think about add to `$dateadded` a $rand=rand(100,999) to be unique, what is your advice to me in this? `$dateadded.'_'$rand`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T17:46:52.257", "Id": "50421", "Score": "0", "body": "How is `rand` going to make anything unique? That way you are indeed slimming the chances, but - as I wrote before - they are already very slim. I'm not sure how to make it unique without using generic names (in that case, [`tempnam`](http://php.net/manual/en/function.tempnam.php) can help you) and/or database (then primary `auto_increment` field can give you the name). Try asking at StackOverflow (or, maybe, Programmers.SE; I'm not sure) about that problem. But, I repeat, unless you have a really huge number of uploads, this will probably never cause any problems." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:58:38.867", "Id": "31579", "ParentId": "31550", "Score": "1" } } ]
{ "AcceptedAnswerId": "31579", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:29:24.420", "Id": "31550", "Score": "1", "Tags": [ "php" ], "Title": "how can I improve the check name file part" }
31550
<p>The <strong>Game of Life</strong>, also known simply as <strong>Life</strong>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.</p> <p>The "game" is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.</p> <h3>Rules:</h3> <p>The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:</p> <ol> <li>Any live cell with fewer than two live neighbours dies, as if caused by under-population.</li> <li>Any live cell with two or three live neighbours lives on to the next generation.</li> <li>Any live cell with more than three live neighbours dies, as if by overcrowding.</li> <li>Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.</li> </ol> <p><a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">From Wikipedia</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:13:51.293", "Id": "31552", "Score": "0", "Tags": null, "Title": null }
31552
A cellular automaton simulation following rules devised by mathematician John Conway.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:13:51.293", "Id": "31553", "Score": "0", "Tags": null, "Title": null }
31553
<p>Review this code, which should return <code>true</code> if a port is in use or <code>false</code> if the port is not in use.</p> <p>Clarification: "In use" means that the port is already open (and used by another application). I'm trying to find a port number between (49152 and 65535) to open that is available.</p> <pre><code>private boolean isPortInUse(String hostName, int portNumber) { boolean result; try { Socket s = new Socket(hostName, portNumber); s.close(); result = true; } catch(Exception e) { result = false; } return(result); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:06:12.617", "Id": "50399", "Score": "2", "body": "Catching `Exception` is not a good practice try to catch the known subclass which you expect..." } ]
[ { "body": "<p>The code can be simplified somewhat:</p>\n\n<pre><code>private boolean isPortInUse(String host, int port) {\n // Assume no connection is possible.\n boolean result = false;\n\n try {\n (new Socket(host, port)).close();\n result = true;\n }\n catch(SocketException e) {\n // Could not connect.\n }\n\n return result;\n}\n</code></pre>\n\n<p>Note, however, that if you want to check for an available port, that could be reflected in the method name:</p>\n\n<pre><code>private boolean availablePort(String host, int port) {\n // Assume port is available.\n boolean result = true;\n\n try {\n (new Socket(host, port)).close();\n\n // Successful connection means the port is taken.\n result = false;\n }\n catch(SocketException e) {\n // Could not connect.\n }\n\n return result;\n}\n</code></pre>\n\n<p>Neither approaches employ object-oriented programming (OOP) techniques, though. In OOP, behaviour (determining port availability) is kept with the object that contains the attributes. For example:</p>\n\n<pre><code>public SocketAnalyzer extends java.net.Socket {\n public boolean isPortAvailable() {\n // ... code here ...\n }\n}\n</code></pre>\n\n<p>Now the initial method simplifies to:</p>\n\n<pre><code>private boolean availablePort(String host, int port) {\n return (new SocketAnalyzer(host, port)).isPortAvailable();\n}\n</code></pre>\n\n<p>And that allows the \"availablePort\" method to be removed completely, if desired:</p>\n\n<pre><code>if( (new SocketAnalyzer(host, port)).isPortAvailable() ) {\n // Launch the server socket on 'port'!\n}\n</code></pre>\n\n<p>This promotes re-use, and shows one more idea: you could extend <code>ServerSocket</code> instead! The code would become:</p>\n\n<pre><code>// The constructor would have to bind to the host/port combination...\n// This is arguably poor form as the constructor really shouldn't do anything.\n// You could, instead, use the superclass' constructor and then call bind,\n// but for the purposes of this example, the idea is key: inherit.\nServerSocketAnalyzer ssa = new ServerSocketAnalyzer( host, port );\n\nif( ssa.isPortAvailable() ) {\n // Code to use the server socket...\n Socket s = ssa.accept();\n}\n</code></pre>\n\n<p>Clean and simple, but there's a race condition. In between the time it takes to determine whether the port is available and the server starts accepting connections to that port, another service may have started to commandeer the port.</p>\n\n<p>The best solution is to allow the server to pick an available port using an atomic operation, as per <a href=\"https://codereview.stackexchange.com/a/31594/20611\">the other answer</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-04T15:08:50.510", "Id": "168300", "Score": "2", "body": "This invites the race condition (where you check that a port is available, but at the moment you try to bind to it it is no longer)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T20:20:07.417", "Id": "424140", "Score": "0", "body": "\"Neither approaches employ object-oriented programming (OOP) techniques, though.\" OOP is not a goal in and of itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T22:41:36.820", "Id": "424157", "Score": "0", "body": "OOP isn't a goal. Maintainable, robust (i.e., not brittle), and reliable software are goals. OOP methodologies are but one way to help achieve those goals. See also: https://stackoverflow.com/a/4002376/59087 and https://r.je/static-methods-bad-practice" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T17:04:22.793", "Id": "31591", "ParentId": "31557", "Score": "5" } }, { "body": "<p>Don't test for port-in-use in advance. Just let your application do what it wants to do, and catch the exception there. The situation can change between the time you test and when you actually try to use the port.</p>\n\n<p>Furthermore, if you are trying to write a server application, you can have Java automatically pick a free port for you. From the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#ServerSocket(int)\">JavaDoc for <code>ServerSocket(int)</code></a>:</p>\n\n<blockquote>\n <p>Creates a server socket, bound to the specified port. A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling <a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#getLocalPort()\"><code>getLocalPort</code></a>.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T21:20:37.893", "Id": "385381", "Score": "1", "body": "not in all cases! When I am starting a long running test suite that relies on a port 30 minutes in, I want to know if that port is in use as early as possible." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T17:44:14.620", "Id": "31594", "ParentId": "31557", "Score": "8" } }, { "body": "<p>Your code takes a <code>host</code> parameter, but your test can only be true if you try to open a local port.</p>\n\n<p>Your <code>host</code> parameter should be replaced by a hardcoded <code>127.0.0.1</code> or <code>InetAddress.getLocalHost().getHostName()</code></p>\n\n<p>If you try this on a remote machine, it will return <code>true</code> if the port is open and in use on the remote machine.</p>\n\n<p>Consider:</p>\n\n<pre><code>private boolean isLocalPortInUse(int port) {\n try {\n // ServerSocket try to open a LOCAL port\n new ServerSocket(port).close();\n // local port can be opened, it's available\n return false;\n } catch(IOException e) {\n // local port cannot be opened, it's in use\n return true;\n }\n}\n</code></pre>\n\n<p>Or :</p>\n\n<pre><code>private boolean isRemotePortInUse(String hostName, int portNumber) {\n try {\n // Socket try to open a REMOTE port\n new Socket(hostName, portNumber).close();\n // remote port can be opened, this is a listening port on remote machine\n // this port is in use on the remote machine !\n return true;\n } catch(Exception e) {\n // remote port is closed, nothing is running on\n return false;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T09:50:01.113", "Id": "68354", "ParentId": "31557", "Score": "2" } }, { "body": "<p>You can shorten this:</p>\n\n<pre><code>public static boolean isAvailable(String host, int portNr) {\n\n boolean isAvailable;\n\n try (var ignored = new Socket(host, portNr)) {\n // Successful connection means the port is taken\n isAvailable = false;\n } catch (IOException e) {\n // Could not connect\n isAvailable = true;\n }\n\n return isAvailable;\n}\n</code></pre>\n\n<p>Keep in mind that on Linux, <a href=\"https://stackoverflow.com/questions/33703965/how-can-i-run-a-spring-boot-application-on-port-80#33704078\">all ports up to 1024</a> can only be bound by root, meaning that <code>isAvailable</code> does not tell you whether you can actually bind your server to the returned port.</p>\n\n<p>Here's a similar way using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/net/ServerSocket.html\" rel=\"nofollow noreferrer\">ServerSocket</a> that has worked for my server application to find out whether I'm able to bind to a socket:</p>\n\n<pre><code>public static boolean canBind(String host, int portNr) {\n boolean canBind;\n var address InetAddress.getByName(host);\n\n try (var ignored = new ServerSocket(portNr, 0, address)) {\n canBind = true;\n } catch (IOException e) {\n canBind = false;\n }\n return canBind;\n}\n</code></pre>\n\n<p>This is how you might use <code>canBind</code> to find a bindable port for your server (all this assumes a Java version of 10 or later):</p>\n\n<pre><code>public static void main(String... args) {\n\n var host = \"0.0.0.0\";\n\n var portRange = closedRange(8080, 9020);\n var portMaybe = portRange.stream()\n .filter(portNr -&gt; canBind(host, portNr))\n .findFirst();\n\n portMaybe.ifPresentOrElse(port -&gt; {\n var address = new InetSocketAddress(host, port);\n startServer(address);\n\n }, () -&gt; System.err.println(\"Could not find port to bind to in this range: \"\n + portRange));\n}\n\nprivate static List&lt;Integer&gt; closedRange(int startInclusive, int endInclusive) {\n return IntStream.rangeClosed(startInclusive, endInclusive)\n .boxed()\n .collect(Collectors.toList());\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T20:18:25.960", "Id": "219604", "ParentId": "31557", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T19:18:29.837", "Id": "31557", "Score": "14", "Tags": [ "java", "error-handling", "socket" ], "Title": "Checking if a port is in use" }
31557
<p>The objective is to increment the page visits by one. The user should not be able to do this by refreshing. The number of visits can be incremented only if the user's last visit was later than 10 minutes or none at all. This should work regardless of multiple users behind the same IP or router.</p> <p>Does this need any improving?</p> <p>Stack Exchange page views works like <a href="https://meta.stackexchange.com/questions/36728/how-does-stack-overflow-calculate-the-number-of-views-in-a-question">this</a>.</p> <pre><code>//Is data storage available? if(typeof(Storage)!=="undefined") { var tenMinutes = 3600 * 10; //10 minutes var now = new Date(); var visits = JSON.parse(localStorage.getItem('visits')); //Get visits array from local storage var currentVisit = {id:$scope.ad.id, datetime:now}; var duplicate = false; //There is no older visits, user is new here if(!visits){ visits = [currentVisit]; addViewForID(currentVisit.id); } else{ //Check for duplicate visit angular.forEach(visits, function(visit){ if (visit.id == currentVisit.id) { duplicate = true; var visitTime = new Date(visit.datetime); var deltaTime = Math.abs(now.getTime() - visitTime.getTime()); var deltaDays = Math.ceil(deltaTime / (1000 * 3600 * 24)); if (deltaDays &gt; 1 || (deltaDays == 1 &amp;&amp; deltaTime &gt; tenMinutes)) visit.datetime = now; } }) //First time visiting this page if (!duplicate){ visits.push(currentVisit); addViewForID(currentVisit.id); } } //Save visits array in local storage localStorage.setItem('visits', JSON.stringify(visits)); } function addViewForID(id){ FData.incrementVisitsForID(id); } </code></pre>
[]
[ { "body": "<p>My 2 cents:</p>\n\n<ul>\n<li><p>I would not use an array of objects to represent the pages, I would use an object where each <code>$scope.ad.id</code> is a property and where the value is the last time visited. This would take out your loop and dupe management</p></li>\n<li><p>Any enterprising individual is able to artificially inflate the counter, either by clearing the <code>localStorage</code> or by calling <code>FData.incrementVisitsForID(id);</code> in a loop from the console.</p></li>\n<li><p>Are you sure that 10 minutes = 3600 * 10, it seems wrong to me</p></li>\n</ul>\n\n<p>I would counter propose something like this:</p>\n\n<pre><code>//Is data storage available?\nif(typeof(Storage)!==\"undefined\")\n{\n var tenMinutes = 1000 * 60 * 10; //10 minutes\n var now = (new Date()).getTime(); \n //Get visits array from local storage or if that fails, an empty object\n var visits = JSON.parse(localStorage.getItem('visits')) || {}; \n //Get time of last visit, or 0\n var lastVisit = visits[ $scope.ad.id ] || 0;\n //Does it count?\n if( now - lastVisit &gt; tenMinutes)\n {\n FData.incrementVisitsForID( $scope.ad.id );\n }\n //Update visits for the next time\n visits[ $scope.ad.id ] = now;\n //Save visits array in local storage\n localStorage.setItem('visits', JSON.stringify(visits));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T14:44:19.667", "Id": "36700", "ParentId": "31560", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T20:37:15.663", "Id": "31560", "Score": "4", "Tags": [ "javascript", "angular.js" ], "Title": "\"Stack Exchange page visits\" alike implementation" }
31560
<p>I have this jQuery click handler function that has three jobs:</p> <ol> <li>Set the time interval for the refresh rate</li> <li>Change the color on the clicked refresh rate selection</li> <li>Callback the tablesort functions to resort the newly loaded data</li> </ol> <p>I'd like to pull out the separate functionality into named functions, but I'm unsure (being a somewhat JS newb) how to do that an achieve the same behavior.</p> <p>Javascript Code:</p> <pre><code>$(document).ready(function() { $("#refresh-buttons").on("click", "button", function(event) { var interval = 0; switch(event.target.id) { case "refresh-off" : interval = 50000000; $(this).parent().children().removeClass("pressed-button"); $(this).addClass("pressed-button"); break; case "refresh-5-sec" : interval = 5000; $(this).parent().children().removeClass("pressed-button"); $(this).addClass("pressed-button"); break; case "refresh-30-sec" : interval = 30000; $(this).parent().children().removeClass("pressed-button"); $(this).addClass("pressed-button"); break; case "refresh-60-sec" : interval = 60000; $(this).parent().children().removeClass("pressed-button"); $(this).addClass("pressed-button"); break; } if (interval != 0) { clearInterval(intervalId); intervalId = setInterval(function(){ $('#status-tables').load('/dashboard/index #status-tables', function(){ $("#workstation-table").tablesorter(); $("#report-table1").tablesorter({sortList:[[1,0]]} ); $("#report-table2").tablesorter({sortList:[[1,0]]}); }); }, interval); } }); }); </code></pre>
[]
[ { "body": "<p>Add the <code>refresh-rates</code> map to <code>#refresh-buttons</code> element ( use <code>.data()</code> function ), optimize amount of <code>$()</code> calls:</p>\n\n<pre><code>$(document).ready(function() {\n var refresh_btns$;\n\n // you can store id map where ever you prefer to\n // I've figured it would be good to keep them with\n // the element they are related to\n ( refresh_btns$ = $(\"#refresh-buttons\") )\n .data(\n \"refreshRates\",\n {\n \"refresh-off\" :50000000,\n \"refresh-5-sec\" :5000,\n \"refresh-30-sec\" :30000,\n \"refresh-60-sec\" :60000\n }\n )\n .on(\"click\", \"button\", function () {\n var\n interval = refresh_btns$.data(\"refreshRates\")[ this.id ] || 0;\n if (\n interval !== 0\n ) {\n // yeah m_x is right about .toggleClass()\n // it producess weird behaviour\n // this shold to the job\n $( this )\n .addClass(\"pressed-button\")\n .siblings()\n .removeClass(\"pressed-button\");\n\n clearInterval(intervalId);\n intervalId =\n setInterval(\n function () {\n $('#status-tables')\n .load(\n '/dashboard/index #status-tables',\n function () {\n $(\"#workstation-table\").tablesorter();\n $(\"#report-table1, #report-table2\")\n .tablesorter( { sortList : [ [ 1, 0 ] ] } );\n }\n );\n },\n interval\n );\n }\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-25T20:27:11.863", "Id": "50737", "Score": "0", "body": "+1 for mapping ids to refresh rates, but 1) wouldn't this `toggleClass` add `pressed-button` on all buttons that currently don't have it ? 2) why even use a data-attribute ? your are in a closure, use a simple object in a var. Aside from accessing data attributes, you don't even use your `refresh_btns$` var." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T22:40:49.530", "Id": "31566", "ParentId": "31563", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T21:31:37.373", "Id": "31563", "Score": "1", "Tags": [ "javascript", "jquery", "sorting", "user-interface" ], "Title": "Extracting Javascript functions" }
31563
<p>I don't intend on implementing this into an application yet as I'm going to test it first. As such, it doesn't do much beyond rolling. It also overloads some "typical" operators such as <code>==</code> and <code>!=</code>.</p> <p>Most of all, I'm still very unsure about my random number generator. I've read about <code>&lt;random&gt;</code>'s <code>std::uniform_int_distribution</code> and that it has advantages over <code>std::rand</code>, but I'm also not sure if I've put it in a good place. Client code will be forced to use my seed <em>if</em> my source file is used, but my header file is free from this.</p> <p>What could be said about my RNG use? Anything else that could be done?</p> <p><strong>Dice.h</strong></p> <pre><code>#ifndef DICE_H #define DICE_H #include &lt;ostream&gt; class Dice { private: int topValue; // same default type as std::uniform_int_distribution&lt;&gt; public: void roll(); int value() const { return topValue; } }; // the C++ FAQ on SO suggests that these overloads are best as non-members inline bool operator==(Dice const&amp; lhs, Dice const&amp; rhs) { return lhs.value() == rhs.value(); } inline bool operator!=(Dice const&amp; lhs, Dice const&amp; rhs) { return !operator==(lhs, rhs); } inline std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Dice const&amp; obj) { return out &lt;&lt; obj.value(); } #endif </code></pre> <p><strong>Dice.cpp</strong></p> <pre><code>#include "Dice.h" #include &lt;random&gt; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution&lt;&gt; dis(1, 6); void Dice::roll() { topValue = dis(gen); } </code></pre>
[]
[ { "body": "<p>Just based on the code, and in no particular order:</p>\n\n<ul>\n<li>Bikeshedding: as <code>Dice</code> represents a single die, I would call it such.</li>\n<li>You're passing <code>Dice</code> by reference to const everywhere. In your current design it is just an <code>int</code>, and I don't see anything happening that would increase the cost of passing it significantly, or cause it to become non-copyable. As per Optimizing Emergent Structures in C++ you should prefer to pass by value here.</li>\n<li>Your <code>rd</code>, <code>gen</code>, and <code>dis</code> should all be in an anonymous namespace to prevent linker errors when people define things of the same name in other files.</li>\n<li>Does equality and inequality really make sense here? It bothers me that <code>x == y</code> is not preserved after <code>x.roll(); y.roll();</code>. I think I'd stick to accessing <code>value</code> explicitly, and not allow equality on <code>Dice</code>.</li>\n</ul>\n\n<p>As for design: the implicit sharing of state between dice bothers me. It isn't detectable as-is, but it means that there is no way of specifying that a particular die will return particular results (for debugging). If this is used in a multithread application, the results of <code>roll</code> may be surprising; I'm fairly sure <code>uniform_int_distribution&lt;&gt;::operator()</code> should not be called from multiple threads at once.</p>\n\n<p>I think I'd go for the more explicit approach of having an <code>updateRandom</code> and <code>getRandom</code> pair, or ensure thread-safety of <code>roll</code>.</p>\n\n<p>You could also make this more generic:</p>\n\n<pre><code>// die.hpp\nextern std::random_device rd;\nextern std::mt19937 gen;\n\ntemplate&lt;typename T&gt;\nstruct Die {\n T value() const {\n return topValue;\n }\n\n void roll() {\n topValue = dis(gen);\n }\n\nprivate:\n T topValue;\n static std::uniform_int_distribution&lt;T&gt; dis;\n};\n\ntemplate&lt;typename T&gt;\nstd::uniform_int_distribution&lt;T&gt; Die&lt;T&gt;::dis(1, 6);\n\n// die.cpp\nstd::random_device rd;\nstd::mt19937 gen(rd());\n</code></pre>\n\n<p>However, this would have the obvious drawback of the implementation being exposed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T05:28:15.827", "Id": "31714", "ParentId": "31571", "Score": "6" } }, { "body": "<p>Another victim of STL (the guy)'s \"rand() Considered Harmful\" presentation. I too went and verified that my code was using the random number generators correctly.</p>\n\n<p>Aside from @AntonGolov's advice, I would also mention that Dice::roll is not thread safe. If you have multiple threads rolling dice, then they may cause some weird behaviour.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T09:54:40.293", "Id": "31724", "ParentId": "31571", "Score": "1" } }, { "body": "<p>Some points to add to the others:</p>\n\n<ul>\n<li>It seems arbitrary to force clients to make two calls for every roll. <code>roll</code> should return the value. You can keep the method to read it, but don't force it's use.</li>\n<li>While I understand the meaning of <code>topValue</code>, I would prefer <code>lastRoll</code>.</li>\n<li>Add <code>numSides</code> to the constructor to allow d20 et al. This value and the type of distribution--uniform, normal, fixed (for testing), etc.--should determine equality. Two dice are equal if they produce similar sequences--not when they happened to roll the same number previously.</li>\n<li>What happens if I access the last roll before rolling the die for the first time? Does this make sense? </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T03:30:01.360", "Id": "71213", "Score": "0", "body": "Thanks! I haven't even considered the `numSides` one, but it's not a problem. I'll also figure out how to deal with the last point. It seems I may need to `throw` there." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T03:24:50.333", "Id": "41444", "ParentId": "31571", "Score": "5" } } ]
{ "AcceptedAnswerId": "31714", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T05:35:10.053", "Id": "31571", "Score": "7", "Tags": [ "c++", "c++11", "random", "dice" ], "Title": "Random number generation in Dice class" }
31571
<p>I have one programming question:</p> <blockquote> <p>The sine and cosine of \$x\$ can be computed as follows:</p> <blockquote> <p>\$\sin(x) = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \frac{x^9}{9!} - \dots\$</p> <p>\$\cos(x) = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \frac{x^8}{8!} - \dots\$</p> </blockquote> <p>Your task is to compute the sine and cosine for given values of \$x\$ (where \$x\$ is in radians) using the above series up to 5 terms.</p> <h3>Input Format</h3> <p>First line will contain \$N\$, the number of test cases. Next \$N\$ lines will contain the input values of \$x\$:</p> <blockquote> <p>\$1 \le N \le 50\$</p> <p>\$0 \lt x \lt 10\$</p> </blockquote> <p>Each value of \$x\$ can contain up to 2 places of decimal in radians.</p> <h3>Output Format</h3> <p>2 \$N\$ lines, corresponding to the \$N\$ input values of \$x\$. For each input, you will output 2 lines. First line will be the sine and the second line will be the cosine of \$x\$. An error margin of \$\pm\$0.001 will be tolerated while evaluating the answers. Please round off your answer to 3 decimal places.</p> <h3>Sample Input</h3> <pre><code>5 2.83 3.24 0.99 2.74 5.04 </code></pre> <h3>Sample Output <em>[sic]</em></h3> <pre><code> 0.309 -0.943 -0.089 -0.963 0.836 0.549 0.392 -0.914 0.195 2.746 </code></pre> </blockquote> <p>and what I have tried:</p> <pre><code>public class Trigonometric_Ratios { int factorial(int number) { int result = 1; for (int i = 1; i &lt;= number; i++) { result = result * i; } return result; } void calc(double x) { double sinx=0,cosx=0; int i,j = 0; int c; for(i=1;i&lt;10;i+=2) { c=i; sinx += Math.pow(-1,j++)*Math.pow(x,i) / factorial(i); if(i&gt;0) cosx+=Math.pow(-1,j)*Math.pow(x,c-1)/factorial(c-1); } sinx=Math.round( sinx * 1000.0 ) / 1000.0; cosx=-cosx; cosx=Math.round( cosx * 1000.0 ) / 1000.0; System.out.println(sinx+" \n"+(cosx)); } public static void main(String [] args) { int n; Trigonometric_Ratios tr=new Trigonometric_Ratios(); Scanner sc=new Scanner(System.in); n=sc.nextInt(); double a[]=new double[n]; for(int i=0;i&lt;n;i++) { a[i]=sc.nextDouble(); } for(int i=0;i&lt;n;i++) { tr.calc(a[i]); } } } </code></pre> <p>Please review my code. In particular, I am concerned about performance, and would appreciate suggestions on reducing the time complexity.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:00:41.217", "Id": "50382", "Score": "2", "body": "What a lot of languages, looks a lot like Java to me. Where is the class Trigonometric_Ratios? Does this compile? How do the results look? Homework? I wouldn't worry too much about compile time just yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:07:52.583", "Id": "50385", "Score": "0", "body": "You can avoid calculating `Math.pow(x,i)`. You need all powers of x 1..9. This can be done simply by multiplying the previous power of x with x. You also need `factorial` for all values 1..9 so do calculate `fractorial(n)` by `fractorial(n-1)*n`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:08:43.150", "Id": "50386", "Score": "2", "body": "`i` is always `>0` so you can remove the condition `if(i>0)` from your loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:23:26.163", "Id": "50388", "Score": "0", "body": "@JohnMark13 yes i correct class name and output is same like question i post here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:25:06.313", "Id": "50389", "Score": "0", "body": "@MrSmith42 when i am using `factorial(n-1)*n` it is giving Exception `Exception in thread \"main\" java.lang.StackOverflowError`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:27:07.290", "Id": "50391", "Score": "0", "body": "@MrSmith42 how can i get previous power of x" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:29:54.467", "Id": "50392", "Score": "0", "body": "@Rahul Kulhari: I meant: store the value of the previous loop run and use it in the next loop run." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:03:44.857", "Id": "50397", "Score": "0", "body": "well `cos(x)` is `root under(1-sin^2(x))`. So you can only evaluate the value of `sin(x)` and get `cos(x) = Math.sqrt(1-(sin(x) * sin(x)))`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:19:49.687", "Id": "50402", "Score": "0", "body": "@tintinmj: I doubt that this is faster than calculating `cos(x)` because computing `sqrt` is slow because its implementation is also based on a series calculation. But only profiling can show if it is faster. It is worth a try." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T11:41:47.253", "Id": "50404", "Score": "2", "body": "The simplest way to reduce time complexity would be to use an array to store the factorial of all values upto 10(which is the max factorial that you are calculating). Doing it once will be much better than calculating the factorial many times which you are currently doing. Also you are calculating power of x 2 times. It would be better to calculate `x^(c -1)` and then multiply it with x to get `x^c`. Also the variable `c` is unneeded. It is `i` at every iteration of the loop." } ]
[ { "body": "<pre><code>cos(X) = sum (Cn) where Cn=x^2n/2n!\n\nsin(X) = sum (Sn) where Sn=x^(2+1)n/(2n+1)!\n</code></pre>\n\n<p>So, <code>Sn=Cn*x/(2n+1)</code></p>\n\n<pre><code>Cn=S(n-1)*x/2n\n</code></pre>\n\n<p>Start from <code>C0=1</code> and compute <code>S0=C0*x, C1=S0*x/2, S1=C1*x/3</code> etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-08T20:52:47.513", "Id": "336632", "Score": "0", "body": "`Start … compute … etc` saving the space to store not only `x*x`, but `n!` or its inverse, too, for 1 < n < 10. How do the accuracies of `r / 5040`, `r / 3 / 8 / 5 / 6 / 7` and `r * (1/5040)` compare?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T13:18:19.613", "Id": "31581", "ParentId": "31577", "Score": "0" } }, { "body": "<p>Instead of computing <code>Math.pow()</code> from scratch, multiply the previous numerator by <em>x</em><sup>2</sup>. (I suspect that <code>Math.pow()</code> uses logarithms so that it can handle the general case.) Also, instead of computing the factorial from scratch, multiply the previous denominator by the next two numbers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T15:14:17.223", "Id": "31586", "ParentId": "31577", "Score": "2" } }, { "body": "<p>Since the question calls for a precision of ±0.001, it should be safe to stop iterating as soon as a term has an absolute value of less than 0.0005.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T05:11:34.270", "Id": "35662", "ParentId": "31577", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T09:51:25.437", "Id": "31577", "Score": "3", "Tags": [ "java", "performance", "algorithm", "homework", "numerical-methods" ], "Title": "Approximating sines and cosines using up to five terms of the Taylor series" }
31577
<p>I've played with jQuery for some time now but have never written my own plugin.</p> <p>A question was asked: "can I blur an image using jQuery?" and I thought this to be a decent candidate to play with.</p> <p>Here's my code so far:</p> <pre><code>(function ($) { $.fn.blurStuff = function (options) { var defaults = {blurRadius:2, deblurOnHover:false}; var settings = $.extend(defaults, options); $(this).wrap('&lt;div data-blurimage /&gt;'); var blurContainers = $(this).closest('[data-blurimage]'); blurContainers.each(function () { var img = $(this).children(); $(this).css({ 'width': img.width(), 'height': img.height(), 'overflow': 'hidden', 'position': 'relative' }); var clone = img.clone(); clone.css({ 'opacity': 0.2, 'position': 'absolute' }); $(this).append(clone.clone().css({'left': +settings.blurRadius, 'top': +settings.blurRadius})); $(this).append(clone.clone().css({'left': -settings.blurRadius, 'top': +settings.blurRadius})); $(this).append(clone.clone().css({'left': +settings.blurRadius, 'top': -settings.blurRadius})); $(this).append(clone.clone().css({'left': -settings.blurRadius, 'top': -settings.blurRadius})); }); if (settings.deblurOnHover == true) { blurContainers.hover(function () { $(this).children('img:gt(0)').toggle(); }); } return blurContainers; }; })(jQuery); </code></pre> <p><strong>In action: <a href="http://jsfiddle.net/gvee/xvvWj/">http://jsfiddle.net/gvee/xvvWj/</a></strong></p> <p>Example usage:</p> <pre><code>$('img').blurStuff({deblurOnHover: true, blurRadius: 2}); </code></pre> <p>My working logic is to wrap the selector in a parent container and then append 4 translucent clones to this, where each clone is positioned slightly off centre.</p> <p>This works pretty well so far and I'm pleased with my progress but I can conceive a couple of potential bugs that I wanted some opinions on!</p> <ol> <li>Is my approach reasonable? I realise that I'm appending an extra 4 elements to the DOM on each call which is not ideal (I could get away with using just two, laterally or diagonally, but I think 4 produces a better effect)...</li> <li>What to do if a user passes a <code>fixed</code> position element? This will break existing flow.</li> <li>Should I bother validating/sanity checking the parameter values? If so, how should I approach this? Previously I had a parameter called <code>blurOpacity</code> but I removed this because I realised that the wrong values (e.g. <code>1</code>) effectively "breaks" things.</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-18T18:18:19.533", "Id": "72345", "Score": "0", "body": "http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/ Look at using native css blur if the browser supports it. http://caniuse.com/#feat=css-filters And look at css transforms." } ]
[ { "body": "<p>In the code I only would modify the variable declarations:</p>\n\n<pre><code>var defaults = {blurRadius:2, deblurOnHover:false},\nsettings = $.extend(defaults, options),\nimg, blurContainers, clone;\n</code></pre>\n\n<p>Personal preference, but you can read a discusion about it <a href=\"https://stackoverflow.com/questions/3684923/javascript-variables-declare-outside-or-inside-loop\">here</a>.</p>\n\n<p>Answering your questions:</p>\n\n<ol>\n<li>The efect work great. I think the approach is good, don't think\nthat adding four elements would be a big cost.</li>\n<li>You could check if the has the fixed property to avoid breaking anything. </li>\n<li>By the parameters you have rigth now I shouldn't bother. If you decide\nto add the opacity again it would be a good idea to check it. If\ngreater than 0.x use the default instead.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-15T02:22:18.347", "Id": "71738", "Score": "1", "body": "hey, thanks, for sure I'm going to visit you on monday, at work :P" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-15T00:41:09.110", "Id": "41702", "ParentId": "31578", "Score": "5" } }, { "body": "<p>overall it's pretty good! But I have a few minor points:</p>\n\n<ul>\n<li><p>The constant references to <code>$(this)</code> are bad. That call creates a jQuery collection each time. You could just save this as a variable.</p>\n\n<pre><code>var $this = $(this);\n$this.append(...);\n$this.append(...);\n</code></pre></li>\n<li><p>You could combine your defaults and settings to save a reference;</p>\n\n<pre><code>var settings = $.extend({\n blurRadius: 2, \n deblurOnHover: false\n}, options);\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-18T21:37:37.643", "Id": "72392", "Score": "0", "body": "I'd probably argue that he should be using chaining rather than just caching `$this`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T10:22:30.807", "Id": "72478", "Score": "0", "body": "@megawac I am comfortable with the concept on caching but not on chaining, can you elaborate please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T16:03:23.810", "Id": "72585", "Score": "0", "body": "@megawac Perhaps, but it doesn't help from a performance point of view. Calling `append` once with an array of elements would probably be better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T16:49:18.110", "Id": "72595", "Score": "0", "body": "http://masonry.desandro.com/methods.html" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-18T20:16:12.930", "Id": "42002", "ParentId": "31578", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T10:26:39.153", "Id": "31578", "Score": "5", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "My first jQuery plugin - blurStuff()" }
31578
<p>I have the following oops code, I am also monitoring user activity to see if it is idle for more than 5 seconds. I am very new to oops, so just want to understand if there are better way to implement it.</p> <pre><code>#!/usr/bin/python import Tkinter import time class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.running = None self.initialize() def initialize(self): self.grid() self.entryVariable = Tkinter.StringVar() self.entry = Tkinter.Entry(self,textvariable=self.entryVariable) self.entry.grid(column=0,row=0,sticky='EW') self.entry.bind("&lt;Return&gt;", self.OnPressEnter) self.entryVariable.set(u"Enter text here.") button = Tkinter.Button(self,text=u"Click me !", command=self.OnButtonClick) button.grid(column=1,row=0) self.labelVariable = Tkinter.StringVar() label = Tkinter.Label(self,textvariable=self.labelVariable, anchor="w",fg="white",bg="blue") label.grid(column=0,row=1,columnspan=2,sticky='EW') self.labelVariable.set(u"Hello !") self.grid_columnconfigure(0,weight=1) self.resizable(True,False) self.update() self.geometry(self.geometry()) self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) self.after(1000, self.tick) self.eventbind() def OnButtonClick(self): self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" ) self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) def OnPressEnter(self,event): self.labelVariable.set( self.entryVariable.get()+" (You pressed ENTER)" ) self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) def reset(self, *ignore): self.running = None def tick(self, *ignore): if not self.running: self.running = time.time() elif time.time() - self.running &gt; 5: print 'I waited 5 seconds...' self.running = None self.after(1000,self.tick) def eventbind(self): self.bind('&lt;Key&gt;',self.reset) self.bind('&lt;Button-1&gt;',self.reset) if __name__ == "__main__": app = simpleapp_tk(None) app.title('my application') app.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T05:06:33.027", "Id": "50487", "Score": "0", "body": "What is oops? Oops! Did you mean OOP? See also http://programmers.stackexchange.com/questions/92174/what-does-s-stands-for-in-oops" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T04:45:02.680", "Id": "50534", "Score": "0", "body": "@RomanSusi I mean object oriented programming... I just want to know is there a any more better way to write above code" } ]
[ { "body": "<p>Tkinter is not just OOP, it's about <a href=\"http://en.wikipedia.org/wiki/Event-driven_programming\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Event-driven_programming</a> . The code you posted does not yet show enough to be judged, because it's too small and the application purpose is not yet clearly visible. When code will grow, you will need to decompose it into modules, but it is good to think about the strategy before hand.</p>\n\n<p>Tkinter allows to process events in event-driven style, so it's hard to see why do you need \"a tick\" to check if a user presses something. (I am not sure, may be it is intended this way).</p>\n\n<p>One more note I can make is about style. Take alook at <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">http://www.python.org/dev/peps/pep-0008/</a> It's not very important, but makes the code look much nicer.</p>\n\n<p><strong>UPDATE</strong>: <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC (model-view-controller)</a> is very natural approach for Tkinter (as is the case with other GUI frameworks). Please, take a look at <a href=\"http://tkinter.unpythonic.net/wiki/ToyMVC\" rel=\"nofollow noreferrer\">toy MVC</a> (link from an answer to <a href=\"https://stackoverflow.com/questions/7638139/python-tk-with-mvc-pattern\">https://stackoverflow.com/questions/7638139/python-tk-with-mvc-pattern</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T09:36:54.847", "Id": "50545", "Score": "0", "body": "The reason for using tick is, I am writing client - server code and after some interval I want to check that if the connection is still alive..Tkinter waits for events on mainloop, so I couldn't find any other better way to do it.. or another one is , I want to disconnect if the client connection is idle for more than 5 minutes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T10:21:00.780", "Id": "50548", "Score": "0", "body": "Ok. Network connections may require their own threads and queues. Maybe this recipe can help you: http://code.activestate.com/recipes/82965/ (Hinted by Alex Martelli here: http://stackoverflow.com/questions/1988286/asyncore-not-working-properly-with-tkinter-gui)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T06:17:49.790", "Id": "31672", "ParentId": "31582", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T13:29:35.117", "Id": "31582", "Score": "4", "Tags": [ "python", "tkinter" ], "Title": "Python Tkinter OOPS code optimization" }
31582
<p>This is a plugin I wrote a while ago and I'm trying to improve it. Is this the best practice for jQuery plugins? Should I use options for flexibility?</p> <p>The initial aim was to replicate the syntax for <code>.fadeIn()</code> in jQuery.</p> <p>Any pointers would be appreciated.</p> <pre><code>/* AnimateCSS - CSS transitions instead of js */ (function ($, window, document, undefined) { // Function-level strict mode syntax 'use strict'; $.fn.animateCSS = function (effect, delay, callback) { // Return this to maintain chainability return this.each(function () { // Cache $(this) for speed and compression var $this = $(this), transitionEnd = "webkitAnimationEnd mozAnimationEnd msAnimationEnd oAnimationEnd animationEnd", animated = "animated", visibility = "visibility", visible = "visible", hidden = "hidden"; // Create a function we can call later function run() { // Add the animation effect with classes $this.addClass( animated + " " + effect); // Check if the elemenr has been hidden to start with if ($this.css( visibility ) === hidden) { // If it has, show it (after the class has been added) $this.css( visibility, visible); } // If the element is hidden if ($this.is(":" + hidden)) { // Show it $this.show(); } // Event triggered when the animation has finished $this.bind( transitionEnd, function () { // Remove the classes so they can be added again later $this.removeClass(animated + " " + effect); // Add a callback event if (typeof callback === "function") { // Execute the callback callback.call(this); // Unbind the event handlers $this.unbind( transitionEnd ); } }); } // Check if delay exists or if it"s a callback if (!delay || typeof delay === "function") { // If it"s a callback, move it to callback so we can call it later callback = delay; // Run the animation (without delay) run(); } else { // Start a counter so we can delay the animation if required setTimeout( run, delay ); } }); }; })(jQuery, window, document); </code></pre>
[]
[ { "body": "<p>Awesome code,</p>\n\n<ul>\n<li>Well named variables, commented and easy tor read</li>\n<li>JsHint.com has nothing on this code</li>\n<li>Use <code>'use strict'</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T14:54:02.170", "Id": "47786", "ParentId": "31584", "Score": "2" } } ]
{ "AcceptedAnswerId": "47786", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T14:28:45.293", "Id": "31584", "Score": "1", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "jQuery plugin best practice" }
31584
<p>The code takes in nodes with different start time as input and assigns the position such that they will not overlap. As I have coded with too many loops and conditions. Can anyone review the code and help me to make it efficient? Please do review the algorithm to assign positions to the rectangular blocks.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; &lt;/style&gt; &lt;script type="text/javascript" src="d3.v3.min.js?n=1"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery-2.0.3.min.js?n=1"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id= "chart1"&gt;&lt;/div&gt; &lt;div id= "chart2"&gt;&lt;/div&gt; &lt;div id= "chart3"&gt;&lt;/div&gt; &lt;div id= "chart4"&gt;&lt;/div&gt; &lt;script&gt; var margin = {top: 50, right: 20, bottom: 20, left: 10}, w = 400 - margin.left - margin.right, h = 200 - margin.top - margin.bottom; var nodes = [{"id":0, "start":10 , "stop":40, "total":30}, {"id":1, "start":40 , "stop":80, "total":40}, {"id":2, "start":100 , "stop":150, "total":50}, {"id":3, "start":120 , "stop":150, "total":30}, {"id":4, "start":140 , "stop":160, "total":20}]; var flag_move = 1; svg = d3.select("#chart1").append("svg") .attr("width", w + margin.left + margin.right) .attr("height", h + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); nodes.forEach(function(d){ d.y = 30 * d.id; }); svg.append("svg:g") .attr("class","nodes") .selectAll("rect") .data(nodes) .enter().append("svg:rect") .style("fill", "blue") .style("opacity",0.5) .attr("width",function(d) { return (d.total); }) .attr("height", "20") .attr("x",function(d) { return (d.start); }) .attr("y",function(d) { return (d.y); }); // different approach updated_pos_mat = []; nodes.forEach(function(d){ updated_pos_mat.push([d.id]); }); //pass1 var pass = updated_pos_mat.length - 1; while ( pass != 0){ console.log( "At " + (3-pass) + " pass"); var removed = 0; for( var i=1;i&lt;updated_pos_mat.length;i++){ temp_ival = updated_pos_mat[i]; console.log(" Before comaparison, at iteration " + i + " : " + " Updated position matrix is"); console.log(updated_pos_mat); for(var j=0;j&lt;updated_pos_mat.length;j++){ temp_jval = updated_pos_mat[j]; if(i != j &amp;&amp; i&gt;j &amp;&amp; (i-j == 1)){ if((temp_ival.length == 1) &amp;&amp; (temp_jval.length == 1)){ if(nodes[temp_ival[0]].start &gt; nodes[temp_jval[0]].stop){ console.log("Push the node " + nodes[temp_ival[0]].id + " a level above"); updated_pos_mat[j].push(nodes[temp_ival[0]].id); console.log("After pushing the data update matrix is:"); console.log(updated_pos_mat); break; } } if((temp_ival.length != 1) &amp;&amp; (temp_jval.length == 1)){ for(var k = 0; k&lt; temp_ival.length; k++){ if(nodes[temp_ival[k]].start &gt; nodes[temp_jval[0]].stop){ console.log("Push the node " + nodes[temp_ival[k]].id + " a level above"); updated_pos_mat[j].push(nodes[temp_ival[k]].id); break; } } } if((temp_ival.length == 1) &amp;&amp; (temp_jval.length != 1)){ temp_arr = []; for(var k = 0; k&lt; temp_jval.length; k++){ if(nodes[temp_ival[0]].start &gt; nodes[temp_jval[k]].stop){ temp_arr.push(1); //updated_pos_mat[j].push(nodes[temp_ival[0]].id); //break; } } temp_arr_sum = temp_arr.reduce(function (a, b) { return a + b; }, 0); if(temp_arr_sum == temp_jval.length){ console.log("Push the node " + nodes[temp_ival[0]].id + " a level above"); updated_pos_mat[j].push(nodes[temp_ival[0]].id); } } if((temp_ival.length != 1) &amp;&amp; (temp_jval.length != 1)){ for(var k = 0; k&lt; temp_ival.length; k++){ temp_arr = []; for(var l = 0; l&lt; temp_jval.length; l++){ if(nodes[temp_ival[k]].start &gt; nodes[temp_jval[l]].stop){ //updated_pos_mat[j].push(nodes[temp_ival[k]].id); //break; } } temp_arr_sum = temp_arr.reduce(function (a, b) { return a + b; }, 0); if(temp_arr_sum == temp_jval.length){ console.log("Push the node " + nodes[temp_ival[k]].id + " a level above"); updated_pos_mat[j].push(nodes[temp_ival[k]].id); } } } } } console.log(" After comparison, at iteration " + i + " : " + " Updated position matrix is"); console.log(updated_pos_mat); } for(var u = 1; u&lt;updated_pos_mat.length; u++){ var temp_val = updated_pos_mat[u]; var temp_valp = updated_pos_mat[u-1]; for(var v = 0; v &lt; temp_val.length; v++){ for(var s = 0; s &lt; temp_valp.length; s++){ if( temp_val[v] == temp_valp[s]){ updated_pos_mat[u].splice(v,1); } } } } for(var i = 0; i&lt;updated_pos_mat.length; i++){ //console.log(updated_pos_mat[i].length); if(updated_pos_mat[i].length == 0){ //console.log("removing the empty array"); updated_pos_mat.splice(i,1); } } pass--; } console.log(updated_pos_mat); pass1_y = 0; updated_pos_mat.forEach(function(d){ val = d; if(val.length &gt; 1){ //console.log("reached if loop"); for(var i=0;i&lt;val.length;i++){ //console.log("reached for loop"); i_val = val[i]; nodes[i_val].y = pass1_y; } }else { //console.log("reached else loop"); nodes[val[0]].y = pass1_y; } pass1_y = pass1_y + 30; }) console.log(nodes); svg_1 = d3.select("#chart2").append("svg") .attr("width", w + margin.left + margin.right) .attr("height", h + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); svg_1.append("svg:g") .attr("class","nodes") .selectAll("rect") .data(nodes) .enter().append("svg:rect") .style("fill", "blue") .style("opacity",0.5) .attr("width",function(d) { return (d.total); }) .attr("height", "20") .attr("x",function(d) { return (d.start); }) .attr("y",function(d) { return (d.y); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li><code>console.log()</code> &lt;- Performance killer, at the very least call a custom function that you can uncomment</li>\n<li><code>//updated_pos_mat[j].push(nodes[temp_ival[0]].id);</code> &lt;- Remove dead code for easier reading</li>\n<li><code>temp_arr.reduce(</code> &lt;- While cool, it is far <a href=\"http://jsperf.com/array-reduce-vs-foreach/16\" rel=\"nofollow\">slower</a> than an old skool loop </li>\n<li>From a readability perspective, you have too many 1 char variable names, and your indenting is a mess, making it hard to grok your code and find conceptual problems with the code.</li>\n</ul>\n\n<p>Once you remove the <code>log()</code> calls, the <code>reduce()</code> calls , the dead code and renamed the variables, you should definitely repost the code if it is still too slow. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T15:05:07.610", "Id": "47788", "ParentId": "31585", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T15:13:21.860", "Id": "31585", "Score": "3", "Tags": [ "javascript", "algorithm", "svg", "d3.js" ], "Title": "Displaying overlapping blocks using d3.js" }
31585
<p>I wrote this partly as a learning exercise in TDD. Could I please have feedback on both how to improve the quality of the code and the completeness of the tests?</p> <p>I used LinqPad as my IDE for this, the code has no external dependencies (the test framework is included).</p> <pre><code>void Main() { var tests = new SimpleClassTests(); tests.RunTests(); } // Define other methods and classes here class JsonContains { // start off with simplest case - object with a simple (leaf) value public bool Contains(IDictionary&lt;string, object&gt; tree, string key, object val ) { var pathFound = tree.ContainsKey(key); if (!pathFound) return false; var actual = tree[key]; if (actual != null) return (actual.Equals(val)); else return (val == null); } // and equally simple case - array with a simple (leaf) value public bool Contains(object[] tree, int key, object val ) { var pathFound = key &lt; tree.Length; if (!pathFound) return false; var actual = tree[key]; if (actual != null) return (actual.Equals(val)); else return (val == null); } // let's add depth, part 1 - objects with paths public bool Contains(IDictionary&lt;string, object&gt; tree, IList&lt;object&gt; path, object val ) { var first = path.First(); if(first == null || !(first is string)) throw new ArgumentException(string.Format("Expected string as next item in path but got {0}.", first)); var key = (string)first; var tail = new List&lt;object&gt;(path.Skip&lt;object&gt;(1)); // if there's only one step in the path, call the Key version if (tail == null || tail.Count == 0) { return Contains(tree, key, val); } // so does our non-null tree contain an item for our key? var pathFound = tree.ContainsKey(key); if (!pathFound) { return false; } // Helter skelter time - let's recurse! var nextContext = tree[key]; if (nextContext is System.Dynamic.ExpandoObject) return Contains((System.Dynamic.ExpandoObject)nextContext, tail, val); else return Contains((object[])nextContext, tail, val); } // let's add depth, part 2 - arrays with paths public bool Contains(object[] array, IList&lt;object&gt; path, object val ) { var first = path.First(); if(!(first is int)) throw new ArgumentException(string.Format("Expected int as next item in path but got {0}.", first)); int key = (int)first; var tail = new List&lt;object&gt;(path.Skip&lt;object&gt;(1)); // if there's only one step in the path, call the Key version if (tail == null || tail.Count == 0) { return Contains(array, key, val); } // so does our non-null tree contain an item for our key? var pathFound = key &lt; array.Length; if (!pathFound) { string.Format("couldn't find item for {0}", key).Dump(); return false; } // Helter skelter time - let's recurse... var nextContext = array[key]; if (nextContext is System.Dynamic.ExpandoObject) return Contains((System.Dynamic.ExpandoObject)nextContext, tail, val); else return Contains((object[])nextContext, tail, val); } // slightly more complex case - array to array public bool Contains(object[] container, object[] containee) { for(var n = 0; n &lt; containee.Length; n++) { // string.Format("About to compare '{0}' with '{1}' for item '{2}':", container[n], containee[n], n).Dump(); // if the two objects are trees, ensure we use the tree overload if(container[n] is System.Dynamic.ExpandoObject &amp;&amp; containee[n] is System.Dynamic.ExpandoObject) { if(!Contains((System.Dynamic.ExpandoObject)container[n], (System.Dynamic.ExpandoObject)containee[n])) return false; } // if the tree objects are arrays, ensure we use the array overload else if(container[n] is object[] &amp;&amp; containee[n] is object[]) { if(!Contains((object[])container[n], (object[])containee[n])) return false; } // anything else, treat as simple objects else if(!Contains(container[n], containee[n])) return false; } return true; } // slightly more complex case - tree to tree public bool Contains(IDictionary&lt;string, object&gt; container, IDictionary&lt;string, object&gt; containee) { foreach(var key in containee.Keys) { // string.Format("About to compare '{0}' with '{1}' for key '{2}':", container[key], containee[key], key).Dump(); // if the two objects are trees, ensure we use the tree overload if(container[key] is System.Dynamic.ExpandoObject &amp;&amp; containee[key] is System.Dynamic.ExpandoObject) { if(!Contains((System.Dynamic.ExpandoObject)container[key], (System.Dynamic.ExpandoObject)containee[key])) return false; } // if the tree objects are arrays, ensure we use the array overload else if(container[key] is object[] &amp;&amp; containee[key] is object[]) { if(!Contains((object[])container[key], (object[])containee[key])) return false; } // anything else, treat as simple objects else if(!Contains(container[key], containee[key])) return false; } return true; } // final case - object to object public bool Contains(object container, object containee) { // string.Format("About to compare '{0}' with '{1}':", container, containee).Dump(); if (container == null) return (containee == null); else return container.Equals(containee); } } class SimpleClassTests : UnitTestBase { [Test] public void ArrayOfTreeDoesNotContainArrayOfTree() { var jsonContains = new JsonContains(); dynamic tree1 = new System.Dynamic.ExpandoObject(); var container = new dynamic[]{ tree1 }; container[0].leaf = "red"; container[0].stem = "brown"; container[0].height = 72; dynamic tree2 = new System.Dynamic.ExpandoObject(); var containee = new dynamic[]{ tree2 }; containee[0].height = 72; containee[0].stem = "brown"; containee[0].leaf = "green"; var result = jsonContains.Contains(container, containee); Assert.IsFalse(result); } [Test] public void ArrayOfTreeContainsArrayOfTree() { var jsonContains = new JsonContains(); dynamic tree1 = new System.Dynamic.ExpandoObject(); var container = new dynamic[]{ tree1 }; container[0].leaf = "red"; container[0].stem = "brown"; container[0].height = 72; dynamic tree2 = new System.Dynamic.ExpandoObject(); var containee = new dynamic[]{ tree2 }; containee[0].height = 72; containee[0].stem = "brown"; containee[0].leaf = "red"; var result = jsonContains.Contains(container, containee); Assert.IsTrue(result); } [Test] public void ArrayOfTreeContainsItself() { var jsonContains = new JsonContains(); dynamic tree = new System.Dynamic.ExpandoObject(); var container = new dynamic[]{ tree }; container[0].leaf = "red"; container[0].stem = "brown"; container[0].height = 72; var result = jsonContains.Contains(container, container); Assert.IsTrue(result); } [Test] public void TreeDoesNotContainTree() { var jsonContains = new JsonContains(); dynamic container = new System.Dynamic.ExpandoObject(); container.hello = "World"; container.answer = 42; container.hope = false; container.end = null; dynamic containee = new System.Dynamic.ExpandoObject(); containee.end = null; containee.hope = true; containee.answer = 42; containee.hello = "World"; var result = jsonContains.Contains(container, containee); Assert.IsFalse(result); } [Test] public void TreeContainsTree() { var jsonContains = new JsonContains(); dynamic container = new System.Dynamic.ExpandoObject(); container.hello = "World"; container.answer = 42; container.hope = true; container.end = null; dynamic containee = new System.Dynamic.ExpandoObject(); containee.end = null; containee.hope = true; containee.answer = 42; containee.hello = "World"; var result = jsonContains.Contains(container, containee); Assert.IsTrue(result); } [Test] public void ArrayDoesNotContainArray() { var jsonContains = new JsonContains(); var container = new dynamic[]{ "a", 1, true, "z" }; var containee = new dynamic[]{ "a", 1, true, null }; var result = jsonContains.Contains(container, containee); Assert.IsFalse(result); } [Test] public void ArrayContainsArray() { var jsonContains = new JsonContains(); var container = new dynamic[]{ "a", 1, true, null, "z" }; var containee = new dynamic[]{ "a", 1, true, null }; var result = jsonContains.Contains(container, containee); Assert.IsTrue(result); } [Test] public void ArrayContainsTreeValue() { var jsonContains = new JsonContains(); dynamic tree = new System.Dynamic.ExpandoObject(); var hedge = new dynamic[]{ tree }; hedge[0].leaf = "red"; var path = new List&lt;object&gt;(){0, "leaf"}; var result = jsonContains.Contains(hedge, path, "red"); Assert.IsTrue(result); } [Test] public void ArrayContainsStringValue() { var jsonContains = new JsonContains(); var tree = new dynamic[]{"AA", "BB", "CC"}; var result = jsonContains.Contains(tree, 0, "AA"); Assert.IsTrue(result); } [Test] public void ArrayContainsNumericValue() { var jsonContains = new JsonContains(); // box the double into objects var tree = new dynamic[]{3.14, 42, 999}; var result = jsonContains.Contains(tree, 0, 3.14); Assert.IsTrue(result); } [Test] public void ArrayDoesNotContainStringValue() { var jsonContains = new JsonContains(); var tree = new string[]{"AA", "BB", "CC"}; var result = jsonContains.Contains(tree, 0, "xx"); Assert.IsFalse(result); } [Test] public void ArrayRejectsNonIntKey() { var jsonContains = new JsonContains(); try { dynamic tree = new System.Dynamic.ExpandoObject(); var hedge = new dynamic[]{ tree }; hedge[0].leaf = "red"; var path = new List&lt;object&gt;(){"zero", "leaf"}; var result = jsonContains.Contains(hedge, path, "red"); } catch(Exception e) { Assert.IsTrue(e is ArgumentException); } } [Test] public void TreeRejectsNonStringKey() { var jsonContains = new JsonContains(); try { dynamic tree = new System.Dynamic.ExpandoObject(); var hedge = new dynamic[]{ tree }; hedge[0].leaf = "red"; var path = new List&lt;object&gt;(){0, 0}; var result = jsonContains.Contains(hedge, path, "red"); } catch(Exception e) { Assert.IsTrue(e is ArgumentException); } } [Test] public void SimpleTreeContainsStringValue() { var jsonContains = new JsonContains(); var tree = new Dictionary&lt;string, object&gt;(); tree.Add("key", "val"); var result = jsonContains.Contains(tree, "key", "val"); Assert.IsTrue(result); } [Test] public void SimpleTreeDoesNotContainStringValue() { var jsonContains = new JsonContains(); var tree = new Dictionary&lt;string, object&gt;(); tree.Add("key", "val"); var result = jsonContains.Contains(tree, "key", "xxx"); Assert.IsFalse(result); } [Test] public void SimpleTreeContainsFloatValue() { var jsonContains = new JsonContains(); var tree = new Dictionary&lt;string, object&gt;(); tree.Add("key", 3.14); var result = jsonContains.Contains(tree, new List&lt;object&gt;(){"key"}, 3.14); Assert.IsTrue(result); } [Test] public void SimpleTreeContainsTrueValue() { var jsonContains = new JsonContains(); var tree = new Dictionary&lt;string, object&gt;(); tree.Add("key", true); var result = jsonContains.Contains(tree, "key", true); Assert.IsTrue(result); } [Test] public void SimpleTreeContainsFalseValue() { var jsonContains = new JsonContains(); var tree = new Dictionary&lt;string, object&gt;(); tree.Add("key", false); var result = jsonContains.Contains(tree, "key", false); Assert.IsTrue(result); } [Test] public void SimpleTreeContainsNullValue() { var jsonContains = new JsonContains(); var tree = new Dictionary&lt;string, object&gt;(); tree.Add("key", null); var result = jsonContains.Contains(tree, "key", null); Assert.IsTrue(result); } [Test] public void SimpleTreeDoesNotContainKey() { var jsonContains = new JsonContains(); var tree = new Dictionary&lt;string, object&gt;(); tree.Add("key", "val"); var result = jsonContains.Contains(tree, "xxx", "xxx"); Assert.IsFalse(result); } [Test] public void ExpandoObjectContainsValue() { var jsonContains = new JsonContains(); dynamic tree = new System.Dynamic.ExpandoObject(); tree.root = new System.Dynamic.ExpandoObject(); tree.root.key = "val"; IList&lt;object&gt; path = new List&lt;object&gt;(){"root", "key"}; var result = jsonContains.Contains(tree, path, "val"); Assert.IsTrue(result); } [Test] public void ExpandoObjectContainsNull() { var jsonContains = new JsonContains(); dynamic tree = new System.Dynamic.ExpandoObject(); tree.root = new System.Dynamic.ExpandoObject(); tree.root.key = null; IList&lt;object&gt; path = new List&lt;object&gt;(){"root", "key"}; var result = jsonContains.Contains(tree, path, null); Assert.IsTrue(result); } [Test] public void ExpandoObjectDoesNotContainKey() { var jsonContains = new JsonContains(); dynamic tree = new System.Dynamic.ExpandoObject(); tree.root = new System.Dynamic.ExpandoObject(); tree.root.key = "val"; IList&lt;object&gt; path = new List&lt;object&gt;(){"root", "xxx"}; var result = jsonContains.Contains(tree, path, "val"); Assert.IsFalse(result); } [Test] public void ExpandoObjectDoesNotContainValue() { var jsonContains = new JsonContains(); dynamic tree = new System.Dynamic.ExpandoObject(); tree.root = new System.Dynamic.ExpandoObject(); tree.root.key = "val"; IList&lt;object&gt; path = new List&lt;object&gt;(){"root", "key"}; var result = jsonContains.Contains(tree, path, "xxx"); Assert.IsFalse(result); } } // test framework initially based on http://www.youtube.com/watch?feature=player_detailpage&amp;list=PL3D3F4B7C71FF6AA0&amp;v=hayjhjIKSwA [AttributeUsage(AttributeTargets.Method)] class SetupAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] class TestAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] class TeardownAttribute : Attribute { } class Assert { public bool Passed { get; set; } public string Message { get; private set; } public Assert() { Reset(); } public void Reset() { Passed = true; Message = string.Empty; } public void AreEqual(double expected, double actual) { if(!expected.Equals(actual)) { Passed = false; Message = string.Format("Expected {0}, but was {1}.", expected, actual); } } public void AreEqual(bool expected, bool actual) { if(!expected.Equals(actual)) { Passed = false; Message = string.Format("Expected {0}, but was {1}.", expected, actual); } } public void IsTrue(bool actual) { AreEqual(true, actual); } public void IsFalse(bool actual) { AreEqual(false, actual); } public void WriteResults(string methodName) { if(Passed) Console.WriteLine("Success: {0}", methodName); else Console.WriteLine("Failed: {0} - {1}", methodName, Message); } } abstract class UnitTestBase { protected Assert Assert {get; private set;} public UnitTestBase() { Assert = new Assert(); } public void RunTests() { // run Setup methods var methods = this.GetType().GetMethods(); foreach (var method in methods.Where(m =&gt; m.IsDefined(typeof(SetupAttribute), false))) { this.GetType().InvokeMember(method.Name, BindingFlags.InvokeMethod, null, this, null); } // run Test methods foreach (var method in methods.Where(m =&gt; m.IsDefined(typeof(TestAttribute), false))) { // clear results Assert.Reset(); // run the test this.GetType().InvokeMember(method.Name, BindingFlags.InvokeMethod, null, this, null); // report results Assert.WriteResults(method.Name); } // run Teardown methods foreach (var method in methods.Where(m =&gt; m.IsDefined(typeof(TeardownAttribute), false))) { this.GetType().InvokeMember(method.Name, BindingFlags.InvokeMethod, null, this, null); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T17:41:38.423", "Id": "50419", "Score": "0", "body": "“I used LinqPad as my IDE for this” I don't think that's a good idea. LinqPad is great for small amounts of code, but I would never use it for anything this big. If you can't afford to buy Visual Studio, have you considered Visual Studio Express?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T18:42:33.233", "Id": "50462", "Score": "0", "body": "Hi @svick - I have Visual Studio Enterprise edition, and I suppose it is a little perverse but I like prototyping stuff in LinqPad and decided to take it a little further this time." } ]
[ { "body": "<p>Not sure I should be answering my own question, but having slept on it and reviewed the code my perspective has moved on.</p>\n\n<p>I've reviewed my use cases, and it turns out that I only need the three two-argument overloads, which I wrote last, and can ditch the four other, supposedly simpler, overloads and their associated tests.</p>\n\n<p>I'm not sure whether to draw the lesson that I shouldn't have started with tests which made assumptions about how I was going to implement the solution, or that this just reflects the evolutionary nature of the TDD process. Either way, the code is now smaller and simpler, and I'm happy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T02:34:19.767", "Id": "57560", "Score": "0", "body": "Hi, answering your own post is perfectly acceptable - feel free to even accept it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T18:59:27.740", "Id": "31630", "ParentId": "31587", "Score": "1" } } ]
{ "AcceptedAnswerId": "31630", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T15:49:05.977", "Id": "31587", "Score": "2", "Tags": [ "c#", "json", "tdd" ], "Title": "A C# class to check if one JSON tree (de-serialised as ExpandoObject / Array etc) contains another" }
31587
<p>For the sake of knowledge, I wanted to convert a SQL query to a LINQ query expression. Here is the original SQL:</p> <pre><code>SELECT CT.COURSE_NODE_ID AS CNID, CT.NODE_TEXT FROM COURSE_RELATED_VERSIONS AS CRV INNER JOIN COURSE_TREE AS CT ON CRV.COURSE_NODE_ID = CT.COURSE_NODE_ID WHERE (CRV.COURSE_ID = '38890') AND (CRV.COURSE_PARENT_NODE_ID = '-1') </code></pre> <p>Basically, just grabbing two fields from a table based on certain criteria (keys match, course ID matches criteria, parent node not equal -1). Here's the LINQ query expression that I came up with, using LINQPad:</p> <pre><code>from ct in COURSE_TREEs join crv in COURSE_RELATED_VERSIONS on ct.COURSE_NODE_ID equals crv.COURSE_NODE_ID where crv.COURSE_ID == 38890 &amp;&amp; crv.COURSE_PARENT_NODE_ID == -1 select new {ct.COURSE_NODE_ID, ct.NODE_TEXT} </code></pre> <p>Not too bad, still understandable to my SQL-centric brain. But, for grins, I wondered what this query expression would look like as a lambda expression. For the life of me, I could not figure out the syntax. So, I used the lambda tool in LINQPad to see what my LINQ query expression would look like. Here it is:</p> <pre><code>COURSE_TREEs .Join ( COURSE_RELATED_VERSIONS, ct =&gt; ct.COURSE_NODE_ID, crv =&gt; crv.COURSE_NODE_ID, (ct, crv) =&gt; new { ct = ct, crv = crv } ) .Where (temp0 =&gt; ((temp0.crv.COURSE_ID == 38890) &amp;&amp; (temp0.crv.COURSE_PARENT_NODE_ID == -1))) .Select ( temp0 =&gt; new { COURSE_NODE_ID = temp0.ct.COURSE_NODE_ID, NODE_TEXT = temp0.ct.NODE_TEXT } ) </code></pre> <p>Whoah! Not what I figured the lambda expression query would look like. So, I'm studying the output from LINQPad on how my query expression looks as a lambda expression, and I'm wondering if it can be written any better? I'm still learning the ropes of LINQ (and lambda expressions), but I can't help but feel that the resulting lambda expression here is too complex! Am I wrong? Is it possible to write a lambda expression that produces the same output as the original SQL and query expression, but not be needlessly complex? Perhaps 'complex' is subjective, since it may only appear complex to my SQL brain. I just feel like the lambda expression generated in LINQPad can be written better... I just don't know how.</p>
[]
[ { "body": "<ol>\n<li>LINQ isn't as rigid about the order of clauses as SQL is (this applies to both syntaxes). This means that if you switch your <code>Join</code> around, you can put your <code>Where</code> before your <code>Join</code>.</li>\n<li>If you have <code>Select</code> right after <code>Join</code>, you can combine the two together.</li>\n<li>When the property you're using in an anonymous object creation expression has the same name as the one you're assigning it to, you can omit the name.</li>\n</ol>\n\n<p>This means that your code could be simplified to this:</p>\n\n<pre><code>COURSE_RELATED_VERSIONS\n.Where (crv =&gt; crv.COURSE_ID == 38890 &amp;&amp; crv.COURSE_PARENT_NODE_ID == -1)\n.Join (\n COURSE_TREEs, \n crv =&gt; crv.COURSE_NODE_ID,\n ct =&gt; ct.COURSE_NODE_ID,\n (crv, ct) =&gt; new { ct.COURSE_NODE_ID, ct.NODE_TEXT }\n)\n</code></pre>\n\n<p>But in general, if you're doing something more complicated, you need to follow the pattern in your question. Which is exactly why the query syntax exists: it can make complicated queries much simpler.</p>\n\n<p>Also, I would suggest that your tweak your mapping so that the names follow usual .Net naming conventions (e.g. <code>CourseRelatedVersion</code> or <code>CourseNodeId</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T18:31:26.550", "Id": "31595", "ParentId": "31592", "Score": "2" } } ]
{ "AcceptedAnswerId": "31595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T17:12:36.307", "Id": "31592", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "Can this LINQ lambda expression be written any better?" }
31592
<pre><code>var _ = require("underscore"); var checkSettingsUndefined = function(settings){ if(_.isEmpty(settings)){ throw new Error("settings are empty"); } } var Class = function(settings){ checkSettingsUndefined(settings); this.settings = settings; } Class.prototype.settings = function(){ return this.settings; } module.exports = Class; </code></pre> <p>and here's my unit test</p> <pre><code>it("empty settings should throw error", function(){ var Class = require("Class.js"); expect(function(){ return new Class(); }).to.throwException(function (e) { expect(e.message).to.be("settings are empty"); }); }); </code></pre>
[]
[ { "body": "<p>The abstraction is good but the tight coupling is bad. The only real use case for <code>checkSettingsUndefined</code> is for your <code>Class</code> object.</p>\n\n<p>Here is an example of a more generic method, it just takes an array of validation objects that will be run on their associated calling args.</p>\n\n<pre><code>/**\n * @param {[Object]} validationArray Array of validation configs \n * that follow the api of\n {\n fn: function(value) {},\n message: ''\n }\n * @return Function\n */\n\nfunction createArgValidatorFn(validationArray) {\n\n return function() {\n var argValue,\n validationFn,\n args = arguments;\n\n validationArray.forEach(function(obj, index) {\n validationFn = obj.fn;\n argValue = args[index];\n\n if (validationFn(argValue)) {\n throw new Error('argument[' + index + '] : ' + obj.message);\n }\n\n });\n }\n}\n</code></pre>\n\n<p>You can use in <code>Class</code> by doing:</p>\n\n<pre><code>var classValidationFn = createArgValidatorFn([{\n fn: _.isEmpty,\n message: 'settings are empty'\n }\n]);\n\nvar Class = function(settings){\n classValidationFn.apply(this, arguments);\n this.settings = settings;\n};\n</code></pre>\n\n<p>This will allow to stuff like:</p>\n\n<pre><code>var fn = createArgValidatorFn([{\n fn: function(val) {\n return typeof val !== 'string'\n },\n message: 'Argument must be a string'\n }, {\n fn: function(val) {\n return !val;\n },\n message: 'Argument must be a truthy'\n }\n])\n</code></pre>\n\n<p>fn('a');</p>\n\n<blockquote>\n <p>\"argument[1] : Argument must be truthy\"</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T22:06:37.397", "Id": "31602", "ParentId": "31593", "Score": "1" } } ]
{ "AcceptedAnswerId": "31602", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T17:35:42.760", "Id": "31593", "Score": "1", "Tags": [ "javascript", "object-oriented", "classes", "unit-testing", "node.js" ], "Title": "Throwing error if settings / arguments are undefined is this a good breakout function?" }
31593
<p>This is code from a grappling hook implementation. This is specifically code that, after a block is detected between two way points, it tries to find a path around.</p> <p>This particular piece of the function considers the blocks that are in the way and decides which corners are appropriate to wrap around.</p> <p>The point will always be on the edge. If it's not the very first (anchor) point, it will always be on a corner. So if the problem block is our block we just choose the two closest corners. Otherwise we need to look at this diagram.</p> <p><img src="https://i.imgur.com/ORaTTfm.png" alt="Example"></p> <p>In the picture the block at 3 o'clock corresponds with case 1, at 1:30 is case 3, 12 o'clock is case 2, and 10:30 is case 4. 9 o'clock is a special case, when the point and the block share an orthogonal edge, it should use the far point instead of the near point.</p> <p>Here's my code, <code>problem</code> is a <code>Vec2I</code> which is a <code>std::array&lt;int, 2&gt;</code> with several convenience functions. <code>origin</code> is a <code>GrapplingHookPathPoint</code> which is a <code>struct</code> defined as:</p> <pre><code>struct GrapplingHookPathPoint { GrapplingHookPathPoint() : anchorPoint(Vec2F::filled(nan&lt;float&gt;())), anchorBroken(), endpoint() {} GrapplingHookPathPoint(Vec2I anchoredBlock, Vec2F anchorPoint, bool anchorBroken, bool endpoint) : anchoredBlock(anchoredBlock), anchorPoint(anchorPoint), anchorBroken(anchorBroken), endpoint(endpoint) {} Vec2I anchoredBlock; Vec2F anchorPoint; bool anchorBroken; bool endpoint; bool operator==(GrapplingHookPathPoint const&amp; rhs) const; }; </code></pre> <p><code>Vec2F</code> is <code>std::array&lt;float, 2&gt;</code>, <code>RectF</code> is a Rectangle class</p> <pre><code>if (dest.endpoint &amp;&amp; RectF::withSize(Vec2F(problem), {1, 1}).contains(dest.anchorPoint)) continue; if (origin.anchoredBlock == problem) { Logger::debug("door 0\n"); if (origin.anchorPoint[0] == origin.anchoredBlock[0] &amp;&amp; origin.anchorPoint[1] == origin.anchoredBlock[1]) { // bottom - left corner Logger::debug("subdoor -3\n"); corners.append({problem, Vec2F(problem) + Vec2F{1, 0}, false, false}); corners.append({problem, Vec2F(problem) + Vec2F{0, 1}, false, false}); } else if (origin.anchorPoint[0] == origin.anchoredBlock[0] &amp;&amp; origin.anchorPoint[1] - 1 == origin.anchoredBlock[1]) { // top - left corner Logger::debug("subdoor -2\n"); corners.append({problem, Vec2F(problem) + Vec2F{1, 1}, false, false}); corners.append({problem, Vec2F(problem), false, false}); } else if (origin.anchorPoint[0] - 1 == origin.anchoredBlock[0] &amp;&amp; origin.anchorPoint[1] == origin.anchoredBlock[1]) { // bottom - right corner Logger::debug("subdoor -1\n"); corners.append({problem, Vec2F(problem) + Vec2F{1, 1}, false, false}); corners.append({problem, Vec2F(problem), false, false}); } else if (origin.anchorPoint[0] - 1 == origin.anchoredBlock[0] &amp;&amp; origin.anchorPoint[1] - 1 == origin.anchoredBlock[1]) { // top - right corner Logger::debug("subdoor 0\n"); corners.append({problem, Vec2F(problem) + Vec2F{1, 0}, false, false}); corners.append({problem, Vec2F(problem) + Vec2F{0, 1}, false, false}); } else if (origin.anchorPoint[0] == origin.anchoredBlock[0]) { // on the left Logger::debug("subdoor 1\n"); corners.append({problem, Vec2F(problem), false, false}); corners.append({problem, Vec2F(problem) + Vec2F{0, 1}, false, false}); } else if (origin.anchorPoint[0] - 1 == origin.anchoredBlock[0]) { // on the right Logger::debug("subdoor 2\n"); corners.append({problem, Vec2F(problem) + Vec2F{1, 0}, false, false}); corners.append({problem, Vec2F(problem) + Vec2F{1, 1}, false, false}); } else if (origin.anchorPoint[1] == origin.anchoredBlock[1]) { // on the bottom Logger::debug("subdoor 3\n"); corners.append({problem, Vec2F(problem), false, false}); corners.append({problem, Vec2F(problem) + Vec2F{1, 0}, false, false}); } else if (origin.anchorPoint[1] - 1 == origin.anchoredBlock[1]) { // on the top Logger::debug("subdoor 4\n"); corners.append({problem, Vec2F(problem) + Vec2F{0, 1}, false, false}); corners.append({problem, Vec2F(problem) + Vec2F{1, 1}, false, false}); } else { // we can't route around this block we're inside of it, this shouldn't happen! starAssert(false); } // Decide which two corners we're considering // two cases, either we consider two adjacent corners // or two opposite corners. // Adjacent corners happen when origin and the problem tile // are nearly orthagonal to each other. } else if (origin.anchoredBlock[0] == problem[0] &amp;&amp; origin.anchorPoint[0] != origin.anchoredBlock[0] &amp;&amp; origin.anchorPoint[0] != origin.anchoredBlock[0] + 1) { Logger::debug("door 1\n"); corners = List&lt;GrapplingHookPathPoint&gt;(2, {problem, Vec2F(problem), false, false}); if (origin.anchorPoint[1] &gt; problem[1]) corners[0].anchorPoint += Vec2F(0, 1); corners[1].anchorPoint = corners[0].anchorPoint + Vec2F(1, 0); } else if (origin.anchoredBlock[1] == problem[1] &amp;&amp; origin.anchorPoint[1] != origin.anchoredBlock[1] &amp;&amp; origin.anchorPoint[1] != origin.anchoredBlock[1] + 1) { Logger::debug("door 2\n"); corners = List&lt;GrapplingHookPathPoint&gt;(2, {problem, Vec2F(problem), false, false}); if (origin.anchorPoint[0] &gt; problem[0]) corners[0].anchorPoint += Vec2F(1, 0); corners[1].anchorPoint = corners[0].anchorPoint + Vec2F(0, 1); } else if (((origin.anchoredBlock[0] &gt; problem[0]) == (origin.anchoredBlock[1] &gt; problem[1]) &amp;&amp; origin.anchoredBlock[0] != problem[0] &amp;&amp; origin.anchoredBlock[1] != problem[1]) || ((origin.anchorPoint[0] == origin.anchoredBlock[0] + 1 &amp;&amp; origin.anchoredBlock[0] == problem[0] &amp;&amp; origin.anchoredBlock[1] &gt; problem[1]) || (origin.anchorPoint[1] == origin.anchoredBlock[1] + 1 &amp;&amp; origin.anchoredBlock[1] == problem[1] &amp;&amp; origin.anchoredBlock[0] &gt; problem[0]))) { // Positive Slope Logger::debug("door 3\n"); corners = {{problem, Vec2F(problem) + Vec2F(1, 0), false, false}, {problem, Vec2F(problem) + Vec2F(0, 1), false, false}}; } else { Logger::debug("door 4\n"); corners = {{problem, Vec2F(problem), false, false}, {problem, Vec2F(problem) + Vec2F(1, 1), false, false}}; } </code></pre> <p>This seems needlessly complex, especially the condition for "door 3" and some of the repeated logic.</p> <p>Can you help me pare this down into something easier to understand and more readable?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T19:47:55.477", "Id": "50431", "Score": "0", "body": "I must confess that I don't really understand the problem nor the drawing but my feeling is that you might want to have a look at http://en.wikipedia.org/wiki/Convex_hull_algorithms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-11T13:58:02.607", "Id": "392368", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-13T03:54:22.413", "Id": "392592", "Score": "0", "body": "This question is older than the first revision of your guide, and has had no activity since being fully asked and fully answered 5 years ago. I'm not going to bother. You're welcome to perform the edit to your heart's content, or find four other people to close this question for being too unclear. Thanks." } ]
[ { "body": "<p>I can't follow your code at all, mainly because I don't understand your terminology. What'a a <code>GrapplingHookPathPoint</code>? <code>anchoredBlock</code>? <code>anchorPoint</code>? <code>problem</code>?</p>\n\n<p>Anyway, I'll describe how I would approach the problem instead.</p>\n\n<p>Let's assume that all coordinates are expressed relative to the desired origin point. If not, make it so.</p>\n\n<p>Then, for each square (which I'll call a <code>Block</code>), sort the four vertices according to their angle if they were expressed in polar coordinates. The first and last vertex after sorting are the ones you are looking for. One advantage of this solution over yours is that the squares do not have to be rotationally aligned with the x and y axes. The main benefit is that there are many fewer cases to be covered — the computer, rather than the programmer, does the hard work.</p>\n\n<p>I'd like to avoid having to call <code>atan2()</code>, both because trigonometric functions are computationally intensive and because arctangents fail at 90°. Instead of sorting by the angle, I can just sort by the cosine of the angle, as long as all of the points are on the same side of the X-axis. (The cosine of the angle can be calculated using the rule <a href=\"http://en.wikipedia.org/wiki/Dot_product#Geometric_definition\" rel=\"nofollow\"><strong><em>A</em></strong> ⋅ <strong><em>B</em></strong> = |<strong><em>A</em></strong>| |<strong><em>B</em></strong>| <em>cos</em> θ</a> .) If a square straddles the X-axis, I can try using the Y-axis instead. If a square straddles both the X- and the Y-axis, then it must contain the origin, which is an error.</p>\n\n<p>Tested using <code>clang++ -std=c++11 -g -o cr31597 cr31597.cpp</code> and on <a href=\"http://ideone.com/Yqqpo9\" rel=\"nofollow\">ideone</a>.</p>\n\n<pre><code>#include &lt;algorithm&gt; // for std::sort\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;math.h&gt; // for sqrt\n\n//////////////////////////////////////////////////////////////////////\n\nclass Vec2F {\n public:\n float x, y;\n static const Vec2F ORIGIN, I, J;\n\n Vec2F() : x(0), y(0) {}\n Vec2F(float x, float y) : x(x), y(y) {}\n Vec2F(const Vec2F &amp;other) : x(other.x), y(other.y) {}\n Vec2F &amp;operator=(const Vec2F &amp;other) {\n if (this != &amp;other) {\n x = other.x;\n y = other.y;\n }\n return *this;\n }\n bool operator==(const Vec2F &amp;other) const {\n return x == other.x &amp;&amp; y == other.y;\n }\n const Vec2F operator+(const Vec2F &amp;other) const {\n return Vec2F(x + other.x, y + other.y);\n }\n Vec2F operator-() const {\n return Vec2F(-x, -y);\n }\n Vec2F operator-(const Vec2F &amp;other) const {\n return *this + -other;\n }\n Vec2F operator*(float scale) const {\n return Vec2F(scale * x, scale * y);\n }\n float cross(const Vec2F &amp;other) const {\n return x * other.y - y * other.x;\n }\n float dot(const Vec2F &amp;other) const {\n return x * other.x + y * other.y;\n }\n float magnitude() const {\n return sqrt(x * x + y * y);\n }\n float sinOfAngleRelTo(const Vec2F &amp;ref) const {\n return ref.cross(*this) / ref.magnitude() / this-&gt;magnitude();\n }\n float cosOfAngleRelTo(const Vec2F &amp;ref) const {\n return ref.dot(*this) / ref.magnitude() / this-&gt;magnitude();\n }\n friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;out, const Vec2F &amp;v) {\n return out &lt;&lt; '(' &lt;&lt; v.x &lt;&lt; \", \" &lt;&lt; v.y &lt;&lt; ')';\n }\n};\n\nconst Vec2F Vec2F::ORIGIN(0, 0),\n Vec2F::I(1, 0),\n Vec2F::J(0, 1);\n\n//////////////////////////////////////////////////////////////////////\n\nclass Block {\n public:\n const std::vector&lt;Vec2F&gt; vertices;\n\n // Block is specified by its southwest corner\n Block(const Vec2F &amp;sw) {\n Vec2F v[] = {\n sw + Vec2F::J, sw + Vec2F(1, 1),\n sw, sw + Vec2F::I,\n };\n const_cast&lt;std::vector&lt;Vec2F&gt;&amp; &gt;(vertices) =\n std::vector&lt;Vec2F&gt;(v, v + sizeof(v) / sizeof(Vec2F));\n }\n Block(const Block &amp;other) : vertices(other.vertices) {}\n friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;out, const Block &amp;b) {\n return out &lt;&lt; \"Block&lt;\" &lt;&lt; b.vertices[2] &lt;&lt; \" - \" &lt;&lt; b.vertices[1]\n &lt;&lt; \" centered at \"\n &lt;&lt; b.vertices[2] + (b.vertices[1] - b.vertices[2]) * 0.5\n &lt;&lt; '&gt;';\n }\n private:\n Block &amp;operator=(const Block &amp;other);\n};\n\n//////////////////////////////////////////////////////////////////////\n\n// Comparator for Vec2F to be used to sort points by how much their angle\n// deviates from a reference vector\nclass AxisComparator {\n public:\n static const AxisComparator HORIZ, VERT;\n const Vec2F ref;\n\n AxisComparator(const Vec2F &amp;ref) : ref(ref) {}\n\n // Returns true if a should be ordered before b\n bool operator()(const Vec2F &amp;a, const Vec2F &amp;b) const {\n float cosAngleA = a.cosOfAngleRelTo(ref);\n float cosAngleB = b.cosOfAngleRelTo(ref);\n if (cosAngleA == cosAngleB) {\n // Same angle; the longer vector is considered more extreme.\n return cosAngleA &lt; 0 ? a.magnitude() &gt; b.magnitude()\n : a.magnitude() &lt; b.magnitude();\n } else {\n return cosAngleA &lt; cosAngleB;\n }\n }\n\n // Returns true if at least some pair of vectors are on opposite sides of\n // ref, or if at least one of them is aligned with ref\n bool straddles(const std::vector&lt;Vec2F&gt; &amp;vv) const {\n int side = 0;\n for (auto i = vv.begin(); i != vv.end(); ++i) {\n float sinAngle = (*i).sinOfAngleRelTo(ref);\n if (sinAngle == 0.0) { // aligned with ref\n return true;\n } else if (side == 0) { // 1st time through\n side = (sinAngle &lt; 0) ? -1 : +1;\n } else if (side == +1 &amp;&amp; sinAngle &lt; 0.0) { // wrong side\n return true;\n } else if (side == -1 &amp;&amp; sinAngle &gt; 0.0) { // wrong side\n return true;\n }\n }\n return false;\n }\n};\n\nconst AxisComparator AxisComparator::HORIZ(Vec2F::I),\n AxisComparator::VERT(Vec2F::J);\n\n//////////////////////////////////////////////////////////////////////\n\nclass Grapple {\n public:\n const Block block;\n private:\n std::vector&lt;Vec2F&gt; vertices;\n const Vec2F *v1, *v2;\n\n public:\n Grapple(const Block &amp;b) : block(b), vertices(b.vertices) {\n if (!AxisComparator::HORIZ.straddles(vertices)) {\n std::sort(vertices.begin(), vertices.end(), AxisComparator::HORIZ);\n v1 = &amp;vertices.front();\n v2 = &amp;vertices.back();\n } else if (!AxisComparator::VERT.straddles(vertices)) {\n std::sort(vertices.begin(), vertices.end(), AxisComparator::VERT);\n v1 = &amp;vertices.front();\n v2 = &amp;vertices.back();\n return;\n } else {\n v1 = v2 = NULL;\n }\n }\n bool possible() const {\n return v1 &amp;&amp; v2;\n }\n const Vec2F &amp;vertex1() const {\n return *v1;\n }\n const Vec2F &amp;vertex2() const {\n return *v2;\n }\n};\n\n//////////////////////////////////////////////////////////////////////\n\nint main() {\n Vec2F tests[] = {\n Vec2F(-3.0, -1.0), // &lt; 9 o'clock\n Vec2F(-3.5, +2.5), // 10:30\n Vec2F(-0.5, +4.0), // 12 o'clock\n Vec2F(+2.5, +2.5), // 1:30\n Vec2F(+4.0, -0.5), // 3 o'clock\n Vec2F(-0.5, -0.5), // centered at origin\n Vec2F(+0.0, -0.0), // corner at origin\n };\n for (int i = 0; i &lt; sizeof(tests) / sizeof(tests[0]); ++i) {\n Block b(tests[i]);\n Grapple g(b);\n if (g.possible()) {\n std::cout &lt;&lt; \"Grappling vertices for \" &lt;&lt; g.block &lt;&lt; \": \" &lt;&lt; g.vertex1() &lt;&lt; \" and \" &lt;&lt; g.vertex2() &lt;&lt; std::endl;\n } else {\n std::cout &lt;&lt; g.block &lt;&lt; \" contains the origin!\" &lt;&lt; std::endl;\n }\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-25T07:56:17.973", "Id": "50700", "Score": "0", "body": "I eventually used something different. But this helped me substantially. Thank you very much. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T09:31:07.487", "Id": "31645", "ParentId": "31597", "Score": "3" } } ]
{ "AcceptedAnswerId": "31645", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T18:56:06.063", "Id": "31597", "Score": "5", "Tags": [ "c++", "computational-geometry" ], "Title": "Complex logic that I'm certain can be simplified" }
31597
<p>A program I wrote isn't performing quite to where I had hoped so I went looking to find where the majority of the time of the program was being spent and it was in the function below so I would like to get some eyes on it to help tune it up and make it run a little quicker. Please note I realize it isn't the most readable but I heavily commented it to help prevent this and wrote it in the manner I did since my sole goal of the function is to get the result as fast as possible.</p> <p>The function uses an inlined function of the "Option" class called getPayoffType() which simply returns a value of the class as well as this function:</p> <pre><code>inline double Option::getPayoff(double ulPrice) { return ((cp == Call) ? ((ulPrice + 0.000005 &gt; strike) ? ulPrice - strike : 0.0) : ((strike + 0.000005 &gt; ulPrice) ? strike - ulPrice : 0.0)); } </code></pre> <p>Here's the code:</p> <pre><code>void TrinomialEngine(Option* option, Underlying* underlying) { int timeSteps = 20; //set the number of "time steps" aka the number of steps in the tree, this will later be dynamic double vol = option-&gt;vol; //get a parameter of our model from the Option class double rate = option-&gt;rate; //"" "" PayoffType payoff = option-&gt;getPayoffType(); //" " " " double dt = option-&gt;getTimeToExpiration() / timeSteps; //the length of time (in years) each time step represents double v = rate - vol*vol*0.5; //working in log-units double x = vol*sqrt(2.0*dt); //stock-price jump-size double dis = exp(-rate*dt); //timestep discounting double edx = exp(x); //precomputing this constant to save time double pu = 0.5*(dt*(vol*vol + v*v*dt)/x/x + (v*dt/x)); //up probability double pm = 1.0 - dt*(vol*vol + v*v*dt)/x/x; //middle probability double pd = 0.5*(dt*(vol*vol + v*v*dt)/x/x - (v*dt/x)); //down probability int nodes = timeSteps * timeSteps; //how many "nodes" there are in the tree double* tree = new double[nodes * 3]; /*how the tree is modeled in the array (each asterisk is a node, number is array position) 11 Option 10 Div * 9 Stock 2 Option 8 Option 1 Div * 7 Div * 0 Stock 6 Stock 5 Option 4 Div * 3 Stock timesteps 1 2 0 3 12 28 1 2 3 4 1 4 9 16 */ tree[0] = underlying-&gt;theo; //get a parameter from our "Underlying" class for(int i = 1; i &lt; timeSteps; ++i) //set up the "Stock" prices at each node { tree[i*i*3] = tree[0]*exp(-i*x); //bottom node of each time step tree[i*i*3 + 1] = 0.0; //this will be changed later to actually hold a value for(int j = i*i*3 + 3; j &lt; (i+1)*(i+1)*3; j += 3) { //working up the nodes for the current "time step" tree[j] = tree[j - 3] * edx; tree[j + 1] = 0.0; //this will be changed later to actually hold a value } } //value option at expiry for(int i = timeSteps * timeSteps * 3 - 3; i &gt;= (timeSteps - 1) * (timeSteps - 1) * 3; i -= 3) { //calulating the "Option" value for each node on the last time step of the tree tree[i + 2] = option-&gt;getPayoff( tree[i] + tree[i + 1] ); //inlined function of "Option" class } int j( (timeSteps - 2) * 6 + 3 ); int nodeCount( (timeSteps - 1) * 2 - 1 ); int currStep( timeSteps - 1 ); double exVal(0.0); if (payoff == American) //assume this is always true for now { for(int i = (timeSteps - 1) * (timeSteps - 1) * 3 - 3; i &gt;= 0; i -= 3) { //calculate the value of the option at every other node, working backwards through time steps tree[i + 2] = dis * (tree[i + j + 2] * pd + tree[i + j + 5] * pm + tree[i + j + 8] * pu); //discounted value of option exVal = option-&gt;getPayoff( tree[i] + tree[i + 1] ); //value of option if exercised //the value of the option at these nodes is the maximum of the discounted value and the exercised value if (exVal &gt; tree[i + 2] + 0.000005) tree[i + 2] = exVal; --nodeCount; //tick back how many nodes we ahve evaluated if (nodeCount &lt; 1) { //this is if we've evaluated all the nodes in the timestep so reset our indices j -= 6; --currStep; nodeCount = currStep * 2 - 1; } } } else { for(int i = (timeSteps - 1) * (timeSteps - 1) * 3 - 3; i &gt;= 0; i -= 3) { tree[i + 2] = dis * (tree[i + j + 2] * pd + tree[i + j + 5] * pm + tree[i + j + 8] * pu); --nodeCount; if (nodeCount &lt; 1) { j -= 6; --currStep; nodeCount = (currStep - 1) * 2 - 1; } } } //grab our results! option-&gt;theo = tree[2]; option-&gt;delta = ( tree[11] - tree[5] ) / ( tree[9] - tree[3] ); delete[] tree; //don't forget to free the memory } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T21:02:11.257", "Id": "50434", "Score": "0", "body": "\"//assume this is always true for now\" so you can ditch the else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T21:29:17.533", "Id": "50435", "Score": "1", "body": "Marginally more seriously, you do things like this a couple of times (dt*(vol*vol + v*v*dt)/x/x why not precompute that to save time and give it a name that describes its purpose." } ]
[ { "body": "<p>My advice:</p>\n\n<ol>\n<li><p><strong>Precompute whatever is possible to precompute</strong>. I would say: all those vol*vol, x*x (especially before the double division /x/x). Your compiler may be smart enough to make some optimization itself, but it's better not to risk and to check if some performance improvement can be achieved. It think, however, that you will spend most of the time computing what is inside the loops.</p></li>\n<li><p><strong><code>sqrt()</code> is often a time expensive function</strong>. If you can get rid of it, that's good. But I don't know if it makes sense for you to compute <code>sqrt(2.0*dt)</code> outside <code>TrinomialEngine</code>. If <code>getTimeToExpiration()</code> is almost constant (as is <code>timeSteps</code>) in your application, you could try to precompute that <code>sqrt</code> somewhere else, in order to have it ready. A lot depends on how many times do you call <code>TrinomialEngine</code> and how often are \"options\" changed.</p></li>\n<li><p>Try to <strong>avoid operations inside the loop condition</strong>, index declaration, and keep increment \"easy\".</p>\n\n<p>This is good:</p>\n\n<pre><code>$for(int i = 1; i &lt; timeSteps; ++i)\n</code></pre>\n\n<p>This is bad:</p>\n\n<pre><code>$for(int j = i*i*3 + 3; j &lt; (i+1)*(i+1)*3; j += 3)\n</code></pre>\n\n<p>The risk in having all those \"complex\" for loops is that your <strong>compiler</strong> will fail to optimize them properly, since it is (most of the time) <strong>designed to be good at optimizing loops from 0 to N.</strong></p>\n\n<p>This should give you most of the performance improvement that you can get. I cannot see any other big issue.</p></li>\n<li><p>It has nothing to do with performances, but I would put the brackets <code>{}</code> around <code>tree[i + 2] = exVal;</code> after <code>if (exVal &gt; tree[i + 2] + 0.000005)</code>. That's good practice.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T09:22:24.237", "Id": "31721", "ParentId": "31600", "Score": "1" } } ]
{ "AcceptedAnswerId": "31721", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T20:37:52.870", "Id": "31600", "Score": "2", "Tags": [ "c++", "performance" ], "Title": "Performance issues with Trinomial Tree to calculate price of option" }
31600
<p>Is there is better way to do that more efficiently?</p> <p><strong><code>onCreate()</code>:</strong></p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layout = new Layout(); Event event = new Event(layout); } </code></pre> <p><strong><code>Layout</code> and <code>Event</code>:</strong></p> <pre><code>class Layout { public Layout() { txtName = (EditText)findViewById(R.id.txtName); btnSerch = (Button)findViewById(R.id.btnSerch); group1 = (RadioGroup)findViewById(R.id.group1); } RadioGroup group1; EditText txtName; Button btnSerch; } class Event { public Event(Layout layout) { layout.btnSerch.setOnClickListener(new start_Serch()); } } class start_Serch implements OnClickListener { @Override public void onClick(View view) { Serch(view, layout); } Layout layout; } </code></pre> <p><strong>Main goal: (the main commands of the application)</strong></p> <pre><code>void Serch(View v, Layout layout) { Uri Contacts = android.provider.ContactsContract.Contacts.CONTENT_URI; Cursor C = getContentResolver().query(Contacts, null, null, null, null); if(C != null) { if(C.moveToFirst()) { do { String display_ContactsName = getValue(C, android.provider.ContactsContract.Contacts.DISPLAY_NAME); if (Check(display_ContactsName, C) == true) { break; } }while (C.moveToNext()); } } } </code></pre> <p><strong><code>getValue()</code> and <code>Check()</code>:</strong></p> <pre><code>private String getValue(Cursor cursor, String name) { return cursor.getString(cursor.getColumnIndex(name)); } private boolean Check(String Name, Cursor C) { boolean Found = false; int id = layout.group1.getCheckedRadioButtonId(); switch (id) { case -1: break; case R.id.fullName: if (layout.txtName.getText().toString().equals(Name)) { AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); alert.setTitle("Hey This Contact Is in the LIST!!! yay you are the best lasy man EVER SO G***"); alert.setMessage("The contact "+Name+" was found in this phone... oh ya"); alert.setPositiveButton("ok",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); alert.show(); Found = true; } break; case R.id.Contane: if ( Name.toLowerCase().contains ( layout.txtName.getText ().toString ().toLowerCase())) { AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); alert.setTitle("this is the first result for the name that you typed"); alert.setMessage("The contact "+Name+" was found in this phone... oh ya"); alert.setPositiveButton("ok",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); alert.show(); Found = true; break; } } if (C.isLast() == true&amp;&amp;layout.txtName.getText().toString().equals(Name) == false&amp;&amp; Name.toLowerCase().contains ( layout.txtName.getText ().toString ().toLowerCase()) == false) { AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); alert.setTitle("Hey This Contact Is NOT in the LIST!!!"); alert.setMessage("The contact/part of "+layout.txtName.getText().toString()+" was not found in this phone..."); alert.setPositiveButton("ok",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); alert.show(); } return Found; } </code></pre>
[]
[ { "body": "<p><strong>Naming conventions</strong></p>\n\n<p>Several of your classes and variables defies <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow\">Java naming conventions</a>. A class should start with an uppercase letter and a variable with a lowercase letter (with a possible exception for static final variables, which you do not use).</p>\n\n<p>Here are some changes to conform with the naming conventions</p>\n\n<pre><code>class start_Serch --&gt; class StartSearch\nUri Contacts --&gt; Uri contacts\nCursor C --&gt; Cursor cursor\n</code></pre>\n\n<p><strong>Your classes</strong></p>\n\n<p>Your Event class only job is to set an onClickListener, which it sets <strong>in the constructor</strong>. A constructor should normally not be used to actually perform anything, it should merely store the information it needs to do stuff later. However, I don't think you need your Event class at all. And you especially don't need to store it in a variable (which is never used later).</p>\n\n<p>You also don't need to create the <code>StartSearch</code> class or the <code>Layout</code> class. Instead, store the values in the <code>Layout</code> class in your Activity (the class where the <code>onCreate</code> method is) and let your <code>Activity</code> implement <code>OnClickListener</code>.</p>\n\n<p>So I would change this code in your <code>onCreate</code> method</p>\n\n<pre><code>layout = new Layout();\nEvent event = new Event(layout);\n</code></pre>\n\n<p>To this: </p>\n\n<pre><code>txtName = (EditText)findViewById(R.id.txtName);\nbtnSerch = (Button)findViewById(R.id.btnSerch);\ngroup1 = (RadioGroup)findViewById(R.id.group1);\nbtnSerch.setOnClickListener(this);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:28:18.777", "Id": "35617", "ParentId": "31603", "Score": "2" } }, { "body": "<p><strong>Android Strings</strong></p>\n\n<p>Android provides a nice way of externalizing Strings in a <a href=\"http://developer.android.com/guide/topics/resources/string-resource.html\">strings.xml resource file</a>. Using it right from the start of your project or as soon as possible is a very good idea, you might regret it later if you don't. Using XML-resources in Android is how to provide internationalization of your application. It is also good to keep all strings in one place, so you can get a nice overview of the strings shown in your application.</p>\n\n<p>Speaking of Strings that are showing in your application, <strong>the content of your message String for your AlertDialogs is very questionable.</strong> If I as an user would encounter the message \"f*ck ya\" in an application, I would <strong>never ever</strong> give it a 5 star rating on Google Play. And it honestly does not give me a good impression of you as a person either.</p>\n\n<p>The \"ok\" message is already defined as a string message in Android, and if your dialog button should only close the dialog then you can pass <code>null</code> as the listener. So therefore you can use <code>alert.setPositiveButton(android.R.string.ok, null);</code> which greatly improves code readability.</p>\n\n<p><strong>Readability</strong></p>\n\n<p>Speaking of code readability... I feel that you have an excessive amount of empty lines in your code, including but not restricted to:</p>\n\n<pre><code>if(C != null)\n\n{\n\n alert.setPositiveButton(\"ok\",new DialogInterface.OnClickListener() {\n\n @Override\n\n public void onClick(DialogInterface dialogInterface, int i)\n\n\n do\n\n {\n\n String display_ContactsName = getValue(C, android.provider.ContactsContract.Contacts.DISPLAY_NAME);\n</code></pre>\n\n<p>Instead consider this:</p>\n\n<pre><code>if(C != null)\n{\n ...\n alert.setPositiveButton(\"ok\",new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i)\n ...\n do\n {\n String display_ContactsName = getValue(C, android.provider.ContactsContract.Contacts.DISPLAY_NAME);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:50:23.917", "Id": "57830", "Score": "2", "body": "+1 for [being an example to follow](http://meta.codereview.stackexchange.com/questions/1008/answering-guidelines-answer-length/1010?noredirect=1#1010)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T20:34:22.450", "Id": "57858", "Score": "0", "body": "I Edit white space in questions, because most of the time people copy and paste their code, and some IDE's put tabs in and some put in spaces, and the formatting messes things up, it's not always visible when they are preparing the question. but yeah sometimes people just have a lot of white space." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-09T21:16:12.103", "Id": "239224", "Score": "0", "body": "The questionable content you refer to in the second paragraph [has been removed from the question](http://codereview.stackexchange.com/revisions/31603/3). On SO I would roll that edit back for invalidating an important part of an answer, but I'm not sure how you would want to handle it here. (Especially given that both the users involved are mods!)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T18:38:10.117", "Id": "35618", "ParentId": "31603", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T22:19:53.470", "Id": "31603", "Score": "6", "Tags": [ "java", "android", "search" ], "Title": "Search Android contacts more efficiently" }
31603
<p>I use this <code>Timer</code> function quite a bit lately for all sorts of stuff, and would appreciate if someone could review/analyze/criticize/verify and, of course, suggest things I can do to optimize it for high frequency execution (mainly animation).</p> <p>My goal was to replicate ActionScript's counterpart (<code>Timer</code> class) and its usage simplicity: registering fns for timer's event dispatch, starting/stopping/resetting the timer, etc.</p> <pre><code>// // ;( function ( _host_, _aproto ) { var t = true, f = false, nl = null, timerEvent = { start : "timer-start", timer : "timer", stop : "timer-stop", end : "timer-end" }, un, // === undefined _tm; // Array.prototype extensions helpers: // .each() .keep() .gc() .has() .empty() .substitute() _aproto.each = function ( fn, flgIterBw ) { var len = this.length, i; if ( flgIterBw !== t ) { for ( i = 0; i &lt; len; i++ ) { if ( fn.call( this, i, this[i] ) === f ) break; } } else { for ( i = len; --i &gt;= 0; ) { if ( fn.call( this, i, this[i] ) === f ) break; } } return this; }; _aproto.keep = function ( fn ) { return this.each( function ( i, o ) { ( fn.call( this, i, o ) === t ) || this.splice( i, 1 ); }, t ); }; _aproto.gc = function () { var toremove = slc( arguments ); return this.each( function ( i, o ) { toremove.has( o ) &amp;&amp; this.splice( i, 1 ); }, t ); }; _aproto.has = function ( v ) { return this.indexOf( v ) !== -1; }; _aproto.empty = function () { return ( this.length = 0, this ); }; _aproto.substitute = function ( arr ) { return ( _aproto.push.apply( this.empty(), arr ), this ); }; // helper fns function isobj( o ) { return o === Object( o ); } function isplainobj( o ) { return Object.prototype.toString.call( o ) === "[object Object]"; } function isfn( o ) { return typeof o === "function"; } function isvalid( o ) { return o !== un &amp;&amp; o !== nl &amp;&amp; ( o === o ); } function owns( obj, p ) { return obj.hasOwnProperty( p ); } // loops objects own properties // breaks if fn return false function owneach( obj, fn ) { if ( isobj( obj ) &amp;&amp; isfn( fn ) ) { for ( var p in obj ) { if ( owns( obj, p ) ) { if ( fn.call( obj, p, obj[p] ) === f ) break; } } } return obj; } // attaches set of properties to an object function rig_props( obj, props ) { if ( isobj( obj ) &amp;&amp; isplainobj( props ) ) { owneach( props, function ( p, v ) { obj[p] = v; } ); } return obj; } function slc( arg, i, j ) { return Array.prototype.slice.call( arg, i, j ); } function vacate( obj ) { for ( var p in obj ) { owns( Object.prototype, p ) || ( delete obj[p] ); } return obj; } // 'asyncs' a function function defer( fn ) { var args1 = slc( arguments, 1 ); return function () { var args = args1.concat( slc( arguments ) ), target = this, origfn = fn; setTimeout( function () { return origfn.apply( target, args ); } ); return this; }; } // gives an object basic event handling support // .addListener() .removeListener() .triggerEvent() function listener( obj ) { if ( isobj( obj ) ) { var handlers = {}; rig_props( obj, { // registers set of fns for an event 'e' addListener : function ( e ) { if ( isvalid( e ) ) { var fnargs = slc( arguments, 1 ) .keep( function ( i, o ) { return isfn( o ); } ); owns( handlers, e ) &amp;&amp; ( _aproto.push.apply( handlers[ e ], fnargs ), t ) || ( handlers[ e ] = slc( fnargs ) ); } return obj; }, // removes fns registered for 'e' event removeListener : function ( e ) { if ( isvalid( e ) ) { if ( owns( handlers, e ) ) { var fnargs = slc( arguments, 1 ) .keep( function ( i, o ) { return isfn( o ); } ); fnargs.length &amp;&amp; ( _aproto.gc.apply( handlers[ e ], fnargs ), handlers[ e ].length || ( delete handlers[ e ] ), t ) || ( handlers[ e ].empty(), delete handlers[ e ] ); } } else { owneach( handlers, function ( evt, fns ) { fns.empty(); } ); vacate( handlers ); } return obj; }, // runs fns registered for evt 'e' triggerEvent : function ( e ) { if ( isvalid( e ) ) { if ( owns( handlers, e ) ) { var fireargs = slc( arguments, 1 ); handlers[ e ] .each( function ( k, evhandler ) { defer( evhandler ) .call( obj, { type : e, data : fireargs, target : obj, handler : evhandler } ); } ); } } return obj; } } ); } return obj; } // // declares Timer factory fn _tm = function ( delay, repeatCount ) { return ( function ( delay, fireNTimes ) { var // timer obj host = this, // timer's private state // used/manipulated by api bellow timerState = { 'current-count' : 0, 'delay' : Math.abs( parseFloat( delay ) ) || 1000, 'repeat-count' : Math.abs( parseInt( fireNTimes ) ) || Infinity, 'running' : f, 'interval' : un }, // arguments provided to timer's .start() method // used as args for triggered fns fireargs = []; // attaches api to timer obj // .start() .stop() .reset() .currentCount() .delay() .repeatCount() .running() .state() rig_props( host, { // starts timer event dispatch // sets provided args as // parameters to triggered fns // triggers 'timer-start' event // and 'timer' events start : function () { var startargs; host.running() || ( timerState.running = t, ( startargs = slc( arguments ) ).length &amp;&amp; fireargs.substitute( startargs ), host.triggerEvent.apply( host, [ timerEvent.start ] .concat( fireargs ) ), timerState['current-count'] += 1, host.triggerEvent.apply( host, [ timerEvent.timer ] .concat( fireargs ) ), ( timerState['current-count'] === timerState['repeat-count'] ) &amp;&amp; host.reset() || ( timerState.interval = setInterval( function () { ( timerState['current-count'] &lt; timerState['repeat-count'] ) &amp;&amp; ( timerState['current-count'] += 1, host.triggerEvent.apply( host, [ timerEvent.timer ] .concat( fireargs ) ), ( timerState['current-count'] === timerState['repeat-count'] ) &amp;&amp; host.reset() ); }, timerState.delay ) ) ); return host; }, // pauses triggering timer events // triggers 'timer-stop' event stop : function () { host.running() &amp;&amp; ( ( timerState.interval !== un ) &amp;&amp; ( clearInterval( timerState.interval ), timerState.interval = un ), timerState.running = f, host.triggerEvent.apply( host, [ timerEvent.stop ] .concat( fireargs ) ) ); return host; }, // nulls timer state // triggers 'timer-end' event reset : function () { ( timerState.interval !== un ) &amp;&amp; ( clearInterval( timerState.interval ), timerState.interval = un ); timerState.running = f; timerState["current-count"] = 0; host.triggerEvent.apply( host, [ timerEvent.end ] .concat( fireargs ) ); return host; }, // how many times timer fired currentCount : function () { return timerState['current-count']; }, // return timer's fire rate in ms delay : function () { return timerState.delay; }, // how many times timer will fire 'timer' event repeatCount : function () { return timerState['repeat-count']; }, // returns boolean running : function () { return timerState.running; }, // returns timers intrnal state{} state : function () { return { currentCount : timerState['current-count'], delay : timerState.delay, repeatCount : timerState['repeat-count'], running : timerState.running }; } } ); return host; } ).call( listener( {} ), delay, repeatCount ); }; // // attaches Timer fn to global scope _host_.Timer = _tm; } )( self, Array.prototype ); // // use: // // var // tm = Timer( 1000/50 ); // set timers fq to 50 times a sec // // // register fns for 'timer' event // tm.addListener( // "timer", // function () { console.log( arguments ) }, // doStuff1, // doStuff2 // ); // // someElement.onmouseover = function () { tm.start( someElement ); }; // someElement.onmouseout = function () { tm.stop(); }; // someElement.onclick = function () { tm.reset(); }; // // etc. // </code></pre>
[]
[ { "body": "<p>What's with the variable names? len, un, i, fn, t, f?\nUse the full meaningful names. This is the StopWatch class I use for performance, time measuring.</p>\n\n<pre><code>var StopWatch = function (performance) {\n this.startTime = 0;\n this.stopTime = 0;\n this.running = false;\n this.performance = performance === false ? false : !!window.performance;\n};\n\nStopWatch.prototype.currentTime = function () {\n return this.performance ? window.performance.now() : new Date().getTime();\n};\n\nStopWatch.prototype.start = function () {\n this.startTime = this.currentTime();\n this.running = true;\n};\n\nStopWatch.prototype.stop = function () {\n this.stopTime = this.currentTime();\n this.running = false;\n};\n\nStopWatch.prototype.getElapsedMilliseconds = function () {\n if (this.running) {\n this.stopTime = this.currentTime();\n }\n\n return this.stopTime - this.startTime;\n};\n\nStopWatch.prototype.getElapsedSeconds = function () {\n return this.getElapsedMilliseconds() / 1000;\n};\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code>var stopwatch = new StopWatch();\nstopwatch.start();\n\nfor (var index = 0; index &lt; 100; index++) {\n stopwatch.printElapsed('Instance[' + index + ']');\n}\n\nstopwatch.stop();\n\nstopwatch.printElapsed();\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>Instance[0] [0ms] [0s]\nInstance[1] [2.999999967869371ms] [0.002999999967869371s]\nInstance[2] [2.999999967869371ms] [0.002999999967869371s]\n/* ... */\nInstance[99] [10.999999998603016ms] [0.010999999998603016s]\nElapsed: [10.999999998603016ms] [0.010999999998603016s]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T13:13:51.493", "Id": "50498", "Score": "0", "body": "The variable names are kind of habit and are enough self explanatory and fast to type in. If that's the single critiq to the code I've pressented, then I'm glad you approve the rest of the code. Btw, that's the slick StopWatch fn you got there, but it's missing a topic's point, where the function registrations part for timer ticks comes in?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-01T15:55:59.057", "Id": "51241", "Score": "0", "body": "I second the use of descriptive variable names. You're looking to polish your code, not to continue hacking on it, right? The only meaningless variable I use in my code is `i`, and only when used as a loop index." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T11:30:11.933", "Id": "31650", "ParentId": "31604", "Score": "1" } }, { "body": "<p>There is room for improvement, in no particular order:</p>\n\n<ul>\n<li><p>Formatting</p>\n\n<blockquote>\n<pre><code> for (\n i = 0;\n i &lt; len;\n i++\n ) \n</code></pre>\n \n <p>should really follow normal formatting</p>\n\n<pre><code> for ( i = 0; i &lt; len; i++ )\n</code></pre>\n</blockquote></li>\n<li><p>Formatting: the splitting of conditionals into separate lines is overdone, function <code>rig_props</code> is the worst case of overdoing it. You can find a fairly authoritative style guide <a href=\"http://javascript.crockford.com/code.html\" rel=\"nofollow\">here</a>.</p></li>\n<li><p><a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Arrow head coding</a>. If code has the following, then it was done wrong: </p>\n\n<blockquote>\n<pre><code> }\n );\n }\n );\n }\n }\n return obj;\n }\n }\n );\n }\n return obj;\n}\n</code></pre>\n</blockquote></li>\n<li><p>Naming: please use camelCasing and meaningful names. The code is too hard to follow (<code>slc</code>, <code>t</code>, <code>nl</code>, <code>un</code>, <code>_tm</code>). I understand you are used to it, but if you ever want other people to understand/maintain this, then you need to fix this.</p></li>\n<li><p>Naming: underscores used to indicate private properties/functions. They seem bad form for parameters (<code>_host_</code>, <code>_aproto</code>). See also the Crockford style guide.</p></li>\n<li><p>It defines <code>.each()</code>, and you should really look into using <code>ForEach()</code> instead. Also, look into <code>reverse()</code> for <code>flgIterBw</code>. <code>forEach</code> can be many times faster than a JS loop.</p></li>\n<li><p>Functions like <code>_aproto.keep</code> should have at least a one-liner comment as to what it does.</p></li>\n<li><p>Come to think of it, the code that enhances the array prototype should really be an object on its own, and not stashed away in <code>Timer</code> as the code is re-usable. This would follow the principle of <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">Separation of Concerns</a>.</p></li>\n<li><p>All in all, the code is hard to maintain, not evenly commented and it does not seem to consider the advances made in JS 1.6 (<code>ForEach</code>, filter, etc.) but it still counts on <code>indexOf()</code>.</p></li>\n<li><p>Finally, if the code were to be rewritten with the above in mind, it could get more meaningful code reviews because more reviewers could then grok it.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T18:40:37.313", "Id": "31759", "ParentId": "31604", "Score": "3" } } ]
{ "AcceptedAnswerId": "31759", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T00:15:17.107", "Id": "31604", "Score": "2", "Tags": [ "javascript", "asynchronous", "timer" ], "Title": "Timer factory function" }
31604
<p>I been learning web development for 1.5 month now, and I am trying to improve my code. I can achieve what I want, but I think my code is really bad.</p> <p>For example, I have a bunch of jQuery animations and a bunch of function to 'stop' those animations when another animation is starting. The code seems very inelegant, so how should I improve it? I been learning how to write a jQuery plugin, but I don't think it will help in this case.</p> <pre><code>$(document).ready(function(){ $("#diagonalLine").show(500); $("#line").show(1300); $("#start").show(1500); $("#centerButton").click(function(){ $("#diagonalLine").hide(1500); $("#line").hide(1300); $("#start").hide(500); fadeInWaterloo(); fadeInToronto(); fadeInTop(); $("#selectLine").animate({width:'toggle'},1250);; $("#diagonalSelectLine").show(1450); $("#select").show(1600); }); $("#waterloo7").mouseenter(function(){ fadeInTorontoStop(); fadeInTopStop(); fadeOutToronto(); fadeOutTop(); }); $("#toronto5").mouseenter(function(){ fadeInWaterlooStop(); fadeInTopStop(); fadeOutWaterloo(); fadeOutTop(); //$("#flip").show(1000); //$("#infoBox1").slideDown(2000); }); $("#campus").mouseenter(function(){ fadeInWaterlooStop(); fadeInTorontoStop(); fadeOutWaterloo(); fadeOutToronto(); }); $("#waterloo7").mouseleave(function(){ fadeOutTorontoStop(); fadeOutTopStop(); fadeInToronto(); fadeInTop(); }); $("#toronto5").mouseleave(function(){ fadeInWaterloo(); fadeInTop(); }); $("#campus").mouseleave(function(){ fadeInToronto(); fadeInWaterloo(); }); $("#log-in-button").click(function(){sendLogin(); return false;}); $("#forgotLogin").click(function(){location.href='signUp.html';}); $("#signUp").click(function(){location.href='signUp.html';}); }); //-------------------------------------Toronto Animation Functions-------------------------- function fadeInToronto(){ for (var i=1;i&lt;=5; i++){ $("#toronto"+i).fadeIn(300+i*200); } } function fadeOutToronto(){ for (var i=1; i&lt;=5; i++){ $("#toronto"+i).fadeOut(1100-i*200); } } function fadeInTorontoStop(){ for (var i=1;i&lt;=5; i++){ $("#toronto"+i).fadeIn().stop(); } } function fadeOutTorontoStop(){ for (var i=1; i&lt;=5; i++){ $("#toronto"+i).fadeOut().stop(); } } //-----------------------------------End of Toronto Animation--------------------------- //-----------------------------------Waterloo Animation Functions---------------------------- function fadeInWaterloo(){ $("#waterloo1").fadeIn(0); $("#waterloo2").fadeIn(300); $("#waterloo3").fadeIn(1300); $("#waterloo4").fadeIn(1600); $("#waterloo5").fadeIn(1800); $("#waterloo6").fadeIn(2000); $("#waterloo7").fadeIn(2000); } function fadeInWaterlooStop(){ for (var i=1;i&lt;=7; i++){ $("#waterloo"+i).fadeIn().stop(); } } function fadeOutWaterloo(){ var num = 1100; for (var i=1; i&lt;=7; i++){ $("#waterloo"+i).fadeOut(num); num = num-200; } } function fadeOutWaterlooStop(){ for (var i=1;i&lt;=7; i++){ $("#waterloo"+i).fadeOut().stop(); } } //----------------------------------------End of Waterloo Animation------------------- //-------------------------------------Campus Animation Functions-------------------- function fadeInTop(){ for (var i=1;i&lt;=4; i++){ var id = "#top"+i; $(id).fadeIn(300+i*200); } $("#campus").fadeIn(1100); } function fadeOutTop(){ $("#top1").fadeOut(1100); $("#top2").fadeOut(1100); $("#top3").fadeOut(900); $("#top4").fadeOut(700); $("#campus").fadeOut(500); } function fadeInTopStop(){ for (var i=1;i&lt;=4; i++){ var id = "#top"+i; $(id).fadeIn().stop(); } $("#campus").fadeIn().stop(); } function fadeOutTopStop(){ $("#top1").fadeOut().stop(); $("#top2").fadeOut().stop(); $("#top3").fadeOut().stop(); $("#top4").fadeOut().stop(); $("#campus").fadeOut().stop(); } //-------------------------------------End of Campus Animation--------------- </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:15:00.127", "Id": "50442", "Score": "0", "body": "The first step to improve your code is to get rid of id's and use common classes." } ]
[ { "body": "<p>You could certainly use classes in many places to decrease code duplication. For instance, you could add a <code>top</code> class to all of your \"top\" elements. In that way, you could <code>stop</code> and <code>fadeOut</code> all in one line:</p>\n\n<pre><code>$(\".top\").fadeOut().stop();\n</code></pre>\n\n<p>Similarly, this:</p>\n\n<pre><code>for (var i=1;i&lt;=4; i++){\n var id = \"#top\"+i;\n $(id).fadeIn().stop();\n}\n</code></pre>\n\n<p>would be just this:</p>\n\n<pre><code>$(\".top\").fadeIn().stop();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T00:52:53.467", "Id": "31606", "ParentId": "31605", "Score": "2" } }, { "body": "<p>The general rule is if you're doing something with a static element inside a event, you should cache that reference to this element.</p>\n\n<pre><code>$(\"#button\").click(function(){\n $(\"#diagonalLine\").hide(1500);\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>document.getElementById('button').onclick = function(){\n document.getElementById('diagonalLine').style.display='none';\n}\n</code></pre>\n\n<p>Everytime the user click on #button it traverses the DOM to getElementById and find #diagonalLine. With jQuery there's much more overhead involved, it create a new jQuery object, parses the string <code>#diagonalLine</code>, find the element, bind it to the new object and returns it. There are all sort of thing jQuery do under hood to make it \"magic\".</p>\n\n<pre><code>var diagonalLine = $(\"#diagonalLine\");\n$(\"#centerButton\").click(function(){\n diagonalLine.hide(1500);\n}\n\nvar diagonalLine = document.getElementById('diagonalLine');\ndocument.getElementById('centerButton').onclick = function(){\n diagonalLine.style.display='none';\n}\n</code></pre>\n\n<p>You can also use closures for caching references to elements</p>\n\n<pre><code>$('#button').click=(function(){\n var diagonalLine = $(\"#diagonalLine\");\n return function(){\n diagonalLine.hide(1500);\n }\n})();\n\n\ndocument.querySelector('#button').onclick=(function(){\n var diagonalLine = document.querySelector('#diagonalLine');\n return function(){\n diagonalLine.style.display='none';\n }\n})();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T02:29:36.903", "Id": "50446", "Score": "0", "body": "To be pedantic, `getElementById` is usually implemented using a hash table rather than traversing the DOM, which makes it fairly quick. That said, constructing the jQuery object may make it much more expensive as you point out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T06:49:53.287", "Id": "50447", "Score": "0", "body": "It may be good practice to name variables with dollar prefix to get a hint it's jQuery object: var $diagonalLine = $(\"#diagonalLine\");" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T08:42:49.307", "Id": "50449", "Score": "0", "body": "I think it comes to personal preference, IMO it adds pollution to the code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:29:02.740", "Id": "31608", "ParentId": "31605", "Score": "2" } } ]
{ "AcceptedAnswerId": "31608", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T00:40:58.987", "Id": "31605", "Score": "1", "Tags": [ "javascript", "jquery", "animation" ], "Title": "Various animation functions" }
31605
<p>The following function takes two numbers that are linked with a "user" and calculates an ID number based on that. I have been trying to make this as clean as possible, and would like some advice on how to make this more efficient. an example of the input would be "12195491" for the num and "3120" for the ts, which would output "8511"</p> <pre><code>function getidnumber(num, ts) { num = num.substr(4, 4); ts = ((ts == undefined) ? "3452" : (ts)); var _local5 = ""; var _local1 = 0; while (_local1 &lt; num.length) { var _local4 = Number(num.substr(_local1, 1)); var _local3 = Number(ts.substr(_local1, 1)); var _local2 = String(_local4 + _local3); _local5 = _local5 + _local2.substr(_local2.length - 1); _local1++; } return("@user" + _local5); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:10:11.147", "Id": "50439", "Score": "1", "body": "Could you provide more background? Maybe an example of input and output? Why `\"3452\"`? Why as a string not a number? What is `ts`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:12:53.277", "Id": "50440", "Score": "0", "body": "there are two numbers. a session id, and a userid that is passed to the function. \"3452\" is just a default id for if it is undefined. and so i can return the entire thing as a string, although i dont need to do it that way" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:14:28.563", "Id": "50441", "Score": "0", "body": "ts would be the userid, which is 6 numbers long." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:17:17.067", "Id": "50443", "Score": "0", "body": "The best way to tell how to improve it is if you post examples of inputs and outputs that are valid as well as some invalid ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:22:01.427", "Id": "50444", "Score": "0", "body": "i have edited the question with an example input" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:38:33.490", "Id": "50445", "Score": "0", "body": "So basically you take 4 numbers from the first parameter and add each number to the 4 numbers in the second parameter right? Why not create two arrays out of the strings, then loop, sum, and return the result." } ]
[ { "body": "<p>I think this is a little simpler. These are the changes I'd recommend:</p>\n\n<p>1) Always use a for loop if you have an initialization, test, and increment.</p>\n\n<p>2) I'd prefer variable names that have meaning like _nextDigit</p>\n\n<p>3) Take advantage of the fact that strings can be accessed using the array <code>[]</code> operator</p>\n\n<p>4) Made it explicit that we are taking a single digit by using the modulus operator <code>% 10</code> instead of using <code>_local2.substr(_local2.length - 1)</code>.</p>\n\n<p>5) There was too much switching between strings and numbers; only use numbers for modulus and addition.</p>\n\n<p>6) I didn't rename _local5 but we should probably call it resultString or idNumber depending on what you consider it to be.</p>\n\n<pre><code>function getidnumber(num, ts) {\n num = num.substr(4, 4);\n ts = ((ts == undefined) ? \"3452\" : (ts));\n var _local5 = \"\";\n for (var _local1 = 0; _local1 &lt; num.length; ++_local1) {\n var _nextDigit = (Number(num[_local1]) + Number(ts[_local1])) % 10;\n _local5 = _local5 + _nextDigit;\n }\n return (\"@user\" + _local5);\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T03:28:46.053", "Id": "31609", "ParentId": "31607", "Score": "1" } }, { "body": "<p>Here's a better implementation.</p>\n\n<p>Used the unary <code>+</code> operator for number conversion.</p>\n\n<p>Used <code>null</code> instead of <code>undefined</code> since it's shorter and produces the same result because of type coersion.</p>\n\n<p>Avoid performing a <code>substring</code> operation by starting to iterate from index <code>4</code>.</p>\n\n<p>Cached <code>num.length</code> into <code>len</code> so that we save on property lookups when the condition is evaluated for every loop iteration.</p>\n\n<p>Removed uneeded parenthesis.</p>\n\n<p>Took advantage of the <code>+=</code> operator.</p>\n\n<p>Made sure that every variables were locally scoped. <em>The <code>_local1</code> variable in the selected answer isin't properly scoped.</em></p>\n\n<p>Used a single <code>var</code> statement; it's a better practice to declare variables at the top of the function for readability.</p>\n\n<p>Stole the % 10 idea from the other answer since I thought it was great ;)</p>\n\n<pre><code> function getidnumber (num, ts) {\n var i = 4, \n len = num.length,\n res = '@user';\n\n ts = ts == null? '3452' : ts;\n\n for (; i &lt; len; i++) {\n res += (+num[i] + +ts[i - 4]) % 10;\n }\n\n return res;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T07:10:59.973", "Id": "50448", "Score": "0", "body": "I disagree with declaring variables at the top of the function. I find it better to declare it closer to where it will be used. It is [Accepted practice](http://programmers.stackexchange.com/questions/56585/where-do-you-declare-variables-the-top-of-a-method-or-when-you-need-them) to do so" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T14:51:45.930", "Id": "50460", "Score": "0", "body": "@JeffVanzella, It all depends on the language being used. In JavaScript it's way more common to use a single `var` statement or at least declare the variables at the top of the function, despite variable hoisting. [JSLint](http://www.jslint.com/), one of the most popular JS code quality tool will complain about multiple `var` statements by default. Also, most popular librairies, such as jQuery adopted this coding practice as we can see [here](https://github.com/jquery/jquery/blob/master/src/ajax.js).\nThere are perhaps cases where I tould tolerate it, but here there's no valid reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T16:54:08.567", "Id": "50461", "Score": "0", "body": "these are both great answers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T20:42:53.957", "Id": "50465", "Score": "0", "body": "@riyoken, Thanks! Make sure that you correct the scoping mistake in the answer you selected when you will implement the solution. `_local1` is declared as global." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T21:56:16.723", "Id": "50468", "Score": "0", "body": "@plalx I fixed the \"global\" and up-voted your answer. Thanks!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T06:38:28.230", "Id": "31612", "ParentId": "31607", "Score": "2" } }, { "body": "<p>Another option using maths instead of string operations.</p>\n\n<pre><code>function getIdNumber(num, ts) {\n var r = '';\n ts = (ts === undefined ? 3452 : ts);\n for (var i = 1; i &lt;= 1000; i *= 10) {\n r = (Math.floor(num / i) + Math.floor(ts / i)) % 10 + r;\n }\n return '@user' + r;\n}\n</code></pre>\n\n<p>or similarly</p>\n\n<pre><code>function getIdNumber(num, ts) {\n var r = '';\n ts = (ts === undefined ? 3452 : ts);\n for (var i = 0; i &lt; 4; i++) {\n r = (Math.floor(num) + Math.floor(ts)) % 10 + r;\n num /= 10;\n ts /= 10;\n }\n return '@user' + r;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T00:54:10.460", "Id": "31640", "ParentId": "31607", "Score": "1" } } ]
{ "AcceptedAnswerId": "31612", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T01:07:34.517", "Id": "31607", "Score": "3", "Tags": [ "javascript" ], "Title": "More efficient version of an ID calculator in JavaScript" }
31607
<p>First of all, I am a beginner in Python trying to learn optimizations and proper coding standards.</p> <p>Here is a snippet of code that checks if a number follows the rule: first AND last <code>N</code> digits contain all unique numbers from <code>1</code> to <code>N</code>, but in any order. This also means that in either first <code>N</code> or last <code>N</code> digits, each number appears exactly once.</p> <pre><code>import time start_time = time.time() def is_pandigital(nr, n): digits = ''.join(map(str, range(1, n + 1))) nr = str(nr) for i in digits: if str(i) not in nr[0:9]: return False if str(i) not in nr[-9:]: return False return True assert is_pandigital(1423, 4) is True assert is_pandigital(1423, 5) is False assert is_pandigital(14235554123, 4) is True assert is_pandigital(14235552222, 4) is False # !important assert is_pandigital(1444, 4) is False assert is_pandigital(123564987, 9) is True pandigitals = [] # this loop is strictly for benchmarking is_pandigital for i in range(100000, 999999): if is_pandigital(i, 6): pandigitals.append(i) print pandigitals print time.time() - start_time, "seconds" </code></pre> <p>When running this, the result is:</p> <pre><code>[123456, .......] 2.968 seconds Process finished with exit code 0 </code></pre> <p>The code seems to work fine, but it doesn't appear to be very efficient. Would you have any tips to improve it? Any piece of code and/or idea would be highly appreciated.</p> <p><strong>PS:</strong> I chose this loop so that any improvements to the <code>is_pandigital</code> function would be immediately obvious.</p> <p><strong>Example of numbers I am looking for:</strong></p> <p><strong><code>321</code></strong><code>XXXXXXXXXXXXXXX</code><strong><code>132</code></strong> - good</p> <p><strong><code>321</code></strong><code>XXXXXXXXXXXXXXX</code><strong><code>133</code></strong> - not good, because the last 3 digits dont contain 1, 2 and 3</p> <p><strong><code>231</code></strong> - good</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T10:13:30.827", "Id": "50450", "Score": "0", "body": "Pandigital numbers have a [somewhat different definition](http://en.wikipedia.org/wiki/Pandigital_number)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T12:00:28.313", "Id": "50454", "Score": "0", "body": "That is true, I worded the issue a bit weird, sorry about that. Re-wrote it slightly so it doesn't conflict with the definition of pandigital numbers. This is part of a problem on projecteuler.net" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T23:48:38.973", "Id": "50483", "Score": "0", "body": "Out of curiosity, which problem is this ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T09:22:02.497", "Id": "50491", "Score": "0", "body": "It was problem 104, which requested the first Fibonacci number for which the first 9 + last 9 digits were 1-9 pandigital. The script still ran for 10h before finding the result :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T11:10:04.963", "Id": "50494", "Score": "0", "body": "10 hours for a PE problem: you're probably doing it wrong. You can have a look at the thread now that you have a solution. An easy improvement you could/should do is to remove the n parameter as it will always be 9 and pre compute the set of numbers from 1 to 9." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T11:43:40.570", "Id": "50496", "Score": "0", "body": "Yep, I figured out the problem. Now it runs in 15 seconds instead of 10 hours :P" } ]
[ { "body": "<p>You can rewrite your asserts without comparing to <code>True</code> and <code>False</code>:</p>\n\n<pre><code>assert is_pandigital(1423, 4)\nassert not is_pandigital(1423, 5)\nassert is_pandigital(14235554123, 4)\nassert not is_pandigital(14235552222, 4) # !important\nassert not is_pandigital(1444, 4)\nassert is_pandigital(123564987, 9)\n</code></pre>\n\n<p>You can rewrite your benchmark with list comprehension:</p>\n\n<pre><code># this loop is strictly for benchmarking is_pandigital\npandigitals = [i for i in range(100000, 999999) if is_pandigital(i, 6)]\n</code></pre>\n\n<p>Now for the algorithm itself, I must confess that I have troubles understanding what you want to do as you seem to be calling \"pandigital\" two different things. In any case, I have the feeling that something is wrong in your code, it seems like :</p>\n\n<pre><code> if str(i) not in nr[0:9]:\n return False\n if str(i) not in nr[-9:]:\n return False\n</code></pre>\n\n<p>should be </p>\n\n<pre><code> if str(i) not in nr[0:n]:\n return False\n if str(i) not in nr[-n:]:\n return False\n</code></pre>\n\n<p>and</p>\n\n<pre><code>assert not is_pandigital(9999912399999, 3)\n</code></pre>\n\n<p>should provide you some hints.</p>\n\n<p>I'll go deeper in the code once you confirm that my understanding is correct.</p>\n\n<p><strong>Edit :</strong> I have to go, no time to run benchmarks but here are the improvements. I kept different versions to that you can take ideas out of it.</p>\n\n<pre><code>def is_pandigital(nr, n):\n nr = str(nr)\n beg=nr[0:n]\n end=nr[-n:]\n for i in map(str, range(1, n + 1)):\n if i not in beg or i not in end:\n return False\n return True\n\ndef is_pandigital(nr, n):\n nr = str(nr)\n beg=set(nr[0:n])\n end=set(nr[-n:])\n return beg==end and beg==set(map(str, range(1, n + 1)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T11:30:10.240", "Id": "50451", "Score": "0", "body": "Awesome! Especially the list comprehension, which I didn't know about. The `n` instead of `9` fix (code initially was used to check only pandigital numbers with length 9) also fixed the `assert` you mentioned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T11:58:34.740", "Id": "50453", "Score": "0", "body": "I edited the post to be a bit more clear on the numbers I am looking for" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T12:29:16.537", "Id": "50456", "Score": "1", "body": "First solution - an average of `2.4 seconds` (pretty big improvement), and second version has `4.2 seconds`. I'll see if I can improve on your code, thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T09:19:40.090", "Id": "50490", "Score": "0", "body": "I managed to solve the projecteuler.net problem using your improvement. The rest of the script probably was pretty bad, since it found the result after running 10 hours, but I got it! Thank you" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T10:06:52.317", "Id": "31615", "ParentId": "31614", "Score": "4" } }, { "body": "<p>I'd try by sorting digits:</p>\n\n<pre><code>def adapt_nr(nr):\n nr = [ int(i) for i in list(nr) ]\n nr.sort()\n return nr\n\ndef is_pandigital(nr, n):\n nr = str(nr);\n if len(nr) &lt; n: return False\n chk = list(range(1, n+1))\n if adapt_nr(nr[0:n]) != chk: return False\n if adapt_nr(nr[-n:]) != chk: return False\n return True\n</code></pre>\n\n<p>A built-in sort is quick, and all that is left to compare is that the obtained lists of digits are equal to <code>[1,..,n]</code>.</p>\n\n<p>The check itself might be faster if done with strings instead of lists:</p>\n\n<pre><code>def adapt_nr(nr):\n nr = [ int(i) for i in list(nr) ]\n nr.sort()\n return ''.join([str(i) for i in nr])\n\ndef is_pandigital(nr, n):\n nr = str(nr);\n if len(nr) &lt; n: return False\n chk = ''.join(str(i) for i in list(range(1, n+1)))\n if adapt_nr(nr[0:n]) != chk: return False\n if adapt_nr(nr[-n:]) != chk: return False\n return True\n</code></pre>\n\n<p>You'll have to benchmark for yourself.</p>\n\n<p>I'm a beginner in Python, so some of this can probably be written in a more pythonic way. I'll edit if I get such suggestions in the comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T12:24:59.217", "Id": "50455", "Score": "1", "body": "Quite interesting solutions. The first has an average of `6 seconds` run time, while the second has an average of `10 seconds`, so in this situations lists are better than strings :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T12:16:56.590", "Id": "31618", "ParentId": "31614", "Score": "1" } } ]
{ "AcceptedAnswerId": "31615", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T08:44:10.237", "Id": "31614", "Score": "3", "Tags": [ "python", "optimization", "beginner" ], "Title": "Improve pandigital algorithm" }
31614
<p>The below code is still far from feature complete, but am looking to have some of the sections critiqued to learn better idioms or adjustments (e.g. - yet to be implemented: handling of csv files with headers, exception handling, more robust color labeling for matplotlib graphs, etc.):</p> <pre><code>""" Quantile normalization License: Creative Commons Attribution-ShareAlike 3.0 Unported License http://creativecommons.org/licenses/by-sa/3.0/ This is an implementation of quantile normalization for microarray data analysis. CSV files must not contain header. Format must be as follows: | Gene | Expression value | Example: | ABCD1 | 5.675 | Other restrictions: 1.) Each csv file must contain the same gene set. 2.) Each gene must be unique. Usage on command line: python2.7 quantile_normalization *csv """ import csv import matplotlib.pyplot as plt import numpy as np import random import sys if (len(sys.argv) &gt; 1): file_list = sys.argv[1:] else: print "Not enough arguments given." sys.exit() # Parse csv files for samples, creating lists of gene names and expression values. set_dict = {} for path in file_list: with open(path) as stream: data = list(csv.reader(stream, delimiter = '\t')) data = sorted([(i, float(j)) for i, j in data], key = lambda v: v[1]) sample_genes = [i for i, j in data] sample_values = [j for i, j in data] set_dict[path] = (sample_genes, sample_values) # Create sorted list of genes and values for all datasets. set_list = [x for x in set_dict.items()] set_list.sort(key = lambda (x,y): file_list.index(x)) # Compute row means. L = len(file_list) all_sets = [[i] for i in set_list[0:L+1]] sample_values_list = [[v for i, (j, k) in A for v in k] for A in all_sets] mean_values = [sum(p) / L for p in zip(*sample_values_list)] # Compute histogram bin size using Rice Rule for sample in sample_values_list: bin_size = int(pow(2 * len(sample), 1.0 / 3.0)) # Provide corresponding gene names for mean values and replace original data values by corresponding means. sample_genes_list = [[v for i, (j, k) in A for v in j] for A in all_sets] sample_final_list = [sorted(zip(sg, mean_values)) for sg in sample_genes_list] # Compute normalized histogram bin size using Rice Rule for sample in sample_final_list: bin_size_2 = int(pow(2 * len(sample), 1.0 / 3.0)) # Creates a dictionary with normalized values for the dataset. def exp_pull(sample, gene): sample_name = {genes: values for genes, values in zip([v for i, (j, k) in set_list[sample - 1:sample] for v in j], mean_values)} return round(sample_name.get(gene, 0), 3) # Truncate full path name to yield filename only. file_list = [file[file.rfind("/") + 1:file.rfind(".csv")] for file in file_list] # Pulls normalized expression values for particular genes for all samples. genes_of_interest = ['ERG', 'ETV1', 'ETV4', 'ETV5'] for gene in genes_of_interest: print '\n{}:'.format(gene) for i, file in enumerate(file_list, 1): print '{}: {}'.format(file, exp_pull(i, gene)) # Plot an overlayed histogram of raw data. fig = plt.figure(figsize=(12,12)) ax1 = fig.add_subplot(221) sample_graph_list_raw = [[i for i in sample_value] for sample_value in sample_values_list] colors = ['b', 'g', 'r', 'c', 'm', 'y'] color_list = [random.choice(colors) for file in file_list] for graph, color, file in zip(sample_graph_list_raw, color_list, file_list): plt.hist(graph, bins = bin_size, histtype = 'stepfilled', normed = True, color = None, alpha = 0.5, label = file) plt.title("Microarray Expression Frequencies") plt.xlabel("Value") plt.ylabel("Frequency") plt.legend() # Plot an overlayed histogram of normalized data. ax2 = fig.add_subplot(222) sample_graph_list = [[j for i, j in sample_final] for sample_final in sample_final_list] for graph, color, file in zip(sample_graph_list, color_list, file_list): plt.hist(graph, bins = bin_size_2, histtype = 'stepfilled', normed = True, color = color, alpha = 0.5 , label = file) plt.title("Microarray Expression Frequencies (normalized)") plt.xlabel("Value") plt.ylabel("Frequency") plt.legend() # Plot box plots of raw data. ax3 = fig.add_subplot(223) plt.title("Microarray Expression Values") plt.hold = True boxes = [graph for graph in sample_graph_list_raw] plt.boxplot(boxes, vert = 1) # Plot box plots of normalized data. ax4 = fig.add_subplot(220) plt.title("Microarray Expression Values (normalized)") plt.hold = True boxes = [graph for graph in sample_graph_list] plt.boxplot(boxes, vert = 1) plt.savefig('figures.pdf') plt.savefig('figures.png') plt.show() </code></pre>
[]
[ { "body": "<p>Ì am not sure <code>file_list = [args for args in sys.argv[1:]]</code> calls for list comprehension. I might be wrong but <code>file_list = sys.argv[1:]</code> should do the trick.\nSame applies to other of your list comprehension. If you do want to create a new list out of the previous, <code>list(my_list)</code> does the trick but this is not required when using the slice operations as they return new list already.</p>\n\n<p>The <code>while True:</code> is not really useful, is it ?</p>\n\n<p><code>all_sets = [set_list[i - 1: i] for i in range(1, L + 1)]</code> is this any different from <code>all_sets = [[i] for i in set_list[0:L+1]]</code> ?</p>\n\n<p>Then, I must confess I got lost in the middle of the code. Please have a look at what can be simplified based on my first comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T00:22:02.153", "Id": "50520", "Score": "0", "body": "Good suggestions so far. Have implemented them in the above code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T00:09:03.633", "Id": "31639", "ParentId": "31617", "Score": "2" } } ]
{ "AcceptedAnswerId": "31639", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T11:14:16.090", "Id": "31617", "Score": "4", "Tags": [ "python", "csv", "statistics" ], "Title": "Code correctness and refinement for quantile normalization" }
31617
<p>I have this <code>authenticate!</code> method where I am trying to retrieve their account based on the subdomain, then find the user. if user is found &amp; their password is matched, we return <code>success</code>, else <code>fail</code> in all other cases. here is the code:</p> <pre><code>def authenticate! account = Account.find_by(subdomain: subdomain) if account u = account.users.find_by email: params["user"]["email"] if u.nil? fail! else u.authenticate(params["user"]["password"]) ? success!(u) : fail! end else fail! end end </code></pre> <p>Now, I could simply this further by moving subdomain into a helper method, </p> <pre><code>def subdomain ActionDispatch::Http::URL.extract_subdomains(request.host, 1) end def authenticate! account = Account.find_by(subdomain: subdomain) if account u = account.users.find_by email: params["user"]["email"] if u.nil? fail! else u.authenticate(params["user"]["password"]) ? success!(u) : fail! end else fail! end end </code></pre> <p>But how to I simply these nested conditionals?</p>
[]
[ { "body": "<p>Some programmers don't like the pattern <code>if (var = value)</code> (for understandable reasons), unfortunately, by avoiding it at all costs, you end up writing verbose code like yours. If you have no problems with it:</p>\n\n<pre><code>def authenticate!\n if (account = Account.find_by(subdomain: subdomain)) &amp;&amp;\n (user = account.users.find_by(email: params[\"user\"][\"email\"])) &amp;&amp;\n user.authenticate(params[\"user\"][\"password\"])\n success!(user)\n else\n fail!\n end\nend\n</code></pre>\n\n<p>Note that the parens are there to make more clear that we are doing an assignment and not a comparison (and to avoid operator precendence problems)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T14:51:08.443", "Id": "31620", "ParentId": "31619", "Score": "3" } }, { "body": "<p>Another view on @tokland solution:</p>\n\n<pre><code>def authenticate!\n return fail! unless account = Account.find_by(subdomain: subdomain)\n return fail! unless user = account.users.find_by(email: params[\"user\"][\"email\"])\n return fail! unless user.authenticate(params[\"user\"][\"password\"])\n success! user\nend\n</code></pre>\n\n<p>This intention is to be as close to \"original task explained in common English\" as possible. And <code>return</code> keyword allows me to do that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T18:51:31.360", "Id": "50581", "Score": "1", "body": "While this is probably the more idiomatic in Ruby (in the sense that is what most Ruby programmers would write), and saves some lines, personally I dislike (enormously) 1) early returns, 2) inline conditionals, for a piece of code that is an expression. My rationale: https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T13:18:51.213", "Id": "50631", "Score": "0", "body": "I don't care, what do most Ruby programmers write. My way is to be as close to \"original task explained in common English\" as possible. And `return` keyword allows me to do that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T11:22:00.143", "Id": "31649", "ParentId": "31619", "Score": "8" } }, { "body": "<p>Symantic variant of @Nakilon's answer:</p>\n\n<pre><code> def authenticate!\n user = nil\n return success!(user) if\n account = Account.find_by(subdomain: subdomain)) and\n user = account.users.find_by(email: params[\"user\"][\"email\"]) and\n user.authenticate(params[\"user\"][\"password\"])\n return fail! \n end\n</code></pre>\n\n<p>I prefer @Nakilon, but thought this might be of some interest. Note: 1) <code>user</code> must be initialized (to anything); and 2) the line continuation mark <code>\\</code> is not needed where it's obvious to Ruby that the statement is not complete. I don't know if the latter conforms to the Ruby style guide.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T06:10:42.257", "Id": "32014", "ParentId": "31619", "Score": "1" } } ]
{ "AcceptedAnswerId": "31649", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T13:41:05.627", "Id": "31619", "Score": "4", "Tags": [ "ruby", "ruby-on-rails", "authentication" ], "Title": "Rails authentication checks" }
31619
<p>I have the following function to collect quota information for the given user and return the information on a "ready to use" array:</p> <pre><code>/* Get User Quota Information * * Prepare and array with the user's account disk space information * by ascertaining the amount of space available on its quota, * the used space from that quota and free space remaining. * * @param string $user The system user name * * @return array */ function getUserQuotaInfo($user) { $quota = exec("quota -s -u ".$user); // query server $quota = preg_replace("/[\s-]+/", ' ', $quota); // clear spaces $arr = explode(' ', $quota); $freeSpace = str_replace('M', '', $arr[3]) - str_replace('M', '', $arr[2]); return array( "total" =&gt; $arr[3], "used" =&gt; $arr[2], "free" =&gt; $freeSpace.'M' ); } </code></pre> <p>The function is working well and giving the expected results, but there's a lot going on to manipulate the information in order to have it ready to present to the user.</p> <p>Is there any optimization that can be done as to reduce the possibilities of failure on this function as well as simplifying it?</p>
[]
[ { "body": "<p>I think you should use <a href=\"http://php.net/manual/en/function.escapeshellarg.php\" rel=\"nofollow\"><code>escapeshellarg</code></a> to secure that <code>$user</code> does not do damage through your <code>exec</code> call. Also, you should check if your <code>$arr</code> actually has the required data.</p>\n\n<p>As for optimization, replacing multiple spaces and dashes with single spaces and then exploding such strings seems to me slower than just splitting the string right away, using <a href=\"http://php.net/manual/en/function.preg-split.php\" rel=\"nofollow\"><code>preg_split</code></a>:</p>\n\n<pre><code>$arr = preg_split(\"/[\\s-]+/\", $quota);\n</code></pre>\n\n<p>However, you should still check that <code>count($arr) &gt; 3</code>.</p>\n\n<p>I must say that I am a bit surprised to see this work for you. That means that the user under which PHP is running has the permission to see <strong>other users'</strong> quota. IMO, web server should not be allowed as much.</p>\n\n<p>A better way to do this is to dump all users' quotas in some text file (i.e., using <a href=\"http://linux.about.com/library/cmd/blcmdl8_repquota.htm\" rel=\"nofollow\"><code>repquota</code></a> command; see an example on how to use it <a href=\"http://www.ibm.com/developerworks/library/l-lpic1-v3-104-4/#5-repquota\" rel=\"nofollow\">here</a>), via a cron job run as root, and then make the script that only parses that file.</p>\n\n<p>Or, quite similarly, your cron job can make a file with all the data, i.e., create <code>quota-data.php</code> like this:</p>\n\n<pre><code>&lt;?php\n\n$quota_data = array(\n 'zuul' =&gt; array(\n 'total' =&gt; ...,\n 'used' =&gt; ...,\n 'free' =&gt; ...,\n ),\n ...\n);\n\n?&gt;\n</code></pre>\n\n<p>which you then just include in your script and use the data.</p>\n\n<p>Which of these two approaches is better depends on how often the data is read from the web. If rarely, the text file approach is better, so that parsing is done only when really needed; if often, the second approach is better, as it parses the data only once per update.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T14:57:07.930", "Id": "50561", "Score": "0", "body": "Apart from the advices given, thank you for the `preg_split()` suggestion, it is indeed a great improvement to reduce the amount of code. **Note:** This function is part of a PHP class that receives parameters from a configuration file, actually the `$user` only holds one value per each implementation of this \"application\". The user running the application cannot view any information about other users. Nor the server allows it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T15:05:46.660", "Id": "50562", "Score": "1", "body": "So, `$user` is the user running the application? In that case, `quota -v` should do, without `-u $user`. Note that `-v` is not \"human readable\", which makes it easier to parse (no need to worry if you have \"M\", \"G\",...)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T19:42:07.060", "Id": "31631", "ParentId": "31626", "Score": "3" } }, { "body": "<p>There are a couple of niggles I have with your code. For a start, you're just assuming the <code>exec</code> call will be successful, even though you don't do anything to <em>sanitize</em> the input argument: <code>$user</code>. As Vedran pointed out, this is where <code>escapeshellarg</code> should be used.</p>\n<p>But please, also <a href=\"http://www.php.net/manual/en/function.exec.php\" rel=\"nofollow noreferrer\">read the docs</a>, and look at the function signature of <code>exec</code>:</p>\n<pre><code>string exec ( string $command [, array &amp;$output [, int &amp;$return_var ]] )\n</code></pre>\n<p>On the doc pages, you'll see that the string that this function returns is only <em>the last line of output</em>, not the entire output at all:</p>\n<blockquote>\n<p>Return Values</p>\n<p>The last line from the result of the command.</p>\n</blockquote>\n<p>Hence, I'd write your code like so:</p>\n<pre><code>exec('quota -s -u '.escapeshellarg($user), $output, $status);\nif ($status !== 0)\n{//0 signals successful run\n throw new RuntimeException('exec call failed, with status :'.$status);\n}\n$output = array_map('cleanFunc', $output);\n\n//the cleanFunc needn't be more than:\nfunction cleanFunc($string)\n{\n return preg_split('/[\\s-]+/',$string);\n}\n</code></pre>\n<p>The rest is OK, not great, but OK. What you're doing is, essentially, using a screwdriver as a chisel. PHP is not the best tool for the job at hand, so whichever way you look at it, your code will never be <em>as good a sollution as possible</em>.<br/>\nBut that's not the point...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T14:48:27.233", "Id": "50560", "Score": "0", "body": "Thank you for the the advices given, just a side note on the function `CleanFunc`: you need to replace `preg_split('/[\\s-]+/',' ',$string)` with `preg_split('/[\\s-]+/', $string)` since the string with [`preg_split()`](http://php.net/manual/en/function.preg-split.php) is the second parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T22:12:55.150", "Id": "50594", "Score": "0", "body": "@Zuul: of course, I edited my answer... I got confused looking at your `str_replace`, so used it like it were `preg_replace`... ah well... it's all fixed now" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T10:04:56.130", "Id": "31677", "ParentId": "31626", "Score": "3" } } ]
{ "AcceptedAnswerId": "31631", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T16:38:41.780", "Id": "31626", "Score": "4", "Tags": [ "php" ], "Title": "Getting user quota stats" }
31626
<p>I am reading hadoop source code , Here I have a doubt "org.apache.hadoop.util.StringUtils" they reassigned a list which is already intiailized.</p> <pre><code> public static Collection&lt;String&gt; getStringCollection(String str){ List&lt;String&gt; values = new ArrayList&lt;String&gt;(); if (str == null) return values; StringTokenizer tokenizer = new StringTokenizer (str,","); values = new ArrayList&lt;String&gt;(); while (tokenizer.hasMoreTokens()) { values.add(tokenizer.nextToken()); } return values; } </code></pre> <p>Is there any reason to reassign here?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T01:09:15.660", "Id": "67441", "Score": "0", "body": "This question appears to be off-topic because it is not your own written code." } ]
[ { "body": "<p>It looks like a useless reassignment. It must be some refactoring gone wrong. At worst, it will cause a tiny performance hit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T18:18:47.257", "Id": "31629", "ParentId": "31627", "Score": "2" } }, { "body": "<p>Yes you are right, but it will cause a tiny performance hit! and they should use String.split() instead of StringTokenizer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T08:57:21.757", "Id": "31643", "ParentId": "31627", "Score": "0" } } ]
{ "AcceptedAnswerId": "31629", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T16:56:26.583", "Id": "31627", "Score": "3", "Tags": [ "java" ], "Title": "Is this correct to reassign already intialized variable?" }
31627
<p>As an exercise in learning Scala, I implemented a square root function like this:</p> <pre><code> def sqrt(x: Double): Double = { if (x &lt; 0) throw new IllegalArgumentException("negative numbers not allowed") val threshold = if (x &lt; 1) x / 1e15 else 1e-12 def sqrt(x: Double, p: Double): Double = { if (p == x / p) p // without this condition, non-termination with 1e50 else if (Math.abs(p * p - x) &lt; threshold) { def diff1 = Math.abs(x - p * p) def diff2 = Math.abs(x - x / p * x / p) if (diff1 &lt; diff2) p else x / p } else sqrt(x, (p + x / p) / 2) } sqrt(x, x / 2) } </code></pre> <p>The implementation passes these unit tests:</p> <pre><code> test("sqrt 2") { assert(sqrt(2) === Math.sqrt(2)) } test("sqrt 1e-3") { assert(Math.abs(1e-3 - sqrt(1e-3) * sqrt(1e-3)) === Math.abs(1e-3 - Math.sqrt(1e-3) * Math.sqrt(1e-3))) } test("sqrt 1e-20") { assert(sqrt(1e-20) === Math.sqrt(1e-20)) } test("sqrt 1e-21") { assert(sqrt(1e-21) === Math.sqrt(1e-21)) } test("sqrt 1e20") { assert(sqrt(1e20) === Math.sqrt(1e20)) } test("sqrt 1e50") { assert(sqrt(1e50) === Math.sqrt(1e50)) } </code></pre> <p>My questions:</p> <ol> <li><p>How can I improve this?</p></li> <li><p>Notice the unit test for the case of <code>1e-3</code>. It's more complex than the others to compensate for the difference between <code>sqrt</code> and <code>Math.sqrt</code>. Although the both <code>sqrt</code> and <code>Math.sqrt</code> are equally incorrect (the square of both have the same discrepancy with <code>x</code>), I wonder if I can change the implementation to match the result of <code>Math.sqrt</code>.</p></li> <li><p>I found the error thresholds for <code>&lt; 1</code> and <code>&gt;= 1</code> through trial and error: all unit tests pass with these values and some would fell if I stretched the limits further. I'm wondering if there is a better, proper way of setting suitable thresholds based on <code>x</code> and the numeric limits of the language.</p></li> </ol>
[]
[ { "body": "<p>I'm going to concentrate on the Scala rather than the maths side, because that's my area.</p>\n\n<p>The internal helper function doesn't need two parameters, since the value of x never changes; pushing x repeatedly onto the stack is a waste of time. Also, better to use a case statement than a chain of <code>if...else if...else</code> - much less error prone.</p>\n\n<pre><code>def sqrt(x: Double): Double = {\n if (x &lt; 0) throw new IllegalArgumentException(\"negative numbers not allowed\")\n val threshold = if (x &lt; 1) x / 1e15 else 1e-12\n def sqrtx(p: Double): Double = p match {\n case q if q == x / q =&gt; q // without this condition, non-termination with 1e50\n case q if Math.abs(q * q - x) &lt; threshold =&gt; {\n def diff1 = Math.abs(x - p * p)\n def diff2 = Math.abs(x - x / p * x / p)\n if (diff1 &lt; diff2) p else x / p\n }\n case _ =&gt; sqrtx((p + x / p) / 2)\n }\n sqrtx(x / 2)\n}\n</code></pre>\n\n<p>I renamed the inner function sqrtx to avoid confusion about what it is doing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-27T22:30:52.210", "Id": "213861", "Score": "0", "body": "Another improvement would be replacing the `if (x < 0)...` with `require (x >= 0, ...)`, I don't think it merits a full answer, though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T10:15:55.527", "Id": "31648", "ParentId": "31628", "Score": "7" } }, { "body": "<p>It took a bit to remember where I'd seen this before. Implementing Newton's Method for taking a Square Root was one of the exercises in Odersky's Functional Programming in Scala course on Coursera.</p>\n\n<p>Here is an implementation that's mostly based on the hints and suggestions in that assignment.</p>\n\n<pre><code>object NewtonsMethod {\n def sqrt(x: Double) = {\n require(x &gt;= 0, \"Square Root is undefined for negative numbers\")\n\n def isGoodEnough(guess: Double) = Math.abs(guess * guess - x) / x &lt; 0.001\n def improve(guess: Double) = (guess + x / guess) / 2\n\n @tailrec\n def iter(guess: Double): Double =\n if(isGoodEnough(guess)) guess\n else iter(improve(guess))\n\n iter(1.0)\n }\n}\n</code></pre>\n\n<p>It has some very nice features, one of the most important is the helper function <code>isGoodEnough</code>, which scales the threshold with the size of <code>x</code>. This makes the non-termination check for <code>1e50</code> unnecessary.</p>\n\n<p>It's tail-recursive, and flagged as such, honestly it shouldn't make a difference for this algorithm, but it's a nice touch.</p>\n\n<p>Here's the test suite I used to verify it has the correct behavior.</p>\n\n<pre><code>import org.scalatest.WordSpec\nimport org.scalatest.Matchers\nimport org.scalacheck.Prop\nimport org.scalatest.prop.GeneratorDrivenPropertyChecks\nimport NewtonsMethodSpec._\n\nclass NewtonsMethodSpec extends WordSpec with Matchers with GeneratorDrivenPropertyChecks {\n \"NewtonsMethod.sqrt\" should {\n \"work for very large numbers\" in {\n NewtonsMethod.sqrt(1e50).round(2) shouldBe Math.sqrt(1e50).round(2)\n }\n \"be equivalent to Math.sqrt\" in {\n forAll {\n (d: Double) =&gt; whenever(d &gt;= 0) {\n NewtonsMethod.sqrt(d).round(2) shouldBe Math.sqrt(d).round(2)\n }\n }\n }\n }\n}\n\nobject NewtonsMethodSpec {\n implicit class Roundable(val d: Double) extends AnyVal {\n def round(scale: Int): BigDecimal =\n BigDecimal(d).round(new java.math.MathContext(scale, java.math.RoundingMode.FLOOR))\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-27T23:49:38.277", "Id": "213875", "Score": "0", "body": "This solution is less noisy. The recursion makes it elegant. And even if I don't know exactly how the work is done, the naming is very expressive: Calculation of a square root, ok... good guess number... if within tolerance ready, if not improve result. Got it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-27T23:53:38.200", "Id": "213876", "Score": "0", "body": "I can't take full credit for the design. Odersky leads you to this, or a very similar design, over the course of four or five iterations." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-27T23:26:12.373", "Id": "115222", "ParentId": "31628", "Score": "3" } } ]
{ "AcceptedAnswerId": "31648", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T16:59:02.013", "Id": "31628", "Score": "11", "Tags": [ "algorithm", "unit-testing", "scala", "numerical-methods" ], "Title": "Sqrt (square root) function" }
31628
<p>I'm working on my personal project and have recently had a bit of trouble with a method I wrote during the week.</p> <p>This method compares user input from the same <code>JComboBox</code>. A before and after, if you will. It then makes an appropriate adjustment to a 2nd <code>ComboBox</code> depending on the user's input into the first box. It took me a bit of effort to figure this out. When I finally did, I was pretty happy with myself. Until I realized that the method uses a class variable and ruins any concept of good object-oriented design.</p> <pre><code> /** ** missileBalancer compares the users input before and after selection and adjusts the contents of the OH missile count box as necessary. ** @param JComboBox combobox is the combobox concerning the OP counts, JComboBox combobox1 is the combobox concerning the OH counts, prevOH is the masterOH count. ** @return ** @throws **/ public void missileBalancer(JComboBox combobox, JComboBox combobox1, int prevOP){ int difference = 0; int newOH = 0; int newOP = (int) combobox.getSelectedItem(); //Current OP count int oldOH = (int) combobox1.getSelectedItem();//Current OH count --Adjusting this by the appropriate amount is the goal of this method int oldOP = prevOP; //oldOP is the OP that we are testing against it needs to be set by the program into a var that we can use in our test. if(newOP &lt; oldOP){ oldPac3 = newOP;//We need to keep track of our count outside of the method. }else if(newOP &gt; oldOP){ difference = newOP - oldOP; newOH = oldOH - difference; combobox1.setSelectedItem(newOH); if(newOH &lt; 0){//You cannot set selected item to a jcombobox with a negative number so in all cases where newOH is less than zero we simply set the selected item to 0. combobox1.setSelectedItem(0); } oldPac3 = newOP; } }//End Missile Balancer </code></pre> <p>The problem is with the user of the <code>oldPac3</code> variable. The method cannot always use this variable. I have variables for <code>oldGemT</code> and <code>oldGemC</code>, that this method needs to modify as appropriate. I can think of a couple ways to make this work, but I don't think any of them are very clean. I want the code for this method to be concise and elegant. Any help or some guidance in the right direction would be great. This is the rewritten method. It does what needs doing, but I think it is ugly. I'm posting it because I don't want to give the impression that I'm looking for other people to solve my problems for me. I really just want to write better code. </p> <pre><code>/** ** missileBalancer compares the users input before and after selection and adjusts the contents of the OH missile count box as necessary. ** @param JComboBox combobox is the combobox concerning the OP counts, JComboBox combobox1 is the combobox concerning the OH counts, prevOH is the masterOH count. ** @return ** @throws **/ public void missileBalancer(JComboBox combobox, JComboBox combobox1, int prevOP){ int difference = 0; int newOH = 0; int newOP = (int) combobox.getSelectedItem(); //Current OP count int oldOH = (int) combobox1.getSelectedItem();//Current OH count --Adjusting this by the appropriate amount is the goal of this method int oldOP = prevOP; //oldOP is the OP that we are testing against it needs to be set by the program into a var that we can use in our test. if(newOP &lt; oldOP){ if(combobox.equals(pac_3OpCount)){ oldPac3 = newOP;//We need to keep track of our count outside of the method. } else if(combobox.equals(gemCOpCount)){ oldGemC = newOP; } else if(combobox.equals(gemtOpCount)){ oldGemT = newOP; } }else if(newOP &gt; oldOP){ difference = newOP - oldOP; newOH = oldOH - difference; combobox1.setSelectedItem(newOH); if(newOH &lt; 0){//You cannot set selected item to a jcombobox with a negative number so in all cases where newOH is less than zero we simply set the selected item to 0. combobox1.setSelectedItem(0); } if(combobox.equals(pac_3OpCount)){ oldPac3 = newOP;//We need to keep track of our count outside of the method. } else if(combobox.equals(gemCOpCount)){ oldGemC = newOP; } else if(combobox.equals(gemtOpCount)){ oldGemT = newOP; } } }//End Missile Balancer </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T12:47:21.513", "Id": "50497", "Score": "0", "body": "So you problem is that this method sometimes has to keep it's count in `oldPac3`, but sometimes in other variables such as `oldGemT` or `oldGemC`? Is that it? If it's the case we will not be able to answer without knowing in which cases that might happen and perhaps it would also help to know what all these variables mean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T16:23:17.570", "Id": "50507", "Score": "0", "body": "Yes that is the problem, each of the old variables represents the user selection before the new selection; hence old vs new. When a variables needs to be modified directly correlates to which arguments where passed into the method. I rewrote the method last night so it does what I need and works, but I think it is hideous. Also I apologize if you find my var names confusing. Within the context of the program they make perfect sense and let me know exactly where I'm at in the program when I'm reading the code." } ]
[ { "body": "<h1>TL;DR</h1>\n\n<ol>\n<li>Name your variables more descriptively.</li>\n<li>Never copy-and-paste logic; if you find yourself doing so, make a new method or analyze <em>why</em> you're repeating it.</li>\n<li>Don't pass around components if you don't have to (like <code>JComboBox</code>es). In general, Swing components are global variables.</li>\n<li>Follow appropriate code formatting. (Proper tabs, indentation, spaces between brackets, etc.)</li>\n<li>Don't create unnecessary variables (i.e., <code>int oldOP = prevOP</code>)</li>\n<li>Perform validations and error handling while doing dangerous things like downcasting.</li>\n</ol>\n\n<hr>\n\n<p>I rewrote your entire method as follows just by following some decent object-oriented design practices.</p>\n\n<pre><code>public void balance() {\n if(getOperational() &gt; count) {\n int adjustment = getAdjustment() - (getOperational() - count);\n adjustmentComboBox.setSelectedItem(adjustment &lt; 0 ? 0 : adjustment);\n }\n count = getAdjustment();\n}\n</code></pre>\n\n<p>What I'm going to do is walk through your code step-by-step, explain why I made certain changes, and then present the finished code. I'll also point out any assumptions I've made in constructing my version. I had to make a number of them due to your inexplicable variable names, but it shouldn't affect the final outcome drastically even if I made a mistaken guess as to what the variables meant. You should just have to rename them to something appropriate.</p>\n\n<p>So here are a few assumptions of mine right off the bat:</p>\n\n<ol>\n<li><code>prevOP</code> means the previous count of a given missile;</li>\n<li>anywhere you use the infix <code>Op</code> or <code>OP</code>, it means something like \"operational\"; and,</li>\n<li>anywhere you use the infix <code>Oh</code> or <code>OH</code>, it means something like \"adjustment\".</li>\n</ol>\n\n<p>So let's get started!</p>\n\n<pre><code>public void missileBalancer(JComboBox combobox, JComboBox combobox1, int prevOP){\n</code></pre>\n\n<p>I was skeptical of this method immediately because it's very, very rare to have to pass around GUI elements like this when using Swing. Ideally the combo boxes should all be declared as global fields in the class (i.e., <code>private JComboBox myComboBox</code>) so that all of your code can reference them as necessary. Also, this really breaks Java naming conventions. In general, a method name should be some kind of verb, never a noun like this. If I was skimming code and I saw something called <code>missileBalancer</code>, I would assume it was an object, like of the <code>MissileBalancer</code> class. Anything that's a noun in your code should be an actual object of some kind.</p>\n\n<pre><code>int newOP = (int) combobox.getSelectedItem();\nint oldOH = (int) combobox1.getSelectedItem();\n</code></pre>\n\n<p>I'm not sure how you got this to compile. I received compiler errors saying \"Unable to cast Object to int.\" In any case, that's easily solved by changing the downcast to <code>Integer</code> like so:</p>\n\n<pre><code>int newOP = (Integer) combobox.getSelectedItem();\n</code></pre>\n\n<p>This works thanks to <a href=\"http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow\">autoboxing</a>, and it's a handy trick to remember as you move forward with Java. Even though this bit of code now works, it's still really bad practice since it's a completely unchecked (and therefore unsafe) downcast. In other words, you're just assuming that <code>getSelectedItem()</code> will return something that can be cast to an <code>Integer</code>. We'll return to this later to add some sanity checking and error handling.</p>\n\n<pre><code>int newOH = 0;\nint newOP = (int) combobox.getSelectedItem();\nint oldOH = (int) combobox1.getSelectedItem();\nint oldOP = prevOP;\n\nif(newOP &lt; oldOP){\n if(combobox.equals(pac_3OpCount)) {\n</code></pre>\n\n<p>I just picked this bit out because it contains a lot of your variable declarations. Your code was very, very difficult to decipher because of the names you chose for your variables. If you intend to ever work on a large scale project, you will likely be working with other people. And if you're working with other people, code readability is much, <em>much</em> more important than anything else. There's a common adage that goes something like \"A programmer's job is 10% development, 90% maintenance,\" and that's incredibly true. You'll find that even if you're the only one working on a project, you'll come back to your code and look at this and ask yourself \"...What in the <em>world</em> was I thinking here?\" Believe me, it happens more often than you think.</p>\n\n<p>Bottom line: pick good variable names to try to make your code self-documenting. Note that in the final version that I post below, you can pretty much know exactly what every line of code is trying to do just because I've chosen my variable and method names intuitively.</p>\n\n<p>Also, if you want to be really Java-esque, follow the naming conventions. No underscores in variable names (unless they're <code>public static final String CONSTANTS_LIKE_THIS</code>).</p>\n\n<pre><code>if(combobox.equals(pac_3OpCount)){\n oldPac3 = newOP;//We need to keep track of our count outside of the method.\n}\nelse if(combobox.equals(gemCOpCount)){\n oldGemC = newOP;\n}\nelse if(combobox.equals(gemtOpCount)){\n oldGemT = newOP;\n}\n</code></pre>\n\n<p>Do you see that this bit of code appears twice in your method? It looks like you copied and pasted it. A good rule of thumb is that if you ever hit CTRL+C and CTRL+V in succession, you are probably doing something the hard way. If logic is repeated explicitly like this, it's a sign of bad design. Either it should be refactored or the repeated logic should be encapsulated in its own, separate method. I'll explain what I did with this later.</p>\n\n<pre><code>combobox1.setSelectedItem(newOH);\nif(newOH &lt; 0){//You cannot set selected item to a jcombobox with a negative number so in all cases where newOH is less than zero we simply set the selected item to 0.\n combobox1.setSelectedItem(0);\n}\n</code></pre>\n\n<p>Here you are attempting to do some error handling, which is good. In your comment you say \"You cannot set selected item [in] a [JComboBox] with a negative number\". And that's very true. But notice that you already do so <em>before</em> you perform your error check. First you call <code>combobox1.setSelectedItem(newOH)</code> and <em>then</em> you check to see if <code>newOH</code> is less than zero. But at that point, your code has already broken. Always check for valid data before doing anything else with it.</p>\n\n<p>Now I'll show you step-by-step how I refactored your code and present you with the final version at the end.</p>\n\n<pre><code>private JComboBox PAC3OperationalBox = new JComboBox();\nprivate JComboBox GEMCOperationalBox = new JComboBox();\nprivate JComboBox GEMTOperationalBox = new JComboBox();\nprivate JComboBox PAC3AdjustmentBox = new JComboBox();\nprivate JComboBox GEMCAdjustmentBox = new JComboBox();\nprivate JComboBox GEMTAdjustmentBox = new JComboBox();\n</code></pre>\n\n<p>Notice right away how my variable names tell you <em>exactly</em> what they represent. It's very easy to know what I intend each one to hold. If I had just named them <code>comboBox1</code>, <code>comboBox2</code>, etc., or something even more arcane like <code>pacOPold</code>, it would be much harder to understand. Java is by nature a verbose language which encourages explicit names for things.</p>\n\n<pre><code>public enum Missile {\n\n PAC_3, GEM_C, GEM_T;\n\n private int count = 0;\n private JComboBox operationalComboBox = null;\n private JComboBox adjustmentComboBox = null;\n</code></pre>\n\n<p>If you don't know <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow\">what an enum is</a>, now's a great time to learn. It's a very useful data structure which lets you define exactly what its potential values are. Here, it seems like your missile types are PAC-3s, GEM-Cs, and GEM-Ts, so that's what we have above.</p>\n\n<p>This is why object-oriented programming is so powerful. A missile is a thing in the world with its own properties, and so it is here. This enum may have been more appropriately named <code>MissileType</code>, depending on your preference, since technically it will hold values for multiple missiles, like the <code>count</code>. But having this data structure set up is what will let us completely rewrite your method in just five lines.</p>\n\n<pre><code> public void setComboBoxes(JComboBox operationalBox, JComboBox adjustmentBox) {\n operationalComboBox = operationalBox;\n adjustmentComboBox = adjustmentBox;\n }\n</code></pre>\n\n<p>This will let us set the <code>JComboBox</code> references for each missile type upon initialization. With these references, each missile will be able to calculate its values on its own.</p>\n\n<pre><code> public int getOperational() {\n return MissileUtils.getComboBoxValue(operationalComboBox);\n }\n</code></pre>\n\n<p>I created another class called <code>MissileUtils</code> which performs simple utility functions. I said that I wanted to do some sanity checking on your <code>(Integer) combobox.getSelectedItem()</code> statements, and here's the method where I do that (in MissileUtils`, not in the enum):</p>\n\n<pre><code>public static int getComboBoxValue(JComboBox comboBox) {\n Object selectedItem = comboBox.getSelectedItem();\n if(Integer.class.isInstance(selectedItem)) {\n return Integer.class.cast(selectedItem);\n }\n throw new IllegalArgumentException(\"The combo box must have a valid integer selected.\");\n}\n</code></pre>\n\n<p>It's okay if you don't know what all this does. Basically it's just checking to make sure that the <code>Object</code> returned by <code>getSelectedItem()</code> is actually an <code>Integer</code> before trying to downcast it. If it's not, if will throw an <code>IllegalArgumentException</code>.</p>\n\n<p>I might've rewritten this method like the following, but in my production environment I really dislike using <code>instanceof</code> and this kind of downcasting. (In general, it creates \"code smell\".)</p>\n\n<pre><code>if(selectedItem instanceof Integer) {\n return (Integer) selectedItem;\n}\n</code></pre>\n\n<p>... Now back in the <code>Missile</code> enum, we put all the pieces together to see your refactored method:</p>\n\n<pre><code>public void balance() {\n if(getOperational() &gt; count) {\n int adjustment = getAdjustment() - (getOperational() - count);\n adjustmentComboBox.setSelectedItem(adjustment &lt; 0 ? 0 : adjustment);\n }\n count = getAdjustment();\n}\n</code></pre>\n\n<p>It performs your check to see if the selected value from the first combo box is greater than the current count. If so, it adjusts the second combo box's selected item, incorporating your error handling (checking if the new value is less than 0) using the <a href=\"http://en.wikipedia.org/wiki/%3F%3a#Java\" rel=\"nofollow\">ternary operator</a>. Then we set the count to the second combo box's value, since we do so in all cases. (That was where you were copying and pasting that big block of code around.)</p>\n\n<pre><code>public MissileBalancer() {\n Missile.PAC_3.setComboBoxes(PAC3OperationalBox, PAC3AdjustmentBox);\n Missile.GEM_C.setComboBoxes(GEMCOperationalBox, GEMCAdjustmentBox);\n Missile.GEM_T.setComboBoxes(GEMTOperationalBox, GEMTAdjustmentBox);\n}\n</code></pre>\n\n<p>Here's simply where we give the <code>Missile</code> types references to the needed <code>JComboBox</code>es.</p>\n\n<pre><code>private void callTheNewBalanceMethod(Missile missileType) {\n missileType.balance();\n}\n</code></pre>\n\n<p>... And here's how you would call the new method.</p>\n\n<hr>\n\n<h1>AND IN THE END, THERE WAS CODE</h1>\n\n<pre><code>public class MissileBalancer {\n\n private JComboBox PAC3OperationalBox = new JComboBox();\n private JComboBox GEMCOperationalBox = new JComboBox();\n private JComboBox GEMTOperationalBox = new JComboBox();\n private JComboBox PAC3AdjustmentBox = new JComboBox();\n private JComboBox GEMCAdjustmentBox = new JComboBox();\n private JComboBox GEMTAdjustmentBox = new JComboBox();\n\n private static enum Missile {\n\n PAC_3, GEM_C, GEM_T;\n\n private int count = 0;\n private JComboBox operationalComboBox = null;\n private JComboBox adjustmentComboBox = null;\n\n public int getOperational() {\n return MissileUtils.getComboBoxValue(operationalComboBox);\n }\n\n public int getAdjustment() {\n return MissileUtils.getComboBoxValue(adjustmentComboBox);\n }\n\n public void setComboBoxes(JComboBox operationalBox, JComboBox adjustmentBox) {\n operationalComboBox = operationalBox;\n adjustmentComboBox = adjustmentBox;\n }\n\n public void balance() {\n if(getOperational() &gt; count) {\n int adjustment = getAdjustment() - (getOperational() - count);\n adjustmentComboBox.setSelectedItem(adjustment &lt; 0 ? 0 : adjustment);\n }\n count = getAdjustment();\n }\n }\n\n public MissileBalancer() {\n Missile.PAC_3.setComboBoxes(PAC3OperationalBox, PAC3AdjustmentBox);\n Missile.GEM_C.setComboBoxes(GEMCOperationalBox, GEMCAdjustmentBox);\n Missile.GEM_T.setComboBoxes(GEMTOperationalBox, GEMTAdjustmentBox);\n }\n\n public static int getComboBoxValue(JComboBox comboBox) {\n Object selectedItem = comboBox.getSelectedItem();\n if(Integer.class.isInstance(selectedItem)) {\n return Integer.class.cast(selectedItem);\n }\n throw new IllegalArgumentException(\"The combo box must have a valid integer selected.\");\n }\n\n private void callTheNewBalanceMethod(Missile missileType) {\n missileType.balance();\n }\n</code></pre>\n\n<hr>\n\n<p><em>Note: setting the combo boxes into the</em> <code>enum</code> <em>this way will cause issues if you intend to use the class with concurrency, but the solution for that is left as an exercise for the reader.</em> :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T23:18:10.317", "Id": "50847", "Score": "0", "body": "I want to sincerely thank you for taking the time to break this down and rebuild it. This is my first project and I'm doing it to help build my skill set. Your break down was really well put together. I'm probably 35% through my post-bacc in CS and it probably shows. When I wrote this code I knew it was garbage, but conceptually it was the best I could do at the moment. I don't know anyone in my life that could of done what you did so thats why I turned to the community. I'm not going to lie and say the rest of the code in my project is pristine, but nothing else is really this bad, thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T23:25:02.617", "Id": "50849", "Score": "0", "body": "I still am very appreciative for the breakdown, but I don't think the code you wrote does what mine does. I think the reason why is because of my poor naming conventions which lead you to believe that OH stood for adjustment when it stands for \"On Hand.\" Which is completely cool, cuz I still learned a lot from what you wrote and can see a lot of ways where I can make my code way more elegant. I certainly wasn't looking for anyone to do my work for me. So again sir, I thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T23:42:34.770", "Id": "50850", "Score": "0", "body": "@BobBarker No problem. Don't apologize for your work, either. Everyone starts somewhere, and it's not that bad. :) I think that regardless of the names the code does at least something close to what you were trying to accomplish, but without your entire class and the surrounding context it's hard to tell. Good luck!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T19:03:11.643", "Id": "31863", "ParentId": "31633", "Score": "2" } } ]
{ "AcceptedAnswerId": "31863", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T20:54:31.580", "Id": "31633", "Score": "5", "Tags": [ "java", "object-oriented" ], "Title": "Writing an effective method that reflects good OO design and fixes this broke method" }
31633
<p>My class <code>Person</code> has a number of boolean values: <code>isMoving</code>, <code>hasEyesOpen</code>, <code>isTired</code> etc. They are all independent and eight in total. These values are updated from elsewhere every second. The Person stores the last hundred historical values. My code seems to contain a lot of duplication. Is there a better way to write this class?</p> <p>The main reason that I think this is bad code is that any new boolean must be added in a lot of places.</p> <pre><code>class Person { protected ArrayList&lt;Boolean&gt; histIsMoving = new ArrayList&lt;Boolean&gt;(); protected ArrayList&lt;Boolean&gt; histHasEyesOpen = new ArrayList&lt;Boolean&gt;(); protected ArrayList&lt;Boolean&gt; histIsTired = new ArrayList&lt;Boolean&gt;(); // and 5 more ... public boolean getIsMoving() { return histIsMoving.get( histIsMoving.size()-1 ); } public boolean getHasEyesOpen() { return histHasEyesOpen.get( histHasEyesOpen.size()-1 ); } public boolean getIsTired() { return histIsTired.get( histIsTired.size()-1 ); } // and 5 more ... public ArrayList&lt;Boolean&gt; getHistIsMoving() { return histIsMoving; } public ArrayList&lt;Boolean&gt; getHistHasEyesOpen() { return histHasEyesOpen; } public ArrayList&lt;Boolean&gt; getHistIsTired() { return histIsTired; } // and 5 more ... public function update( boolean newIsMoving, boolean newHasEyesOpen, boolean newIsTired ) { histIsMoving.add( newIsMoving ); histHasEyesOpen.add( newHasEyesOpen ); histIsTired.add( newIsTired ); // and 5 more arguments } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T07:12:30.970", "Id": "50471", "Score": "0", "body": "@NarendraPathai I'm not really asking how my code is, but how this kind of problem should be solved. I just supplied my code in order to show some research effort and motivate the question." } ]
[ { "body": "<p>Well one way to do it is to create a class 'PersonProperty'. You could make it a generic class if you intend to have non-boolean properties in the Person. </p>\n\n<p>The PersonProperty class could have methods getValue(), setValue(), getHistory() and a way of being identified - e.g. getName() that returns 'isTired', 'hasEyes', etc. as string values. </p>\n\n<p>Your Person class could then keep a hashmap container that maps names to 'PersonProperty' objects and methods along the lines of 'getPropertyValue(String propertyName)', 'getPropertyNames()', 'updatePropertyValue(String name, boolean value)'</p>\n\n<pre><code>class PersonProperty {\n\n private ArrayList&lt;Boolean&gt; history = new ArrayList(100);\n private boolean value;\n private String name;\n\n PersonProperty(String name) {\n this.name = name;\n }\n\n public boolean getValue() { return value; }\n public String getName() { return name; }\n public List&lt;Boolean&gt; getHistory() { return Collections.unmodifiableList(history); } \n public void setValue(boolean value) { \n // change value, add to history, make sure history is 100 elements at most\n // a queue container would be more appropriate here by the way\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T07:29:17.033", "Id": "50472", "Score": "0", "body": "That's a neat idea!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T11:06:18.740", "Id": "50473", "Score": "0", "body": "How would you make this \"generic\" to allow for both booleans and doubles, for instance? By replacing all `boolean` with `Object`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T11:59:28.137", "Id": "50474", "Score": "0", "body": "No, I would declare it as a generic class - PersonProperty<T> - and replace all boolean with T - http://docs.oracle.com/javase/tutorial/extra/generics/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:32:27.357", "Id": "50475", "Score": "0", "body": "Would it be possible to make a HashMap of such PersonProperties?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T07:27:38.930", "Id": "31635", "ParentId": "31634", "Score": "3" } } ]
{ "AcceptedAnswerId": "31635", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T07:07:21.760", "Id": "31634", "Score": "-1", "Tags": [ "java" ], "Title": "How to organize these several lists of booleans to avoid code duplication?" }
31634
<p>When a user clicks the "Move Up" button, I grab the current elements <code>procedureid</code> and <code>sortOrder</code>. I then need for "Move Up" to grab the element above it and navigate down to a link inside the <code>&lt;p id="btncontainer"&gt;</code> element and grab that <code>procedureid</code> and <code>sortorder</code>.</p> <p>This seems like a mess to me and I am afraid it could break easily because of the many chains. Is there a way to simplify this?</p> <pre><code>// Sorting on the Process page 'Procedures' tab. jQuery(".btnMoveUp").click(function () { var object = jQuery(this); var currProcedureID = object.data('procedureid'); var currsortOrder = object.data('sortorder'); //var prevProcedureID = jQuery(this).parents('li.span6').prev().prev().css("background-color", "red"); var prevProcedureID = object.parents('li.span6').prev().prev().find('.btnContainer').find('a').data('procedureid'); var prevSortOrder = object.parents('li.span6').prev().prev().find('.btnContainer').find('a').data('sortorder'); console.log(currProcedureID); console.log(currsortOrder); console.log(prevProcedureID); console.log(prevSortOrder); }); </code></pre> <p>HTML:</p> <pre><code>&lt;ul class="commentlist"&gt; &lt;li class="span6"&gt; &lt;img src="../../Images/thumbs/doc.png" alt="" class="pull-left"&gt; &lt;div class="comment-info"&gt; &lt;h4&gt; &lt;a href="/MasterList/ViewProcedure/123"&gt; XYZ Process Server&lt;/a&gt;&lt;/h4&gt; &lt;h5&gt; &lt;small&gt;Owner: &lt;/small&gt;&lt;a href="javascript:void(0);"&gt;user&lt;/a&gt;&lt;/h5&gt; &lt;br&gt; &lt;p&gt; Enter Description for XYZ Process Server Procedure &lt;/p&gt; &lt;br&gt; &lt;p class="btnContainer"&gt; &lt;a href="javascript:void(0);" class="btn btn-small btnMoveDown" data-procedureid="123" data-sortorder="1"&gt;&lt;span class="iconfa-double-angle-down"&gt; &lt;/span&gt;Move Down&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;br style="clear: both;"&gt; &lt;li class="span6"&gt; &lt;img src="../../Images/thumbs/doc.png" alt="" class="pull-left"&gt; &lt;div class="comment-info"&gt; &lt;h4&gt; &lt;a href="/MasterList/ViewProcedure/122"&gt; XYZ2 Process Server&lt;/a&gt;&lt;/h4&gt; &lt;h5&gt; &lt;small&gt;Owner: &lt;/small&gt;&lt;a href="javascript:void(0);"&gt;user&lt;/a&gt;&lt;/h5&gt; &lt;br&gt; &lt;p&gt; Enter Description for XYZ1 Process Server Procedure &lt;/p&gt; &lt;br&gt; &lt;p class="btnContainer"&gt; &lt;a href="javascript:void(0);" class="btn btn-small btnMoveUp" data-procedureid="122" data-sortorder="2"&gt;&lt;span class="iconfa-double-angle-up icon-white"&gt; &lt;/span&gt;Move Up&lt;/a&gt; &lt;a href="javascript:void(0);" class="btn btn-small btnMoveDown" data-procedureid="122" data-sortorder="2"&gt;&lt;span class="iconfa-double-angle-down"&gt; &lt;/span&gt;Move Down&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;br style="clear: both;"&gt; &lt;li class="span6"&gt; &lt;img src="../../Images/thumbs/doc.png" alt="" class="pull-left"&gt; &lt;div class="comment-info"&gt; &lt;h4&gt; &lt;a href="/MasterList/ViewProcedure/121"&gt; XYZ3 Process Server&lt;/a&gt;&lt;/h4&gt; &lt;h5&gt; &lt;small&gt;Owner: &lt;/small&gt;&lt;a href="javascript:void(0);"&gt;user&lt;/a&gt;&lt;/h5&gt; &lt;br&gt; &lt;p&gt; Enter Description for XYZ3 Process Server Procedure &lt;/p&gt; &lt;br&gt; &lt;p class="btnContainer"&gt; &lt;a href="javascript:void(0);" class="btn btn-small btnMoveUp" data-procedureid="121" data-sortorder="3"&gt;&lt;span class="iconfa-double-angle-up icon-white"&gt; &lt;/span&gt;Move Up&lt;/a&gt; &lt;a href="javascript:void(0);" class="btn btn-small btnMoveDown" data-procedureid="121" data-sortorder="3"&gt;&lt;span class="iconfa-double-angle-down"&gt; &lt;/span&gt;Move Down&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;br style="clear: both;"&gt; &lt;li class="span6"&gt; &lt;img src="../../Images/thumbs/doc.png" alt="" class="pull-left"&gt; &lt;div class="comment-info"&gt; &lt;h4&gt; &lt;a href="/MasterList/ViewProcedure/120"&gt; XYZ4 Process Server&lt;/a&gt;&lt;/h4&gt; &lt;h5&gt; &lt;small&gt;Owner: &lt;/small&gt;&lt;a href="javascript:void(0);"&gt;user&lt;/a&gt;&lt;/h5&gt; &lt;br&gt; &lt;p&gt; Enter Description for XYZ4 Process Server Procedure &lt;/p&gt; &lt;br&gt; &lt;p class="btnContainer"&gt; &lt;a href="javascript:void(0);" class="btn btn-small btnMoveUp" data-procedureid="120" data-sortorder="4"&gt;&lt;span class="iconfa-double-angle-up icon-white"&gt; &lt;/span&gt;Move Up&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;br style="clear: both;"&gt; &lt;/ul&gt; </code></pre>
[]
[ { "body": "<p>Don't rely on <code>prev()</code> to traverse <code>&lt;br&gt;</code> tags and other strange code that isn't valid, as a <code>&lt;br&gt;</code> tag can't be a direct child of an UL.</p>\n\n<p>If you remove the <code>&lt;br&gt;</code> tag you can use <code>prev('li')</code> to get the previous li :</p>\n\n<pre><code>jQuery(function($) {\n $(\".btnMoveUp\").on('click', function () {\n var $this = $(this),\n currProcedureID = $this.data('procedureid'),\n currsortOrder = $this.data('sortorder'),\n $prevLi = $this.prev('li'),\n $anchor = $prevLi.find('.btnContainer a'),\n prevProcedureID = $anchor.data('procedureid'),\n prevSortOrder = $anchor.data('sortorder');\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:13:51.273", "Id": "50477", "Score": "0", "body": "I tried to move the `<br>` outside of the UL but this allowed the LI elements to appear side to side. So this is something in the template I will have to fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:20:35.703", "Id": "50478", "Score": "0", "body": "Are you sure `prev` works like that? http://jsfiddle.net/itay1989/bL4Qv/1/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:25:01.527", "Id": "50479", "Score": "0", "body": "Alright I moved the br tag outside the UL and updated it and this is working, I like this method and the method @Itay provided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:38:47.063", "Id": "50480", "Score": "0", "body": "@Itay - yes, `prev()` works like that, but the selector passed to prev is a filter, it only traverses to the **first** previous element and checks if that element matches the filter, it does not jump elements if you pass a selector." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:39:58.083", "Id": "50481", "Score": "0", "body": "@JamesWilson - if removing the break makes the LI elements float side by side, you have CSS that makes them float side by side, as that is not the default behaviour." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:37:23.667", "Id": "50482", "Score": "0", "body": "Yeah I was able to find it and fix it. This works very nicely." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T20:58:38.750", "Id": "31638", "ParentId": "31636", "Score": "1" } } ]
{ "AcceptedAnswerId": "31638", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T20:47:08.187", "Id": "31636", "Score": "-1", "Tags": [ "javascript", "jquery", "html" ], "Title": "Grabbing elements with a \"Move Up\" button" }
31636
<p>I've just started learning Java and went to compare my finished product to some others on Stack Overflow. Is there a reason why mine is "simple" and the others seem ridiculously hard to even understand (for me)? <a href="https://stackoverflow.com/questions/4138827/check-string-for-palindrome">Link to the other palindrome checker</a>.</p> <p>Can you just break it down for me (the good/bad/ugly of my code)? Constructive criticism would be great as I'm very good at memorizing the books I use to learn Java. I just have a hard time implementing them and it's always good to have a second opinion.</p> <pre><code>public class Checker { public static void main(String [] args) { String original = "hannah"; String reversed = original; for (String part : original.split(" ")) { System.out.println(original); System.out.println(new StringBuilder(part).reverse().toString()); } System.out.print(original.equals(new StringBuilder(reversed).reverse().toString())); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T04:17:57.883", "Id": "50485", "Score": "0", "body": "Can you just break it down for me. The good/bad/ugly of my code? Constructive criticism would be great as I'm very good at memorizing the books I use to learn java I just have a hard time implementing them and its always good to have a second opinion. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T04:20:40.017", "Id": "50486", "Score": "0", "body": "Ah, okay. That's more clear. :-) I'm not a Java person, so someone else will have to look at this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T07:52:50.157", "Id": "50488", "Score": "1", "body": "In opposite to the 'other palindrome checker' you create a new reversed String and than compare them. The 'other palindrome checker' does not creates any new String and only reads each character once. Therefore the 'other palindrome checker' is likely to be faster and needs less memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T14:58:09.470", "Id": "50502", "Score": "0", "body": "I just want to point out that your solution is also the one that got the most votes in the stackoverflow post you linked above. It's always a good idea to read more than just the selected answer when consulting stackoverflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T00:43:21.760", "Id": "50525", "Score": "0", "body": "Yea, I did see that selected answer, however I was curious as to what made mine different than the original question. Like I said, I'm very new to this and was just curious. :)" } ]
[ { "body": "<p>The most misleading part of the code is this: <code>String reversed = original;</code> — <code>reversed</code> is not reversed at all! Let's get rid of that confusion right away. Also note a few minor points…</p>\n\n<pre><code>public class Checker\n{\n public static void main(String[] args) {\n // Consider using args instead of hard-coding your test case\n String original = \"hannah\";\n for (String part : original.split(\" \")) {\n // I think you meant to print part instead of original here...\n System.out.println(part);\n // System.out.println() implicitly calls .toString() on its argument\n System.out.println(new StringBuilder(part).reverse());\n }\n System.out.print(original.equals(new StringBuilder(original).reverse().toString()));\n }\n}\n</code></pre>\n\n<p>Get in the habit of splitting meaningful chunks of work into functions whenever possible.</p>\n\n<pre><code>public class Checker\n{\n private static String reverse(String s) {\n return new StringBuilder(s).reverse().toString();\n }\n\n public static boolean isPalindrome(String original) {\n return original.equals(reverse(original));\n }\n\n public static void main(String[] args) {\n String original = \"hannah\";\n for (String word : original.split(\" \")) {\n System.out.println(word);\n System.out.println(reverse(word));\n }\n System.out.print(isPalindrome(original));\n }\n}\n</code></pre>\n\n<p>That's more readable now, isn't it?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T00:40:41.013", "Id": "50524", "Score": "0", "body": "Thank you 200_success. I was just going by the default \"public static void main(String [] args) {\" that shows in my book as this was kind of straying away from what the book is teaching. I know farther on it goes into using a \"tester\" so you can test your code easier." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T09:55:48.197", "Id": "31647", "ParentId": "31641", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T03:27:58.383", "Id": "31641", "Score": "3", "Tags": [ "java", "beginner", "palindrome" ], "Title": "Palindrome Checker" }
31641
<p>Failing to get a solution to my problem from other people, I got tired of waiting and wrote this (rather rushed) Text class to deal with the text problems I've been having in Pygame. I wanted the text to update itself, so that it would be unnecessary to keep track of its original position. After playing a lot with it, I found this solution:</p> <pre><code>class Text(object): def __init__(self, value, size, color, left_orientation=False, font=None, x=0, y=0, top=None, bottom=None, left=None, right=None, centerx=None, centery=None): self._size = size self._color = color self._value = value self._font = pygame.font.Font(font, self._size) self.width, self.height = self._font.size(self._value) self.left_orientation = left_orientation self.image = self._create_surface() self.rect = self.image.get_rect() if x: self.rect.x = x if y: self.rect.y = y if top: self.rect.top = top if bottom: self.rect.bottom = bottom if left: self.rect.left = left if right: self.rect.right = right if centerx: self.rect.centerx = centerx if centery: self.rect.centery = centery def _create_surface(self): return self._font.render(self._value, True, self._color) def set_value(self, new_value): if new_value != self._value: self._value = new_value self.image = self._create_surface() new_rect = self.image.get_rect(x = self.rect.x, y = self.rect.y) if self.left_orientation: width_diff = new_rect.width - self.rect.width new_rect.x = self.rect.x - width_diff self.rect = new_rect def set_position(self, x_or_x_and_y, y=None): if y != None: self.rect.x = x_or_x_and_y self.rect.y = y else: self.rect.x = x_or_x_and_y[0] self.rect.y = x_or_x_and_y[1] </code></pre> <p>So, if a text is supposed to increase to the left, all that I have to do is initialize a Text object with the <code>left_orientation</code> parameter set to <code>True</code> and, whatever the rect is, it will update itself to remain at it's original position.</p> <p>Is this a good solution? If not, what would be a better one?</p>
[]
[ { "body": "<p>This is copied from <a href=\"https://codereview.stackexchange.com/a/31539/11728\">my answer</a> to your question \"<a href=\"https://codereview.stackexchange.com/q/31408/11728\">What about my Pong game?</a>\".</p>\n\n<ol>\n<li><p>The <code>Text._size</code> member is only used to create the font, so there is no need to store it in the instance.</p></li>\n<li><p>Why not make <code>Text</code> a subclass of <code>pygame.sprite.Sprite</code> so that you can draw it using a sprite group?</p></li>\n<li><p>Lots of code is repeated betwen <code>Text.__init__</code> and <code>Text.set_value</code>. Why not have the former call the latter?</p></li>\n<li><p>The <code>Text.__init__</code> constructor takes many keyword arguments, which you then apply to <code>self.rect</code> like this:</p>\n\n<pre><code>if top: self.rect.top = top\n...\n</code></pre>\n\n<p>The first problem is that the test <code>if top:</code> means that you can't set <code>top</code> to zero. You should write something like this:</p>\n\n<pre><code>if top is not None: self.rect.top = top\n</code></pre>\n\n<p>But it would be much simpler to use Python's <code>**</code> keyword argument mechanism to take any number of keyword arguments, and pass them all to <a href=\"http://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect\" rel=\"nofollow noreferrer\"><code>Surface.get_rect</code></a>.</p></li>\n</ol>\n\n<p>Applying all these improvements yields the following:</p>\n\n<pre><code>class Text(pygame.sprite.Sprite):\n def __init__(self, text, size, color, font=None, **kwargs):\n super(Text, self).__init__()\n self.color = color\n self.font = pygame.font.Font(font, size)\n self.kwargs = kwargs\n self.set(text)\n\n def set(self, text):\n self.image = self.font.render(str(text), 1, self.color)\n self.rect = self.image.get_rect(**self.kwargs)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-25T15:47:18.197", "Id": "31796", "ParentId": "31642", "Score": "3" } } ]
{ "AcceptedAnswerId": "31796", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T07:31:12.177", "Id": "31642", "Score": "1", "Tags": [ "python", "pygame" ], "Title": "Text class for Pygame" }
31642
<p>This is a simple program that can tell you your zodiac sign (Chinese or Western) and the year in which you were born. I made this using very basic beginning knowledge with C++ as practice.</p> <p>I'm looking for some quick reviews on my code to see if there is anything I'm doing wrong or could be done better, making sure I'm not picking up any bad habits, and that it is easy to read.</p> <pre><code>#include &lt;iostream&gt; #include &lt;ctime&gt; int main() { int iZodiac; time_t rawtime; struct tm* timeinfo; time( &amp;rawtime ); timeinfo = localtime( &amp;rawtime ); std::cout &lt;&lt; "----Zodiac Program----" &lt;&lt; std::endl; do { std::cout &lt;&lt; "\nWhat would you like to do?" &lt;&lt; std::endl; std::cout &lt;&lt; "1.) Chinese Zodiac" &lt;&lt; std::endl; std::cout &lt;&lt; "2.) Western Zodiac" &lt;&lt; std::endl; std::cout &lt;&lt; "3.) Year Born" &lt;&lt; std::endl; std::cout &lt;&lt; "4.) Quit Program" &lt;&lt; std::endl; std::cin &gt;&gt; iZodiac; if (!std::cin || iZodiac &lt;= 0 || iZodiac &gt; 4) { std::cin.clear(); std::cin.ignore(1000, '\n'); std::cout &lt;&lt; "\nI'm sorry but that is not an option. Please answer 1, 2, 3 or 4." &lt;&lt; std::endl; } //Start Chinese Zodiac Option if (iZodiac == 1) { int iCbirth; int iCzodiac; while ((std::cout &lt;&lt; "\nEnter year born." &lt;&lt; std::endl) &amp;&amp; !(std::cin &gt;&gt; iCbirth)) { std::cout &lt;&lt; "\nI'm sorry but that is an invalid answer. Please answer using numbers." &lt;&lt; std::endl; std::cin.clear(); std::cin.ignore(1000, '\n'); } iCzodiac = iCbirth-((iCbirth/12)*12); if (iCzodiac == 0){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Monkey." &lt;&lt; std::endl; } else if (iCzodiac == 1){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Rooster." &lt;&lt; std::endl; } else if (iCzodiac == 2){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Dog." &lt;&lt; std::endl; } else if (iCzodiac == 3){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Pig." &lt;&lt; std::endl; } else if (iCzodiac == 4){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Rat." &lt;&lt; std::endl; } else if (iCzodiac == 5){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Ox." &lt;&lt; std::endl; } else if (iCzodiac == 6){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Tiger." &lt;&lt; std::endl; } else if (iCzodiac == 7){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Rabbit." &lt;&lt; std::endl; } else if (iCzodiac == 8){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Dragon." &lt;&lt; std::endl; } else if (iCzodiac == 9){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Snake." &lt;&lt; std::endl; } else if (iCzodiac == 10){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Horse." &lt;&lt; std::endl; } else if (iCzodiac == 11){ std::cout &lt;&lt; "\nYour Chinese Zodiac is the Goat." &lt;&lt; std::endl; } } //End Chinese Zodiac Option //Start Western Zodiac Option if (iZodiac == 2) { int iMonth; int iDay; while ((std::cout &lt;&lt; "\nEnter month born." &lt;&lt; std::endl) &amp;&amp; !(std::cin &gt;&gt; iMonth)) { std::cout &lt;&lt; "\nI'm sorry but that is an invalid answer. Please answer using numbers." &lt;&lt; std::endl; std::cin.clear(); std::cin.ignore(1000, '\n'); } while ((std::cout &lt;&lt; "\nEnter day born." &lt;&lt; std::endl) &amp;&amp; !(std::cin &gt;&gt; iDay)) { std::cout &lt;&lt; "\nI'm sorry but that is an invalid answer. Please answer using numbers." &lt;&lt; std::endl; std::cin.clear(); std::cin.ignore(1000, '\n'); } if (iMonth == 12) { if (iDay &gt;= 22) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Capricorn." &lt;&lt; std::endl; } else if (iDay &lt;= 21) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Sagittarius." &lt;&lt; std::endl; } } else if (iMonth == 11) { if (iDay &gt;= 23) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Sagittarius." &lt;&lt; std::endl; } else if (iDay &lt;= 22) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Scorpio." &lt;&lt;std::endl; } } else if (iMonth == 10) { if (iDay &gt;= 23) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Scorpio." &lt;&lt; std::endl; } else if (iDay &lt;= 22) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Libra." &lt;&lt;std::endl; } } else if (iMonth == 9) { if (iDay &gt;= 23) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Libra." &lt;&lt; std::endl; } else if (iDay &lt;= 22) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Virgo." &lt;&lt;std::endl; } } else if (iMonth == 8) { if (iDay &gt;= 23) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Virgo." &lt;&lt; std::endl; } else if (iDay &lt;= 22) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Leo." &lt;&lt;std::endl; } } else if (iMonth == 7) { if (iDay &gt;= 23) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Leo." &lt;&lt; std::endl; } else if (iDay &lt;= 22) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Cancer." &lt;&lt;std::endl; } } else if (iMonth == 6) { if (iDay &gt;= 22) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Cancer." &lt;&lt; std::endl; } else if (iDay &lt;= 21) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Gemini." &lt;&lt;std::endl; } } else if (iMonth == 5) { if (iDay &gt;= 22) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Gemini." &lt;&lt; std::endl; } else if (iDay &lt;= 21) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Taurus." &lt;&lt;std::endl; } } else if (iMonth == 4) { if (iDay &gt;= 21) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Taurus." &lt;&lt; std::endl; } else if (iDay &lt;= 20) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Aries." &lt;&lt;std::endl; } } else if (iMonth == 3) { if (iDay &gt;= 21) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Aries." &lt;&lt; std::endl; } else if (iDay &lt;= 20) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Pisces." &lt;&lt;std::endl; } } else if (iMonth == 2) { if (iDay &gt;= 20) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Pisces." &lt;&lt; std::endl; } else if (iDay &lt;= 19) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Aquarius." &lt;&lt;std::endl; } } else if (iMonth == 1) { if (iDay &gt;= 21) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Aquarius." &lt;&lt; std::endl; } else if (iDay &lt;= 20) { std::cout &lt;&lt; "\nYour Western Zodiac sign is Capricorn." &lt;&lt;std::endl; } } } //End Western Zodiac Option //Start Year Born Option if (iZodiac == 3) { int iAge; int iYear; int iBirth; iYear = (timeinfo-&gt;tm_year + 1900); while ((std::cout &lt;&lt; "\nEnter your current age." &lt;&lt; std::endl) &amp;&amp; !(std::cin &gt;&gt; iAge)) { std::cout &lt;&lt; "\nI'm sorry but that is an invalid answer. Please answer using numbers." &lt;&lt; std::endl; std::cin.clear(); std::cin.ignore(1000, '\n'); } iBirth = iYear-iAge; std::cout &lt;&lt; "\nYou were born in the year " &lt;&lt; iBirth &lt;&lt; std::endl; } //End Year Born Option } while (iZodiac != 4); std::cout &lt;&lt; "\nThank you for playing, Good bye." &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T13:54:34.290", "Id": "50643", "Score": "0", "body": "Thank you everyone for all your help. This has given me a good bit to study, some of which I need to become more knowledgeable on, (such as functions & loops) others I need to learn still.(like switchs, strings, and that the get thing) There is lots mentioned that I don't understand reasons for, but those questions are easily cleared up through so googling. Anywho it may be a while and I can't promise it will be the same program but I look forward to coming back with something better for everyone. Also need to better learn how to use this forum... @jamal" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T14:04:59.150", "Id": "50644", "Score": "0", "body": "You're welcome! Good luck with your studying. These are some common mistakes for newcomers to the language, so it's great that you're willing to learn about and maintain good habits. Feel free to come back here whenever. Moreover, you may accept one of these answers *if* you've received satisfying reviews. It's entirely optional, though." } ]
[ { "body": "<ul>\n<li><p>Since this is C++, prefer <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::size_t</code></a> over C-like <code>size_t</code>. With <code>&lt;ctime&gt;</code>, <code>time_t</code> should also be <code>std::time_t</code>. Keep the <code>std::</code> consistent for all necessary aspects of the STL.</p></li>\n<li><p>Declare/initialize variables as close in scope as possible:</p>\n\n<pre><code>int iZodiac;\nstd::cin &gt;&gt; iZodiac;\n</code></pre>\n\n<p>This is also an example of Hungarian notation, which is generally discouraged. Just name it <code>zodiac</code> or something similar.</p></li>\n<li><p>There's no need for this within the <code>while</code> condition:</p>\n\n<pre><code>while ((std::cout &lt;&lt; \"\\nEnter your current age.\" &lt;&lt; std::endl) /* ... */)\n</code></pre>\n\n<p>As this isn't a condition, it should just go inside the loop body. The <code>std::cin</code> <em>should</em> stay, as you're needing to verify that the input was valid.</p></li>\n<li><p>This program should <em>definitely</em> be modular. In other words, it should utilize more functions. The <code>do</code>-<code>while</code> loop extends through all of <code>main()</code>, reducing readability and maintainability.</p>\n\n<p>For instance, the menu and input validation should stay in <code>main()</code>. <em>That</em> can be in a <code>do</code>-<code>while</code> loop by itself. This will prevent the program from shifting control to the other functions until the user selects an appropriate menu choice. Each choice could could a function (except \"quit,\" which will just fall back to the end of <code>main()</code> for program termination).</p></li>\n<li><p>All the conditional blocks are confusing to navigate. One option, although not the best but simple, is with a <em>concise</em> <code>switch</code> statement. For instance, you could put this into a function that receives <code>zodiac</code> and returns the corresponding animal string (not the entire message).</p>\n\n<p>This uses <a href=\"http://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\"><code>std::string</code></a>, which is the C++ STL implementation of a <code>char</code> array with added features and optimization. I recommend that you become familiar with it.</p>\n\n<pre><code>int zodiac = birth-((birth/12)*12);\n\nstd::cout &lt;&lt; \"Your Chinese Zodiac is \" &lt;&lt; getChineseSign(zodiac);\n\nstd::string getChineseSign(const int zodiac)\n{\n switch (zodiac)\n {\n case 0 : return \"Monkey\";\n case 1 : return \"Rooster\";\n // ...\n case 10: return \"Horse\";\n case 11: return \"Goat\";\n\n // throw an exception if not 0-11\n // include &lt;stdexcept&gt; to use this\n default: throw std::logic_error(\"unknown zodiac\");\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T18:43:22.750", "Id": "50510", "Score": "0", "body": "Great, only that I'd advise to use some kind of map (not necessarily a map DS) in place of the switch block. Long switches are ugly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T18:46:01.543", "Id": "50511", "Score": "0", "body": "@busy_wait: I was actually just thinking of a map at first, but wasn't sure how exactly it would be done here. I'd say a `switch` could be a *start*, as long as it shortens some of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T23:43:49.600", "Id": "50517", "Score": "0", "body": "Actually, the division and multiplication won't cancel each other out as it'll be an integer division. Its a convoluted way to calculate the modulus." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T23:47:56.473", "Id": "50518", "Score": "0", "body": "@WinstonEwert: Hm. I never knew about that. I suppose it was obvious since there were no comments explaining it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-22T14:42:56.220", "Id": "338880", "Score": "0", "body": "`'\\n'` will still cause a flush just the same as `std::endl` as the output is to an interactive device. See https://stackoverflow.com/a/25569849/2498188." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T16:59:57.503", "Id": "31655", "ParentId": "31652", "Score": "14" } }, { "body": "<p>I don't have much to say after Jamal's comment. </p>\n\n<p>However, I just wanted to point out that some tests are not useful. All the logic around Western Zodia sign could be simplified and probably should be extracted in a function on its own.</p>\n\n<pre><code> switch(iMonth) {\n case 12: return (iDay &gt;= 22) ? \"Capricorn\" : \"Sagittarius\";\n case 11: return (iDay &gt;= 23) ? \"Sagittarius\" : \"Scorpio\";\n case 10: return (iDay &gt;= 23) ? \"Scorpio\" : \"Libra\";\n case 9: return (iDay &gt;= 23) ? \"Libra\" : \"Virgo\";\n case 8: return (iDay &gt;= 23) ? \"Virgo\" : \"Leo\";\n case 7: return (iDay &gt;= 23) ? \"Leo\" : \"Cancer\";\n case 6: return (iDay &gt;= 22) ? \"Cancer\" : \"Gemini\";\n case 5: return (iDay &gt;= 22) ? \"Gemini\" : \"Taurus\";\n case 4: return (iDay &gt;= 21) ? \"Taurus\" : \"Aries\";\n case 3: return (iDay &gt;= 21) ? \"Aries\" : \"Pisces\";\n case 2: return (iDay &gt;= 20) ? \"Pisces\" : \"Aquarius\";\n case 1: return (iDay &gt;= 21) ? \"Aquarius\" : \"Capricorn\";\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T00:25:43.100", "Id": "50521", "Score": "0", "body": "This is mostly why I based my `switch` example around the Chinese Zodiac in particular-- it's much simpler. As far as `switch` goes, this would probably be good enough. Surely there's a nicer way of doing both zodiacs, thinking back to @busy_wait's mentioning of a map." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T00:19:05.710", "Id": "31662", "ParentId": "31652", "Score": "4" } }, { "body": "<p>I would do the following 3 things.<br>\nThen I would come back and ask the question again.</p>\n\n<ol>\n<li><p>Modularize your code.<br>\nPut each zodiac variant into its own function.</p></li>\n<li><p>Remove repeated code.<br>\nAnything that is done repeatedly refactor to be only done once. Then the small amounts that are different are the bits you can concentrate on.</p>\n\n<pre><code> if (iCzodiac == 0){\n std::cout &lt;&lt; \"\\nYour Chinese Zodiac is the Monkey.\" &lt;&lt; std::endl;\n }\n else if (iCzodiac == 1){\n std::cout &lt;&lt; \"\\nYour Chinese Zodiac is the Rooster.\" &lt;&lt; std::endl;\n }\n .....\n\n// Can be made much easier to read as:\n\nstd::string zodiakAnimal = getZodiakAnimal(iCzodiac);\nstd::cout &lt;&lt; \"\\nYour Chinese Zodiac is the .\" &lt;&lt; zodiakAnimal &lt;&lt; \"\\n\";\n</code></pre></li>\n<li><p>Stop using Hungarian notation for your variables.</p>\n\n<pre><code>int iCzodiac; // Really. I can see it's an int by the type.\n\n// Prefer human readable names\nint chinese_zodiac;\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-23T16:20:17.660", "Id": "31694", "ParentId": "31652", "Score": "8" } }, { "body": "<p>Just as an aside to the good answers you have already been given:</p>\n\n<h1>Consider handling leap years</h1>\n\n<p>During a leap year the dates for the different zodiacs change.</p>\n\n<pre><code>bool leapyear = (year % 4 == 0) &amp;&amp; ((year % 100 != 0) || (year % 400 == 0)); \n</code></pre>\n\n<h1>Consider expressing your if zodiac in day of year</h1>\n\n<p>You are currently testing each of the zodiac signs for month and then day, giving you a total of 12*2 = 24 if statements. If you instead convert (month + day) into (day of year) you only need 12 statements.</p>\n\n<p>You can do something like:</p>\n\n<pre><code>int dayOfYear(int month, int day){\n // Ignores leap years\n static int daysUntilMonth[] = {0, // Jan 1st \n 31, // Feb 1st\n 31 + 28, // Mar 1st\n 59 + 31, // Apr 1st\n 90 + 30, // May 1st\n 120 + 31, // Jun 1st\n 151 + 30, // Jul 1st\n 181 + 31, // Aug 1st\n 212 + 31, // Sep 1st\n 243 + 30, // Oct 1st\n 273 + 31, // Nov 1st\n 304 + 30 // Dec 1st\n };\n if( month &lt; 1 || month &gt; 12){\n throw std::exception(\"Invalid month!\");\n }\n return daysUntilMonth[month - 1] + day;\n}\n</code></pre>\n\n<p>And then when determining which zodiac it is you can do something like this:</p>\n\n<pre><code>int day_year = dayOfYear(month, day);\nif(day_year &gt;= dayOfYear(12, 22)){\n // Capricorn\n} else if(day_year &gt;= dayOfYear(11, 23)){\n // Sagittarius\n} else if(day_year &gt;= dayOfYear(10, 23)){\n // Scorpio\n} .. // And so forth\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-22T15:11:05.370", "Id": "178529", "ParentId": "31652", "Score": "2" } } ]
{ "AcceptedAnswerId": "31655", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T15:41:30.133", "Id": "31652", "Score": "9", "Tags": [ "c++", "beginner", "datetime" ], "Title": "Simple zodiac sign program" }
31652
<p>I have the following code below and I am trying to improve it. How can I know if there is any limitations/drawbacks writing this way and why? Any possible error conditions? </p> <p>What can be improved on this code? Thoughts? Suggestions?</p> <pre><code>&lt;!DOCTYPE html &gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js&gt;&lt;/script&gt; &lt;script language="javascript"&gt; $(document).ready(function() { $("#submit").click(function (event) { // wire up this as an onclick event to the submit button. var searchTerm = $("#search").val(); // get the user-entered search term var URL = "http://api.flickr.com/services/feeds/photos_public.gne"; var ID = "25053835@N03"; var tags="&amp;tags="+ searchTerm; var tagmode="&amp;tagmode=any"; var jsonFormat = "&amp;format=json&amp;jsoncallback=?"; var ajaxURL= URL+"?id="+ID+tags+tagmode+jsonFormat; $.getJSON(ajaxURL,function(data){ $("h1").text(data.title); $.each(data.items, function(i,photo) { var photoHTML = "&lt;h4&gt;" +photo.tags + "&lt;/h4&gt;"; photoHTML += '&lt;a href="' + photo.link + '"&gt;'; photoHTML += '&lt;img src="' + photo.media.m + '"&gt;&lt;/a&gt;'; $('#photos').append(photoHTML).fadeIn(2000); }); }); }); }); //table cell selection $(document).ready(function(){ var getval = function(html) { alert(html); } $('#tblMain td').on('click', function(){ getval($(this).html()); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div align="center"&gt; &lt;h2&gt;flicker tag search&lt;/h2&gt; &lt;div&gt;Enter Search Term&lt;/div&gt; &lt;input type="text" id=search /&gt; &lt;input type="button" id=submit value="Search" /&gt; &lt;div id="photos"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Adding in a timeout to the JSONP request is a good idea as suggested by <a href=\"https://codereview.stackexchange.com/a/31663/22816\">Noval Agung Prayogo</a>.</p>\n\n<p>Other than that, there's not a lot to change...</p>\n\n<ul>\n<li><code>$(document).ready(function () { ... });</code> can be written as <code>$(function () { ... });</code>.</li>\n<li>Move everything into a single <code>$(function () { ... });</code></li>\n<li>Function expressions should end in a semicolon</li>\n</ul>\n\n<p>so here:</p>\n\n<pre><code>var getval = function(html) {\n alert(html);\n} // &lt;-- there should be a semicolon here.\n</code></pre>\n\n<p>You may also want to consider having a function to create your ajaxUrl variable so that it can be reused elsewhere if you need to.</p>\n\n<p>E.G.</p>\n\n<pre><code>// wrap in an immediately invoked function expressions (IIFE) passing in window\n// (the global object in a browser).\n(function (w) {\n \"use strict\";\n\n w.ns = {}; // ns will be used a namespace to avoid polluting global scope.\n w.ns.flickr = {};\n\n w.ns.flickr.generateUrl = (function () {\n // These wont change so keep them as constants accessed via closures\n // in the returned function below.\n var URL = \"http://api.flickr.com/services/feeds/photos_public.gne\",\n ID = \"25053835@N03\";\n\n return function (tags, tagMode, format, callbackName) {\n // Use some defaults to simplify calling in the simplest case.\n tagMode = tagMode || 'any';\n format = format || 'json';\n callbackName = callbackName || '?';\n\n return URL + '?id=' + ID + \n '&amp;tags=' + tags + \n '&amp;tagmode=' + tagMode + \n '&amp;format=' + format + \n '&amp;jsoncallback=' + callbackName;\n };\n }());\n}(window));\n</code></pre>\n\n<p>Then in your code you can just call: </p>\n\n<pre><code>ns.flickr.generateUrl($(\"#search\").val());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T09:36:01.530", "Id": "50544", "Score": "0", "body": "JS doesn't need semicolons. they are optional. See: http://davidwalsh.name/javascript-semicolons and http://www.codecademy.com/blog/78-your-guide-to-semicolons-in-javascript . But +1 for good code example" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T10:02:14.363", "Id": "50546", "Score": "0", "body": "@Pinoniq - Semicolons are optional in that the JS compiler is able to figure out where they should go most of the time. However, this can often lead to hard to trace bugs and unexpected behaviour. For safety's sake, most people agree that it's in your best interest to always include the semicolons. e.g. both http://jshint.com and http://jslint.com will complain about missing semicolons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T10:12:44.723", "Id": "50547", "Score": "0", "body": "You sum up my point :) semi colons are a best practice. I just wanted to point out that they are not required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-28T13:26:16.897", "Id": "51014", "Score": "0", "body": "@RobH - Thanks looks lot cleaner. I have one question, I noticed you have something called (window) at teh end of the function. Could you explain on that and why you took that approach?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T05:21:56.227", "Id": "31670", "ParentId": "31654", "Score": "2" } }, { "body": "<ul>\n<li>Put your JavaScript into a separate *.js file. Avoid mixing HTML, CSS, and JavaScript.</li>\n<li>Move your JavaScript out of and just before , so that JavaScript's blocking nature does not prevent the HTML from loading, if there's an exception</li>\n<li>Use <a href=\"http://www.jshint.com/\" rel=\"nofollow\">JSHint</a></li>\n<li>Use functions with names instead of anonymous functions as event handlers. This improves readability, makes debugging easier and allows for testing and reuse of the event handler.</li>\n</ul>\n\n<p>These are just a few improvements, that won't necessarily make your code run better, but they do improve maintainability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T08:15:41.880", "Id": "31676", "ParentId": "31654", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T16:29:38.410", "Id": "31654", "Score": "3", "Tags": [ "javascript", "jquery", "html", "image", "ajax" ], "Title": "Flickr tag search" }
31654