body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>The following bit of code requires a <code>string.maketrans</code> table that is only used inside a single function.</p> <p>I have written three versions of the program that place the table at different locations in the code. The differing placement of the table results in quite varying performance in the creation of <code>DNA</code> instances and calls to the <code>to_rna</code> method.</p> <p>So, which one of these variants is preferable? Or is there even a different, better solution?</p> <p>Version 1:</p> <pre><code>from string import maketrans DNA_RNA_TRANSLATION_TABLE = maketrans('GCTA', 'CGAU') class DNA(object): """Represent a strand of DNA.""" def __init__(self, dna_string): self.dna_string = dna_string def to_rna(self): """Return the RNA complement of the DNA strand.""" return self.dna_string.translate(DNA_RNA_TRANSLATION_TABLE) </code></pre> <p>Version 2:</p> <pre><code>from string import maketrans class DNA(object): """Represent a strand of DNA.""" __rna_translation_table = maketrans('GCTA', 'CGAU') def __init__(self, dna_string): self.dna_string = dna_string def to_rna(self): """Return the RNA complement of the DNA strand.""" return self.dna_string.translate(self.__rna_translation_table) </code></pre> <p>Version 3:</p> <pre><code>from string import maketrans class DNA(object): """Represent a strand of DNA.""" def __init__(self, dna_string): self.dna_string = dna_string def to_rna(self): """Return the RNA complement of the DNA strand.""" translation_table = maketrans('GCTA', 'CGAU') return self.dna_string.translate(translation_table) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T15:37:44.693", "Id": "76495", "Score": "2", "body": "As it stands, this post isn't asking for code to be reviewed, and could be closed as primarily opinion-based. You could remove versions 2 and 3, and ask for version 1 to be peer reviewed, mentioning your concern with the placement of `maketrans`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T16:14:07.127", "Id": "76504", "Score": "1", "body": "@Mat'sMug: I get your point. I've added a sentence to make clear that performance, too, is an important aspect in this problem. Yet I don't quite see how the provision of three basic options would make a review of the problem impossible?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T16:24:58.277", "Id": "76507", "Score": "5", "body": "@simon CodeReview is (often) about applying best practices to code, not deciding what those best practices are (which is on topic on [programmers.se]. It is a subtle, but important difference" } ]
[ { "body": "<p>I will answer your question in an unexpected way : the better solution is, as far as I can tell, much more straightforward than what you are doing.</p>\n\n<p>Indeed, <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\">you don't need a class</a> : your class has an <code>__init__</code> and a single method <code>to_rna</code>, it might as well be a single function.</p>\n\n<pre><code>from string import maketrans\n\ndef dna_to_rna(dna_string):\n \"\"\"Return the RNA complement of the DNA strand.\"\"\"\n return dna_string.translate(maketrans('GCTA', 'CGAU'))\n</code></pre>\n\n<p>I think see this the neatest solution. Then if on only want to create the table only once for performance reason, you can put it a variable outside the function but it's probably not needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:25:11.320", "Id": "76713", "Score": "3", "body": "And if performance is the concern, consider caching the maketrans as a default value for an extra parameter to the function. That makes it both a local variable (fast) and customizable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T22:07:39.280", "Id": "77686", "Score": "0", "body": "Thanks for your answer, @Josay! You're absolutely right that using a class here is absolutely unnecessary. The only reason I did it anyway was because it was specified in the test for the exercise that I wrote this code for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:45:05.647", "Id": "78334", "Score": "0", "body": "Your \"you don't need a class\" link was both enlightening and amusing - thank you!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T09:37:22.453", "Id": "44241", "ParentId": "44164", "Score": "6" } }, { "body": "<h1>Make the table local</h1>\n\n<p>See Michael Urman's comment on <a href=\"https://codereview.stackexchange.com/a/44241/37331\">Josay's answer</a>. For both optimisation and readability it is beneficial to make <code>translation_table</code> local to the <code>to_rna</code> object method. In your version 1 it is a global variable, in your version 2 it is a class attribute, and in your version 3 it is a local variable but it is created from scratch each time the function is called. Global variables take longer to look up than class attributes, which take longer to look up than local variables. In this particular case I would expect the speed up due to using a local variable to be small since considerably more time will be taken up using the table than initially looking up the variable that holds it (except for very short DNA strands...).</p>\n\n<p>What will make a big difference is not having to recreate the table every time you call the method. For this reason I expect you are currently seeing approaches 1 and 2 running faster than approach 3. However, approach 3 keeps the definition of the table within the method, so it can easily be seen by anyone looking at that method, and doesn't need to be looked at by anyone not focussed on that method. This makes it more readable for everyone involved.</p>\n\n<p>In this case it can be both readable and fast. You can keep the table definition within the method <strong>and</strong> ensure it is only created once (when the method is first defined) by making it an extra parameter with a default value, as Michael suggests.</p>\n\n<p>Since the table is intended to be set up once and never changed, you may also want to call it <code>TRANSLATION_TABLE</code> in all upper case, which is the convention for constants in Python.</p>\n\n<h1>Example object method</h1>\n\n<pre><code>def to_rna(self, TRANSLATION_TABLE=maketrans('GCTA', 'CGAU')):\n \"\"\"Return the RNA complement of the DNA strand.\"\"\"\n return self.dna_string.translate(TRANSLATION_TABLE)\n</code></pre>\n\n<p>In general this also makes it customisable (you can feed in a different table if you ever want to use the same method for a different type of translation). Even if the DNA to RNA translation is all you are likely to use this method for, this approach is still worthwhile for the combination of readability and speed. In this case the upper case table name makes it clear to other programmers that you do not expect the function to be customised in practice.</p>\n\n<p>This approach will work equally well whether you take <a href=\"https://codereview.stackexchange.com/a/44241/37331\">Josay's advice</a> of not using a class, or end up adding extra features and needing a class after all.</p>\n\n<h1>Example function without a class</h1>\n\n<pre><code>def dna_to_rna(dna_string, TRANSLATION_TABLE=maketrans('GCTA', 'CGAU')):\n \"\"\"Return the RNA complement of the DNA strand.\"\"\"\n return dna_string.translate(TRANSLATION_TABLE)\n</code></pre>\n\n<hr>\n\n<h1>EDIT: The numbers: comparing timings</h1>\n\n<p>As Gareth Rees comments below, this explanation isn't reliable without measurement. So I ran the 4 versions and the timings were not quite what I expected...</p>\n\n<p>Note that I'm using Python 3, so instead of <code>from string import maketrans</code> I'm just using <code>str.maketrans</code>. These timings should be measured again if you are using Python 2.</p>\n\n<p>First I ran each of the 4 versions (1 to 3 from the question, plus my version), creating an object of the class and calling <code>to_rna</code> 100,000,000 times. I used a null string to create the object as it is only the lookup of the table constant I was interested in measuring. As expected, with the default local parameter giving minimum lookup overhead, version 4 is the fastest for calling <strong>once the object is created</strong>.</p>\n\n<pre>\nFile to_rna cumulative total running time\nVersion1 69.741 84.363 154.089\nVersion2 78.881 159.077 159.077\nVersion3 136.938 262.078 366.644\nVersion4 64.813 79.246 153.369\n</pre>\n\n<p>The table shows results for the following code added to each class definition file:</p>\n\n<pre><code>def lots_of_calls():\n test = DNA('')\n for i in range(100000000):\n unused = test.to_rna()\n\nif __name__ == '__main__':\n lots_of_calls()\n</code></pre>\n\n<p>Timings were measured from the command line:</p>\n\n<pre><code>python -m cProfile version1.py\n</code></pre>\n\n<p>All times are in seconds.</p>\n\n<p>Contrary to my expectations, the global constant in version 1 was significantly faster than the class attribute in version 2. I don't have a reason for this, which just goes to show how important it is to measure rather than guess...</p>\n\n<p>Where I expected versions 1 and 2 to be the fastest was when creating a new object each time the translation is required, since the global constant and class attribute only need to be created once, and simply added by reference to each new object. Both versions 3 and 4 require constructing the table from scratch for each new object (or so I had presumed), so I expected them to be considerably slower in this case.</p>\n\n<p>I ran each of the 4 versions again, creating an object and calling <code>to_rna</code>, and repeating to create a new object 100,000,000 times, calling its <code>to_rna</code> method each time. To my surprise the time taken to run <code>__init__</code> was similar for all 4 versions, which meant that with its faster <code>to_rna</code> call, version 4 was still significantly faster than the others - the opposite of what I had expected.</p>\n\n<pre>\nFile init class to_rna cumulative to_rna total running time\nVersion1 58.671 81.608 98.953 390.794\nVersion2 60.628 87.671 104.809 394.145\nVersion3 60.452 147.612 284.876 616.561\nVersion4 59.039 74.342 91.624 383.731\n</pre>\n\n<p>The table shows results for the following code:</p>\n\n<pre><code>def lots_of_calls():\n for i in range(100000000):\n test = DNA('')\n unused = test.to_rna()\n\nif __name__ == '__main__':\n lots_of_calls()\n</code></pre>\n\n<p>So in both cases, version 1 is the fastest of the original 3 versions. However, version 4 is the fastest overall <strong>even when creating an object just for a single call</strong>.</p>\n\n<p>I don't know the reason for this. My best guess would be that the table for the default parameter is created once when the class is defined, and then just added as a reference in each new object that is created (rather than a new default table being created for each new object).</p>\n\n<p>If this is the case, it doesn't cause any conflict between objects. I created an object, overrode its table by calling <code>to_rna</code> with a table instead of zero arguments, and then called it again with zero arguments. The default table was used, so any override applies only to that particular call and that particular object instance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T21:53:20.167", "Id": "77685", "Score": "0", "body": "Thanks for the detailed answer! One thing I didn't understand is why the table is an object attribute in Version 3. If it's created inside the method, shouldn't it be a local variable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T22:30:11.903", "Id": "77688", "Score": "0", "body": "Thanks @simon you are correct - I have reworded my answer to reflect this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T23:09:47.250", "Id": "77696", "Score": "2", "body": "Speculation about timing is unsatisfying. Numbers, please!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T01:16:54.387", "Id": "77724", "Score": "0", "body": "@Gareth I agree. Thanks for raising this. Ideally I should time local/object/class/global variable look up. I believe Python searches the namespaces in [that order](http://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) so it finds them sooner the earlier they come in that ordering. However, I don't know if checking whether a parameter with a default has received an argument adds on enough time to cancel that out, so I accept that I'm not comparing like for like." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T01:18:36.900", "Id": "77725", "Score": "0", "body": "I still recommend using the parameter with a default because it is readable (keeps the description of the table with the only function that uses it). I don't feel the need to test that a default is quicker than creating the table from scratch in function each call, but I should make time to compare the timings for the global and class attribute cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T17:53:34.083", "Id": "78338", "Score": "0", "body": "@GarethRees I've added in some timings now, and they've highlighted my misconceptions. This will make me far less likely to guess in future, so thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T11:32:38.730", "Id": "78509", "Score": "1", "body": "You're welcome! There's really no substitute for measurement. (You might want to look at the [`timeit`](http://docs.python.org/3/library/timeit.html) module, which you could use to simplify your timing code.)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T00:19:02.457", "Id": "44480", "ParentId": "44164", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T15:30:58.303", "Id": "44164", "Score": "3", "Tags": [ "python", "performance", "constants" ], "Title": "Where should I place the constant?" }
44164
<p>I've been working on a 3D mathematical vector class which should be as streamlined as possible for use in numerical simulations. It will be used to model 3D-physical vectors.</p> <p>Here, 3D-vector should be taken in mathematical sense, meaning a tuple (a,b,c).</p> <p>I hoped to design it in a modern and fast way - but one is never perfect. So, I would be interested in some input from your side. Any tips for making this faster?</p> <pre><code>//threevector.h #ifndef threevector_h_ #define threevector_h_ #include &lt;fstream&gt; #include &lt;cmath&gt; #include &lt;array&gt; template &lt;class T&gt; class threevector { private: static const int dim = 3; //dimension of vector std::array&lt;T,dim&gt; container; public: //constructors and assignment threevector(const double a = 0, const double b = 0, const double c = 0): container({{a,b,c}}) {}; //standard constructor threevector(const threevector&amp; a): container(a.container) {}; //copy constructor // add once gcc 4.7 is used // threevector(threevector&amp;&amp; other): threevector() {swap(*this, other);} // move constructor threevector&amp; operator=(threevector rhs) //assignment { swap(*this, rhs); return *this; } void swap(threevector&amp; first, threevector&amp; second) {first.container.swap(second.container);} //operators threevector&amp; operator+=(const threevector&amp; rhs) { container[0] += rhs.container[0]; container[1] += rhs.container[1]; container[2] += rhs.container[2]; return *this; } threevector&amp; operator-=(const threevector&amp; rhs) { *this += -rhs; return *this; } threevector&amp; operator*=(const double rhs) //scalar multiplication assignment { container[0] *= rhs; container[1] *= rhs; container[2] *= rhs; return *this; } threevector&amp; operator/=(const double rhs) //scalar division assignment { *this *= 1./rhs; return *this; } threevector operator+() const //unary plus { threevector a(*this); return a; } threevector operator-() const //unary minus { threevector a(*this); a *= -1; return a; } T&amp; operator[](const int input) {return container[input];} //access operator const T&amp; operator[](const int input) const {return container[input];} // const access operator //utility functions double abs() const {return sqrt(container[0]*container[0]+container[1]*container[1]+ container[2]*container[2]);} double abs_sq() const {return pow(abs(),2);} void reset() { container[0] = 0; container[1] = 0; container[2] = 0;} }; //output operator template&lt;class T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const threevector&lt;T&gt;&amp; obj) { os &lt;&lt; std::fixed &lt;&lt; "(" &lt;&lt; obj[0] &lt;&lt; "," &lt;&lt; obj[1] &lt;&lt; "," &lt;&lt; obj[2] &lt;&lt; ")"; return os; } //addition operator template&lt;class T&gt; inline threevector&lt;T&gt; operator+(threevector&lt;T&gt; lhs, const threevector&lt;T&gt;&amp; rhs) { lhs += rhs; return lhs; } //subtraction operator template&lt;class T&gt; inline threevector&lt;T&gt; operator-(threevector&lt;T&gt; lhs, const threevector&lt;T&gt;&amp; rhs) { lhs -= rhs; return lhs; } //scalar product template&lt;class T&gt; inline double operator*(const threevector&lt;T&gt;&amp; lhs, const threevector&lt;T&gt;&amp; rhs) {return lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2];} //product with scalar template&lt;class T&gt; inline threevector&lt;T&gt; operator*(const double lhs, threevector&lt;T&gt; rhs) { rhs[0] *= lhs; rhs[1] *= lhs; rhs[2] *= lhs; return rhs; } //product with scalar template&lt;class T&gt; inline threevector&lt;T&gt; operator*(threevector&lt;T&gt; lhs, const double rhs){return rhs*lhs;} // scalar division template&lt;class T&gt; inline threevector&lt;T&gt; operator/(threevector&lt;T&gt; lhs, const double rhs){return lhs*(1./rhs);}; #endif </code></pre>
[]
[ { "body": "<p>Your design is a little bit confusing. You define your class as a template class, but just about everything takes and returns a <code>double</code>. Generally, you should try and be consistent: will this class work for any numeric-like <code>T</code>? Then make sure it has constructors that take a <code>T</code> instead of a <code>double</code>:</p>\n\n<pre><code>threevector(T a = T(), T b = T(), T c = T())\n</code></pre>\n\n<p>Similarly for the overloaded operators that multiply/divide by a scalar, and so on.</p>\n\n<p>The name <code>threevector</code> is awkward. At the least it should be <code>three_vector</code>, but that's still a little awkward. <code>vector_3d</code> is more of the \"standard\" name for this kind of thing.</p>\n\n<p>Your include guards should generally be in all-caps. This is because they are global in scope, and you want to do as much as possible to minimize the possibility of potential name clashes.</p>\n\n<pre><code>#ifndef threevector_h_ // should be THREE_VECTOR_H_\n#define threevector_h_ // or VECTOR_3D_H_\n</code></pre>\n\n<p>You have some semi-colons where they aren't needed:</p>\n\n<pre><code>threevector(const double a = 0, const double b = 0, const double c = 0):\ncontainer({{a,b,c}}) {}; //standard constructor\nthreevector(const threevector&amp; a): container(a.container) {}; // &lt;--- Not needed\n</code></pre>\n\n<p>Comments like <code>//standard constructor</code> are obvious and don't really need to be there. Further, your copy constructor and copy assignment operator are redundant; the compiler generated ones are sufficient. </p>\n\n<p>It's often easiest to write <code>operator+</code> (and <code>-</code>, <code>*</code> etc) in terms of <code>operator+=</code>:</p>\n\n<pre><code>vector_3d operator+(const vector_3d&amp; a, const vector_3d&amp; b)\n{\n vector_3d result(a);\n result += b;\n return result;\n}\n</code></pre>\n\n<p>For something this simple, it's unlikely you'll be able to speed it up much. The only potential that I can see is replacing the call to <code>pow()</code> in:</p>\n\n<pre><code>double abs_sq() const {return pow(abs(),2);}\n</code></pre>\n\n<p>with something like:</p>\n\n<pre><code>T abs_sq() const\n{\n const T ab = abs(); // abs() should also return a T\n return ab * ab;\n}\n</code></pre>\n\n<p>which avoids the overhead of a function call to <code>pow</code>. In practice, this is unlikely to make much of a difference, however.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T09:46:38.280", "Id": "76884", "Score": "0", "body": "\"Further, your copy constructor and copy assignment operator are redundant; the compiler generated ones are sufficient.\"\nAre you sure that the compiler knows about copy-and-swap?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:23:28.700", "Id": "76915", "Score": "1", "body": "In this case, it doesn't need to. You only really need to use copy-and-swap with a resource managing class. Your class doesn't manage any resources (that is, anything that is directly `new`ed), hence copy-and-swap is redundant." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T00:13:21.593", "Id": "44212", "ParentId": "44167", "Score": "6" } }, { "body": "<ul>\n<li><p>Many of these comments are pointless. They should only be needed if something is not obvious and needs explanation. There's no need for individual comments for each constructor and operator; these are already noticeable to those familiar with C++.</p></li>\n<li><p>There's no need for <code>inline</code> here. Code in headers are automatically <code>inline</code>, so this would apply to all the code here. Having it here anyway wouldn't cause a problem as the compiler could just remove it, but I'd remove them anyway.</p></li>\n<li><p><code>dim</code> could just be renamed to <code>dimensions</code>, so that you won't need a comment for it:</p>\n\n<pre><code>static const int dimensions = 3;\n</code></pre></li>\n<li><p>This is not too readable:</p>\n\n<pre><code>void swap(threevector&amp; first, threevector&amp; second) \n{first.container.swap(second.container);}\n</code></pre>\n\n<p>This would also reduce maintainability, especially if additional lines will need to be added. Using your existing curly brace style, you'll have this:</p>\n\n<pre><code>void swap(threevector&amp; first, threevector&amp; second) \n{\n first.container.swap(second.container);\n // now you can easily add additional lines\n}\n</code></pre>\n\n<p>I'd also recommend keeping this consistent throughout the code. You already use it some places (with the multi-line functions), but this should also be done with the single-line functions.</p></li>\n<li><p>For statements like these:</p>\n\n<pre><code>threevector&amp; operator-=(const threevector&amp; rhs) \n{\n *this += -rhs;\n return *this;\n}\n</code></pre>\n\n<p>you can make it a single line:</p>\n\n<pre><code>threevector&amp; operator-=(const threevector&amp; rhs) \n{\n return *this += -rhs;\n}\n</code></pre></li>\n<li><p>I'd use some parenthesis in the scalar product for clarity:</p>\n\n<pre><code>{\n return (lhs[0] * rhs[0]) + (lhs[1] * rhs[1]) + (lhs[2] * rhs[2]);\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T00:13:48.540", "Id": "44213", "ParentId": "44167", "Score": "5" } } ]
{ "AcceptedAnswerId": "44212", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T16:30:50.847", "Id": "44167", "Score": "11", "Tags": [ "c++", "performance", "c++11" ], "Title": "3D mathematical vector class" }
44167
<p>I'm new to Python and I'm wondering is there a way to streamline this clunky code I've written. Maybe a built-in function I've never come across before?</p> <p>I run through two lists of binary numbers and if the same number appears at the same index in list one and two, do x.</p> <p>So in the example below the number 1 appears at index 2 in both lists.</p> <pre><code>list1 = [0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] list2 = [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0] for position, binary in enumerate(list1): for placement, number in enumerate(list2): if position == placement and binary == 1 and binary == number: do x </code></pre>
[]
[ { "body": "<p>Your solution's time complexity is O(n<sup>2</sup>), which is far from optimal. Your lists contain 19 elements - so your solution performs an order of 361 operations. \nIn order to get a linear solution, you can simulate a \"<a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged &#39;c&#39;\" rel=\"tag\">c</a>-style\" <code>for</code> loop using <code>range</code>:</p>\n\n<pre><code>for i in range(len(list1)): # assuming the lists are of the same length\n if list1[i]==list2[i]:\n do x\n</code></pre>\n\n<p>Now the loop runs exactly 19 times - much better!</p>\n\n<p>Another thing: your code checks if <code>binary==1</code>. Is it what you want? If so, Python's equal operator can operate on three arguments, making it more readable:</p>\n\n<pre><code>for i in range(len(list1)): # assuming the lists are of the same length\n if list1[i]==list2[i]==1:\n do x\n</code></pre>\n\n<p>Lastly, you may want to represent a binary number using the most natural way - as a number. Aside from space consideration, most languages (including Python) have standard binary (often called <code>bitwise</code>) operations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T17:07:28.360", "Id": "76517", "Score": "0", "body": "It probably is what he wants.. Looks like he's ANDing everything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T17:10:12.140", "Id": "76519", "Score": "0", "body": "Yeah, but the description says \"same number\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T17:11:33.847", "Id": "76520", "Score": "0", "body": "Good point. I missed that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T17:00:10.003", "Id": "44171", "ParentId": "44168", "Score": "9" } }, { "body": "<p>Python has a neat built in called 'zip' which creates a pairwise list from multiple iterables. So you could do:</p>\n\n<pre><code>pairwise = zip (list1, list2)\nmatched_digits = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]\n</code></pre>\n\n<p>Which zips up the list and returns the indices of all the pairs which match</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:31:45.563", "Id": "44185", "ParentId": "44168", "Score": "5" } }, { "body": "<p>I would do it like this</p>\n\n<pre><code>for i,j in zip (list1, list2):\n if i == 1 and i == j:\n do(x)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:59:08.457", "Id": "44198", "ParentId": "44168", "Score": "2" } } ]
{ "AcceptedAnswerId": "44171", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T16:42:16.880", "Id": "44168", "Score": "8", "Tags": [ "python", "beginner", "python-2.x" ], "Title": "Streamlined for-loop for comparing two lists" }
44168
<p>Attached is a generic code I wrote to create an Excel file with x number of worksheets.</p> <p>The problem I am having is that it's pretty slow, like 5 seconds a sheet. It was my understanding that using a <code>for</code> loop when creating the tables was ideal, but the issue seems to be with tables containing over a thousand or so records... I still wouldn't think it should take this long.</p> <p>Any pointers would be appreciated. Also, if I am completely out in left field with this code let me know; up-to-date Excel code resources seem to be hard to find.</p> <pre><code>public static string Export(string excelFileName, string[] excelWorksheetName, string tableStyle, params System.Data.DataTable[] dt) { Application xls = new Application(); xls.SheetsInNewWorkbook = dt.Length; // Create our new excel application and add our workbooks/worksheets Workbooks workbooks = xls.Workbooks; Workbook workbook = workbooks.Add(); // Hide our excel object if it's visible. xls.Visible = false; // Turn off calculations if set to automatic; this can help prevent memory leaks. xls.Calculation = xls.Calculation == XlCalculation.xlCalculationAutomatic ? XlCalculation.xlCalculationManual : XlCalculation.xlCalculationManual; // Turn off screen updating so our export will process more quickly. xls.ScreenUpdating = false; // Create an excel table and fill it will our query table. int iterator = dt.Length - 1; for (int i = 0; i &lt;= iterator; i++) { // Turn off calculations if set to automatic; this can help prevent memory leaks. Worksheet worksheet = (Worksheet)xls.Worksheets[i + 1]; worksheet.Name = excelWorksheetName[i]; worksheet.Select(); if (dt[i].Rows.Count &gt; 0) { // Format this information as a table. Range tblRange = worksheet.get_Range("$A$1");//string.Format("$A$1", dt[i].Rows.Count + 1)); tblRange.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange, tblRange, System.Type.Missing, XlYesNoGuess.xlYes, System.Type.Missing).Name = excelWorksheetName[i]; tblRange.Select(); tblRange.Worksheet.ListObjects[excelWorksheetName[i]].TableStyle = tableStyle; // Create a row with our column headers. for (int column = 0; column &lt; dt[i].Columns.Count; column++) { worksheet.Cells[1, column + 1] = dt[i].Columns[column].ColumnName; } // Export our data table information to excel. for (int row = 0; row &lt; dt[i].Rows.Count; row++) { for (int column = 0; column &lt; dt[i].Columns.Count; column++) { worksheet.Cells[row + 2, column + 1] = (dt[i].Rows[row][column].ToString()); } } } // Freeze our column headers. xls.Application.Range["2:2"].Select(); xls.ActiveWindow.FreezePanes = true; xls.ActiveWindow.DisplayGridlines = false; // Auto fit our rows and columns. xls.Application.Cells.EntireColumn.AutoFit(); xls.Application.Cells.EntireRow.AutoFit(); // Select the first cell in the worksheet. xls.Application.Range["$A$2"].Select(); // Turn off alerts to prevent asking for 'overwrite existing' and 'save changes' messages. xls.DisplayAlerts = false; } string SaveFilePath = string.Format(@"{0}.xls", excelFileName); workbook.SaveAs(SaveFilePath, XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); workbook.Close(); // Release our resources. Marshal.ReleaseComObject(workbook); Marshal.ReleaseComObject(workbooks); Marshal.ReleaseComObject(xls); Marshal.FinalReleaseComObject(xls); return SaveFilePath; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:14:10.230", "Id": "76819", "Score": "2", "body": "You're using the old COM style interaction with the office application, so it's not surprising. Have you looked into dropping this and using the [OpenXML SDK?](http://msdn.microsoft.com/en-us/library/office/bb448854(v=office.15).aspx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T17:05:47.687", "Id": "77646", "Score": "2", "body": "Please don't edit the original code after is had been reviewed: see [Can I edit my own question to include suggested changes from answers?](http://meta.codereview.stackexchange.com/a/1483/34757) for details." } ]
[ { "body": "<h2>Comments</h2>\n<p>Your code has way too many comments, mostly redundant ones - some are even obsolete!</p>\n<p>Good comments should say <em>why</em>, not <em>what</em>.</p>\n<blockquote>\n<pre><code>// Create our new excel application and add our workbooks/worksheets\nWorkbooks workbooks = xls.Workbooks;\nWorkbook workbook = workbooks.Add();\n</code></pre>\n</blockquote>\n<p>This comment says <em>what</em> the code is doing, and it's lying - you're not <em>creating</em> a new Excel application, you're using an existing instance. Remove it.</p>\n<blockquote>\n<pre><code>// Hide our excel object if it's visible.\nxls.Visible = false;\n</code></pre>\n</blockquote>\n<p>This comment adds no value, and is lying to a certain extent: you don't actually care whether it's already visible or not. Better just remove it.</p>\n<blockquote>\n<pre><code>// Turn off calculations if set to automatic; this can help prevent memory leaks.\nxls.Calculation = xls.Calculation == XlCalculation.xlCalculationAutomatic ? XlCalculation.xlCalculationManual : XlCalculation.xlCalculationManual;\n</code></pre>\n</blockquote>\n<p>This one is accurate and informative - it says <em>why</em> you're turning off automatic calculations.. but it also says <em>what</em> the code is doing. Better rephrase it:</p>\n<pre><code>// turning off automatic calculations improves performance and can help prevent memory leaks.\nxls.Calculation = (xls.Calculation == XlCalculation.xlCalculationAutomatic) \n ? XlCalculation.xlCalculationManual \n : XlCalculation.xlCalculationManual;\n</code></pre>\n<p>Notice how readability is improved by splitting the ternary operation into 3 lines. It appears the condition is moot, since both ends produce the same assignation. The instruction should be rewritten as simply:</p>\n<pre><code>xls.Calculation = XlCalculation.xlCalculationManual;\n</code></pre>\n<blockquote>\n<pre><code>// Turn off screen updating so our export will process more quickly.\nxls.ScreenUpdating = false;\n</code></pre>\n</blockquote>\n<p>Again, says <em>what</em> - the <em>why</em> makes it closely related to the previous statement. Thus:</p>\n<pre><code>// turning off automatic calculations and screen updating \n// improves performance and can help prevent memory leaks.\nxls.Calculation = XlCalculation.xlCalculationManual;\nxls.ScreenUpdating = false;\n</code></pre>\n<blockquote>\n<pre><code>// Create an excel table and fill it will our query table.\n</code></pre>\n</blockquote>\n<p>Remove. This one adds no value.</p>\n<blockquote>\n<pre><code>for (int i = 0; i &lt;= iterator; i++)\n{\n // Turn off calculations if set to automatic; this can help prevent memory leaks.\n Worksheet worksheet = (Worksheet)xls.Worksheets[i + 1];\n worksheet.Name = excelWorksheetName[i];\n worksheet.Select();\n</code></pre>\n</blockquote>\n<p>Apparently the code under that comment was moved, but the comment remained.</p>\n<hr />\n<p>As for performance, @Will's comment is accurate - COM interop is hurting you here. What's slowing it down is the many calls to the Excel object model (COM interop <em>in itself</em> incurs a performance penalty, but Excel interop somehow makes it even worse). The only way is to limit the number of times you're accessing the Excel object model.</p>\n<p>An alternative approach could be to write the data in a .csv file, and use the Excel object model to import the .csv data all in one shot (rather than looping into rows and columns to write the data &quot;manually&quot;), and then to format the workbook and save it in .xlsx format.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T15:06:54.187", "Id": "44675", "ParentId": "44169", "Score": "13" } }, { "body": "<p>Completed the new code, runs much faster than before without switching to XML options. This is almost instantaneous creation even with large files.</p>\n\n<pre><code>public static string Export(string excelFileName, \n string[] excelWorksheetName, \n string tableStyle, \n params System.Data.DataTable[] dt)\n{\n Application excel = new Application();\n excel.DisplayAlerts = false;\n excel.Visible = false;\n excel.ScreenUpdating = false;\n\n Workbooks workbooks = excel.Workbooks;\n Workbook workbook = workbooks.Add(Type.Missing);\n\n // Count of data tables provided.\n int iterator = dt.Length;\n for (int i = 0; i &lt; iterator; i++)\n {\n Sheets worksheets = workbook.Sheets;\n Worksheet worksheet = (Worksheet)worksheets[i + 1];\n worksheet.Name = excelWorksheetName[i];\n\n int rows = dt[i].Rows.Count;\n int columns = dt[i].Columns.Count;\n // Add the +1 to allow room for column headers.\n var data = new object[rows + 1, columns];\n\n // Insert column headers.\n for (var column = 0; column &lt; columns; column++)\n {\n data[0, column] = dt[i].Columns[column].ColumnName;\n }\n\n // Insert the provided records.\n for (var row = 0; row &lt; rows; row++)\n {\n for (var column = 0; column &lt; columns; column++)\n {\n data[row + 1, column] = dt[i].Rows[row][column];\n }\n }\n\n // Write this data to the excel worksheet.\n Range beginWrite = (Range)worksheet.Cells[1, 1];\n Range endWrite = (Range)worksheet.Cells[rows + 1, columns];\n Range sheetData = worksheet.Range[beginWrite, endWrite];\n sheetData.Value2 = data;\n\n // Additional row, column and table formatting.\n worksheet.Select();\n sheetData.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange,\n sheetData,\n System.Type.Missing,\n XlYesNoGuess.xlYes,\n System.Type.Missing).Name = excelWorksheetName[i];\n sheetData.Select();\n sheetData.Worksheet.ListObjects[excelWorksheetName[i]].TableStyle = tableStyle;\n excel.Application.Range[\"2:2\"].Select();\n excel.ActiveWindow.FreezePanes = true;\n excel.ActiveWindow.DisplayGridlines = false;\n excel.Application.Cells.EntireColumn.AutoFit();\n excel.Application.Cells.EntireRow.AutoFit();\n\n // Select the first cell in the worksheet.\n excel.Application.Range[\"$A$2\"].Select();\n }\n\n // Turn off alerts to prevent asking for 'overwrite existing' and 'save changes' messages.\n excel.DisplayAlerts = false;\n\n // Save our workbook and close excel.\n string SaveFilePath = string.Format(@\"{0}.xls\", excelFileName);\n workbook.SaveAs(SaveFilePath, XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);\n workbook.Close(false, Type.Missing, Type.Missing);\n excel.Quit();\n\n // Release our resources.\n Marshal.ReleaseComObject(workbook);\n Marshal.ReleaseComObject(workbooks);\n Marshal.ReleaseComObject(excel);\n Marshal.FinalReleaseComObject(excel);\n\n return SaveFilePath;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T14:46:32.377", "Id": "44976", "ParentId": "44169", "Score": "1" } } ]
{ "AcceptedAnswerId": "44976", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-12T16:46:52.217", "Id": "44169", "Score": "15", "Tags": [ "c#", "performance", "excel" ], "Title": "Creating Excel document is very slow" }
44169
<p>I'm working with AutoFac to do some DI. I think I've got a decent grip on things, but just ran into a question I had with my code and thought I'd check:</p> <pre><code>public class AutofacRegistrations { public static void RegisterAndSetResolver() { // Create the container builder. var containerBuilder = new ContainerBuilder(); // Register the Web API controllers. containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Only generate one SessionFactory ever because it is expensive. containerBuilder.Register(x =&gt; new NHibernateConfiguration().Configure().BuildSessionFactory()).SingleInstance(); // Everything else wants an instance of Session per HTTP request, so indicate that: containerBuilder.Register(x =&gt; x.Resolve&lt;ISessionFactory&gt;().OpenSession()).InstancePerApiRequest(); containerBuilder.Register(x =&gt; LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType)).InstancePerApiRequest(); // TODO: I don't THINK I should actually be making a DAO factory per API request. I think the whole point of a Factory is to make them once. containerBuilder.RegisterType&lt;NHibernateDaoFactory&gt;().As&lt;IDaoFactory&gt;().InstancePerApiRequest(); containerBuilder.RegisterType&lt;StreamusManagerFactory&gt;().As&lt;IManagerFactory&gt;().InstancePerApiRequest(); // Build the container. ILifetimeScope container = containerBuilder.Build(); // Create the depenedency resolver. var dependencyResolver = new AutofacWebApiDependencyResolver(container); // Configure Web API with the dependency resolver. GlobalConfiguration.Configuration.DependencyResolver = dependencyResolver; } } </code></pre> <p>You can see that I am registering an <code>NHibernateDaoFactory</code> and a <code>StreamusManagerFactory</code> as <code>InstancePerApiRequest</code>. This doesn't feel right to me because I think creating a Factory is supposed to be a relatively expensive endeavour and they should probably be <code>.SingleInstance()</code> similiar to the <code>ISessionFactory</code>. </p> <p>However, my NHibernateDaoFactory has a dependency on Session:</p> <pre><code>... public NHibernateDaoFactory(ISession session) { if (session == null) throw new NullReferenceException("session"); Session = session; } public IErrorDao GetErrorDao() { return ErrorDao ?? (ErrorDao = new ErrorDao(Session)); } .... </code></pre> <p>and my ManagerFactory has a dependency on the DaoFactory:</p> <pre><code>... public StreamusManagerFactory(ILog logger, IDaoFactory daoFactory) { if (logger == null) throw new NullReferenceException("logger"); if (daoFactory == null) throw new NullReferenceException("daoFactory"); Logger = logger; DaoFactory = daoFactory; } public IErrorManager GetErrorManager() { return ErrorManager ?? (ErrorManager = new ErrorManager(Logger, DaoFactory.GetErrorDao())); } ... </code></pre> <p>This leaves me having to create new factories per request. Is this correct?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T17:04:08.077", "Id": "76516", "Score": "2", "body": "Per *Design Patterns: Elements of Reusable Object-Oriented Software* (the famous GoF book), An *abstract factory* is often used as a *singleton*. I don't know [tag:autofac] very well (never used it), but I'm sure it has a way of specifying a \"singleton\" *lifestyle* (Ninject has it as \"InSingletonScope\")." } ]
[ { "body": "<p>Just got one thing to say on your code:</p>\n\n<h3>Your Comments add close to no value!</h3>\n\n<p>your code is littered with comments and empty lines</p>\n\n<blockquote>\n<pre><code>//Create the Container Builder\nvar containerBuilder = new ContainerBuilder();\n</code></pre>\n</blockquote>\n\n<p>The comment is in fact almost exactly the same as the code below. And it's not only there, it's the same with every comment in the <code>AutofacRegistrations</code> you posted. </p>\n\n<hr> \n\n<p>Other than that, if your factory has a dependency on <code>Session</code> you maybe did something wrong. Instead you could try to pass the <code>Session</code> to the already instantiated singleton factory, when calling the <code>GetErrorDao()</code> Function.</p>\n\n<p>That would instead look something like that:</p>\n\n<pre><code>public IErrorDao GetErrorDao(Session session)\n{\n return ErrorDao ?? (ErrorDao = new ErrorDao(session));\n}\n</code></pre>\n\n<p>this would decouple both your <code>NHibernateDaoFactory</code> and your ManagerFactory and let them be free to use a singleton pattern instead. Which in turn greatly reduces the stress your application puts on the system.</p>\n\n<p>You'd need to cascade this up the Dependency Chain, but that's a small price to pay to have a decoupled Factory Instance for all Requests / Sessions instead of one for each Session.<br>\nYou'd thus need to modify your GetErrorManager too:</p>\n\n<pre><code>public IErrorManager GetErrorManager(Session session)\n{\n return ErrorManager ?? (ErrorManager = new ErrorManager(Logger, DaoFactory.GetErrorDao(session)));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T18:57:39.407", "Id": "77650", "Score": "0", "body": "The comments were simply taken directly from the AutoFac documentation... https://code.google.com/p/autofac/wiki/WebApiIntegration but I appreciate your concern. I do understand that I should be speaking about 'Why' and not just being explicit, but I didn't feel the need to remove comments from other's documentation.\n\nI'll consider inverting control of Session all the way up, but I thought the whole point of a Factory was to obfuscate that logic from others. That said, it does look like bubbling it up would be quite beneficial. I'll work on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T19:08:03.360", "Id": "77651", "Score": "3", "body": "@Sean the point of a Factory is to have a way to instantiate classes of a certain Interface Type, without needing to know the Class itself / have to care which implementation it actually is." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T18:08:01.510", "Id": "44684", "ParentId": "44170", "Score": "6" } } ]
{ "AcceptedAnswerId": "44684", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T16:55:11.800", "Id": "44170", "Score": "10", "Tags": [ "c#", "dependency-injection", "autofac" ], "Title": "Should a Factory ever be generated per request?" }
44170
<p>I wrote a service object that emails a list of files to a list of email addresses.</p> <p>I am unsure about my <code>emails</code> method. It splits a string into an array of emails. It then loops over the array and rejects any elements that do not match the email regex. The return value is an array of valid emails stripped of whitespace.</p> <p>Another thing I'm getting a bad feeling about is the caching of the bucket, <code>@bucket ||= ...</code>, and the <code>url = get_urls</code> temp variable in the <code>send_email</code> method.</p> <pre><code>class FileSharingService def initialize(files, params) @files = files @params = params @client = AWS::S3.new end def send_email urls = get_urls emails.each do |email| FileSharingMailer.email_files(email, params[:message], urls) end end def emails @params[:emails].split(',').reject do |email| email.strip! email !~ /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i end end def get_urls @files.map do |file| bucket.objects[file.current_version.path].url_for(:get, expires: 1.week.from_now) end end def bucket @bucket ||= @client.buckets[ENV['S3_BUCKET']] end end </code></pre>
[]
[ { "body": "<h1>Good job on</h1>\n\n<ul>\n<li>Tightly focused methods that do what their name says</li>\n<li>Non-surprising formatting</li>\n<li>Testable design</li>\n</ul>\n\n<p>This is pretty good code</p>\n\n<h1>Environment variable</h1>\n\n<p>There's a few things that bother me about this class's use of the S3_BUCKET environment variable.</p>\n\n<ul>\n<li>It makes unit test awkward, as the test must either set the environment variable and then restore it, or it must stub ENV#[], either of which is a minor pain.</li>\n<li>It hard-codes the environment variable name</li>\n</ul>\n\n<p>My first thought was to have the class take the bucket name as an argument with a default:</p>\n\n<pre><code>def initialize(files, params, bucket_name = ENV['S3_BUCKET'])\n</code></pre>\n\n<p>But I think that is a half measure. Instead, let's just pass in the bucket:</p>\n\n<pre><code>def initialize(files, params, bucket)\n</code></pre>\n\n<p><code>bucket</code> is an instance of this class, which does a lazy fetch of the AWS::S3 bucket:</p>\n\n<pre><code>require 'forwardable'\nrequire 'memoist'\n\nclass Bucket\n\n extend Forwardable\n\n def initialize(bucket_name = ENV['S3_BUCKET'])\n @client = AWS::S3.new\n @bucket_name = bucket_name\n end\n\n def_delegator :bucket, :objects\n\n private\n\n def bucket\n @client.buckets[@bucket_name]\n end\n memoize :bucket\n\nend\n</code></pre>\n\n<ul>\n<li>The <a href=\"http://rubygems.org/gems/memoist\" rel=\"nofollow\">memoist gem</a> Is a fancy version of \"@bucket ||= ...\".</li>\n<li><a href=\"http://www.ruby-doc.org/stdlib-2.1.1/libdoc/forwardable/rdoc/Forwardable.html#method-i-def_delegator\" rel=\"nofollow\">Forwardable#def_delegator</a> delegates the #object method to the result of the #bucket method.</li>\n</ul>\n\n<p>The use of the Bucket class has these advantages:</p>\n\n<ul>\n<li>FileSharingService:\n<ul>\n<li>no longer has to know about the environment variable.</li>\n<li>does not have to concern itself with lazy-initialization and caching.</li>\n<li>can now be easily tested in isolation--just give it a test double for its bucket instance.</li>\n</ul></li>\n<li>Bucket can be easily tested in isolation.</li>\n</ul>\n\n<h1>Checking email addresses</h1>\n\n<p>I would consider taking the regular expression in this expression:</p>\n\n<pre><code>email !~ /\\A[\\w+\\-.]+@[a-z\\d\\-.]+\\.[a-z]+\\z/i\n</code></pre>\n\n<p>And, at a minimum, give it a constant. The goal is to make the code more self-documenting:</p>\n\n<pre><code>WELL_FORMED_EMAIL_ADDRESS = /\\A[\\w+\\-.]+@[a-z\\d\\-.]+\\.[a-z]+\\z/i\n...\nemail !~ WELL_FORMED_EMAIL_ADDRESS\n</code></pre>\n\n<p>I might go one step farther and move the entire check into another class. Make it someone else's responsibility to know what's a good email address and what's not:</p>\n\n<pre><code>EmailAddress.well_formed?(email)\n</code></pre>\n\n<h1>params</h1>\n\n<p>The only use the class makes of <em>params</em> is of <code>@params[:emails]</code>. If that is unlikely to change in the future, I would consider just passing in the email addresses, and not concerning this class with params at all.</p>\n\n<pre><code>def initialize(files, email_addresses, ...)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:40:49.893", "Id": "76545", "Score": "0", "body": "Thank you for an excellent explanation. Re extracting the email validation to a separate class... where would that class go in terms of directory structure? At first though I think `lib`... great observation re the `ENV` variable. I did not give that much thought, but what you say makes perfect sense. Re the params, I'm only using `message` and `emails` keys." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:44:17.060", "Id": "76547", "Score": "0", "body": "I would only add the `memoize` gem has a warning to use other gems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:00:16.243", "Id": "76554", "Score": "0", "body": "@Mohamad You are welcome. Thank _you_ for the great code to review. Also, thanks for the tip about memoist. I've been using it a while and didn't realize it was deprecated. I've edited the answer to suggest _memoist_ instead. In a rails project, _lib_ is a good place for classes such as EmailAddress." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:02:02.810", "Id": "76557", "Score": "0", "body": "Notes on `ENV`, `memoize`, ... +1 Excellent answer" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:26:10.597", "Id": "44179", "ParentId": "44173", "Score": "4" } } ]
{ "AcceptedAnswerId": "44179", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T17:28:42.760", "Id": "44173", "Score": "3", "Tags": [ "ruby", "email" ], "Title": "Creating a pure Ruby object (PORO) to email files in a Rails application" }
44173
<p>I wrote a couple reviews for this <a href="https://codereview.stackexchange.com/questions/36482/rpsls-game-in-c">CR post</a>. In my most recent review, I refactored @Malachi 's code to fit OO design. I'm looking for any advice/hints/criticisms on it.</p> <p>A review is welcome for both the OO design I implemented and the `main() method which is a bit sloppy.</p> <p>Here is the entire dump:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace RPSLS { class Program { static void Main(string[] args) { var endGameMenu = new string[] { "Play Again", "Clear Score", "Quit" }; var me = new Human(); var computer = new Computer(); var playAgain = true; do { Game.Play(me, computer); Console.WriteLine("Your scorecard: " + me.GetScoreCard()); int result; do { Console.WriteLine("Options:"); Utils.PrintMenu(endGameMenu.ToList()); result = Utils.PromptForRangedInt(0, endGameMenu.Length - 1, "Choose an Option: "); if (result == 1) { me.ClearScore(); Console.Clear(); Utils.WriteLineColored("Your score has been cleared", ConsoleColor.Green); } } while (result != 0 &amp;&amp; result != 2); Console.Clear(); playAgain = result == 0; } while (playAgain); } } enum Gesture { Rock = 1, Paper = 2, Scissors = 3, Spock = 4, Lizard = 5 } enum Performance { Lost = -1, Tied = 0, Won = 1 } abstract class Player { public uint Wins { get; private set; } public uint Loses { get; private set; } public uint Ties { get; private set; } public abstract Gesture GetMove(); public string GetScoreCard() { return "[Wins: " + Wins + "] [Loses " + Loses + "] [Ties " + Ties + "]"; } public void ClearScore() { Wins = Loses = Ties = 0; } public void GiveResult(Performance performance) { switch (performance) { case Performance.Lost: Loses++; break; case Performance.Tied: Ties++; break; case Performance.Won: Wins++; break; } } } class Human : Player { public override Gesture GetMove() { Utils.PrintMenu(Game.Gestures.Select(g =&gt; g.ToString()).ToList(), 1); return (Gesture)Utils.PromptForRangedInt((int)Game.Gestures.First(), (int)Game.Gestures.Last(), "Please choose your Gesture: "); } } class Computer : Player { public override Gesture GetMove() { return (Gesture)Game.Gestures.GetValue(new Random().Next(Game.Gestures.Length)); } } static class Game { public static Gesture[] Gestures = (Gesture[])Enum.GetValues(typeof(Gesture)); private static Dictionary&lt;Tuple&lt;int, int&gt;, string&gt; Rules = new Dictionary&lt;Tuple&lt;int, int&gt;, string&gt;() { {Tuple.Create&lt;int,int&gt;(1,3), "Crushes"}, {Tuple.Create&lt;int,int&gt;(1,5), "Crushes"}, {Tuple.Create&lt;int,int&gt;(2,1), "Covers"}, {Tuple.Create&lt;int,int&gt;(2,4), "Disproves"}, {Tuple.Create&lt;int,int&gt;(3,2), "Cuts"}, {Tuple.Create&lt;int,int&gt;(3,5), "Decapitates"}, {Tuple.Create&lt;int,int&gt;(4,3), "Smashes"}, {Tuple.Create&lt;int,int&gt;(4,1), "Vaporizes"}, {Tuple.Create&lt;int,int&gt;(5,2), "Eats"}, {Tuple.Create&lt;int,int&gt;(5,4), "Poisons"} }; public static void Play(Player player1, Player player2) { Gesture p1move = player1.GetMove(); Gesture p2move = player2.GetMove(); Console.Write("Player 1 Chose "); Utils.WriteLineColored(p1move.ToString(), ConsoleColor.Green); Console.Write("Player 2 Chose "); Utils.WriteLineColored(p2move.ToString(), ConsoleColor.Green); int result = WhoWon(p1move, p2move); switch (result) { case 0: player1.GiveResult(Performance.Tied); player2.GiveResult(Performance.Tied); break; case 1: player1.GiveResult(Performance.Won); player2.GiveResult(Performance.Lost); break; case 2: player1.GiveResult(Performance.Lost); player2.GiveResult(Performance.Won); break; } if (result == 0) Console.WriteLine("It was a tie!"); else Console.WriteLine("Player {0} won, because {1}.", result, GetReason(result == 1 ? p1move : p2move, result == 1 ? p2move : p1move)); } private static int WhoWon(Gesture p1move, Gesture p2move) { return p1move == p2move ? 0 : Rules.Keys.Where(key =&gt; key.Item1 == (int)p1move &amp;&amp; key.Item2 == (int)p2move).FirstOrDefault() != null ? 1 : 2; } private static string GetReason(Gesture winner, Gesture loser) { return winner + " " + Rules[Tuple.Create((int)winner, (int)loser)] + " " + loser; } } static class Utils { public static int PromptForRangedInt(int min = int.MinValue, int max = int.MaxValue, string prompt = "Please enter an Integer: ") { int g; do { Console.Write(prompt); if (int.TryParse(Console.ReadLine(), out g)) { if (g &gt;= min &amp;&amp; g &lt;= max) return g; Console.WriteLine("You entered {0}, but the input must be in the range of ({1} - {2}. Please try again...", g, min, max); } else Console.WriteLine("That is not a number. Please try again..."); } while (true); } public static void PrintMenu(List&lt;string&gt; values, int baseIndex = 0) { values.ForEach(value =&gt; Console.WriteLine("{0}: {1}", baseIndex++, value)); } public static void WriteLineColored(string text, ConsoleColor color) { var curr = Console.ForegroundColor; Console.ForegroundColor = color; Console.WriteLine(text); Console.ForegroundColor = curr; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:30:36.273", "Id": "76563", "Score": "0", "body": "you should do that the other way around. post the update separate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:41:36.813", "Id": "76565", "Score": "1", "body": "@Malachi done ;)" } ]
[ { "body": "<p>one thing to start with.</p>\n\n<p>I would get rid of your <code>playAgain</code> variable and replace the while statement like this</p>\n\n<h2>Original Code:</h2>\n\n<pre><code>do\n{\n Game.Play(me, computer);\n Console.WriteLine(\"Your scorecard: \" + me.GetScoreCard());\n int result;\n do\n {\n Console.WriteLine(\"Options:\");\n Utils.PrintMenu(endGameMenu.ToList());\n result = Utils.PromptForRangedInt(0, endGameMenu.Length - 1, \"Choose an Option: \");\n if (result == 1)\n {\n me.ClearScore();\n Console.Clear();\n Utils.WriteLineColored(\"Your score has been cleared\", ConsoleColor.Green);\n }\n } while (result != 0 &amp;&amp; result != 2);\n Console.Clear();\n playAgain = result == 0;\n} while (playAgain);\n</code></pre>\n\n<p><strike></p>\n\n<h2>New Code:</h2>\n\n<pre><code>do\n{\n Game.Play(me, computer);\n Console.WriteLine(\"Your scorecard: \" + me.GetScoreCard());\n int result;\n do\n {\n Console.WriteLine(\"Options:\");\n Utils.PrintMenu(endGameMenu.ToList());\n result = Utils.PromptForRangedInt(0, endGameMenu.Length - 1, \"Choose an Option: \");\n if (result == 1)\n {\n me.ClearScore();\n Console.Clear();\n Utils.WriteLineColored(\"Your score has been cleared\", ConsoleColor.Green);\n }\n } while (result != 0 &amp;&amp; result != 2);\n Console.Clear();\n} while (result == 0);\n</code></pre>\n\n<p>I am pretty sure that you can use <code>result</code> because anything inside the loop is within the same scope as what is in the <code>while</code> clause as long as it is part of a <code>do while</code> statement.</p>\n\n<p>I have been wrong before though\n</strike></p>\n\n<hr>\n\n<h2>Even Newer Code</h2>\n\n<pre><code>int result;\ndo\n{\n Game.Play(me, computer);\n Console.WriteLine(\"Your scorecard: \" + me.GetScoreCard());\n Console.WriteLine(\"Options:\");\n Utils.PrintMenu(endGameMenu.ToList());\n result = Utils.PromptForRangedInt(0, endGameMenu.Length - 1, \"Choose an Option: \");\n if (result == 1)\n {\n me.ClearScore();\n Console.Clear();\n Utils.WriteLineColored(\"Your score has been cleared\", ConsoleColor.Green);\n }\n Console.Clear();\n} while (result == 0 || result == 1);\n</code></pre>\n\n<p>Here you have kept the same functionality and reduced the code to one loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:18:52.673", "Id": "76538", "Score": "0", "body": "You can do this only if you declare result outside the loop, as in C# the scope closes before the while condition is checked. I thought about implementing it this way, but I just wanted to keep the menu somewhat separated from the main game loop. that is the only reason I even used a `playAgain` bool." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:36:12.763", "Id": "76543", "Score": "0", "body": "if you did it this way you would eliminate an entire variable, but you would be controlling two `do while` loops with the same variable. maybe it should be restructured a different way...@BenVlodgi" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:45:56.163", "Id": "76548", "Score": "0", "body": "thank you @Olivier I Copy Pasted a lot of the answer...lol" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:01:04.510", "Id": "76555", "Score": "1", "body": "@Oliver While yes this does reduce it down to one loop, i also will automatically replay the game if the user chooses to clear their score, which may not be intended. In the original original code it was 2 separate questions, I combined it all into a menu which would not progress until an option was chosen, except when clear score was chosen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:07:07.920", "Id": "76560", "Score": "3", "body": "The reviewer gets reviewed? I like that!!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:10:08.380", "Id": "44178", "ParentId": "44177", "Score": "4" } }, { "body": "<p>After some criticisms on my <code>Main</code> method, I've re-written it to the following. This implementation starts the user off at the main menu, which is easily scaled. To add a menu option, simply add the text to the <code>gameMenu</code> <code>array</code>, and add a corresponding action to take place in the switch statement. This implementation avoids multiple loops and confusions about what exactly is going on.</p>\n\n<pre><code>static void Main(string[] args)\n{\n var gameMenu = new string[] { \"Play\", \"Clear Score\", \"Quit\" };\n var me = new Human();\n var computer = new Computer();\n var playAgain = true;\n do\n {\n Utils.WriteLineColored(\"Options:\", ConsoleColor.White);\n Utils.PrintMenu(gameMenu.ToList());\n switch(Utils.PromptForRangedInt(0, gameMenu.Length - 1, \"Choose an Option: \"))\n {\n case 0:\n Console.Clear();\n Game.Play(me, computer);\n Console.WriteLine(\"Your scorecard: \" + me.GetScoreCard() + Environment.NewLine);\n break;\n case 1:\n Console.Clear();\n me.ClearScore();\n Utils.WriteLineColored(\"Your score has been cleared\", ConsoleColor.Green);\n break;\n case 2:\n Console.Clear();\n playAgain = false;\n Console.Write(\"Good bye, thanks for playing!\\nPress any Key to contine...\");\n Console.ReadKey(true);\n break;\n }\n } while (playAgain);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:29:57.160", "Id": "76562", "Score": "1", "body": "I do like that. it gives me a nice fuzzy feeling" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:25:37.453", "Id": "44184", "ParentId": "44177", "Score": "4" } }, { "body": "<p><code>Main</code> has already been taken care of so I'm going to concentrate on the other stuff:</p>\n\n<ol>\n<li><p><code>enum Performance</code> seems like an odd name considering that it represents the result of a game - calling it <code>Result</code> or <code>GameResult</code> seems more appropriate.</p></li>\n<li><p>Your code makes the implicit assumption that the gestures are numbered consecutively starting at 1 which is not ideal. Your utility functions could just take the enum as a parameter use it to print the menu and parse the proper selection. Something like this</p>\n\n<pre><code>public static void PrintEnumSelection&lt;T&gt;()\n{\n var t = typeof(T);\n\n if (!t.IsEnum)\n throw new ArgumentException(\"type must be an enum\");\n\n Enum.GetValues(typeof(T)).Cast&lt;T&gt;().ToList().ForEach(value =&gt; Console.WriteLine(\"{0}: {1}\", (int)value, value));\n}\n</code></pre>\n\n<p>Unfortunately you can't do <code>where T : Enum</code> although technically <a href=\"https://stackoverflow.com/a/8086788/220986\">there is a work around</a> for that.</p>\n\n<p>Similarly have a <code>ParseEnumSelection</code> which checks if the input is one of the enum constants.</p></li>\n<li><p>There is nothing which really identifies the player - the class should have a <code>Name</code> property.</p></li>\n<li><p><code>GiveResult</code> should be renamed to <code>RecordResult</code>.</p></li>\n<li><p>In your games class your rules definition uses <code>int</code>s to define which gesture beats which other gesture. Again this makes an implicit assumption about how your enums are numbered and in which order they are. So the tuples should be <code>Tuple&lt;Gesture, Gesture&gt;</code> rather than <code>Tuple&lt;int, int&gt;</code></p></li>\n<li><p>In <code>Play</code> you first have a switch on the result and the again you have comparisons to check for teh same thing again and a convoluted condition for printing which player won. If you move that logic up into the switch as well the code become easier to read and follow and you check the result only once:</p>\n\n<pre><code> int result = WhoWon(p1move, p2move);\n switch (result)\n {\n case 0: \n player1.GiveResult(Performance.Tied);\n player2.GiveResult(Performance.Tied);\n Console.WriteLine(\"It was a tie!\");\n break;\n case 1: \n player1.GiveResult(Performance.Won); \n player2.GiveResult(Performance.Lost); \n Console.WriteLine(\"Player 1 won, because {0}.\", GetReason(p1move));\n break;\n case 2: \n player1.GiveResult(Performance.Lost); \n player2.GiveResult(Performance.Won); \n Console.WriteLine(\"Player 2 won, because {0}.\", GetReason(p2move));\n break;\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T08:09:14.197", "Id": "44234", "ParentId": "44177", "Score": "4" } } ]
{ "AcceptedAnswerId": "44234", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:03:56.237", "Id": "44177", "Score": "8", "Tags": [ "c#", "game", ".net", "community-challenge", "rock-paper-scissors" ], "Title": "RPSLS refactored to Object Oriented" }
44177
<p>I was using setTimeouts for a project where a callback will be called after a duration, but the user has the options of extending, pausing or stopping the timeout. I felt using the default setTimeout was a bit clunky, especially since I needed to remember the timeout ids, and I decided to create a timeout utility object. I was wondering if I'm doing this properly, and whether you could give me some tips on how to refactor my code?</p> <p><strong>Object definition</strong></p> <pre><code>//Utility object that makes it easier to control timeouts function Timer(duration, callback) { this._duration = duration; this._callback = callback; this._id = -1; this._paused = true; this._lastRunTime = -1; this._remainingTime = this._duration; } //calls the current timeout; if a function is passed, run that function //instead of default callback (but do not change the default callback) Timer.prototype.callTimer = function(aCallback, aDuration) { var that = this, //sets callback and duration to default values if not passed in callback = aCallback || this._callback, duration = aDuration || this._duration; //if a previous timeout has been set, clear it if (this._id &gt; -1 ) { clearTimeout(this._id); } //executes the callback and resets the timer this._id = setTimeout(function() { callback(); that.resetTimer(); }, duration); this._paused = false; //rememebers the time when the timer was run (for pauseTimer) this._lastRunTime = new Date(); } Timer.prototype.resetTimer = function() { this._remainingTime = this._duration; this._paused = true; this._lastRunTime = -1; clearTimeout(this._id); } //changes the default callback //if second argument is true, execute callTimer Timer.prototype.changeCallback = function(callback, callTimer) { this._callback = callback; if (callTimer) this.callTimer(); } Timer.prototype.pauseTimer = function() { if (this._lastRunTime === -1) { throw new Error('Timer has not been run yet'); } //if currently paused, call timer with remaining time left if (this._paused) { this._lastRunTime = new Date(); this.callTimer(this._callback, this._remainingTime); } //else pause else { clearTimeout(this._id); //subtract the amount of time that has elapsed this._remainingTime -= (new Date() - this._lastRunTime); } //toggles the _paused variable this._paused = !this._paused; } </code></pre> <p><a href="http://fiddle.jshell.net/6nhGW/" rel="nofollow">http://fiddle.jshell.net/6nhGW/</a></p> <p><strong>Test Code</strong></p> <pre><code>var button = document.getElementById('extendTimeout'), button2 = document.getElementById('tempChangeCallback'), button3 = document.getElementById('changeCallback'), button4 = document.getElementById('resetTimer'), button5 = document.getElementById('pauseTimer'), startTime, timeout = -1; var timer = new Timer(3000, function() { console.log('Total time elapsed: ' + (new Date() - startTime)); startTime = null; }) button.addEventListener('click', function() { if (!startTime) startTime = new Date(); timer.callTimer(); }) button2.addEventListener('click', function() { if (!startTime) startTime = new Date(); timer.callTimer(function() { console.log('Temporarily change callback'); console.log('Total time elapsed: ' + (new Date() - startTime)); startTime = null; }); }) button3.addEventListener('click', function() { timer.changeCallback(function() { console.log('Callback has been changed!'); startTime = null; }, true); }); button4.addEventListener('click', function() { timer.resetTimer(); startTime = null; }); button5.addEventListener('click', function() { if (!startTime) startTime = new Date(); timer.pauseTimer(); }); </code></pre>
[]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>I would not use <code>_</code> to prefix all your variables, it would make more sense to either actually use private variables or write a comment that this variables should not be touched by callers</li>\n<li><code>pauseTimer</code> lies, since you toggle. I would call it <code>toggleTimer</code> or <code>startStopTimer</code></li>\n<li>Your code is well commented except for <code>//toggles the _paused variable</code> which is kind of obvious ;)</li>\n<li>Besides some missing semicolons, your code looks fine on JsHint.com</li>\n<li>I think in <code>callTimer</code> you could have called your paramater <code>callback</code>, then do <code>callback = callback || this.callback</code> and then use <code>callback</code> in your closure.</li>\n</ul>\n\n<p>All in all, good, re-usable code. </p>\n\n<p>For my own purposes I would probably make the private variables really private and move the functions out of <code>prototype</code> into the constructor. That would increase memory footprint, but I would never use more than a dozen of these at the same time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T02:41:45.057", "Id": "76637", "Score": "0", "body": "@konijin Thank you for your comments, and it's really helpful! I considered using private variables but decided against it due to the increased memory footprint, but you make a good point that we don't really need too many of them around." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T02:44:03.287", "Id": "76639", "Score": "0", "body": "On overriding the callback in callTime, I don't fully understand what you mean - do you mean that we shouldn't do callback = callback || this.callback, and instead do this.callback = callback || this.callback? The only problem is this would overwrite the default callback that we set initially?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T23:28:59.770", "Id": "76848", "Score": "0", "body": "Yes, the default would be changed, I guess if you call it 3 times with a different callback that it would not make sense to change `this.callback`, will update my question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:45:15.717", "Id": "44194", "ParentId": "44181", "Score": "1" } } ]
{ "AcceptedAnswerId": "44194", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T18:35:14.047", "Id": "44181", "Score": "3", "Tags": [ "javascript", "object-oriented", "timer" ], "Title": "Utility object for setTimeout" }
44181
<p>I know there is a simpler way of doing this, but I just really can't think of it right now. Can you please help me out?</p> <pre><code>String sample = "hello world"; char arraysample[] = sample.toCharArray(); int length = sample.length(); //count the number of each letter in the string int acount = 0; int bcount = 0; int ccount = 0; int dcount = 0; int ecount = 0; int fcount = 0; int gcount = 0; int hcount = 0; int icount = 0; int jcount = 0; int kcount = 0; int lcount = 0; int mcount = 0; int ncount = 0; int ocount = 0; int pcount = 0; int qcount = 0; int rcount = 0; int scount = 0; int tcount = 0; int ucount = 0; int vcount = 0; int wcount = 0; int xcount = 0; int ycount = 0; int zcount = 0; for(int i = 0; i &lt; length; i++) { char c = arraysample[i]; switch (c) { case 'a': acount++; break; case 'b': bcount++; break; case 'c': ccount++; break; case 'd': dcount++; break; case 'e': ecount++; break; case 'f': fcount++; break; case 'g': gcount++; break; case 'h': hcount++; break; case 'i': icount++; break; case 'j': jcount++; break; case 'k': kcount++; break; case 'l': lcount++; break; case 'm': mcount++; break; case 'n': ncount++; break; case 'o': ocount++; break; case 'p': pcount++; break; case 'q': qcount++; break; case 'r': rcount++; break; case 's': scount++; break; case 't': tcount++; break; case 'u': ucount++; break; case 'v': vcount++; break; case 'w': wcount++; break; case 'x': xcount++; break; case 'y': ycount++; break; case 'z': zcount++; break; } } System.out.println ("There are " +hcount+" h's in here "); System.out.println ("There are " +ocount+" o's in here "); </code></pre>
[]
[ { "body": "<p>Oh woah! xD It's just.. woah! What patience you have to write all those variables.</p>\n\n<p>Well, it's Java so you can use a HashMap.</p>\n\n<p>Write something like this:</p>\n\n<pre><code>String str = \"Hello World\";\nint len = str.length();\nMap&lt;Character, Integer&gt; numChars = new HashMap&lt;Character, Integer&gt;(Math.min(len, 26));\n\nfor (int i = 0; i &lt; len; ++i)\n{\n char charAt = str.charAt(i);\n\n if (!numChars.containsKey(charAt))\n {\n numChars.put(charAt, 1);\n }\n else\n {\n numChars.put(charAt, numChars.get(charAt) + 1);\n }\n}\n\nSystem.out.println(numChars);\n</code></pre>\n\n<ol>\n<li>We do a <code>for</code> loop over all the string's characters and save the current char in the <code>charAt</code> variable</li>\n<li>We check if our HashMap already has a <code>charAt</code> key inside it\n\n<ul>\n<li>If it's true we will just get the current value and add one.. this means the string has already been found to have this char.</li>\n<li>If it's false (i.e. we never found a char like this in the string), we add a key with value 1 because we found a new char</li>\n</ul></li>\n<li>Stop! Our HashMap will contain all chars (keys) found and how many times it's repeated (values)!</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:05:46.333", "Id": "76569", "Score": "2", "body": "As an added bonus, this also supports more than just lower case letters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:19:14.387", "Id": "76586", "Score": "6", "body": "You might consider a TreeMap instead of a HashMap so that the data, when printed, is ordered by the collection itself (if you were going to print them all). If you are going to stay with a HashMap, you might consider the initalcapacity argument on the constructor as you're not going to get more than 26 letters in this situation. Best practices and all that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:20:20.910", "Id": "76587", "Score": "0", "body": "@MichaelT TreeMap great! I would anyway set the initialSize to str.length() since it could be every char is never repeated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:26:04.157", "Id": "76588", "Score": "1", "body": "Then it would be `min(str.len(),26)` because if it is longer than 26 characters there *will* be duplicated characters... though we're both kind of ignoring spaces. Still, its only a hint to the system and it will grow if it needs to. The default to start with is 16 (and then it grows to 32, and then to 64). I'd still use one of the [navigablemap](http://docs.oracle.com/javase/7/docs/api/java/util/NavigableMap.html) implementations for its sorted nature. I kind of like the skip list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:28:05.620", "Id": "76589", "Score": "0", "body": "Yup, min(str.length(), 26). It's just to avoid the \"grow cost\" if not needed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-16T01:18:57.557", "Id": "392944", "Score": "0", "body": "+1 especially for the \"_woah_\"s and the \"_Stop!_\"" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-12T20:03:06.900", "Id": "44187", "ParentId": "44186", "Score": "34" } }, { "body": "<p>A possibly faster, and at least more compact version than using a <code>HashMap</code> is to use a good old integer array. A <code>char</code> can actually be typecasted to an <code>int</code>, which gives it's ASCII code value.</p>\n\n<pre><code>String str = \"Hello World\";\nint[] counts = new int[(int) Character.MAX_VALUE];\n// If you are certain you will only have ASCII characters, I would use `new int[256]` instead\n\nfor (int i = 0; i &lt; str.length(); i++) {\n char charAt = str.charAt(i);\n counts[(int) charAt]++;\n}\n\nSystem.out.println(Arrays.toString(counts));\n</code></pre>\n\n<p>As the above output is a bit big, by looping through the integer array you can output just the characters which actually occur:</p>\n\n<pre><code>for (int i = 0; i &lt; counts.length; i++) {\n if (counts[i] &gt; 0)\n System.out.println(\"Number of \" + (char) i + \": \" + counts[i]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:32:40.130", "Id": "76763", "Score": "4", "body": "You don't need to cast `Character.MAX_VALUE` to an int, nor do you need to cast `chartAt` to an int. Internally they are represented as numbers and will work just fine. You can even use `char i` instead of `int i` in your printing loop to avoid the cast to `char` there as well.\n\nThe nice thing about making it an array like this is that it can make for very readable code. You can get the count for any char by just saying `counts['a']` to get the count for 'a'." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:11:19.770", "Id": "44190", "ParentId": "44186", "Score": "21" } }, { "body": "<p>Yes... there is a simpler way. You have two choices, but each about the same. Use an Array, or a Map. The more advanced way of doing this would certainly be with a Map. </p>\n\n<p>Think about a map as a type of array where instead of using an integer to index the array you can use anything. In our case here we'll use char as the index. Because chars are ints you could just use a simple array in this case, and just mentally think of 'a' as 0, but we're going to take the larger step today.</p>\n\n<pre><code>String sample = \"Hello World!\";\n\n// Initialization\nMap &lt;Character, Integer&gt; counter = new HashMap&lt;Character, Integer&gt;();\nfor(int c = 'a'; c &lt;= 'z'; c++){\n counter.put((Character)c, 0);\n}\n\n// Populate\nfor (int i = 0; i &lt; sample.length(); i++){\n if(counter.containsKey(sample.charAt(i)))\n counter.put(sample.charAt(i), counter.get(sample.charAt(i)) + 1 );\n}\n</code></pre>\n\n<p>Now anytime you want to know how many of whatever character there was just call this method</p>\n\n<pre><code>int getCount(Character character){\n if(counter.containsKey(character))\n return counter.get(character);\n else return 0;\n}\n</code></pre>\n\n<p>Note: This only will work for counting punctuation. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:13:56.020", "Id": "76572", "Score": "0", "body": "Your code will throw `NullPointerException` for `counter.get(s.charAt(i)) + 1` when char is not `'a'..'z'` :( `null + 1` throws." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:14:52.677", "Id": "76573", "Score": "0", "body": "@SimonAndréForsberg was just about to fix that, and make a note that this only counter letters" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-29T07:12:48.027", "Id": "371152", "Score": "0", "body": "`containsKey(i)`? That sounds like a clear mistake." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-12T20:12:23.167", "Id": "44191", "ParentId": "44186", "Score": "5" } }, { "body": "<ol>\n<li><p>Actually, there is an even better structure than maps and arrays for this kind of counting: <a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained\"><code>Multiset</code>s</a>. <a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained\">Documentation of Google Guava mentions a very similar case</a>:</p>\n\n<blockquote>\n <p>The traditional Java idiom for e.g. counting how many times a word occurs in a document is something like:</p>\n\n<pre><code>Map&lt;String, Integer&gt; counts = new HashMap&lt;String, Integer&gt;();\nfor (String word : words) {\n Integer count = counts.get(word);\n if (count == null) {\n counts.put(word, 1);\n } else {\n counts.put(word, count + 1);\n }\n}\n</code></pre>\n \n <p>This is awkward, prone to mistakes, and doesn't support collecting a variety of useful statistics, like the total number of words. We can do better. </p>\n</blockquote>\n\n<p>With a multiset you can get rid of the <code>contains</code> (or <code>if (get(c) != null)</code>) calls, what you need to call is a simple <code>add</code> in every iteration. Calling <code>add</code> the first time adds a single occurrence of the given element.</p>\n\n<pre><code>String input = \"Hello world!\";\n\nMultiset&lt;Character&gt; characterCount = HashMultiset.create();\nfor (char c: input.toCharArray()) {\n characterCount.add(c);\n}\nfor (Entry&lt;Character&gt; entry: characterCount.entrySet()) {\n System.out.println(entry.getElement() + \": \" + entry.getCount());\n}\n</code></pre>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><blockquote>\n<pre><code>int length = sample.length();\n....\nfor (int i = 0; i &lt; length; i++) {\n char c = arraysample[i];\n</code></pre>\n</blockquote>\n\n<p>You could replace these three lines with a foreach loop:</p>\n\n<pre><code>for (char c: arraysample) {\n</code></pre></li>\n<li><blockquote>\n<pre><code>int length = sample.length();\n....\nfor (int i = 0; i &lt; length; i++) {\n char c = arraysample[i];\n</code></pre>\n</blockquote>\n\n<p>You don't need the <code>length</code> variable, you could use <code>sample.length()</code> in the loop directly:</p>\n\n<pre><code>for (int i = 0; i &lt; sample.length(); i++) {\n</code></pre>\n\n<p>The JVM is smart, it will optimize that for you.</p></li>\n<li><blockquote>\n<pre><code>char arraysample[] = sample.toCharArray();\nint length = sample.length();\nfor (int i = 0; i &lt; length; i++) {\n char c = arraysample[i];\n</code></pre>\n</blockquote>\n\n<p>It's a little bit confusing that the loop iterating over <code>arraysample</code> but using <code>sample.length()</code> as the upper bound. Although their value is the same it would be cleaner to use <code>arraysample.length</code> as the upper bound.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T22:47:45.910", "Id": "44208", "ParentId": "44186", "Score": "9" } }, { "body": "<p>The use of functional programming can even simplify this problem to a great extent.</p>\n\n<pre><code>public static void main(String[] args) {\n\n String myString = \"hello world\";\n\n System.out.println(\n myString\n .chars()\n .mapToObj(c -&gt; String.valueOf((char) c))\n .filter(str -&gt; !str.equals(\" \"))\n .collect(Collectors.groupingBy(ch -&gt; ch, Collectors.counting()))\n\n );\n}\n</code></pre>\n\n<p>First we get the stream of integers from the string</p>\n\n<pre><code>myString.chars()\n</code></pre>\n\n<p>Next we transform the integers into string</p>\n\n<pre><code>mapToObj(c -&gt; String.valueOf((char) c))\n</code></pre>\n\n<p>Then we filter out the charcters we don't need to consider, for example above we have filtered the spaces.</p>\n\n<pre><code>filter(str -&gt; !str.equals(\" \"))\n</code></pre>\n\n<p>Then finally we collect them grouping by the characters and counting them</p>\n\n<pre><code>collect(Collectors.groupingBy(ch -&gt; ch, Collectors.counting()))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-29T07:16:06.150", "Id": "371153", "Score": "0", "body": "Why do you need to convert the characters to strings? Why don't you use `.codePoints()` instead of `.chars()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-29T07:18:00.770", "Id": "371154", "Score": "0", "body": "What does the variable `p` stand for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-30T03:05:28.747", "Id": "371307", "Score": "0", "body": "Sorry for that p, changed it to ch denoting character" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-29T06:07:17.693", "Id": "193185", "ParentId": "44186", "Score": "0" } } ]
{ "AcceptedAnswerId": "44187", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T19:52:49.457", "Id": "44186", "Score": "16", "Tags": [ "java", "strings" ], "Title": "Count number of each char in a String" }
44186
<p>I'm writing a simple remote PC app (mouse-keyboard). Android is client and is connect with WiFi to Java PC Server. I'm using TCP but I see a bit of latency compared to other remote apps. Then I used UDP and didn't see any latency or wrong data. UDP look like it's working well. I'm sending a String to Server like these: "a","B","2". Can I use UDP for keyboard remoting?</p> <p>Client on Android (TCP):</p> <p>Sending to Server a String method like these("a","C","5"):</p> <pre><code>public void commandto(String sip, int port ,String byt) { try { Socket sockClient = new Socket(); sockClient.connect(new InetSocketAddress(sip,port),9000); //os= new DataOutputStream(sockClient.getOutputStream()); //OutputStream os = sockClient.getOutputStream(); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sockClient.getOutputStream())),true); out.println(byt); out.flush(); Log.w("Client", "Client sent message"); sockClient.close(); }catch (final UnknownHostException e) { // }catch (final IOException e) { // } } </code></pre> <p>TCP Server code:</p> <pre><code>private void cAccept (int portt) throws AWTException { try{ ss = new ServerSocket(portt); }catch (IOException e){ lblInf.setText("Could not listen on port :"+portt+" "+e.getMessage()); } lblInf.setText("Server is started!"); } while(true){ try{ s = ss.accept(); br = new BufferedReader(new InputStreamReader(s.getInputStream())); String command =br.readLine(); System.out.println(command+"\n"); if(command!=""){ type(command); } s.close(); br.close(); }catch (IOException e){ try { if(s!=null) s.close(); if(br!=null) br.close(); } catch (IOException es) { // TODO Auto-generated catch block es.printStackTrace(); } lblInf.setText("Server is stopped!"); lblInf2.setText(""); } } } </code></pre> <p>Start Server Button code:</p> <pre><code> btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnStart.setEnabled(false); btnStop.setEnabled(true); thread = new Thread() { public void run(){ try { cAccept(9512); } catch (AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; thread.start(); } }); </code></pre> <p>As I've said, I especially see better latency for upper case. If I use UDP, using the following code.</p> <p>UDP Client sending a String...</p> <pre><code> private void runUdpClient(String a) { DatagramSocket ds = null; try { ds = new DatagramSocket(); InetAddress serverAddr = InetAddress.getByName("192.168.2.100"); DatagramPacket dp; dp = new DatagramPacket(a.getBytes(), a.length(), serverAddr, 9512); ds.send(dp); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (ds != null) { ds.close(); } } } </code></pre> <p>UDP server:</p> <pre><code> private void runUdpServer() { while(true){ String lText; byte[] lMsg = new byte[1000]; DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length); DatagramSocket ds = null; try { ds = new DatagramSocket(9512); //disable timeout for testing //ds.setSoTimeout(100000); ds.receive(dp); lText = new String(lMsg, 0, dp.getLength()); if(lText!=""){ type(lText); System.out.println(lText); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (ds != null) { ds.close(); } } } } </code></pre> <p>How can I improve the speed? Or should I continue with UDP? If you have any idea or something, I would like to hear it.</p> <p><strong>EDİT 1 :</strong></p> <p>I've changed somethings for this answer.</p> <blockquote> <p>"Then, when I look at your code, i see that you are creating a new TCP socket for every single character that you send."</p> </blockquote> <pre><code>public class TCPclient extends Activity { Socket sockClient; PrintWriter out; . . . } </code></pre> <p>and method</p> <pre><code> public void commandto(String sip, int port ,String byt) { try { sockClient = new Socket(); . . out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sockClient.getOutputStream())),true); ... } } </code></pre> <p>and I've changed it with this on TCP Server side.</p> <pre><code> String command =br.readLine(); System.out.println(command+"\n"); if(command!=""){ type(command); } </code></pre> <p>-</p> <pre><code> private void cAccept (int portt) throws AWTException { . . . while(true){ .... command =br.readLine(); System.out.println(command+"\n"); type(command) } } </code></pre> <p>Already I've using these on TCP Server</p> <pre><code> public class TCPServer extends JFrame{ ... private ServerSocket ss= null; private Socket s =null; private BufferedReader br=null; ... } </code></pre> <p>Now is looking better. But I see a bit of latency compared to other remote apps. How can I more improve it for latency?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:24:33.127", "Id": "76576", "Score": "3", "body": "From the looks of it, proper indentation should come before everything else. This looks quite messy and should really be improved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:41:32.097", "Id": "76579", "Score": "0", "body": "It is messy I know it. But what can I do for improve it? Why I'm getting latency , I think It's not about messy. Is it possible sending a string , server side or key press?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:53:43.227", "Id": "76580", "Score": "1", "body": "I'm not familiar with any of the specifics. I've just noticed this aspect, which I still believe is important, even though it's not related to latency. And if you're aware it's messy, then you should clean it up. That'll make your code much easier to read and will be more attractive for reviewers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:01:25.860", "Id": "76582", "Score": "0", "body": "Yes my codes not clean and unreadably. I'm now testing on this app. If I didn't get latency, of course I'll do setting the app with OOP." } ]
[ { "body": "<p>I would expect UDP to be slightly faster in latency than TCP, but not so that you could measure it by 'feel'. I would expect the differences to be in the order of micro-seconds.</p>\n\n<p>Then, when I look at your code, i see that you are creating a new TCP socket for every single character that you send.</p>\n\n<p>This is a real problem, and is not the way that TCP is supposed to be used.</p>\n\n<p>TCP is a stateful connection, and needs a fair amount of communication to ensure both sides of the socket are are steady and reliable state. This overhead is what is creating your latency each time you connect.</p>\n\n<p>With TCP connections it is standard to connect the socket at the beginning of your application, and to then leave it connected <em>the whole time</em>. All you need to do is send a byte each time a key is pressed, rather than re-creating the entire connection.</p>\n\n<p>With UDP, it is stateless, and there is no guarantee on delivery. it is also much faster/easier to create connections, because there is no need for negotiation.</p>\n\n<p>On the other hand, if the key-stroke does not get through, it won't show up on the screen either, and the user can be the 'resend' mechanism.... if the user types a key, and it does not show up on the screen, the user can type it again.</p>\n\n<p>So, UDP may be a useful protocol for you, and you may want to keep it... but... the reason it is so much faster than TCP is because you are using TCP completely against the way it is designed to be used.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T11:15:58.197", "Id": "76682", "Score": "0", "body": "I've edited my question, looking your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:55:05.493", "Id": "76772", "Score": "0", "body": "\"rolfl\" Can you check my new edit? I have see same problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:58:42.957", "Id": "76774", "Score": "0", "body": "@sallamaniaa - come join us in the [2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) chat room, go through some things." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T00:09:11.910", "Id": "44211", "ParentId": "44189", "Score": "5" } } ]
{ "AcceptedAnswerId": "44211", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:09:41.493", "Id": "44189", "Score": "8", "Tags": [ "java", "android", "tcp" ], "Title": "Latency problem for keyboard remoting from Android phone" }
44189
<p>I've got the following code to find the shortest path between two nodes using almost-Dijkstra's-algorithm which was written for an exercise, and I'm looking for things to improve my general Scala style. What I currently have:</p> <pre><code> object Graphs { case class Node[T](value : T) case class Edge[T](from : Node[T], to : Node[T], dist : Int) def shortest[T](edges : Set[Edge[T]], start : T, end : T) : Option[List[Edge[T]]] = { val tentative = edges.flatMap(e =&gt; Set(e.from, e.to)).map(n =&gt; (n, if (n.value == start) Some(List.empty[Edge[T]]) else None )).toMap def rec(tentative : Map[Node[T], Option[List[Edge[T]]]]) : Option[List[Edge[T]]] = { val current = tentative.collect{ case (node, Some(route)) =&gt; (node, route)}.toList.sortBy(_._2.length).headOption current match { case None =&gt; None case Some((node, route)) =&gt; { if (node.value == end) Some(route) else { val fromHere = edges.filter(e =&gt; e.from == node) val tentupdates = for(edge &lt;- fromHere if tentative.contains(edge.to)) yield { tentative.get(edge.to) match { case None =&gt; throw new Error("broken algorithm") case Some(Some(knownroute)) if (knownroute.map(_.dist).sum &lt; route.map(_.dist).sum + edge.dist) =&gt; (edge.to, Some(knownroute)) case _ =&gt;(edge.to, Some(edge :: route)) } } val newtentative = (tentative ++ tentupdates) - node rec(newtentative) } } } } rec(tentative) } } </code></pre> <p>First of, getting some feedback on the correctness would be nice.</p> <p>For the algorithm itself, I already know it could be refined by keeping track of the unevaluated edges, and for a more general solution keeping a second accumulator with the solved set wouldn't cost me much more, but I get the general idea of how to implement that.</p> <p>I'm thinking of replacing Node with Scalaz TypeTags, and would like some feedback on whether that's a good idea.</p> <p>Other than that, I'd like some feedback on general style, and how to improve readability - I have quite long lines now for example. Also, types like <code>Map[Node[T], Option[List[Edge[T]]]]</code> sort of hurt my eyes, I'd love to know how I could improve that.</p> <p>Lastly, I really don't like my</p> <pre><code>case Some(Some(knownroute)) if (knownroute.map(_.dist).sum &lt; route.map(_.dist).sum + edge.dist) =&gt; (edge.to, Some(knownroute)) case _ =&gt; (edge.to, Some(edge :: route)) </code></pre> <p>the first case is only used as a filter, I'm actually looking for something like </p> <pre><code>case None || Some(Some(knownroute)) if (knownroute.map(_.dist).sum &gt; route.map(_.dist).sum + edge.dist) =&gt; (edge.to, Some(edge :: route)) </code></pre> <p>but I don't know how to express that.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T22:01:54.367", "Id": "76594", "Score": "0", "body": "Nice problem! Your search algorithm is quite custom. Is it okay if we change the implementation a bit? If not then could you please add comments of what you're doing to make it easier for us? Usually Dijkstra uses distances to keep track of its progress." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T22:07:50.213", "Id": "76595", "Score": "0", "body": "This keeps track of distances as well, but the distance is evaluated on the fly as `route.map(_.distance).sum`. I know this is inefficient if the routes are quite large. I considered keeping a `Tuple2[List[Edge[T], Int]` rather than just a `List[Edge[T]`, but I figured that was trivial anyway, and would clutter the clarity of the implementation (a production version would have it, but this is basically a toy). If you would like to propose changes to the algorithm, by all means do!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T23:10:15.423", "Id": "76603", "Score": "0", "body": "If that's the case then `.sortBy(_._2.length)` is not optimal. It should be adding the weights together and choosing the next candidate based on the shortest weighted path." } ]
[ { "body": "<p>There are a few things how this could be improved.</p>\n\n\n\n<p>First, a few minor quibbles about syntax:</p>\n\n<ul>\n<li><p>When using a type annotation, do not put a space before the <code>:</code> – <code>name: Type</code>, please. (<a href=\"http://docs.scala-lang.org/style/types.html#annotations\" rel=\"nofollow\">source</a>)</p></li>\n<li><p>In a chain of higher-order methods, do not use the <code>.</code> to invoke the method. For example this</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>val tentative = edges.flatMap(e =&gt; Set(e.from, e.to)).map(n =&gt; (n, if (n.value == start) Some(List.empty[Edge[T]]) else None )).toMap\n</code></pre>\n\n<p>should be</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>val tentative = edges flatMap (e =&gt; Set(e.from, e.to)) map (n =&gt; (n, if (n.value == start) Some(List.empty[Edge[T]]) else None)).toMap\n</code></pre>\n\n<p>(<a href=\"http://docs.scala-lang.org/style/method-invocation.html#higherorder_functions\" rel=\"nofollow\">source</a>)</p></li>\n<li><p>When a chain of transformations is very long, splitting inside the lambdas can be an acceptable solution:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>val tentative = edges flatMap (\n e =&gt; Set(e.from, e.to)\n ) map (n =&gt;\n (n, if (n.value == start) Some(List.empty[Edge[T]]) else None)\n ).toMap\n</code></pre></li>\n<li><p><code>yield { block }</code> is “evil” and should be avoided. <code>for</code>-comprehensions can be rewritten less clearly with <code>flatMap</code> and <code>filter</code>, but this may actually be preferable when the transformations are deeply nested.</p></li>\n</ul>\n\n<p>Now let's look at this piece of your code:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>for(edge &lt;- fromHere if tentative.contains(edge.to)) yield {\n tentative.get(edge.to) match {\n case None =&gt; throw new Error(\"broken algorithm\")\n case Some(Some(knownroute)) if (knownroute.map(_.dist).sum &lt; route.map(_.dist).sum + edge.dist) =&gt; (edge.to, Some(knownroute))\n case _ =&gt;(edge.to, Some(edge :: route))\n }\n}\n</code></pre>\n\n<p>As I said, this could be rewritten to avoid the comprehension.</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>fromHere filter (edge =&gt; tentative.contains(edge.to)) flatMap { edge =&gt;\n tentative.get(edge.to) match {\n case None =&gt; throw new Error(\"broken algorithm\")\n case Some(Some(knownroute)) if (knownroute.map(_.dist).sum &lt; route.map(_.dist).sum + edge.dist) =&gt; (edge.to, Some(knownroute))\n case _ =&gt; (edge.to, Some(edge :: route))\n }\n}\n</code></pre>\n\n<p>The <code>tentative.get(…)</code> returns an <code>Option</code>, which will be <code>None</code> if no element for that key was found. But that means we can get rid of the <code>filter</code>! Instead, we <code>map</code> over the result of the <code>get</code>, which removes one level of <code>Option</code>s:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>fromHere flatMap { edge =&gt;\n tentative.get(edge.to) map {\n case Some(knownroute) if (knownroute.map(_.dist).sum &lt; route.map(_.dist).sum + edge.dist) =&gt; (edge.to, Some(knownroute))\n case _ =&gt; (edge.to, Some(edge :: route))\n }\n}\n</code></pre>\n\n<p>Destructuring the <code>Option</code> with Pattern matching is a bit tedious. Actually, we want to do one thing, <code>orElse</code> some default case.</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>fromHere flatMap { edge =&gt;\n tentative.get(edge.to) map { maybeRoute =&gt;\n maybeRoute filter (knownroute =&gt;\n knownroute.map(_.dist).sum &lt; route.map(_.dist).sum + edge.dist\n ) map (knownroute =&gt;\n Pair(edge.to, Some(knownroute)\n ) getOrElse (Pair(edge.to, Some(edge :: route)))\n }\n}\n</code></pre>\n\n<p>But this is an unreadable mess! Yes, it somehow is. We can improve this by adding a <code>Route</code> class, e.g:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>case class Route[T](route: List[Edge[T]], dist: Int) {\n val length = route.length\n\n def this(route: List[Edge[T]]) = this(route, route map (_.dist) sum)\n\n def this() = this(List.empty[Edge[T]], 0)\n\n def ::(edge: Edge[T]) = Route(edge :: route, dist + edge.dist)\n}\n\nval tentative: Map[Node[T], Option[Route[T]] = ...\n</code></pre>\n\n<p>The main advantage is that this keeps track of a route's distance, which means the above code becomes the slightly more accessible</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>fromHere flatMap { edge =&gt;\n tentative.get(edge.to) map { maybeRoute =&gt;\n val maybeBetterRoute =\n maybeRoute filter (knownRoute =&gt; knownRoute.dist &lt; route.dist + edge.dist)\n maybeBetterRoute map (knownRoute =&gt;\n Pair(edge.to, Some(knownroute)\n ) getOrElse (\n Pair(edge.to, Some(edge :: route))\n )\n }\n}\n</code></pre>\n\n<p>You calculate the <code>fromHere</code> each time, which is an <em>O(n)</em> calculation, I think:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>val fromHere = edges.filter(e =&gt; e.from == node)\n</code></pre>\n\n<p>It may be better to build a <code>Map[Node[T], List[Edge[T]]]</code> before the recursion, which is also a fairly cheap operation:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>val edgesBySource = edges groupBy (_.from)\n</code></pre>\n\n<p>then: <code>val fromHere = edgesBySource.get(node).flatten</code>. I assume this would pay off soon for non-tiny graphs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:40:32.060", "Id": "76702", "Score": "0", "body": "great stuff! I'll get cracking on it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T12:05:33.680", "Id": "44249", "ParentId": "44195", "Score": "2" } } ]
{ "AcceptedAnswerId": "44249", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:50:28.107", "Id": "44195", "Score": "6", "Tags": [ "algorithm", "scala", "graph" ], "Title": "Dijkstra-like routing algorithm" }
44195
<p>Here is my implementation of a simple 3 rotor Enigma machine in C++:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; using namespace std; char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char rotors[3][27] = { "EKMFLGDQVZNTOWYHXUSPAIBRCJ", "AJDKSIRUXBLHWTMCQGZNPYFVOE", "BDFHJLCPRTXVZNYEIWGAKMUSQO" }; char reflector[] = "YRUHQSLDPXNGOKMIEBFZCWVJAT"; char key[] = "ABC"; long mod26(long a) { return (a%26+26)%26; } int li (char l) { // Letter index return l - 'A'; } int indexof (char* array, int find) { return strchr(array, find) - array; } string crypt (const char *ct) { // Sets initial permutation int L = li(key[0]); int M = li(key[1]); int R = li(key[2]); string output; for ( int x = 0; x &lt; strlen(ct) ; x++ ) { int ct_letter = li(ct[x]); // Step right rotor on every iteration R = mod26(R + 1); // Pass through rotors char a = rotors[2][mod26(R + ct_letter)]; char b = rotors[1][mod26(M + li(a) - R)]; char c = rotors[0][mod26(L + li(b) - M)]; // Pass through reflector char ref = reflector[mod26(li(c) - L)]; // Inverse rotor pass int d = mod26(indexof(rotors[0], alpha[mod26(li(ref) + L)]) - L); int e = mod26(indexof(rotors[1], alpha[mod26(d + M)]) - M); char f = alpha[mod26(indexof(rotors[2], alpha[mod26(e + R)]) - R)]; output += f; } return output; } int main () { for ( int i = 0; i &lt; 1000000; i++) { crypt ("PZUFWDSASJGQGNRMAEODZJXQQKHSYGVUSGSU"); } return 0; } </code></pre> <p>Benchmark ran on a 2.66ghz Core 2 Duo for 1 million decrypts:</p> <p><a href="https://gist.github.com/rd13/7372208" rel="nofollow">C++ Version</a>:</p> <pre><code>11.64s user 0.02s system 97% cpu 11.963 total </code></pre> <p>I'm not a C++ programmer, I first wrote this in Javascript and then translated it into C++.</p> <p>Whilst 1 million in ~10 seconds is OK, I feel that my implementation isn't optimal. Are there any optimisations, or micro optimisations that you could recommend to my C++ code to make it faster? Maybe I should try a different language? Any suggestions are welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-04T18:49:16.140", "Id": "308726", "Score": "0", "body": "Which is faster: int, long, boolean, or double make your constants constant - saves time" } ]
[ { "body": "<p>I think you can improve the <em>'Inverse rotor pass'</em> a lot by hard-code the inverted rotors instead of searching the inverse function every time.</p>\n\n<p>Your <code>a</code> is never below <code>-26</code> so you could try to replace </p>\n\n<pre><code>long mod26(long a)\n{\n return (a%26+26)%26;\n}\n</code></pre>\n\n<p>by</p>\n\n<pre><code>long mod26(long a)\n{\n return (a+26)%26;\n}\n</code></pre>\n\n<p>But only profiling will tell you if / how much speed improvement that brings. Also you should always profile before trying to optimize. See were the bottleneck is.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:18:31.793", "Id": "44200", "ParentId": "44196", "Score": "5" } }, { "body": "<p>Let's profile this a little bit (this is on a dual-core i7, so a bit quicker):</p>\n\n<blockquote>\n <p>Running Time Self Symbol Name</p>\n \n <p>3984.0ms 100.0% 0.0 Main Thread 0x2856c</p>\n \n <p>3982.0ms 99.9% 0.0 start</p>\n \n <p>3982.0ms 99.9% 1.0 main</p>\n \n <p>3936.0ms 98.7% 3081.0 crypt(char const*)</p>\n \n <p>640.0ms 16.0% 640.0 _platform_strchr</p>\n \n <p>126.0ms 3.1% 102.0 std::__1::basic_string, std::__1::allocator >::push_back(char)</p>\n \n <p>89.0ms 2.2% 89.0 strlen</p>\n \n <p>14.0ms 0.3% 14.0 DYLD-STUB$$strchr</p>\n \n <p>14.0ms 0.3% 4.0 free</p>\n \n <p>8.0ms 0.2% 1.0 szone_free_definite_size</p>\n \n <p>7.0ms 0.1% 7.0 DYLD-STUB$$strlen</p>\n \n <p>2.0ms 0.0% 2.0 operator delete(void*)</p>\n \n <p>2.0ms 0.0% 0.0 _dyld_start</p>\n</blockquote>\n\n<p>Ok, so more than 98% of the time is spent in the <code>crypt</code> function (which isn't surprising really). Almost 16% of the time is spent in <code>strchr</code>, with another 3.1% spent in <code>push_back</code>. There's also a few percent (2.2) spent doing <code>strlen</code>. </p>\n\n<p>Ok, so how do we cut down on these:</p>\n\n<p>Firstly, we'll switch over to using <code>std::array&lt;char&gt;</code> instead of <code>char *</code>. These are both stack-allocated (and so we don't incur the dynamic allocation overhead of <code>std::string</code> or <code>std::vector</code>), but <code>std::array</code> knows its size, and will allow us to remove the <code>strlen</code> in the crypt function:</p>\n\n<pre><code>#include &lt;array&gt;\n\nconst std::array&lt;char, 27&gt; alpha = {\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"};\nconst std::array&lt;std::array&lt;char, 27&gt;, 3&gt; rotors\n{\n {{\"EKMFLGDQVZNTOWYHXUSPAIBRCJ\"},\n {\"AJDKSIRUXBLHWTMCQGZNPYFVOE\"},\n {\"BDFHJLCPRTXVZNYEIWGAKMUSQO\"}}\n};\n\nconst std::array&lt;char, 27&gt; reflectors = {\"YRUHQSLDPXNGOKMIEBFZCWVJAT\"};\nconst std::array&lt;char, 4&gt; key = {\"ABC\"};\n</code></pre>\n\n<p>The <code>indexof</code> function then needs to change as well (and I'm going to rename it to <code>index_of</code>, which is easier to read):</p>\n\n<pre><code>template &lt;size_t N&gt;\nstd::size_t index_of (const std::array&lt;char, N&gt;&amp; str, int find)\n{\n for(std::size_t i = 0; i &lt; N; ++i) {\n if(str[i] == find) return i;\n }\n return -1;\n}\n</code></pre>\n\n<p><code>crypt</code> now looks like:</p>\n\n<pre><code>template &lt;size_t N&gt;\nstd::array&lt;char, N&gt; crypt (const std::array&lt;char, N&gt;&amp; ct)\n{\n // Sets initial permutation\n int L = li(key[0]);\n int M = li(key[1]);\n int R = li(key[2]);\n\n std::array&lt;char, N&gt; output;\n\n for ( unsigned x = 0; x &lt; N ; x++ ) {\n int ct_letter = li(ct[x]);\n\n // Step right rotor on every iteration\n R = static_cast&lt;int&gt;(mod26(R + 1));\n\n // Pass through rotors\n char a = rotors[2][mod26(R + ct_letter)];\n char b = rotors[1][mod26(M + li(a) - R)];\n char c = rotors[0][mod26(L + li(b) - M)];\n\n // Pass through reflector\n char ref = reflectors[mod26(li(c) - L)];\n\n // Inverse rotor pass\n long d = mod26(index_of(rotors[0], alpha[mod26(li(ref) + L)]) - L);\n long e = mod26(index_of(rotors[1], alpha[mod26(d + M)]) - M);\n char f = mod26(index_of(rotors[2], alpha[mod26(e + R)]) - R);\n\n output[x] = alpha[f];\n }\n\n return output;\n}\n</code></pre>\n\n<p>which is close to what it was, but with a few minor changes (no <code>+=</code> on a <code>string</code>, as we know already how large it will be and simple assign directly into that index).</p>\n\n<p>And we now call it like so:</p>\n\n<pre><code>int main ()\n{\n for ( int i = 0; i &lt; 1000000; i++) {\n crypt(std::array&lt;char, 37&gt;{\"PZUFWDSASJGQGNRMAEODZJXQQKHSYGVUSGSU\"});\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Let's profile this again:</p>\n\n<blockquote>\n <p>Running Time Self Symbol Name</p>\n \n <p>2873.0ms 100.0% 0.0 Main Thread 0x2c7ff</p>\n \n <p>2872.0ms 99.9% 0.0 start</p>\n \n <p>2872.0ms 99.9% 2.0 main</p>\n \n <p>2870.0ms 99.8% 2870.0 std::__1::array crypt&lt;37ul>\n (std::__1::array const&amp;)</p>\n \n <p>1.0ms 0.0% 0.0 _dyld_start</p>\n</blockquote>\n\n<p>Ok, so everything except <code>crypt</code> has now been inlined. If we apply the modification from @MrSmith42, we shave even more time off:</p>\n\n<blockquote>\n <p>Running Time Self Symbol Name</p>\n \n <p>1855.0ms 100.0% 0.0 Main Thread 0x2ca5c</p>\n \n <p>1854.0ms 99.9% 0.0 start</p>\n \n <p>1854.0ms 99.9% 1.0 main</p>\n \n <p>1853.0ms 99.8% 1853.0 std::__1::array crypt&lt;37ul>\n (std::__1::array const&amp;)</p>\n \n <p>1.0ms 0.0% 0.0 _dyld_start</p>\n</blockquote>\n\n<p>We have imposed a fairly large constraint however: we need to know the size of the string to be encrypted at compile-time (so no reading it from a file or <code>stdin</code> or the like). If this will always be the case, then this provides a fairly significant speed-up on my hardware.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:19:40.717", "Id": "76724", "Score": "0", "body": "How are you compiling this? On your version (g++ -std=c++11 enigma.cpp), runtime is 20.85s. On my version (g++ enigma.cpp) runtime is 11.63s?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T23:58:24.953", "Id": "76851", "Score": "0", "body": "This is under `clang`. Are you compiling with `-O2` or `-O3`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T02:25:17.450", "Id": "76854", "Score": "0", "body": "@StuR I suggest trying the two on an online compiler like http://coliru.stacked-crooked.com/ - and doing timings with that. I get a decrease from ~9.5s to about ~5.5s using the above changes." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T02:42:41.573", "Id": "44221", "ParentId": "44196", "Score": "10" } }, { "body": "<p>You provide the timing of the 4 different versions. </p>\n\n<p>But that is useless without the code (if you wrote the perl version as badly as the C++ version then its not surprising you get bad results). Before times are useful for a comparison we need to make sure that the tests are comparable. So we really need the code for all four versions. Then we can get criticism of all four code bases and work to get them aligned to the best implementation of the appropriate languages. Once we have done that then we can do realistic timings.</p>\n\n<h2>Note 1:</h2>\n\n<p>Stop using <code>C</code></p>\n\n<pre><code> string crypt (const char *ct)\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code> string crypt (std::string const&amp; ct)\n</code></pre>\n\n<h2>Note 2:</h2>\n\n<p>This allows a much needed speedup here:</p>\n\n<pre><code>for ( int x = 0; x &lt; strlen(ct) ; x++ ) {\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>for (char c : ct)\n// or if using C++03\nfor (std::string::const_iterator c = ct.begin(); c != ct.end(); ++c)\n</code></pre>\n\n<p>This should improve performance considerably as you are not re-calculating string length all the time.</p>\n\n<h2>Note 3:</h2>\n\n<p>Always do timing after you have compiled the optimized version</p>\n\n<pre><code>g++ -O3 &lt;stuff&gt;\n</code></pre>\n\n<h2>Note 4:</h2>\n\n<p>These values are const</p>\n\n<pre><code>int L = li(key[0]);\nint M = li(key[1]);\nint R = li(key[2]);\n</code></pre>\n\n<p>Try:</p>\n\n<pre><code>int const L = li(key[0]);\nint const M = li(key[1]);\nint const R = li(key[2]);\n</code></pre>\n\n<h2>Note 5:</h2>\n\n<p>This looks decidedly inefficient:</p>\n\n<pre><code>int d = mod26(indexof(rotors[0], alpha[mod26(li(ref) + L)]) - L);\n</code></pre>\n\n<p>Looking at:</p>\n\n<pre><code>indexof(rotors[0], alpha[mod26(li(ref) + L)])\n\n\n// indexof(&lt;C-String&gt; , &lt;char&gt;)\n// Does a linear search of the string.\n// That is very inefficient. Why not use std::unordered_map&lt;char, int&gt;.\n// If you don't want to waste space use std::map&lt;char, int&gt;\n</code></pre>\n\n<h2>Note 5:</h2>\n\n<p>You may think this is C++ but it's not.<br>\nThis is a C implementation and not a good one.</p>\n\n<p>The javascript version relies on an engine written in C++ that is highly optimized. If you don't apply the same techniques that were used by the javascript engine, then I am not surprised that you get similar results. I would expect the C++ version to run 100x faster \n(not 4x) than javascript.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T05:48:35.277", "Id": "76649", "Score": "0", "body": "Linear searches on very short strings such as these will (most probably) outperform `map` lookups." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T11:08:41.970", "Id": "76680", "Score": "0", "body": "Source code for the other versions are in my question, if you click on where it says for example \"Javascript Version:\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:34:41.753", "Id": "76715", "Score": "1", "body": "@Yuushi: Maybe (if they were shorter). But if you are going to make that claim you better be able to back it up. Did you time it? In my world O(ln(n)) is better than O(n) unless **proved** otherwise and with a bit of work you could probably make it O(1)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T02:18:27.413", "Id": "76853", "Score": "0", "body": "Here you go: http://coliru.stacked-crooked.com/a/87669fd0d562983f - with just an upper-case alphabet, `std::array` is significantly faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T03:58:38.467", "Id": "76859", "Score": "0", "body": "Used your code. Change I made (remove the `srand()`) as that is not useful when doing timing tests. On Mac Book Pro: 2.3 GHz Core i7. `g++ --version == clang-500.2.79`. Built using `g++ -std=c++11 -O3 time.cpp`: Ran each test three times. Array(75/78/77) unordered_set(74/78/78) set(75/74/78). All looks about the same to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T03:59:48.470", "Id": "76860", "Score": "0", "body": "I think you may find that having random sets of data may have scewed your results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T07:45:29.330", "Id": "76878", "Score": "0", "body": "If I remove the call to `srand()`, I get array: 71/73/74, unordered_set: 142/147/145, set: 290/288/302. Compiled using `g++-4.8 (GCC) 4.8.2` with `std=c++11 -O3`. However, using `clang++ (clang-500.2.79) (based on LLVM 3.3svn)` with the same `-std=c++11 -O3` I get array: 73/71/75, unordered_set: 72/72/74, set: 72/71/71. Seems like there is quite a difference between gcc and clang here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:44:56.813", "Id": "76979", "Score": "0", "body": "@Yuushi: More likely is that clang was built for your processor while the g++ version was built for a generic processor. Thus g++ can not take advantage of processor specific optimizations. Try getting a correctly built g++. The differences between clang++ and g++ should be insignificant." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-13T04:48:08.870", "Id": "44229", "ParentId": "44196", "Score": "7" } } ]
{ "AcceptedAnswerId": "44221", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T20:52:10.690", "Id": "44196", "Score": "12", "Tags": [ "c++", "performance", "cryptography", "simulation", "enigma-machine" ], "Title": "Enigma simulator performance" }
44196
<p>Can someone please let me know if they see glaring issues with this code? I tested a handful of cases and it seems to work but in other threads. I often see much more concisely written versions of this. I just want to know if anything I have done is superfluous or just stylistically poor form.</p> <pre><code>#include &lt;stdio.h&gt; int value = 5; int values[] = {2,4,5,12,23,34}; int n = 6; int re_search(int value, int values[], int n); int main(void) { re_search(value, values, n); return 0; } int re_search(int value, int values[], int n) { int first = 0; int last = n-1; int middle = (first+last)/2; while (first &lt;= last) { if (value == values[middle]) { printf("Found it!\n"); return 0; } else if (value &gt; values[middle]) { first = middle + 1; middle = (first + last) / 2; return re_search(value, &amp;values[middle], last-first); } else { last = middle - 1; return re_search(value, &amp;values[middle], last-first); } middle = (first + last) / 2; } printf("Did not find it\n"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:48:27.753", "Id": "76592", "Score": "1", "body": "As @syb0rg noted, you have a stray `if(value <0)` that causes compilation to fail. Furthermore, if you try with `int value = 34` instead of 5, it won't find it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T23:37:27.257", "Id": "76612", "Score": "1", "body": "There is a standard library function [`bsearch()`](http://www.cplusplus.com/reference/cstdlib/bsearch/) that can accomplish this same task, so I am tagging this with \"reinventing-the-wheel\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T00:17:49.490", "Id": "76615", "Score": "0", "body": "@200_success thanks for catching this. I now see it will not find the value if it is either the first or last in the array. Now just need to figure out why. Probably something to do with how I calculate middle. I thought this would recursively shorten the array such that every number would eventually be a \"middle\" to be compared to the value" } ]
[ { "body": "<p>Your solution combines iteration and recursion, which means that a lot of unnecessary work is done. Normally you'll want to choose only one method.</p>\n\n<p>A simple iterative version:</p>\n\n<pre><code>int re_search(int value, int values[], int n)\n{\n int first = 0;\n int last = n-1;\n int middle = (first+last)/2;\n\n for(;first &lt;= last;middle = (first + last) / 2)\n {\n if (value == values[middle])\n {\n printf(\"Found it!\\n\");\n return 0;\n }\n else if (value &gt; values[middle])\n {\n first = middle + 1;\n } \n else\n {\n last = middle - 1;\n } \n }\n printf(\"Did not find it\\n\");\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T23:15:00.593", "Id": "76605", "Score": "0", "body": "So I don't need the while loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T23:16:51.617", "Id": "76607", "Score": "0", "body": "I've replaced the `while` loop with an equivalent `for` loop - that's mostly a matter of taste. The major change is that the function is no longer recursive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T00:03:49.640", "Id": "76614", "Score": "0", "body": "@opd You've been pretty active for a new user. Feel free to join us in our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:36:29.450", "Id": "44202", "ParentId": "44199", "Score": "6" } }, { "body": "<h1>Things you did well</h1>\n\n<ul>\n<li><p>Declaring your parameters as <code>void</code> when you don't take in any arguments.</p></li>\n<li><p>Keeping your dependencies to a minimum.</p></li>\n</ul>\n\n<h1>Things you could improve</h1>\n\n<h3>Bugs:</h3>\n\n<ul>\n<li><p>You sorted your array for your program.</p>\n\n<blockquote>\n<pre><code>int values[] = {2,4,5,12,23,34};\n</code></pre>\n</blockquote>\n\n<p>Your program fails to find your <code>value</code> if your array is not sorted initially.</p>\n\n<pre><code>int values[] = {9,4,3,12,69,34};\n</code></pre>\n\n<p>Let the computer do the hard work by using <a href=\"http://www.cplusplus.com/reference/cstdlib/qsort/\" rel=\"nofollow\"><code>qsort()</code></a>.</p></li>\n</ul>\n\n<h3>Efficiency:</h3>\n\n<ul>\n<li><p>Recursion is slowing you down in your <code>re_search()</code> method. Use iteration instead. The conversion isn't too hard, there are a lot of similarities.</p>\n\n<pre><code>int binarySearch(int a[], int low, int high, int target)\n{\n while (low &lt;= high)\n {\n int middle = low + (high - low)/2;\n if (target &lt; a[middle]) high = middle - 1;\n else if (target &gt; a[middle]) low = middle + 1;\n else return middle;\n }\n return -1;\n}\n</code></pre></li>\n</ul>\n\n<h3>Variables/Initialization:</h3>\n\n<ul>\n<li><p>You shouldn't use global variables.</p>\n\n<blockquote>\n<pre><code>int value = 5;\nint values[] = {2,4,5,12,23,34};\nint n = 6;\n</code></pre>\n</blockquote>\n\n<p>The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.</p>\n\n<p>To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).</p>\n\n<p>If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.</p>\n\n<p>So instead of using global variables, initialize the variables in <code>main()</code>, and pass them as arguments to functions if necessary.</p></li>\n<li><p>Right now your <code>n</code> variable is hard coded.</p>\n\n<blockquote>\n<pre><code>int n = 6;\n</code></pre>\n</blockquote>\n\n<p>Since this is just the number of elements in your array, we can make this a bit more dynamic, so that you don't have to change it if you add a few more elements to your array.</p>\n\n<pre><code>int n = sizeof(values)/sizeof(values[0]);\n</code></pre></li>\n<li><p>Right now you are hard coding the number you are looking for. </p>\n\n<blockquote>\n<pre><code>int value = 5;\n</code></pre>\n</blockquote>\n\n<p>I would either let the user enter it, or determine a random number to search for.</p>\n\n<pre><code>srand((unsigned int) time(NULL)); // seeding\nint val = values[rand() % n];\n</code></pre></li>\n</ul>\n\n<h3>Syntax/Styling:</h3>\n\n<ul>\n<li><p>You print out items to the console within your <code>re_search()</code> method.</p>\n\n<blockquote>\n<pre><code>printf(\"Found it!\\n\");\n...\nprintf(\"Did not find it\\n\");\n</code></pre>\n</blockquote>\n\n<p>I would have it so your function only evaluates if the number exists in the array and returns whether it could find it or not. Then let <code>main()</code> do all the printing to the console based on that information.</p>\n\n<pre><code>printf(\"%s\\n\", (re_search(value, values, n)) ? \"Found it!\" : \"Didn't find it.\");\n</code></pre></li>\n</ul>\n\n<h1>Final Code</h1>\n\n<p>I've rewritten your code so that it is bug free, and so that it is a bit more dynamic. I also rewrote some bits so you could see what was going on, and so the program was more transparent.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\nint binarySearch(int a[], int low, int high, int target)\n{\n while (low &lt;= high)\n {\n int middle = low + (high - low)/2;\n if (target &lt; a[middle]) high = middle - 1;\n else if (target &gt; a[middle]) low = middle + 1;\n else return middle;\n }\n return -1;\n}\n\nint compare(const void *a, const void *b)\n{\n return (*(int*)a - *(int*)b);\n}\n\nvoid printArray(int arr[], int size)\n{\n printf(\"{ \");\n for (int i = 0; i &lt; size; i++) printf(\"%d, \", arr[i]);\n puts(\"}\");\n}\n\nint main(void)\n{\n int values[] = {16, 7, 5, 94, 24, 34};\n int n = sizeof(values)/sizeof(values[0]); // find the number of elements in the array\n qsort(values, n, sizeof(values[0]), compare);\n srand((unsigned int) time(NULL)); // seeding\n int val = values[rand() % n]; // fetch a random value in the array\n int found = binarySearch(values, 0, n - 1, val);\n\n printArray(values, n); // just so we can see the sorted array\n if (found &gt;= 0) printf(\"Found %d at index %d\\n\", val, found);\n else printf(\"Didn't find %d\\n\", val);\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T23:14:13.777", "Id": "76604", "Score": "0", "body": "Good suggestions. Your code is so much cleaner. Passing in 0 and n-1 seems like the more optimal approach vs. setting variables in the function and passing in the length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T23:15:51.470", "Id": "76606", "Score": "0", "body": "@syb0rg: For [this answer](http://codereview.stackexchange.com/a/44171/33366), why did you make the \"(n^2)\" into a subscript? (I'm not talking about just making the \"^2\" into a superscript.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T23:19:18.513", "Id": "76610", "Score": "0", "body": "@RickyDemer That is more of a discussion for the [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor). I'll talk more about it there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T23:52:42.643", "Id": "76613", "Score": "0", "body": "The input array being already sorted is usually considered a precondition for binary search. For example, [Java's `binarySearch()`](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch\\(int[],%20int\\)) says that if the array is not sorted, the results are undefined." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:43:52.673", "Id": "44205", "ParentId": "44199", "Score": "10" } } ]
{ "AcceptedAnswerId": "44205", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:14:58.537", "Id": "44199", "Score": "7", "Tags": [ "c", "recursion", "binary-search", "reinventing-the-wheel" ], "Title": "Can this recursive binary search in C be made more concise?" }
44199
<p>I have a situation where I need to store fields of differing types of some data structures along with some similar metadata (The application takes data from one of many sources, some data possibly coming from more than one source, and then does stuff with it).</p> <p>The solution I came up with was to create a class that would hold each piece of data which I could then add to each object. The <code>DataParam</code> object can be loaded with any data type that's determined when it's first constructed. When we get or set it later, those methods are passed a class type similar to what we are getting or setting. Since we always check against the value we originally "typed" our object with, we can never accidentally set it to some other type of value (and mess everything up).</p> <p>The reason these are all generic methods and the entire class isn't a generic is because I need to store <code>DataParam</code> in a container and that wouldn't be possible if the class itself was a generic (I can't store a <code>DataParam&lt;String&gt;</code>, and a <code>DataParam&lt;int&gt;</code> in one container).</p> <pre><code>public class DataParam { public String name public boolean wasUpdated private String type private boolean isArray private Object data; public &lt;T&gt; DataParam(String name, Class&lt;T&gt; typeClass) { this.name = name; type = typeClass.getName(); isArray = typeClass.isArray(); data = null; wasUpdate = false; } public &lt;T&gt; T get(Class&lt;T&gt; typeClass) { if(type.equals(typeClass.getName()) &amp;&amp; isArray == typeClass.isArray()) return typeClass.cast(data); else return null; } public &lt;T&gt; T set(T obj, Class&lt;T&gt; typeClass) { if(type.equals(typeClass.getName()) &amp;&amp; isArray == typeClass.isArray()) data = (Object) obj; } public String doSomething() { //An example of doing different things based on type switch(type) { case "java.lang.String": if(isArray) return TakesAStringArray(get(String[].class)); else return TakesAString(get(String.class)); break; case "java.lang.Integer": return TakesAnInteger(get(Integer.class)); break; case "myPackage.DataParam": return TakesADataParam(get(myPackage.DataParam.class)); break; //default: Do nothing } } public DataObj { protected HashMap&lt;String,DataParam&gt; fields; //Other functions } public SpecificObj extends DataObj { public SpecificObj() { fields.add(new DataParam("name", String.class)); fields.add(new DataParam("obj", myPackage.DataParam.class)); fields.add(new DataParam("count", Integer.class)); } } </code></pre> <p>My questions are, is there anything blatantly obviously wrong with this, like I'm gonna screw myself over later? Is there a better way that I should consider?</p> <p>This should be type safe, right? (I'm checking the class every time I do anything with that piece of data, but it just seems weird that I have to do it myself versus like, the compiler raising an error that I'm doing it wrong).</p>
[]
[ { "body": "<p>What you are doing appears to be sane. The use of generics is primarily as a compile-time validator (and it makes some code simpler, like not having to cast things).</p>\n\n<p>If you don't know the types of your data at compile time, then you can't use generics.</p>\n\n<p>So, you have run-time specified data, and that's OK. Do you handle that as well as it can be handled? That is the real question.</p>\n\n<p>Items I can see that raise question-marks:</p>\n\n<ul>\n<li>Why are you saving away the Class name (as <code>type</code>) when you can save away the actual Class?</li>\n<li><code>wasUpdated</code> is not used.</li>\n<li><code>type</code> is a bad name for a Java variable. It conflicts with <code>java.lang.Type</code>, and you don't need it anyway if you are going to store the Class instead of its name.</li>\n<li>if you <em>do</em> keep the class, then you can use the <code>Class.isInstance(...)</code> method to ensure the data types are correct, instead of specifying the class as part of the retrieval in the <code>get(Class&lt;T&gt; clazz)</code> method... or, you can confirm they are the same with a simple <code>.equals()</code> call instead of the name/isArray check.</li>\n<li>the methods like <code>return TakesAnInteger(...)</code> should have a lower-case <code>t</code> to start with.... <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow noreferrer\">this is the Java convention for method names</a>.</li>\n<li>Similarly, Java convention is to put the opening brace <code>{</code> for a block <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#15395\" rel=\"nofollow noreferrer\">on the same line as the method declaration</a>.</li>\n</ul>\n\n<p><strong><em>Edit: with Class saved instead of name and isArray</em></strong></p>\n\n<p>Also, I note now that you are missing some semi-colons in your data declarations.... and also, you are missing return values from some of your methods.</p>\n\n<pre><code>public class DataParam {\n public String name;\n public Class&lt;?&gt; dataClass;\n public boolean wasUpdated;\n private Object data;\n\n public DataParam(String name, Class&lt;?&gt; typeClass) {\n this.name = name;\n dataClass = typeClass;\n data = null;\n wasUpdated = false;\n }\n\n public &lt;T&gt; T get(Class&lt;T&gt; typeClass) {\n if(dataClass.equals(typeClass)) {\n return typeClass.cast(data);\n }\n return null;\n }\n\n public &lt;T&gt; T set(T obj, Class&lt;T&gt; typeClass) {\n if(dataClass.equals(typeClass)) {\n T toreturn = typeClass.cast(data);\n data = obj;\n return toreturn;\n }\n return null;\n }\n\n public String doSomething() {\n //An example of doing different things based on type\n //.......\n return null;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T02:50:14.523", "Id": "76640", "Score": "0", "body": "I can save the actual class? Can you elaborate? I assumed class was a generic and there would be no way to store Class<T> when T wouldn't be able to be referenced by the DataParam class.\n\nwasUpdated will be used later, it isn't shown here. It was more of an example of meta-data.\n\nWill change variable name when I figure out how to store the class.\n\nAnd points noted on the convention parts. I'll see what I can do. But more explanation on the storing the class will help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T03:00:50.927", "Id": "76642", "Score": "0", "body": "Edited answer with the example" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T03:49:14.397", "Id": "76645", "Score": "0", "body": "Thank you very much! This is also a great example of use of the wildcards. Perfect response." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T02:04:44.697", "Id": "44219", "ParentId": "44216", "Score": "6" } }, { "body": "<p>You are breaking encapsulation and the <a href=\"https://www.google.com/url?sa=t&amp;source=web&amp;rct=j&amp;ei=tu0oU93HA8SV2QWUgYHgBA&amp;url=http://en.m.wikipedia.org/wiki/Liskov_substitution_principle&amp;cd=1&amp;ved=0CCcQFjAA&amp;usg=AFQjCNGM74bnoc_aC8055nhn73jYmG3gxA&amp;sig2=E3UlV-Lsw4MGlGPovYQdqA\" rel=\"nofollow\">Liskov substitution principle</a> by exposing the individual parameter objects to clients. I expect getting a value looks something like this:</p>\n\n<pre><code>String host = dataObj.get(\"host\").get(String.class);\n</code></pre>\n\n<p>Blech! :) You could solve the problem and expose a cleaner API by providing type-specific accessors.</p>\n\n<pre><code>String host = dataObj.getString(\"host\");\n\npublic String getString(String name) {\n return get(name, String.class);\n}\n</code></pre>\n\n<p>Assuming a set of ten to twenty common types, you can make your API easier to use with these helpers. For the rest, the generic accessor will suffice. Either way, encapsulate all parameter item creation and use behind container methods, which you may already have since you left them out.</p>\n\n<pre><code>public &lt;T&gt; T get(String name, Class&lt;T&gt; type) {\n return getParam(name).get(type);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T01:35:03.943", "Id": "77727", "Score": "0", "body": "Actually, I cleaned up my code a few days ago and I came out with roughly the same method you have there at the end. I noticed that Java's SQL ResultSet has a .getString, .getLong, etc. and I wanted to implement something like that as well, I just wasn't sure how. I really like the return get(name, String.class), I didn't think of anything like that at all but I really like that. Thanks for the reply!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T01:13:59.383", "Id": "44717", "ParentId": "44216", "Score": "4" } } ]
{ "AcceptedAnswerId": "44219", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T01:10:00.293", "Id": "44216", "Score": "11", "Tags": [ "java", "generics", "type-safety" ], "Title": "Pattern for storing object of varying type" }
44216
<p>I have a requirement to validate file names related to architecture <em>after</em> they are uploaded. Once they have been uploaded I must warn the user if the file name is <strong>not</strong> standards compliant.</p> <p><strong>What's in a name</strong></p> <p>To be standards compliant a file name must consist of 7 parts after the extension is removed from the name, and:</p> <ol start="2"> <li>part 1 is the project code; an arbitrary set of letters (including diacritics, Ã, Â, etc) and numbers.</li> <li>part 2 is the discipline that the file relates to.</li> <li>part 3 is the project phase.</li> <li>part 4 is a 4-digit document number in the format of xxxx (0001, 0002, etc...)</li> <li>part 5 is the subject that the document relates to.</li> <li>part 6 is the floor that the project relates to.</li> <li>part 7 is the revision number; the format is RXX (R00, R01, etc...)</li> <li>parts must be in said order.</li> </ol> <p>Parts 2, 3, 5, and 6 must each be an abbreviation in a predefined set of values. Validating them is a simple matter of looking up if the abbreviate exists.</p> <p>I wrote a single class for each part. For the sake of brevity I included only one class out of four. But assume all four <strong>are identical</strong>. The only difference is the constant of acceptable abbreviations.</p> <pre><code>class FileName attr_reader :name def self.valid?(name) new(name).valid? end # Valid file name # ABCD-ARQ-AP-0022-ACS-LOC-R00.jpeg def initialize(name) # Split individual parts into an array, ignoring .extension @name = name.split('.').first.split('-') end def valid? name.length == 7 &amp;&amp; project_code_valid? &amp;&amp; discipline_valid? &amp;&amp; phase_valid? &amp;&amp; document_number_valid? &amp;&amp; subject_valid? &amp;&amp; level_valid? &amp;&amp; revision_valid? end def project_code @project_code ||= name[0] end def project_code_valid? project_code !~ /\P{Alnum}/ &amp;&amp; project_code.length == 4 end def discipline @discipline ||= name[1] end def discipline_valid? Discipline.value_valid?(discipline) end def phase @phase ||= name[2] end def phase_valid? Phase.value_valid?(phase) end def document_number @document_number ||= name[3] end def document_number_valid? document_number !~ /[^0-9]/ &amp;&amp; document_number.length == 4 end def subject @subject ||= name[4] end def subject_valid? Subject.value_valid?(subject) end def level @level ||= name[5] end def level_valid? Level.value_valid?(level) end def revision @revision ||= name[6].split('R') end def revision_valid? revision.length == 2 &amp;&amp; revision.first.empty? &amp;&amp; revision.last !~ /[^0-9]/ &amp;&amp; revision.last.length == 2 end end class Discipline DISCIPLINES = { 'Acessibilidade' =&gt; 'ACE', 'Acústica' =&gt; 'ACU' # Snip... } def self.value_valid?(value) new(value).value_valid? end def initialize(value) @value = value end def value_valid? DISCIPLINES.values.include?(@value) end end class Phase # Snip... end class Subject # Snip... end class Level # Snip... end </code></pre> <p><strong>Usage</strong></p> <pre><code> # files_helper.rb def file_name_valid?(file) unless FileName.valid?(file.name) content_tag :span, 'Invalid File Name', class: 'label-danger' end end </code></pre> <p><strong>Issues I have with the code</strong></p> <ol> <li>The aforementioned classes for parts 2, 3, 5, and 6 have a lot of duplication. As mentioned, they are identical except for the hash of acceptable values. Maybe inheritance is a good option?</li> <li>The <code>valid?</code> method looks very long winded.</li> <li>The classes are floating around in the file, raising the possibility of a name clash.</li> <li>The <code>FileName</code> class should be instantiated once. It should be a singleton. I'm not sure how to implement singletons in Rails.</li> <li>There's a lot of memoization (<code>@level ||= name[6]</code>) in the accessor methods I wrote for the different name parts.</li> <li>Can the <code>project_code_valid?</code> and <code>document_number_valid?</code> methods be more compact? Can Regex be used to check string length instead of having a separate check?</li> <li>All abbreviations (parts 2, 3, 5, and 6) should be uppercase; my regexes do not account for this.</li> <li>Again in parts parts 2, 3, 5, and 6, I am instantiating the class each time. Should this be memoized?</li> <li>The <code>revision</code> method seems too magical. <ol> <li>It splits the string by <code>R</code>. A valid rev should produce an array of two elements: <code>["", "00"]</code>.</li> <li>The first element of this array has to be <code>empty?</code> because splitting by <code>R</code> removes it and returns an empty string.</li> <li>And the last element has to be a number made up of two digits. I'm not sure this will be readable in 5 months.</li> </ol></li> <li>The same can be said about the readability of my accessor methods that retrieve the parts. E.g. <code>@level ||= name[5]</code>. There are important details hidden in <code>name[5]</code>. And that is the 5th part should represent a level. This does not seem obvious enough.</li> </ol>
[]
[ { "body": "<h3>Issues you have with the code</h3>\n\n<ol>\n<li><p><em>The aforementioned classes for parts 2, 3, 5, and 6 have a lot of duplication. As mentioned, they are identical except for the hash of acceptable values. Maybe inheritance is a good option?</em></p>\n\n<p>You're right that they are repetitive, but the validators are are short and clear. I'd leave them alone.</p></li>\n<li><p><em>The <code>valid?</code> method looks very long winded.</em></p>\n\n<p>It's not too bad. You are, after all, running seven different validators on seven parts of the string.</p></li>\n<li><p><em>The classes are floating around in the file, raising the possibility of a name clash.</em></p>\n\n<p>Do the classes <code>Discipline</code>, <code>Phase</code>, <code>Subject</code>, and <code>Level</code> exist solely for the purpose of filename validation? If so, they might be overkill, but you could always put them inside a module as a namespace to avoid interfering with other code. If they are being used for other purposes by the rest of your application as well, then you shouldn't have to worry about clashing with your own code, right?</p></li>\n<li><p><em>The <code>FileName</code> class should be instantiated once. It should be a singleton. Not sure how to implement singletons in Rails.</em></p>\n\n<p>I don't see why you would want to make <code>FileName</code> a singleton. Perhaps you mean to say that you only want to call class methods on <code>FileName</code>? (See #8 below.)</p></li>\n<li><p><em>There's a lot of memoization (<code>@level ||= name[6]</code>) in in the accessor methods I wrote for the different name parts.</em></p>\n\n<p>Memoization for something as trivial as extracting an array element is absurd. You could just as easily write:</p>\n\n<pre><code>def level\n name[6]\nend\n</code></pre>\n\n<p>But why not assign <code>@level</code> in the constructor and declare an <code>attr_reader :level</code> instead? In fact, you just got confused yourself: the level is actually <code>name[5]</code>. Better to not bother with array indexes at all — see my solution below.</p></li>\n<li><p><em>Maybe the <code>project_code_valid?</code> and <code>document_number_valid?</code> methods can be more compact? Can Regex be used to check string length instead of having a separate check?</em></p>\n\n<p>Yes. Get rid of the double negative (negated match against a regex that checks for bad characters) and just ask for exactly what you want to accept.</p>\n\n<pre><code>def project_code_valid?\n project_code =~ /\\A[A-Z0-9]{4}\\z/\nend\n</code></pre></li>\n<li><p><em>All abbreviations (parts 2, 3, 5, and 6) should be uppercase; my regexes do not account for this.</em></p>\n\n<p>If you want uppercase, use an uppercase character class.</p></li>\n<li><p><em>Again in parts parts 2, 3, 5, and 6, I am instantiating the class each time. This should be memoized?</em></p>\n\n<p>Memoization is not the solution. If you don't want to instantiate objects, use class methods instead.</p>\n\n<pre><code>class Discipline\n DISCIPLINES = {\n 'Accessibilidade' =&gt; 'ACE',\n 'Acústica' =&gt; 'ACU',\n }\n\n def self.value_valid?(value)\n DISCIPLINES.values.include?(value)\n end\nend\n</code></pre>\n\n<p>Similarly, if the only purpose of the <code>FileName</code> class is so that you can call <code>FileName.valid?(…)</code> and get a simple yes/no answer, then just use class methods instead of instance methods.</p></li>\n<li><p><em>The <code>revision</code> method seems too magical.</em></p>\n\n<p>Indeed, I find it weird that it returns a two-element array whose first element is an empty string. What good is that to the caller? Wouldn't it be better to return just the two-digit string instead?</p></li>\n<li><p><em>The same can be said about the readability of my accessor methods that retrieve the parts. E.g. <code>@level ||= name[5]</code>. There are important details hidden in <code>name[5]</code>. And that is the 5th part should represent a level. This does not seem obvious enough.</em></p>\n\n<p>I'm not sure what you mean by this question. If you're saying that <code>LOC</code> is an abbreviation that stands for something, then maybe <code>filename.level</code> should return a <code>Level</code> object instead of a string.</p></li>\n</ol>\n\n<h3>Proposed solution</h3>\n\n<pre><code>class FileName\n attr_reader :name\n attr_reader :project_code, :discipline, :phase, :document_number, :subject, :level\n\n # Exceptional implementation below\n # attr_reader :revision\n\n def self.valid?(name)\n new(name).valid?\n end\n\n # Valid file name\n # ABCD-ARQ-AP-0022-ACS-LOC-R00.jpeg\n\n def initialize(name)\n @name = name\n\n # Split individual parts into an array, ignoring .extension.\n # If there are fewer than seven hyphen-delimited parts, then\n # @revision will be nil and validation will fail. If there\n # are more than seven parts, then @revision will contain a\n # hyphen and validation will fail.\n parts = name.split('.', 2).first.split('-', 7)\n @project_code, @discipline, @phase, @document_number, @subject, @level, @revision = parts\n end\n\n def valid?\n # Testing revision first will detect if there are not exactly 7 parts earlier.\n revision_valid? &amp;&amp;\n level_valid? &amp;&amp;\n subject_valid? &amp;&amp;\n document_number_valid? &amp;&amp;\n phase_valid? &amp;&amp;\n discipline_valid? &amp;&amp;\n project_code_valid?\n end\n\n # If revision is valid, return it with the leading 'R' stripped off.\n def revision\n revision_valid? ? @revision[1..-1] : @revision\n end\n\n def project_code_valid?\n project_code =~ /\\A[\\p{Lu}\\d]{4}\\z/\n end\n\n def discipline_valid?\n Discipline.value_valid?(discipline)\n end\n\n def phase_valid?\n Phase.value_valid?(phase)\n end\n\n def document_number_valid?\n document_number =~ /\\A\\d{4}\\z/\n end\n\n def subject_valid?\n Subject.value_valid?(subject)\n end\n\n def level_valid?\n Level.value_valid?(level)\n end\n\n def revision_valid?\n @revision =~ /\\AR\\d{2}\\z/\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T12:55:50.707", "Id": "76691", "Score": "0", "body": "Thank you for this critique. My regex seemed a bit complex because I need to allow for diacritic characters (`Â, Ã` etc...) and I'm not sure how to do that AND apply uppercase. The classes are only mean to respond to `valid?` for now. The accessor methods I plan to use in a presenter so I could retrieve the different file parts in a report." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T18:12:16.067", "Id": "78630", "Score": "0", "body": "I chose this answer because, in the end, my classes were needed to work a bit more. I think they now justify their existence." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T05:41:59.850", "Id": "44232", "ParentId": "44223", "Score": "7" } }, { "body": "<p>I don't know if you really need to create classes for checking each of the substrings in the file name prefix. After all, there are only two types of checks that need to be made: against a list or matching a regex. Consider a simple, straighforward approach like this:</p>\n\n<pre><code>FNAME_SECTION = [\n {offset: 0, name: \"Project code\" , regex: /^\\p{Alnum}{4}$/ },\n {offset: 1, name: \"Discipline\" , list: ['ACE', 'ARQ'] },\n {offset: 2, name: \"Project phase\" , list: ['AP', 'BP'] },\n {offset: 3, name: \"Document number\", regex: /^\\d{4}$/ }, \n {offset: 4, name: \"Subject\" , list: ['ACS', 'BCS'] },\n {offset: 5, name: \"Level\" , list: ['LOC', 'KOV'] },\n {offset: 6, name: \"Revision\" , regex: /^R\\d{2}$/ } \n ]\n</code></pre>\n\n<p>.</p>\n\n<pre><code>def fname_valid?(fname)\n @groups = fname.split('.').first.split('-')\n if @groups.size != FNAME_SECTION.size\n puts \"Filename should have #{FNAME_SECTION.size} groups, but has #{@groups.size}\"\n return nil\n end \n\n err = []\n\n FNAME_SECTION.each_with_index do |h,i|\n str = @groups[h[:offset]] \n if h.key?(:list)\n err &lt;&lt; i unless h[:list].include?(str)\n elsif h.key?(:regex)\n err &lt;&lt; i unless str =~ h[:regex]\n else\n err &lt;&lt; i\n end \n end\n\n if err.empty?\n puts \"File name prefix is valid\"\n return true\n end\n\n puts \"File name prefix is invalid\"\n err.each {|i| puts loc_msg(i)}\n return false\nend\n</code></pre>\n\n<p>.</p>\n\n<pre><code>private\n\ndef loc_msg(i)\n \" Error in group offset #{FNAME_SECTION[i][:offset]} (#{FNAME_SECTION[i][:name]})\"\nend\n</code></pre>\n\n<p>.</p>\n\n<pre><code>fname_valid?('ABCD-ARQ-AP-0022-ACS-LOC-R00.jpeg')\n # File name prefix is valid\nfname_valid?('ABC7-ACE-CP-002a-BCS-LOc-R000.jpeg')\n # File name prefix is invalid\n # Error in group offset 2 (Project phase)\n # Error in group offset 3 (Document number)\n # Error in group offset 5 (Level)\n # Error in group offset 6 (Revision)\nfname_valid?('ABCD-ARQ-AP-0022-ACS-LOC.jpeg')\n # Filename prefix should have 7 groups, but has 6\n</code></pre>\n\n<p>The way I've displayed the error messages may not be what you want, but that would not be difficult to change. Note that, when a file name has an invalid format, I've listed all the reasons it is invalid.</p>\n\n<p>When matching a substring against a regex, notice that the length of the substring is checked by including start/end anchors and avoiding the use of <code>re+</code>, <code>re*</code> and <code>re?</code>.</p>\n\n<p>For validity checks that involve a list of possible values, I've made the list an array of the values from your hashes, as the keys did not appear to be used. If the keys are needed, those arrays could be replaced with hashes. </p>\n\n<p>A potential problem with this approach is that it's not very flexible. If, for example, a validity check were changed to involve something other than matching a list or a regex, it might be difficult to alter the code to accommodate it.</p>\n\n<p>I initially considered a different approach that offered greater flexibility. It retained the array of hashes, <code>FNAME_SECTION</code>, possibly changed somewhat, but also had a module that looked something like this:</p>\n\n<pre><code>module CustomValidityChecks\n def document_number_valid?\n ...\n end\n\n def revision_valid?\n ...\n end\nend\n</code></pre>\n\n<p>This module contains the validity checks that could not be done from the information in <code>FNAME_SECTION</code> alone. The following is executed in the main class, when it is parsed:</p>\n\n<pre><code>@custom_validity_checks = CustomValidityChecks.instance_methods(false)\n</code></pre>\n\n<p>This saves all those methods in the class instance variable <code>@custom_validity_checks</code>. One could then use the earlier approach to make the validity checks that draw only on the information in <code>FNAME_SECTION</code>, and cycle through <code>@custom_validity_checks</code> to perform the others:</p>\n\n<pre><code>@custom_validity_checks.each { |m| send(m) }\n</code></pre>\n\n<p>Note that methods can be added to or deleted from the module (or renamed), with no need to alter any of the other code.</p>\n\n<p>A variant of this approach would be create a subclass of the main class for each of these custom checks, and then use the hook <a href=\"http://www.ruby-doc.org/core-2.1.0/Class.html#method-i-inherited\" rel=\"nofollow\">Class#inherited</a> to build the array <code>@custom_validity_checks</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T13:28:46.730", "Id": "76929", "Score": "0", "body": "It's great to see a completely different approach to the problem. Thank you very much!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T13:32:34.240", "Id": "76930", "Score": "0", "body": "I do in fact like the way you have constructed the errors, too. This can be useful if I want to indicate the exact error." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T23:23:58.210", "Id": "44308", "ParentId": "44223", "Score": "9" } } ]
{ "AcceptedAnswerId": "44232", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T03:11:02.473", "Id": "44223", "Score": "11", "Tags": [ "ruby", "design-patterns", "file", "formatting" ], "Title": "Ruby format analyser" }
44223
<p>I am trying to create a method that reverses a string that will handle every case. So far the cases I have come up with are</p> <pre><code>"" "abcdef" "abbbba" null </code></pre> <p>I haven't been able to handle these conditions however</p> <p>escape characters</p> <pre><code>"\n" "\t" </code></pre> <p>Not sure how to make <code>\n</code> or <code>\t</code> into a string</p> <p>special characters such as</p> <pre><code>áe </code></pre> <p>code:</p> <pre><code>public static String reverseStr(String str) { if ( str == null ) { return null; } int len = str.length(); if (len &lt;= 0) { return ""; } char[] strArr = new char[len]; int count = 0; for (int i = len - 1; i &gt;= 0; i--) { strArr[count] = str.charAt(i); count++; } return new String(strArr); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T08:36:57.023", "Id": "76663", "Score": "0", "body": "We can review your code, but questions about how you can add a new feature to your code is not the topic of this site." } ]
[ { "body": "<p>There is a good overview of string reversal algorithms in <a href=\"https://codereview.stackexchange.com/a/42985/36217\">this answer</a>. It should explain how special characters like é can be handled. I don't see what's your problem with \"\\n\" and \"\\t\". These are strings already.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T06:50:44.057", "Id": "76654", "Score": "1", "body": "Sorry I should have been a bit more specific. I wanted to handle inputs when `\\n` is given by someone with out any programming experience whatsoever and expect `n\\` to be returned not a newline." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T06:58:05.150", "Id": "76656", "Score": "1", "body": "How does that someone enter `\\n`? Does he edit source code or provide input on CLI? If the former is true, leave a comment, otherwise I think his or her input will not be interpreted anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T08:38:47.580", "Id": "76665", "Score": "0", "body": "@Liondancer If `\\n` is a special case and should only return a normal `n`, that should be handled before reversing the string IMO. Be aware though that `\\n` is just the programmatic way of writing ASCII number 10 (line feed)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T06:44:38.270", "Id": "44233", "ParentId": "44231", "Score": "3" } }, { "body": "<p>A little suggestion. Instead of </p>\n\n<p><code>if (len &lt;= 0) {</code></p>\n\n<p>I'd write </p>\n\n<p><code>if (str.isEmpty()) {</code></p>\n\n<p>because it's more readable.</p>\n\n<p>Available since Java 1.6.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-24T07:58:23.877", "Id": "164078", "ParentId": "44231", "Score": "0" } } ]
{ "AcceptedAnswerId": "44233", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T05:19:12.403", "Id": "44231", "Score": "0", "Tags": [ "java", "strings" ], "Title": "reversing a string test cases" }
44231
<p>I have written a system for handling the dispatch of events between objects. (I need this functionality for a larger project I am working on. Objects should be able to dispatch events without knowing anything about the objects that will receive them. If this indicates that there is something seriously wrong with my larger design, please tell me.)</p> <p>I currently have two classes: EventHandler and EventListener. (There's a third class in the package, ResolvableEventObject, but it just adds a resolve() method to the basic EventObject that is called once the event is finished with dispatch.)</p> <p>The code is as follows. (imports were skipped) </p> <p>(If you need more explanation, please ask.)</p> <p>Note: this is the old code, kept for TwoThe's answer. See below for new code.</p> <h2>EventManager.class</h2> <pre><code>public class EventManager //The manager holds all the EventListeners, //and dispatches events among them. { //Singleton pattern, as multiple managers is nonsensical. private static EventManager INSTANCE = null; private HashMap&lt;Class&lt;? extends EventObject&gt;, ArrayList&lt;EventListener&gt;&gt; listeners; private int lockCount = 0; private ArrayList&lt;ListenerStub&gt; delayedListeners; public static EventManager getInstance() { if (INSTANCE == null) { INSTANCE = new EventManager(); } return INSTANCE; } private EventManager() { listeners = new HashMap(); delayedListeners = new ArrayList(); } /*Adds a listener if there's nothing using the set of listeners, or delays it * until the usage is finished if something is. * Package protected because nothing other than EventListener's registerListener() * should call it. Eqivalent statements apply for removeListener() below. */ void addListener(Class&lt;? extends EventObject&gt; c, EventListener m) { if (lockCount == 0) { realAddListener(c, m); } else { delayListenerOperation(c, m, true); } } void realAddListener(Class&lt;? extends EventObject&gt; c, EventListener m) { if (!listeners.containsKey(c)) { listeners.put(c, new ArrayList&lt;EventListener&gt;()); } ArrayList&lt;EventListener&gt; list = listeners.get(c); list.add(m); System.out.println("added"); } void removeListener(Class&lt;? extends EventObject&gt; c, EventListener m) { if (lockCount == 0) { realRemoveListener(c, m); } else { delayListenerOperation(c, m, false); } } private void realRemoveListener(Class&lt;? extends EventObject&gt; c, EventListener m) { ArrayList&lt;EventListener&gt; list = listeners.get(c); list.remove(m); System.out.println("removed"); } private void delayListenerOperation(Class&lt;? extends EventObject&gt; c, EventListener m, boolean add) { delayedListeners.add(new ListenerStub(c, m, add)); System.out.println("delayed"); } public void dispatchEvent(EventObject e) { ListenerLock l = new ListenerLock(); //This odd construction seems to force garbage collection. //Security measure to clean up old objects before dispatching events. System.gc(); try { Thread.sleep(1); } catch (Exception ex) { } //end of odd construction dispatchEvent(e, e.getClass()); //Hiding recursive call from user l.release(); if (e instanceof ResolvableEventObject) { ((ResolvableEventObject) e).resolve(); //ResolvableEventObject is my class, it's just an EventObject with a //resolve() method. } } private void dispatchEvent(EventObject e, Class C) { ArrayList&lt;EventListener&gt; list = listeners.get(C); if (list != null) { for (int i = 0; i &lt; list.size(); i++) { EventListener listener = list.get(i); listener.handleEvent(e); } } if (EventObject.class.isAssignableFrom(C.getSuperclass())) { dispatchEvent(e, C.getSuperclass()); } } private void resolveDelayedListeners() { for (ListenerStub listenerStub : delayedListeners) { if (listenerStub.isAdd()) { realAddListener(listenerStub.getC(), listenerStub.getM()); } else { realRemoveListener(listenerStub.getC(), listenerStub.getM()); } } } private class ListenerStub /* * This class is used to hold the data of the listeners to be removed * until the lock on the listener set is released. */ { private Class&lt;? extends EventObject&gt; c; private EventListener m; private boolean add; ListenerStub(Class&lt;? extends EventObject&gt; c, EventListener m, boolean add) { this.c = c; this.m = m; this.add = add; } public Class&lt;? extends EventObject&gt; getC() { return c; } public EventListener getM() { return m; } public boolean isAdd() { return add; } } public class ListenerLock /* * This is a basic lock that is used to prevent modifications to the list of * listeners. It releases when told, or when finalized if forgotten. */ { boolean released = false; ListenerLock() { lockCount++; } public void release() { if (!released) { lockCount = Math.min(0, lockCount - 1); released = true; if (lockCount == 0) { resolveDelayedListeners(); } } } protected void finalize() throws Throwable { super.finalize(); release(); } } } </code></pre> <h2>EventListener.class</h2> <pre><code>public class EventListener { /* * An EventListener pairs a class (EventObject or a subtype) with a method on an object. * It can hold either a strong or a weak reference to the object, and defaults weak. * It uses reflection to call the specified method. */ Object source; Method handler = null; Class E; WeakReference&lt;Object&gt; sourceReference; public EventListener(Class&lt;? extends EventObject&gt; E, Object source, String handlingMethod, boolean weakReference) { if (weakReference) { this.source = null; sourceReference = new WeakReference(source); } else { this.source = source; sourceReference = null; } /* * This structure sets up the call to the specified method on the specified * object. If no method is found for the specified class to listen to, * superclasses are tried until either a valid method is found or EventObject * is reached with no match. */ Class C = E; while (EventObject.class.isAssignableFrom(C) &amp;&amp; handler == null) { try { this.handler = source.getClass().getMethod(handlingMethod, C); } catch (NoSuchMethodException e) { C = C.getSuperclass(); } } if (handler == null) { throw new IllegalArgumentException("No method with the signature: " + handlingMethod + "(" + E.getSimpleName() + ") found."); } this.E = E; } public EventListener(Class&lt;? extends EventObject&gt; E, Object source, String handlingMethod) { this(E, source, handlingMethod, true); } void handleEvent(EventObject event) //package protected because it should only be //called by EventManager's dispatchEvent(). { if (source == null) { //source == null iff using weak references. if (sourceReference.get() == null) { //referenced object garbage collected, //delete listener. deregisterListener(); return; } try { handler.invoke(sourceReference.get(), event); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } } else { try { handler.invoke(source, event); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } } } public void registerListener() //registers a listener with the manager. //Reference to listener is required to deregister later. { EventManager.getInstance().addListener(E, this); } public void deregisterListener() { EventManager.getInstance().removeListener(E, this); } } </code></pre> <p>New code:</p> <h2>EventManager.java</h2> <pre><code>public final class EventManager //The manager holds all the EventListeners, and dispatches events among them. { private static EventManager INSTANCE = new EventManager(); //Singleton pattern, as multiple managers is nonsensical. private HashMap&lt;Class&lt;? extends EventObject&gt;, LinkedList&lt;EventListener&gt;&gt; listeners; private int lockCount = 0; private LinkedList&lt;ListenerStub&gt; delayedListeners; public static EventManager getInstance() { return INSTANCE; } private EventManager() { listeners = new HashMap(); delayedListeners = new LinkedList(); } /*Adds a listener if there's nothing using the set of listeners, or delays it * until the usage is finished if something is. * Package protected because nothing other than EventListener's registerListener() * should call it. Eqivalent statements apply for removeListener() below. */ void addListener(Class&lt;? extends EventObject&gt; clazz, EventListener listener) { if (lockCount == 0) { realAddListener(clazz, listener); } else { delayListenerOperation(clazz, listener, true); } } private void realAddListener(Class&lt;? extends EventObject&gt; clazz, EventListener listener) { if (!listeners.containsKey(clazz)) { listeners.put(clazz, new LinkedList&lt;EventListener&gt;()); } LinkedList&lt;EventListener&gt; list = listeners.get(clazz); list.add(listener); System.out.println("added"); } void removeListener(Class&lt;? extends EventObject&gt; clazz, EventListener listener) { if (lockCount == 0) { realRemoveListener(clazz, listener); } else { delayListenerOperation(clazz, listener, false); } } private void realRemoveListener(Class&lt;? extends EventObject&gt; clazz, EventListener listener) { LinkedList&lt;EventListener&gt; list = listeners.get(clazz); list.remove(listener); System.out.println("removed"); } private void delayListenerOperation(Class&lt;? extends EventObject&gt; clazz, EventListener listener, boolean add) { delayedListeners.add(new ListenerStub(clazz, listener, add)); System.out.println("delayed"); } public void dispatchEvent(EventObject event) { ListenerLock l = new ListenerLock(); dispatchEvent(event, event.getClass()); //Hiding recursive call from user l.release(); if (event instanceof ResolvableEventObject) { ((ResolvableEventObject) event).resolve(); //ResolvableEventObject is my class, it's just an EventObject with a //resolve() method. } } private void dispatchEvent(EventObject event, Class clazz) { LinkedList&lt;EventListener&gt; list = listeners.get(clazz); if (list != null) { for (int i = 0; i &lt; list.size(); i++) { EventListener listener = list.get(i); listener.handleEvent(event); } } if (EventObject.class.isAssignableFrom(clazz.getSuperclass())) { dispatchEvent(event, clazz.getSuperclass()); } } private void resolveDelayedListeners() { for (ListenerStub listenerStub : delayedListeners) { if (listenerStub.isAdd()) { realAddListener(listenerStub.getListenerClass(), listenerStub.getListener()); } else { realRemoveListener(listenerStub.getListenerClass(), listenerStub.getListener()); } } } private class ListenerStub /* * This class is used to hold the data of the listeners to be removed * until the lock on the listener set is released. */ { private Class&lt;? extends EventObject&gt; clazz; private EventListener listener; private boolean add; ListenerStub(Class&lt;? extends EventObject&gt; clazz, EventListener listener, boolean add) { this.clazz = clazz; this.listener = listener; this.add = add; } public Class&lt;? extends EventObject&gt; getListenerClass() { return clazz; } public EventListener getListener() { return listener; } public boolean isAdd() { return add; } } public class ListenerLock /* * This is a basic lock that is used to prevent modifications to the list of * listeners. It releases when told, or when finalized if forgotten. */ { boolean released = false; ListenerLock() { lockCount++; } public void release() { if (!released) { lockCount = Math.min(0, lockCount - 1); released = true; if (lockCount == 0) { resolveDelayedListeners(); } } } protected void finalize() throws Throwable { super.finalize(); release(); } } } </code></pre> <h2>EventListener.java</h2> <pre><code>public final class EventListener { /* * An EventListener pairs a class (EventObject or a subtype) with a method on an object. * It can hold either a strong or a weak reference to the object, and defaults weak. * It uses reflection to call the specified method. */ Object source = null; Method handler = null; Class clazz; WeakReference&lt;Object&gt; sourceReference; public EventListener(Class&lt;? extends EventObject&gt; clazz, Object source, String handlingMethod, boolean weakReference) { if (weakReference) { this.source = null; sourceReference = new WeakReference(source); } else { this.source = source; sourceReference = null; } /* * This structure sets up the call to the specified method on the specified * object. If no method is found for the specified class to listen to, * superclasses are tried until either a valid method is found or EventObject * is reached with no match. */ Class C = clazz; while (EventObject.class.isAssignableFrom(C) &amp;&amp; handler == null) { try { this.handler = source.getClass().getMethod(handlingMethod, C); } catch (NoSuchMethodException e) { C = C.getSuperclass(); } } if (handler == null) { throw new IllegalArgumentException("No method with the signature: " + handlingMethod + "(" + clazz.getSimpleName() + ") found."); } this.clazz = clazz; } public EventListener(Class&lt;? extends EventObject&gt; clazz, Object source, String handlingMethod) { this(clazz, source, handlingMethod, true); } void handleEvent(EventObject event) //package protected because it should only be //called by EventManager's dispatchEvent(). { if (source == null) { //source == null iff using weak references. if (sourceReference.get() == null) { //referenced object garbage collected, delete listener. deregisterListener(); return; } try { handler.invoke(sourceReference.get(), event); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } } else { try { handler.invoke(source, event); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } } } public void registerListener() //registers a listener with the manager. Reference to listener //is required to deregister later. { EventManager.getInstance().addListener(clazz, this); } public void deregisterListener() { EventManager.getInstance().removeListener(clazz, this); } } </code></pre> <p>Could you please tell me whether this is proper practice, or if there is a better way to do it? I am knowledgeable about Java, but this is the first time I have done anything like this. </p> <p>Also, is there anything you notice that is hurting performance? I haven't had a chance to test it with regards to speed, but my functionality tests completed almost instantly after compile.</p> <p>If you were wondering, this is intended to be used as part of a library for a larger project, as well as other subsequent projects with complex message passing between unspecified objects that don't reference each other.</p>
[]
[ { "body": "<p>In general an event listener is something used often in Java programs, that is why there are already a lot of event managers that you can use, for example the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Observable.html\" rel=\"noreferrer\">Observable</a> pattern. So what you are basically doing is to <a href=\"http://en.wikipedia.org/wiki/Reinventing_the_wheel\" rel=\"noreferrer\">reinvent the square wheel</a>. It is a good idea to always look for the work of others first before doing unnecessary work.</p>\n\n<blockquote>\n<pre><code>private static EventManager INSTANCE = null; \n</code></pre>\n</blockquote>\n\n<p>The proper <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern#Eager_initialization\" rel=\"noreferrer\">singleton pattern</a> to use is:</p>\n\n<pre><code>private static final EventManager INSTANCE = new EventManager(); \n</code></pre>\n\n<p>This reduces the <code>getInstance()</code> Method to:</p>\n\n<pre><code>public static EventManager getInstance() {\n return INSTANCE;\n}\n</code></pre>\n\n<p>Some people discuss whether or not you even need a <code>getInstance()</code> method here, since you could just modify <code>INSTANCE</code> to be public instead vs \"the Java way\".</p>\n\n<blockquote>\n<pre><code>private ArrayList&lt;ListenerStub&gt; delayedListeners;\n</code></pre>\n</blockquote>\n\n<p>You seem to use ArrayList for all purposes. There are other List-types in Java that suit certain situations better than an ArrayList. You should have a look at those and try to get a feeling when to use which list. In this particular case i.E. a LinkedList is better.</p>\n\n<blockquote>\n<pre><code>private EventManager()\n</code></pre>\n</blockquote>\n\n<p>This should be protected, just in case you want to eventually inherit this class at any point in the future. <code>private</code> should only be used to prevent inheritance on purpose.</p>\n\n<blockquote>\n<pre><code>delayListenerOperation(c, m, true);\n</code></pre>\n</blockquote>\n\n<p>What is the purpose of delaying listeners? I don't really see one in your event system. If you want to make sure some events are processed later, try a PriorityQueue to sort Events based on their order. Working with \"global\" variables for these purposes is prone to threading issues or coding mistakes.</p>\n\n<blockquote>\n<pre><code>ListenerLock l = new ListenerLock();\n</code></pre>\n</blockquote>\n\n<p>This is a C++-pattern in Java, it won't work as expected and shouldn't be used. You should use a class-global <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html\" rel=\"noreferrer\">Lock</a> if you really need to lock something. But since this code isn't thread-safe at all, I don't see the reason for a lock.</p>\n\n<blockquote>\n<pre><code>System.gc();\n</code></pre>\n</blockquote>\n\n<p><strong>Never!</strong> do that, unless you have a really good reason to and absolutely know and have proven that you must do it. The garbage collector is very smart in the way it works, and those constructs just dumb it down and cause hick-ups or a waste of processing time.</p>\n\n<blockquote>\n<pre><code>Thread.sleep(1);\n</code></pre>\n</blockquote>\n\n<p>Why? What do you try to archive with that? This serves no purpose.</p>\n\n<blockquote>\n<pre><code>ListenerStub(Class&lt;? extends EventObject&gt; c, EventListener m, boolean add)\n</code></pre>\n</blockquote>\n\n<p>c, m or add are not a good choice for variable names. Try to be expressive so you still know what this does should you have to review the code in 2 years.</p>\n\n<blockquote>\n<pre><code>public class ListenerLock\n</code></pre>\n</blockquote>\n\n<p>Reinventing the wheel once more. See <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html\" rel=\"noreferrer\">Lock</a> for the already existing (and actually working) implementation.</p>\n\n<blockquote>\n<pre><code>protected void finalize() throws Throwable\n</code></pre>\n</blockquote>\n\n<p>Again: <strong>never</strong> do that. This is prone to many errors as you can never tell when this function is actually called.</p>\n\n<blockquote>\n<pre><code>public class EventListener\n</code></pre>\n</blockquote>\n\n<p>This should be an <code>Interface</code> if you want other classes to be able to implement this. Otherwise every class needs to use this as a base class, and in Java you can only inherit from one class. That would as well simplify a lot of your handling code down to a simple</p>\n\n<pre><code>void handleEvent(EventObject e)\n</code></pre>\n\n<p>in the actual class that is supposed to handle the event.</p>\n\n<blockquote>\n<pre><code>if (weakReference) {\n this.source = null;\n sourceReference = new WeakReference(source);\n} else {\n this.source = source;\n sourceReference = null;\n}\n</code></pre>\n</blockquote>\n\n<p>If you use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/ref/Reference.html\" rel=\"noreferrer\">Reference</a> as base class here and write your own <code>StandardReference&lt;T&gt;</code> class you can simplify this to:</p>\n\n<pre><code>this.source = weakReference ? new WeakReference(source) : new StandardReference(source);\n</code></pre>\n\n<p>This would be more elegant and remove the duplicated variable.</p>\n\n<h1>Summary</h1>\n\n<p>You wrote a lot of code to duplicate existing functionality but did neither improve nor add to the existing one. I would suggest to remove those classes and work with the existing functionality to solve your problem.</p>\n\n<p>That would remove all bugs and potential bugs from the code you have, and will be future-proof should there be any major changes to Java.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:38:12.740", "Id": "76766", "Score": "0", "body": "@TwoThe Thank you for looking at my code, but your answer doesn't fit my needs. First, listeners are delayed if someone attempts to add/remove them while an event is being dispatched. Second, Lock won't work here because both a, Lock causes blocking while I need to delay the listener instead, and b, only one Lock may be held at a time, but I may need multiple locks held at once. This code causes the listener to be delayed if a lock exists, and added/removed once it is released. Third, how should I ensure that my locks are cleaned up if forgotten about without finalize()? (Cont.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:39:24.260", "Id": "76767", "Score": "0", "body": "Fourth, **EventListener should not be subclassed!** An EventListener holds a Method reference which is called on handleEvent(). The usage is: new EventListener(EventObject subclass to listen for, object to call method on, name of method [, false if strong reference]). Then, you call registerListener() on the new object, and it will listen for events to be dispatched. The code you said \"handles the event\" actually is still part of the setup for the EventListener. (it's in the constructor.) handleEvent() is what \"handles the event\" but it just passes the call to the specified method. (Cont.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:41:00.220", "Id": "76769", "Score": "0", "body": "Finally, I would like to implement your StandardReference idea, but how would I go about doing that?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:06:01.857", "Id": "44258", "ParentId": "44235", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T08:15:49.223", "Id": "44235", "Score": "7", "Tags": [ "java", "event-handling" ], "Title": "Event Handling system in Java" }
44235
<p>I have a generic extension method for validating my entities. The main idea is to be able to specify at runtime (context related) the criteria for validating a specific entity (with the end goal of saving it in the data base).</p> <pre><code>public static Boolean IsValidEntity&lt;T&gt;(this T entity, List&lt;Predicate&lt;T&gt;&gt; predicates) { Boolean res = true; predicates.ForEach(p =&gt; res &amp;= (Boolean)p.DynamicInvoke(entity)); return res; } </code></pre> <p>Inside my repository I can then use (simplified as this is not the scope but is somewhat necessary for the question context): </p> <pre><code>public void SaveIntProperty(int myProperty, List&lt;Predicate&lt;int&gt;&gt; predicates) { if (myProperty.IsValidEntity&lt;int&gt;(predicates)) { //save to data base or other actions } } </code></pre> <p>A simple example on a list of <code>int</code>s would be to search for elements which (in a particular context) need to be both <em>even</em> and <em>less than 8</em>. </p> <pre><code>List&lt;int&gt; numbers = new List&lt;int&gt;() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //dynamically create the validation criteria List&lt;Predicate&lt;int&gt;&gt; predicates = new List&lt;Predicate&lt;int&gt;&gt;();// List&lt;Delegate&gt;(); Predicate&lt;int&gt; lessThan = x =&gt; x &lt; 8; predicates.Add(lessThan); Predicate&lt;int&gt; even = x =&gt; x % 2 == 0; predicates.Add(even); numbers.ForEach(n =&gt; SaveIntProperty(n, predicates)); </code></pre> <p>The <code>IsValidEntity</code> extension method works and looks simple enough. However, I'm having doubts about the performance and the extensibility. Is the use of the <code>ForEach</code> ok? Should I pass the predicates differently? Should I use something else instead of predicates?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:24:31.117", "Id": "76694", "Score": "2", "body": "There is no reason to use `List.ForEach()`, just use a normal `foreach`, it's actually even few characters shorter." } ]
[ { "body": "<p>You can simplify your extension method a bit as so:</p>\n\n<pre><code>public static Boolean IsValidEntity&lt;T&gt;(this T entity, IEnumerable&lt;Predicate&lt;T&gt;&gt; predicates)\n{\n return predicates.All(p =&gt; (bool)p.DynamicInvoke(entity));\n}\n</code></pre>\n\n<p>This is a bit better for readability, and shouldn't have any cost in efficiency as LINQ short-circuits with All. I also switched your <code>List</code> for <code>IEnumerable</code>, just to save an unnecessary <code>ToList</code> call if you end up with some other kind of collection.</p>\n\n<p>You should also check if you really need that <code>DynamicInvoke</code>. If not, you can further simplify to</p>\n\n<pre><code>public static Boolean IsValidEntity&lt;T&gt;(this T entity, IEnumerable&lt;Predicate&lt;T&gt;&gt; predicates)\n{\n return predicates.All(p =&gt; p(entity));\n}\n</code></pre>\n\n<p>Depending on your wider design, this might be enough. However, since you asked about extensibility, you can see that having to build predicates isn't the nicest business. For example, you had your 'less than 8' predicate. What if elsewhere in the code you wanted 'less than 7'? You'd have to repeat the (albeit very simple in this example) logic, just with a different number. </p>\n\n<p>If you tried to refactor this to adhere to the Don't Repeat Yourself principle, you might then end up with something like a <code>PredicateFactory</code> class which exists purely to build common predicates based on parameters. But this isn't fantastic design either. It would likely end up as a monolith of public methods without much cohesion, and violate the open/closed and single responsibility principle.</p>\n\n<p>A better option might be to create an interface like:</p>\n\n<pre><code>interface IEntityValidator&lt;T&gt;\n{\n bool IsValid(T Entity);\n}\n</code></pre>\n\n<p>Instead of predicates, you can now create and use classes which implement this interface. This gives better adherence to the design principles I mentioned before, and allows you take full advantage of polymorphism (for more complicated validation you might find that inheritance is useful, for example). At this point your original method would be:</p>\n\n<pre><code>public static Boolean IsValidEntity&lt;T&gt;(this T entity, IEnumerable&lt;IEntityValidator&lt;T&gt;&gt; validators)\n{\n return validators.All(v =&gt; v.IsValid(entity));\n}\n</code></pre>\n\n<p>To my mind, that line is simple and readable enough that it may no longer warrant its own method, especially its own extension method which will apply to every single type. Validation doesn't seem like something that would be done in too many places, so even if you didn't like that line, you might just move it to a private method somewhere. That's more a matter of taste, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:21:36.823", "Id": "76693", "Score": "0", "body": "I don't see how does the interface help anything. I think that pretty much everything you can do with a single method interface, you can also do with a delegate. For example, you can still have each validator in a separate class, you would just use `MyValidator.Validate` (or `new MyValidator().Validate`) instead of `new MyValidator()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:28:13.177", "Id": "76695", "Score": "0", "body": "@svick I don't think there's anything you absolutely couldn't do with a delegate instead of an interface, especially since any class could just return a delegate which references private members. But at that point it just seems like a weirder way of doing the same thing. Why have a class that returns a function as a delegate rather than just have that function be a public member? I didn't really understand what you meant with that example though, so I could be missing your point" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:32:36.823", "Id": "76697", "Score": "0", "body": "I don't mean a method returning a delegate, I mean using that method as a delegate. Where you would have a class that implements `IEntityValidator<T>`, I would have a (possibly static) method and use that method as the `Predicate`. E.g. `Predicate<int> validator = new MyValidator().Validate;` (where `Validate()` is the validation method) instead of `IEntityValidator<int> validator = new MyValidator();`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:38:27.213", "Id": "76699", "Score": "0", "body": "@svick Oh, right. Well I don't know Andrei's overall design, but having an interface means you don't have to hard-code dependencies. Adhering to the Dependency Inversion Principle means you can inject them, mock them in a test, use an IoC container, whatever. It's not always something that's important, but given what a lightweight thing the interface is and how little I know of the wider project design, it seems like a sensible thing to suggest by default. As a personal preference, I'd also find an interface like that very expressive in terms of readability" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:01:29.717", "Id": "76708", "Score": "0", "body": "@BenAaronson, I don't have a highly complex design. I want to have as much \"freedom\" in my DAL as possible. I'm thinking that, for different clients, I need to have different business rules for specific entity types. It would then make sense that I can specify the validation rules from outside the DAL, with as little effort as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:07:10.080", "Id": "76711", "Score": "1", "body": "@AndreiV I'd say the IEntityValidator is appropriate then." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T10:07:53.877", "Id": "44243", "ParentId": "44238", "Score": "5" } } ]
{ "AcceptedAnswerId": "44243", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T09:17:56.537", "Id": "44238", "Score": "3", "Tags": [ "c#", "performance", "validation", "extension-methods" ], "Title": "Validating an entity using a dynamic list of predicates" }
44238
<p>I am refining my reliable UDP library, its at its 3rd iteration now. It is quiet a bit multi-threaded with almost all major operations having dedicated threads. I need your opinion on the following critical worker methods. </p> <h3>Legend</h3> <pre><code>TAgUDP : Indy UDP Server derived class. TAgUDPPeer : Class containing a peer's information. FPacketLostTimeout : 2 times the ping. SendIDPacket : Constructs packets. TAgList &lt;T&gt; = class ( TList &lt;T&gt; ) private fLock : TMREWSync; public constructor Create; destructor Destroy; override; procedure BeginRead; inline; procedure BeginWrite; inline; procedure EndRead; inline; procedure EndWrite; inline; end; TAgUDPOp : Enumerator representing packet command types. TAgUDPPacket = class protected FID : Word; FCommand : TAgUDPOp; FSenderID : TGUID; FRecipientID : TGUID; FMsg : TAgBuffer; FTimeStamp : TDateTime; FResendCount : Byte; public constructor Create; destructor Destroy; override; end; TAgUDPPeerState = ( AwaitingLoginReply, Connecting, OneWayP2P, Connected, Dead, SetForRemoval ); </code></pre> <h3>Packet Manager</h3> <pre><code>procedure TAgUDP.PacketManager; procedure ManagePacketsForAllLists ( AList: TAgList &lt;TAgUDPPeer&gt; ); var Peer : TAgUDPPeer; Packet : TAgUDPPacket; I : NativeInt; J : SmallInt; Diff : Cardinal; begin AList.BeginRead; for I := AList.Count - 1 downto 0 do begin Peer := AList [I]; if Peer.FState &lt;&gt; TAgUDPPeerState.Connected then continue; if Peer.SentPackets.Count = 0 then continue; for J := Peer.SentPackets.Count - 1 downto 0 do begin try Packet := Peer.SentPackets [J]; if Packet.FResendCount &lt; 5 then begin Diff := MillisecondsBetween ( Now, Packet.FTimeStamp ); if ( Diff &lt; Peer.FPacketLostTimeout ) and ( Diff &lt;= 50 ) then continue; Packet.FTimeStamp := Time; Packet.FResendCount := Packet.FResendCount + 1; if Peer.LocalPeer then SendBuffer ( Peer.FPrivateIP, Peer.FPrivatePort, TIdBytes ( Packet.FMsg.ToBytes )) else SendBuffer ( Peer.FPublicIP, Peer.FPublicPort, TIdBytes ( Packet.FMsg.ToBytes )); end else Peer.SentPackets.Delete ( J ); except Peer.SentPackets.Delete ( J ); end; end; end; AList.EndRead; end; begin ManagePacketsForAllLists ( FClientsList ); ManagePacketsForAllLists ( FServersList ); end; </code></pre> <h3>Peer Manager</h3> <pre><code>procedure TAgUDP.PeerManager; var Peer : TAgUDPPeer; I : NativeInt; DT : TDateTime; Diff : NativeInt; ForceDisconnect : Boolean; begin DT := Now; ForceDisconnect := False; FClientsList.BeginWrite; for I := FClientsList.Count - 1 downto 0 do begin try Peer := FClientsList [I]; if Peer.FState &lt;&gt; TAgUDPPeerState.SetForRemoval then begin Diff := MillisecondsBetween ( DT, Peer.FLastPacketTime ); if Diff &gt; FAliveTimeout then begin Peer.BeginWrite; Dec ( Diff, 30000 ); if Diff &gt; FRemoveTimeout then begin Peer.State := TAgUDPPeerState.SetForRemoval; ForceDisconnect := True; end else Peer.State := TAgUDPPeerState.Dead; Peer.EndWrite; end; end else begin if FServerPersonality and ForceDisconnect then Peer.SendIDPacket ( nil, TAgUDPOp.ForcedEndOfSession ); FClientsList.Delete ( I ); end; except FClientsList.Delete ( I ); end; end; FClientsList.EndWrite; if FServersList.Count = 0 then exit; FServersList.BeginWrite; for I := FServersList.Count - 1 downto 0 do begin try Peer := FServersList [I]; if Peer.FState = TAgUDPPeerState.SetForRemoval then begin Peer.SendIDPacket ( nil, TAgUDPOp.EndOfSesion ); FServersList.Delete ( I ); end else begin Diff := MillisecondsBetween ( DT, Peer.FLastPacketTime ); if Diff &gt; fAliveTimeout then begin Peer.BeginWrite; Peer.State := TAgUDPPeerState.Dead; Peer.EndWrite; end; end; except FServersList.Delete ( I ); end; end; FServersList.EndWrite; end; </code></pre> <p>Please give some advice on improving them. Also will it be alright, if I merge these with each other i.e. they will be worked by a single thread. I was thinking of utilizing thread pools to accommodate groups of connected clients. The intended audience number in the thousands.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T07:47:20.710", "Id": "77215", "Score": "0", "body": "Please at least comment, not just up vote!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T20:04:51.240", "Id": "77661", "Score": "0", "body": "I think there's very few Delphi gurus around here. It is easy to see that you've asked a good question, but most people probably don't know what to say :) I know some Delphi though, but it's been a while since I've used it. I'll try to take a look at your question later on." } ]
[ { "body": "<blockquote>\n <p><strong>give some advice on improving them</strong></p>\n</blockquote>\n\n<p>Add some expository introductory comments describing how your library is to be used and called, what makes it \"reliable\", and how and why it's different from TCP (what most people think of for reliable UDP) and from <a href=\"http://en.wikipedia.org/wiki/Reliable_User_Datagram_Protocol\" rel=\"nofollow noreferrer\">RUDP</a>. Explain when, where, and how you're dealing with timeouts, dropped packets, duplicate packets, corrupted packets, and all the other possible things that can go wrong.</p>\n\n<p>Inside the code itself, add explanatory comments throughout describing why the code does what it does. For now, the code and lack of comments probably isn't seductive enough to attract much attention.</p>\n\n<p>Also see <a href=\"https://codereview.stackexchange.com/questions/148544/semi-reliable-communications-using-udp/148923\">this \"reliable\" UDP question/answer</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T05:14:31.667", "Id": "81665", "Score": "0", "body": "Noted, I'll do just that soon enough." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-06T03:19:38.197", "Id": "46424", "ParentId": "44239", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T09:24:18.093", "Id": "44239", "Score": "6", "Tags": [ "optimization", "multithreading", "networking", "delphi" ], "Title": "Handling packets and peers in a reliable UDP library" }
44239
<p>I'm using the Game of Life Kata to help me learn JavaScript. I've picked up the syntax through Codecademy tutorials, but my current skill level is Novice.</p> <p>The example code has working functionality for initialising a <code>World</code> with live cells and asking it to 'tick'.</p> <p>All suggestions for improvement are welcome. I'd especially like feedback on the following:</p> <ul> <li>JavaScript idioms and conventions</li> <li>Function and variable scoping</li> <li>Making use of built-in functions and datatypes</li> </ul> <p></p> <pre><code>myapp = {}; /** * World represents a 2 dimensional square matrix of cells. * @param dimension * @param liveCellCoordinates * @returns {myapp.World} */ myapp.World = function(dimension, liveCellCoordinatesArray) { this.dimension = dimension; this.liveCellCoordinates = liveCellCoordinatesArray; }; /** * * @returns {Array} of live cells after tick. */ myapp.World.prototype.tick = function() { var nextGenerationOfLiveCells = []; // for each cell in world for(var y=0; y&lt;this.dimension; y++) { for(var x=0; x&lt;this.dimension; x++) { var liveNeighbours = this.getLiveNeighbourCount(x, y); if(this.isCellAlive(x, y)) { if(isSurvivor(liveNeighbours)) { nextGenerationOfLiveCells.push([x,y]); } } else { if(isBorn(liveNeighbours)) { nextGenerationOfLiveCells.push([x,y]); } } } } this.liveCellCoordinates = nextGenerationOfLiveCells; return nextGenerationOfLiveCells; }; myapp.World.prototype.getLiveNeighbourCount = function(x, y) { var liveNeighbours = 0; if(this.isCellAlive(x-1, y-1)) liveNeighbours++; if(this.isCellAlive(x, y-1)) liveNeighbours++; if(this.isCellAlive(x+1, y-1)) liveNeighbours++; if(this.isCellAlive(x-1, y)) liveNeighbours++; if(this.isCellAlive(x+1, y)) liveNeighbours++; if(this.isCellAlive(x-1, y+1)) liveNeighbours++; if(this.isCellAlive(x, y+1)) liveNeighbours++; if(this.isCellAlive(x+1, y+1)) liveNeighbours++; // jstestdriver.console.log("&gt;&gt;&gt; liveNeighbours of ", x, y, ": ", liveNeighbours); return liveNeighbours; }; myapp.World.prototype.isCellAlive = function(x, y) { for(var cell in this.liveCellCoordinates) { if(x === this.liveCellCoordinates[cell][0] &amp;&amp; y === this.liveCellCoordinates[cell][1]) { return true; } } return false; }; function isBorn(liveNeighbours) { return liveNeighbours === 3; } function isSurvivor(liveNeighbours) { return liveNeighbours === 2 || liveNeighbours === 3; } </code></pre>
[]
[ { "body": "<p>Looks quite good overall; not much to criticise. (I'm not looking at the overall structure or logic - just the style; the game of life can be written in so many ways)</p>\n\n<p>Anyway, what I have is very trivial:</p>\n\n<ul>\n<li>Missing indentation in the bodies of <code>tick</code> and <code>getLiveNeighbourCount</code></li>\n<li>Don't use a <code>for...in</code> loop for arrays (in <code>isCellAlive</code>); better and clearer to use a regular <code>for</code>-loop like you do elsewhere.</li>\n<li>You ought to define <code>myapp</code> as <code>window.myapp</code>. Right now it's <em>implicitly</em> global, because it's missing a <code>var</code> declaration, but you might as well make that explicit (or perhaps it doesn't need to be global at all?)</li>\n<li>Some more comments in the code itself would probably be nice. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T12:01:20.587", "Id": "44248", "ParentId": "44240", "Score": "5" } }, { "body": "<pre><code>myapp = {};\n</code></pre>\n\n<p>I think the general convention is to use camelCase, so <code>myApp</code>. But, why are you creating a namespace with only one property? And then later, with e.g. isBorn, you create functions in the global namespace? In any case, I would never use namepsaces named \"myX\" in any production code.</p>\n\n<pre><code>myapp.World.prototype.tick = function() {\n</code></pre>\n\n<p>Tick is a function!? I would expect <code>tick</code> to be a number, used by functions to know how often something has run etc.. Maybe <code>update</code> would be a better name?</p>\n\n<pre><code>for(var y=0; y&lt;this.dimension; y++) {\n</code></pre>\n\n<p>To ease readability I would suggest moving the <code>var</code> keywords outside the loops. Better yet, declare them when the function opens. This will help you know which scope they are defined in.</p>\n\n<p>I would use <code>for (y = 0; y &lt; dimension; y++) {</code>. Note that <code>dimension</code> is no longer <code>this.dimension</code>. You should define <code>var dimension = this.dimension</code> at the top. Avoid unnecessary lookups where you can, especially for loops.</p>\n\n<p>As for spacing in <code>if</code> constructs, there seem to be differing opinions. JSLint prefers <code>if (this.isCellAlive(x, y)) {</code>, jQuery prefers <code>if ( this.isCellAlive(x, y) ) {</code>.</p>\n\n<pre><code> nextGenerationOfLiveCells.push([x,y]);\n</code></pre>\n\n<p>I think you should use objects instead of arrays. Arrays give you no benefit at all over objects. For example <code>{ x: x, y: y }</code> instead of <code>[x,y]</code></p>\n\n<pre><code>this.liveCellCoordinates = nextGenerationOfLiveCells;\nreturn nextGenerationOfLiveCells;\n};\n</code></pre>\n\n<p>This seems like an unnecessary side effect. Why set <code>this.liveCellCoordinates</code> if you are then going to return it? Maybe the function calling <code>.tick()</code> should be setting <code>this.liveCellCoordinates</code> or maybe this function should have a different return value? Something actually meaningful?</p>\n\n<pre><code>function isBorn(liveNeighbours) {\n return liveNeighbours === 3;\n}\n\nfunction isSurvivor(liveNeighbours) {\n return liveNeighbours === 2 || liveNeighbours === 3;\n}\n</code></pre>\n\n<p>You're defining these 2 variables as globals. Considering your earlier attempt at namespacing I want to believe these should not be globals.</p>\n\n<p>Better yet, enclose the entire code in self-invoking functions to avoid leaking these two functions to the global object:</p>\n\n<pre><code>var myApp = (function () {\n // Your code here\n return {\n World: World\n };\n}());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T16:56:58.890", "Id": "45764", "ParentId": "44240", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T09:29:48.190", "Id": "44240", "Score": "7", "Tags": [ "javascript", "game-of-life", "scope" ], "Title": "Conway's Game of Life - Conventional JavaScript?" }
44240
<p>I am building a backend to a mobile application that will be hosted on a Django site connected to a PostgreSQL database. </p> <p>I have never built anything to accomplish this before and this is my first go at it. I have not studied this type of application before so please let me know if the below code follows best practices for this task, is secure, and doesn't have any obvious problems. If there is an industry standard for this that is very different, please let me know what it is and why it is preferred. </p> <p>My client connects via the view readJSON:</p> <pre><code>@csrf_exempt def readJSON(request): if request.method == 'POST': try: c = connections['postgres_db'].cursor() json_data = json.loads(request.body) if json_data['tag'] == 'register': return HttpResponse(cc().register(c, json_data)) elif json_data['tag'] == 'syncprofile': return HttpResponse(cc().syncProfile(c, json_data)) ################ A long list of other possible tags else: raise Http404 finally: c.close() else: raise Http404 </code></pre> <p>I have a separate class that holds all the code to handle the incoming JSON requests. This is one such function. </p> <pre><code> def register(self, c, json_data): import bcrypt as bc salt = bc.gensalt() pwrd = json_data['data']['password'] hash = bc.hashpw(pwrd, salt) try: c.execute("INSERT INTO profiles VALUES (DEFAULT, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (json_data['data']['email'], hash, salt, json_data['data']['date_created'], json_data['data']['state_lvl'], True, json_data['data']['first_name'], json_data['data']['last_name'], json_data['data']['sex'], json_data['data']['age'], json_data['data']['state'], json_data['data']['country'], json_data['data']['language'], json_data['data']['device_type'], json_data['data']['device'], json_data['data']['device_width'], json_data['data']['device_height'], json_data['data']['device_screen_density'] )) json_response = json.dumps({"success": 1, "errors": 0}) return HttpResponse(json_response, mimetype="application/json") except Exception,e: json_response = json.dumps({"success": 0, "errors": 1, "msg": str(e)}) return HttpResponse(json_response, mimetype="application/json") </code></pre> <p>And here is the JSON structure for the above function. </p> <pre><code> { "tag":"register", "data":{ "email":"email@email.com", "password":"app123", "date_created":"07/10/1967", "state_lvl":"1", "first_name":"John", "last_name":"Smith", "sex":"m", "age":23, "state":"CA", "country":"USA", "language":"english", "device_type":"phone", "device":"Nexus-5", "device_width":400, "device_height":800, "device_screen_density":331 } } </code></pre>
[]
[ { "body": "<h3>readJSON()</h3>\n\n<p>Returning HTTP 404 (\"Not Found\") is improper, unless you are deliberately sending obfuscatory responses as a kind of security-by-obscurity measure. If you require a POST, and the client sends anything but a POST, the proper response should <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6\" rel=\"nofollow\">HTTP 405 (\"Method Not Allowed\")</a>. For a body that does not have an appropriate JSON tag, I think that the appropriate response would be a non-specific <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1\" rel=\"nofollow\">HTTP 400 (\"Bad Request\")</a>.</p>\n\n<p>In if-else branches, prefer to put the branch with less code first, to get it out of the way and reduce mental load. Usually, that means putting the error handler first. As a bonus, you can eliminate one level of indentation.</p>\n\n<p>Instead of the try-finally construct, use a <code>with</code> block for the database cursor.</p>\n\n<p>Assuming that there is an exact correspondence between the JSON tags and the method names of <code>cc()</code>, you could dispatch dynamically. (Your <code>syncProfile()</code> method doesn't match <code>'syncprofile'</code>, but you could rename your methods accordingly.)</p>\n\n<pre><code>@csrf_exempt\ndef readJSON(request):\n if request.method != 'POST':\n raise Http405\n json_data = json.loads(request.body)\n\n # Whitelist allowable function calls for security\n if json_data['tag'] not in ['register', 'syncprofile', … ]:\n raise Http400\n\n cc_method = getattr(cc(), json_data['tag'])\n with connections['postgres_db'].cursor() as c:\n return HttpResponse(cc_method(c, json_data))\n</code></pre>\n\n<h3>register()</h3>\n\n<p>Imports should be listed at the top of the file. I wouldn't alias <code>bcrypt</code> as <code>bc</code>, as the latter sacrifices clarity just to save a few characters.</p>\n\n<p>There are a lot of columns to be inserted, and a long parameter list. I think it would be less error prone if you used named placeholders.</p>\n\n<pre><code>import bcrypt\n\ndef register(self, c, json_data):\n attr = dict(json_data['data'])\n attr['salt'] = bcrypt.gensalt()\n password = attr['password']\n attr['hash'] = bcrypt.hashpw(password, attr['salt'])\n attr['true'] = True\n try:\n c.execute(\"\"\"INSERT INTO profiles VALUES (DEFAULT\n , %(email)s\n , %(hash)s\n , %(salt)s\n , %(date_created)s\n , %(state_lvl)s\n , %(true)s\n , %(first_name)s\n , %(last_name)s\n , %(sex)s\n , %(age)s\n , %(state)s\n , %(country)s\n , %(language)s\n , %(device_type)s\n , %(device)s\n , %(device_width)s\n , %(device_height)s\n , %(device_screen_density)s\n )\"\"\", attr);\n json_response = json.dumps({\"success\": 1, \"errors\": 0})\n except Exception, e:\n json_response = json.dumps({\"success\": 0, \"errors\": 1, \"msg\": str(e)})\n return HttpResponse(json_response, mimetype=\"application/json\")\n</code></pre>\n\n<p>It's a bit odd that you let the client specify the profile creation date. I would just let the database issue a timestamp.</p>\n\n<p>I think that the long parameter list is indicative of a problematic database schema. If you ever want to add another attribute to the user profile, that would require a schema alteration. The <code>profiles</code> table should probably be split into an <code>accounts</code> table containing the essentials and an <code>account_attributes</code> table that stores arbitrary key-value pairs.</p>\n\n<pre><code>CREATE TABLE accounts\n( id SERIAL PRIMARY KEY\n, email TEXT NOT NULL\n, hash TEXT NOT NULL\n, salt TEXT NOT NULL\n, date_created DATE NOT NULL DEFAULT statement_timestamp()\n);\n\nCREATE TABLE account_attributes\n( account_id INTEGER NOT NULL\n, attribute TEXT NOT NULL\n, value TEXT NOT NULL\n, PRIMARY KEY (account_id, attribute)\n, FOREIGN KEY (account_id) REFERENCES accounts (id)\n);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T13:30:19.503", "Id": "78294", "Score": "0", "body": "I was tempted to add a link to the definition of 404 in the same resource as the others links but I don't quite like the end of the explanation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T06:20:52.577", "Id": "44937", "ParentId": "44244", "Score": "2" } }, { "body": "<p>In case it helps a little ... in your register function, you can simplify the creation of the string for the c.execute statement.</p>\n\n<pre><code>execute_text = (\"INSERT INTO profiles VALUES (DEFAULT, %s, %s, %s, %s, %s, %s\" %\n (json_data['data']['email'], hash, salt, \n json_data['data']['date_created'], json_data['data']['state_lvl'], \n True,))\njson_fields = ['first_name', 'last_name', 'sex', 'age', 'state', 'country',\n 'language', 'device_type', 'device', 'device_width', 'device_height',\n 'device_screen_density']\n\nfor field in json_fields:\n execute_text = \"%s, %s\" % (execute_text, json_data['data'][field])\nexecute_text = \"%s)\" % execute_text\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T12:48:22.013", "Id": "44964", "ParentId": "44244", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T10:11:53.210", "Id": "44244", "Score": "8", "Tags": [ "python", "json", "api", "django" ], "Title": "Django API Implementation" }
44244
<p>When running Code Analysis on my project I get the following warning:</p> <blockquote> <p>CA2202 : Microsoft.Usage : Object 'fs' can be disposed more than once in method</p> </blockquote> <p>I don't see the problem, and the code compiles fine and produces the expected results in all test cases. If I remove the <code>fs.Dispose();</code> statement then Code Analysis instead produces this warning:</p> <blockquote> <p>object 'fs' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'fs' before all references to it are out of scope.</p> </blockquote> <p>I am much grateful if you can review my code so that I can learn the proper way of disposing resources.</p> <pre><code> private string ReadFileContent(string filename, Encoding encoding, string category, FileArchive archiveConfig) { FileStream fs = null; StreamReader sr = null; string fileContent = string.Empty; _logger.Debug("Reading file content of \"" + category + "\" file \"" + filename + "\""); try { fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 64 * 1024, FileOptions.SequentialScan); fs.Position = 0; sr = new StreamReader(fs, encoding, true); fileContent = sr.ReadToEnd(); } catch (Exception) { ArchiveFile(filename, archiveConfig.ErrorFolder, category, _logger); throw; } finally { if (sr != null) sr.Dispose(); if (fs != null) fs.Dispose(); } return fileContent; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T10:39:36.010", "Id": "76675", "Score": "5", "body": "The normal way to use `IDisposable` objects is `using (FileStream fs = new FileStream(…)) { … }`, which removes much ugliness from that code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T11:51:38.950", "Id": "76685", "Score": "0", "body": "@amon Yes, but I still want to catch Exceptions and handle them. Do you mean I should use try/catch inside the `using` block?" } ]
[ { "body": "<p>As @amon mentioned, the correct way of referencing <code>IDisposable</code> Objects in C# is the using-statement.</p>\n\n<p>In general you then have the try-catch block around the using statement to catch eventual initialization errors. This means your Code would look somewhat like this:</p>\n\n<pre><code>String fileContent = String.Empty;\n_logger.Debug(\"Debug-String\");\n\ntry{\n using(FileStream fs = new Filestream(filename, FileMode.Open, FileAccess.ReadWrite,\n FileShare.None, 64 * 1024, FileOptions.SequentialScan){\n fs.Position = 0;\n using (StreamReader sr = new Streamreader(fs, encoding, true){\n fileContent = sr.ReadToEnd();\n }\n }\n}\ncatch (Exception){\n ArchiveFile(filename, archiveConfig.ErrorFolder, category, _logger);\n throw;\n}\n\nreturn fileContent;\n</code></pre>\n\n<p>This also allows you to declare variables only when used. </p>\n\n<p>Finally a small note on <code>filename</code>... you are using camelCase in all variables but that. Be consistent in your naming schema</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-21T15:56:13.133", "Id": "247589", "Score": "0", "body": "Nice answer. However, filename is a valid naming. Microsoft uses same way on some of the variables as well. Also here is another example; https://en.wikipedia.org/wiki/Filename" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:12:36.510", "Id": "44254", "ParentId": "44245", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T10:24:55.377", "Id": "44245", "Score": "3", "Tags": [ "c#", "memory-management" ], "Title": "MS CA2202: Object can be disposed more then once" }
44245
<p>I am relatively new to Perl and would like to check that the code I am writing docent have any major flaws in it or any bad practices.</p> <p>This is a fairly simple sub but one that gets used often. Seems to work OK. Simply reads a text file that has parameters in it set by the user.</p> <p>Config.txt</p> <pre><code>#cucm username and password of user associated with phones username = bob password = bobPass #subnet details. Use /30 to start with to test 2 phones before entire subnet subnet = 10.64.97.216/32 #HFS web server details IP and folder webserver = http://10.64.164.230/Desktop/ #image file names. Full and Thumbnail size imgFullSize = screen_F.png imgThumSize = screen_S.png </code></pre> <p>Perl sub that reads the file:</p> <pre><code>sub readConfigFile { print $lfh "Reading Config.txt file\n"; #path to the config file my $configF = "config.txt"; if($DEBUG == 1){print "opening config File\n";} open(my $configFhandle, '&lt;', $configF) or die "Unable to open file, $!"; my @arrFileData=&lt;$configFhandle&gt;; #Slurp! #go through each of the lines in the file for (my $i = 0; $i &lt;= $#arrFileData; ++$i) { local $_ = $arrFileData[$i]; if($DEBUG == 1){print "Reading line:$_";} #check to see if the line is a comment... if it is skip it if($_ =~ /^#/) { if($DEBUG == 1){print "Line is comment. Skiping:$_";} next; } #split the line into the key and value my @dataKV = split /=/, $_; #check to see that Key and Value exist ... if not skip it my $arrSize = @dataKV; if($arrSize &lt;= 1) { if($DEBUG == 1){print "Read Config: Error: No Key AND Value found:$_";} next; } #remove all leading and end white spaces around elements s{^\s+|\s+$}{}g foreach @dataKV; for (my $x = 0; $x &lt;= $#dataKV; $x++) { if($DEBUG == 1){print "Key:$dataKV[$x]\n";} given($dataKV[$x]) { when (/^username/) { $usr = $dataKV[++$x]; if($DEBUG == 1){print "Value Username:$dataKV[$x]\n";} next; } when (/^password/) { $pass = $dataKV[++$x]; if($DEBUG == 1){print "Value password:$dataKV[$x]\n";} next; } when (/^subnet/) { @arrSubnets = $dataKV[++$x]; if($DEBUG == 1){print "Value Subnet:$dataKV[$x]\n";} next; } when (/^webserver/) { $webserver = $dataKV[++$x]; if($DEBUG == 1){print "Value webserver:$dataKV[$x]\n";} next; } when (/^imgFullSize/) { $imgFull = $dataKV[++$x]; if($DEBUG == 1){print "Value imgFullSize:$dataKV[$x]\n";} next } when (/^imgThumSize/) { $imgThum = $dataKV[++$x]; if($DEBUG == 1){print "Value imgThumSize:$dataKV[$x]\n";} next } }#end of switch statement }#end of for loop going through the key and value line }#end of For loop going though the lines in the config print "*********************************\n"; print "*Config imported\n"; print "*********************************\n"; print "*username :$usr\n"; print "*password :$pass\n"; print "*subnet :@arrSubnets\n"; print "*webserver :$webserver\n"; print "*imgFullSize :$imgFull\n"; print "*imgThumSize :$imgThum\n"; print "*********************************\n"; print "Is this above correct?[Y]:"; my $confirm = &lt;&gt;; if($confirm !~ /^Y/) { print $lfh "Config file needs to be changed. Closing script down.\n"; close($lfh) or warn "Unable to close the file handle: $!"; close($configFhandle) or warn "Unable to close the file handle: $!"; print "Script will now terminate. Please amend \"Config.txt\" file and re-run script. Press any key to terminate"; &lt;&gt;; exit; } #close the file close($configFhandle) or warn "Unable to close the file handle: $!"; print $lfh "Y pressed by User. Config all good.\n"; } </code></pre> <p>Any advise on how to improve this would be great.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T11:11:49.423", "Id": "76681", "Score": "2", "body": "Can you use CPAN modules? If yes (and it's not an excercise) use [`Config::Tiny`](https://metacpan.org/pod/Config::Tiny) or another module for reading ini files." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:20:10.480", "Id": "76889", "Score": "0", "body": "@Xaerxess thanks for that and maybe in production i might use that module but more interested in improving my code" } ]
[ { "body": "<p>Well, here is how I'd write that subroutine. I thoroughly commented the code to explain my choices.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>use strict;\nuse warnings;\nuse autodie; # automatic error handling for \"open\" and other builtins\nuse IO::Handle; # object oriented syntax for filehandles\n\n# DEBUG is a compile-time constant initialized by an environment variable.\n# If it is false, the debug statements will get optimized away.\nuse constant DEBUG =&gt; $ENV{DEBUG};\n\n# the log file handle and debug file handle\n# Here, I opened both to STDERR\nopen my $lfh, '&gt;&amp;', STDERR;\nopen my $dfh, '&gt;&amp;', STDERR;\n\n# close the $lfh file handle regardless of how the script terminates.\nEND {\n no autodie;\n close $lfh or warn \"Unable to close the log file handle: $!\";\n}\n\n# the main part of our script\n{\n my $filename = \"config.txt\";\n # \"read_config_file\" is a function that takes one argument and returns one value.\n my $config = read_config_file($filename);\n # if the check fails, exit this script with error code \"1\".\n # the default error code (zero) is considered a success.\n ui_check_config_ok(\\*STDOUT, $config, $filename) or exit 1;\n\n # now we can do stuff with the $config, e.g.\n my $usr = $config-&gt;{username};\n}\n\n# Name your variables in snake_case, not with camelCase.\n# This function *only* parses the config file.\n# It does not interact with the user.\n# Such separation of concern makes your code easier to maintain:\n# every function should do one thing only.\nsub read_config_file {\n # Subroutines can take an argument list.\n # We unpack it like this:\n my ($filename) = @_;\n\n $lfh-&gt;say(\"Reading config file $filename\");\n DEBUG and $dfh-&gt;say(\"Opening config file $filename\");\n\n my %known_keys = map { $_ =&gt; 1 } qw/\n username password subnet webserver imgFullSize imgThumSize\n /;\n\n # we wills store the config in this hash\n my %config;\n\n open my $fh, \"&lt;\", $filename;\n\n # don't slurp the file, we loop over it line by line\n LINE:\n while (&lt;$fh&gt;) {\n # trim the line\n s{\\A\\s+}{};\n s{\\s+\\z}{};\n\n DEBUG and $dfh-&gt;say(\"Reading line: $_\");\n if (/^#/) {\n DEBUG and $dfh-&gt;say(\"Line is comment, skipping.\");\n next LINE;\n }\n\n # * We use the /x flag on regexes to be able to structure the regex with spaces\n # they won't match, they're just decoration\n # * instead of assigning to an array, we assign to a list of scalars.\n # If the \"split\" fails, the last one should be \"undef\"\n # * We only accept one \"=\" per line, and produce 2 fragments max. So\n # foo = bar = baz\n # will produce $key=\"foo\", $value=\"bar = baz\".\n my ($key, $value) = split m{\\s* [=] \\s*}x, $_, 2;\n if (not defined $value) {\n DEBUG and $dfh-&gt;say(\"Ignoring config error: no key = value pair found on line: $_\");\n next LINE;\n }\n\n DEBUG and $dfh-&gt;say(\"Value $key:$value\");\n $config{$key} = $value;\n\n # a sanity check – you don't do anything on unknown keys\n if (not exists $known_keys{$key}) {\n $lfh-&gt;say(\"The config provided the unknown key $key, ignoring.\")\n }\n }\n\n # another sanity check – did the user forget to specify some properties?\n for my $key (keys %known_keys) {\n if (not exists $config{$key}) {\n $lfh-&gt;say(\"The config didn't provide a key $key, ignoring.\")\n }\n }\n\n return \\%config;\n}\n\n# another subroutine that provides the user interface to ask whether the data is correct\n# It will return a truth value whether the config was OK.\nsub ui_check_config_ok {\n # Here, we see an argument list with three values\n my ($ui_fh, $config, $filename) = @_;\n\n $ui_fh-&gt;say($_) for\n \"*********************************\",\n \"*Config imported\",\n \"*********************************\",\n \"*username :$config-&gt;{username}\",\n \"*password :$config-&gt;{password}\",\n \"*subnet :$config-&gt;{subnet}\",\n \"*webserver :$config-&gt;{webserver}\",\n \"*imgFullSize :$config-&gt;{imgFullSize}\",\n \"*imgThumSize :$config-&gt;{imgThumSize}\",\n \"*********************************\";\n $ui_fh-&gt;print(\"Is this above correct?[Y]:\");\n if (&lt;STDIN&gt; =~ /^\\s*Y/) {\n $lfh-&gt;say(\"The user pressed Y. Config is good.\");\n return 1;\n }\n\n $lfh-&gt;say(\"Config file contains false information, please correct.\");\n $lfh-&gt;say(\"Terminating script\");\n $ui_fh-&gt;say(\"The script will now terminate.\");\n $ui_fh-&gt;say(\"Please amend the file $filename and rerun the script.\");\n $ui_fh-&gt;say(\"Press any key to terminate...\");\n &lt;&gt;;\n return 0;\n}\n</code></pre>\n\n<p>Note how indentation made this code much easier to read than the dump you provided. Please use indentation!</p>\n\n<p>I actually do not generally use <code>IO::Handle</code>, but it makes stuff more obvious when having more than one file handle. The <code>autodie</code> module is a bit inflexible, but I highly encourage it when you are still new with Perl, as it provides sensible defaults. You do not manually have to close file handles if they are variables declared with <code>my</code> – they will get closed automatically, and it's highly unlikely that closing a file will fail (file handles are not only used for physical files, but also for other things like pipes, where the <code>close</code> can fail).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:21:54.647", "Id": "76890", "Score": "0", "body": "thanks for that (especially for the comments) It will take me some time to digest all the information but this is exactly the feedback i was looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:22:52.893", "Id": "44264", "ParentId": "44246", "Score": "4" } } ]
{ "AcceptedAnswerId": "44264", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T10:46:00.127", "Id": "44246", "Score": "3", "Tags": [ "beginner", "perl", "file" ], "Title": "Reading a config file" }
44246
<p>I want to find total word count in string. I have two methods as mentioned below.</p> <pre><code>public static int Wordcount(string strName) { bool wordfound; int ctr = 0; for (int i = 0; i &lt; strName.Length; ) { wordfound = false; while ((i &lt; strName.Length) &amp;&amp; (strName[i] == ' ')) i++; while ((i &lt; strName.Length) &amp;&amp; (strName[i] != ' ')) { if (!wordfound) { ctr++; wordfound = true; } i++; } } return ctr; } </code></pre> <hr> <pre><code>public static int Wordcount1(string strName) { string temp = null; int ctr = 0; for (int i = 0; i &lt; strName.Length; i++) { if (strName[i] != ' ') { if (temp == null) ctr++; temp += strName[i]; } else if (strName[i] == ' ') temp = null; } return ctr; } </code></pre> <p>Can anyone please comment on better approach w.r.t. logic, performance and memory utilization?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T12:31:18.983", "Id": "76689", "Score": "0", "body": "Did you write those? What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:37:25.873", "Id": "76698", "Score": "0", "body": "If you care about performance and memory, why don't you measure them yourself?" } ]
[ { "body": "<p>Let's analyze each approach:</p>\n\n<pre><code>public static int Wordcount1(string strName)\n{\n string temp = null;\n int ctr = 0;\n\n for (int i = 0; i &lt; strName.Length; i++)\n {\n if (strName[i] != ' ')\n {\n if (temp == null)\n ctr++;\n\n temp += strName[i];\n }\n else if (strName[i] == ' ')\n temp = null;\n }\n\n return ctr;\n}\n</code></pre>\n\n<p>You are using <code>temp</code> string only as boolean flag (whether its null or not). So, you don't need to store current word in this variable. Actually <code>temp += strName[i]</code> creates many strings in memory, because strings are immutable. So, its performance and memory consuming. Remove it.</p>\n\n<p>Also you don't need second if. If char is not white space, then it is white space. There is no third option. And improve naming - don't use prefixes for variable names.</p>\n\n<pre><code>public static int Wordcount(string text)\n{\n bool wordFound = false\n int count = 0;\n\n for (int i = 0; i &lt; text.Length; i++)\n {\n if (text[i] != ' ' &amp;&amp; !wordFound)\n { \n wordFound = true;\n count++\n continue;\n }\n\n if (wordFound)\n wordFound = false;\n }\n\n return count;\n}\n</code></pre>\n\n<hr>\n\n<p>Another approach:</p>\n\n<pre><code>public static int GetWordsCount(string strName)\n{\n bool wordfound;\n int ctr = 0;\n\n for (int i = 0; i &lt; strName.Length; )\n {\n wordfound = false;\n\n while ((i &lt; strName.Length) &amp;&amp; (strName[i] == ' '))\n i++;\n\n while ((i &lt; strName.Length) &amp;&amp; (strName[i] != ' '))\n {\n if (!wordfound)\n {\n ctr++;\n wordfound = true;\n }\n i++;\n }\n }\n\n return ctr;\n}\n</code></pre>\n\n<p>For me its a little harder to understand, because you are incrementing loop variable in loop body on some conditions inside other loops. But you are not creating strings here as you do in your second approach. So it's definitely better in terms of performance and memory usage, than you original second approach.</p>\n\n<p>In second approach you can eliminate usage of boolean flag, and condition check in second while loop. Also with some comments this code becomes easier to understand:</p>\n\n<pre><code>public static int GetWordsCount(string text)\n{ \n int count = 0;\n\n for (int i = 0; i &lt; text.Length; )\n { \n // process to next word \n while ((i &lt; text.Length) &amp;&amp; (text[i] == ' '))\n i++;\n\n if (i &lt; text.Length)\n count++;\n\n // loop till the word end\n while ((i &lt; text.Length) &amp;&amp; (text[i] != ' '))\n i++; \n }\n\n return count;\n}\n</code></pre>\n\n<hr>\n\n<p>But of course its better to use already existing functionality:</p>\n\n<pre><code>return text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length;\n</code></pre>\n\n<p>Its not that fast, and it creates array of words which uses memory. But it's easy to understand for other developers. So, instead of doing premature optimization, I'd go with this approach and modified it only in case of performance problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:42:02.457", "Id": "76703", "Score": "1", "body": "The term “white space” usually means any of the space characters (including `'\\t'` and `'\\n'`), not just the single space character `' '` (or `'\\x20'`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:45:28.673", "Id": "76704", "Score": "1", "body": "@svick agree, it's better to use something like `Char.IsWhiteSpace`. Also there is punctuation symbols which also should be considered as word boundaries. E.g. if somebody wrote `hello,world`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:21:33.797", "Id": "44255", "ParentId": "44250", "Score": "4" } } ]
{ "AcceptedAnswerId": "44255", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T12:25:50.800", "Id": "44250", "Score": "3", "Tags": [ "c#", "strings", "parsing" ], "Title": "Which approach is preferable string parsing?" }
44250
<p>The array size is &lt;= 16. The difference is defined as:</p> <pre><code>diff[i] = array[i+1] - array[i]; </code></pre> <p>I need to find the number of permutations of the original array, which have a difference that is a permutation of the difference of the original array.</p> <p>This is my code:</p> <pre><code>public class Main { Scanner scan = new Scanner(System.in); int N; int [] array_base; int [] first_diff; int result; public static void main(String[] args) { Main main = new Main(); main.read(); main.run(); } void read() { N = scan.nextInt(); array_base = new int [N]; for (int i = 0; i&lt;N; i++) { array_base[i] = scan.nextInt(); } first_diff = first_difference(); } int [] first_difference() { int [] temp = new int [N-1]; for (int i=0; i &lt; N-1; i++) { temp[i] = array_base[i+1] - array_base[i]; } return temp; } void run() { permute(array_base,0); System.out.println(Integer.toString(result)); } public void permute(int[] array, int k) { for(int i=k; i&lt;array.length; i++) { int temp; temp = array[i]; array[i] = array[k]; array[k] = temp; permute(array, k+1); int temp2; temp2 = array[i]; array[i] = array[k]; array[k] = temp2; } if (k == array.length-1) { calculate(array); } } void calculate(int [] array) { int [] diff_values = new int [array.length-1]; for (int i = 0; i &lt; array.length-1; i++) { diff_values[i] = array[i+1] - array[i]; } compare(diff_values); } void compare(int [] values) { boolean [] used_new = new boolean [values.length]; boolean [] used_first = new boolean [values.length]; for (int i = 0; i &lt; values.length; i++) { used_new[i] = false; used_first[i] = false; } for (int i = 0; i &lt; values.length; i++) { for (int j = 0; j &lt; values.length; j++) { if (used_new[j]) { } else if (first_diff[i] == values[j]) { used_new[j] = true; used_first[i] = true; break; } } if (used_first[i] == false) break; } if (areAllTrue(used_new) &amp;&amp; areAllTrue(used_first)) { result += 1; } } public boolean areAllTrue(boolean[] array) { for(boolean b : array) if(!b) return false; return true; } } </code></pre> <p>I do, however, see that this code is not fast as it could be. Could anyone give me some advice on how to speed it up?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:38:09.120", "Id": "76732", "Score": "0", "body": "Can you please provide some examples of input/output ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:48:06.117", "Id": "76790", "Score": "0", "body": "Input:\n9\n1 4 2 5 7 6 9 8 3\n\nOutput:\n8" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T23:05:35.473", "Id": "77070", "Score": "0", "body": "I tried to have a new look at your question again and still cannot understand what you are trying to achieve. Would you mind giving more details about your examples (like giving explicitly the 8 permutations) ?" } ]
[ { "body": "<p>You are using a class just to be able to able to mess with some kind of global values. This makes your code very hard to understand. It took me a while to unroll it all and get the following code :</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class Main {\n\n public static void main(String[] args) {\n run(read());\n\n run(fake_read());\n }\n\n static int[] fake_read() {\n int[] a = {1, 4, 2, 5, 7, 6, 9, 8, 3};\n return a;\n }\n\n static int[] read() {\n Scanner scan = new Scanner(System.in);\n int N = scan.nextInt();\n int [] array = new int [N];\n for (int i = 0; i&lt;N; i++) {\n array[i] = scan.nextInt();\n }\n return array;\n }\n\n static int [] first_difference(int[] array) {\n int N = array.length;\n int [] temp = new int [N-1];\n for (int i=0; i &lt; N-1; i++) {\n temp[i] = array[i+1] - array[i];\n }\n return temp;\n }\n\n static void run(int[] array) {\n int [] first_diff = first_difference(array);\n int n = permute(array,0, first_diff);\n System.out.println(Integer.toString(n));\n }\n\n static public int permute(int[] array, int k, int [] first_diff)\n {\n int result = 0;\n for(int i=k; i&lt;array.length; i++)\n {\n int temp = array[i];\n array[i] = array[k];\n array[k] = temp;\n result += permute(array, k+1, first_diff);\n temp = array[i];\n array[i] = array[k];\n array[k] = temp;\n }\n if (k == array.length-1)\n {\n result += calculate(array, first_diff);\n }\n return result;\n }\n\n static int calculate(int [] array, int [] first_diff) {\n int [] diff_values = new int [array.length-1];\n for (int i = 0; i &lt; array.length-1; i++) {\n diff_values[i] = array[i+1] - array[i];\n }\n return compare(diff_values, first_diff);\n }\n\n static int compare(int [] values, int [] first_diff) {\n int result = 0;\n boolean [] used_new = new boolean [values.length];\n boolean [] used_first = new boolean [values.length];\n for (int i = 0; i &lt; values.length; i++) {\n used_new[i] = false;\n used_first[i] = false;\n }\n for (int i = 0; i &lt; values.length; i++) {\n for (int j = 0; j &lt; values.length; j++) {\n if (!used_new[j] &amp;&amp; first_diff[i] == values[j]) {\n used_new[j] = true;\n used_first[i] = true;\n break;\n }\n }\n if (!used_first[i]) break;\n }\n if (areAllTrue(used_new) &amp;&amp; areAllTrue(used_first)) {\n result += 1;\n }\n return result;\n }\n\n static public boolean areAllTrue(boolean[] array)\n {\n for(boolean b : array) if(!b) return false;\n return true;\n }\n}\n</code></pre>\n\n<p>I'll be honest with you, I was hoping that once this was done, I'd be facing something somewhat easier to understand but it is not the case (the poor documentation and the function names do not help at all). I guess one could find a simpler (and faster ?) solution but the thing is that I don't even understand what is expected. The question might need clarification.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T00:10:32.913", "Id": "44311", "ParentId": "44253", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T12:59:50.263", "Id": "44253", "Score": "0", "Tags": [ "java", "performance", "combinatorics" ], "Title": "Finding the number of permutations of an integer array with equaling difference (not in order)" }
44253
<p>I have this currently working code, but it's extremely slow. I'm talking almost an hour to execute, if it executes at all (our server isn't all that great to start with). Is there a better way to write this?</p> <p>Basically, I am wanting to return the Top 5 parts, that match a distinct pattern code within the same table. So, if there were 100 distinct pattern codes in my <code>[PartNumber]</code> table, I would end up with 500 records.</p> <p><strong>ORIGINAL at time of question posting (Executes in 32 minutes):</strong></p> <pre><code>DECLARE @PartInfo TABLE( [PartNumber] [varchar](64) NOT NULL, [PatternCode] [varchar](64) NOT NULL, [LanguageCode] [varchar](24) NOT NULL); DECLARE @PatternCode nvarchar(64); DECLARE pattern_Cursor CURSOR LOCAL SCROLL STATIC FOR SELECT TOP 1000 [PartNumber].[PatternCode] FROM [Web_Service].[dbo].[PartNumber] [PartNumber] WHERE PatternCode NOT LIKE 'NOT FOUND' GROUP BY [PartNumber].[PatternCode] OPEN pattern_Cursor; FETCH NEXT FROM pattern_Cursor INTO @PatternCode; WHILE @@FETCH_STATUS = 0 BEGIN INSERT INTO @PartInfo SELECT TOP 5 [PartNumberInfo].* FROM [Web_Service].[dbo].[PartNumber] [PartNumber] WHERE [PartNumber].[PatternCode] = @PatternCode; FETCH NEXT FROM pattern_Cursor INTO @PatternCode; END CLOSE pattern_Cursor; DEALLOCATE pattern_Cursor; SELECT * FROM @PartInfo ORDER BY [@PartInfo].[PatternCode] </code></pre> <p><strong>First revision (Executes in 24 minutes):</strong></p> <pre><code>CREATE TABLE #PartInfo ([PartNumber] [varchar](64) NOT NULL, [PatternCode] [varchar](64) NOT NULL, [LanguageCode] [varchar](24)); DECLARE @PatternCode nvarchar(64); DECLARE pattern_Cursor CURSOR FAST_FORWARD FOR SELECT [PartNumber].[PatternCode] FROM [Web_Service].[dbo].[PartNumber] [PartNumber] WHERE PatternCode &lt;&gt; 'NOT FOUND' GROUP BY [PartNumber].[PatternCode] OPEN pattern_Cursor; FETCH NEXT FROM pattern_Cursor INTO @PatternCode; WHILE @@FETCH_STATUS = 0 BEGIN INSERT INTO #PartInfo SELECT TOP 5 [PartNumber].* FROM [Web_Service].[dbo].[PartNumber] [PartNumber] WHERE [PartNumber].[PatternCode] = @PatternCode ORDER BY [PartNumber].[DateTimeValidated] DESC; FETCH NEXT FROM pattern_Cursor INTO @PatternCode; END CLOSE pattern_Cursor; DEALLOCATE pattern_Cursor; SELECT * FROM #PartInfo ORDER BY [#PartInfo].[PatternCode] </code></pre> <p><strong>FINAL COMPLETED AND WORKING CODE (executes in 15 seconds):</strong></p> <pre><code>SET NOCOUNT ON GO SET ARITHABORT ON GO SET ANSI_PADDING ON GO DECLARE @TopCount int = 5; SELECT [DistinctTop].[PartNumber] ,[DistinctTop].[PatternCode] ,[DistinctTop].[LanguageCode] FROM (SELECT [PartNumber] ,[PatternCode] ,[LanguageCode] ,RANK() OVER (PARTITION BY [PatternCode] ORDER BY [PartNumber]) AS RowRank FROM PartNumberInfo) AS [DistinctTop] WHERE [DistinctTop].[RowRank] &lt;= @TopCount ORDER BY [DistinctTop].[PatternCode]; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:32:06.297", "Id": "76714", "Score": "1", "body": "If a query ever takes more than 30s to run, it's not being correctly done. (Usually, 1s is the limit for \"something is fishy\".)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:49:57.477", "Id": "76716", "Score": "1", "body": "@ANeves I can't say I fully agree with that. I've seen some pretty efficient, fully indexed queries take upwards of a minute. I mean, in most cases I can probably agree, but also considering our server isn't all that great I can't really base anything on that logic. A query could take 2 seconds at 6am, but 2 minutes at 11am and there's really nothing I can do on that end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:56:39.827", "Id": "76718", "Score": "1", "body": "Make it a rule of thumb, more than a rule. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:58:44.330", "Id": "76719", "Score": "1", "body": "Please do not update the original code from answers. That will invalidate them. You may add the updated code below the original." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:58:20.460", "Id": "76737", "Score": "0", "body": "are you using SQL Server?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:56:53.450", "Id": "76803", "Score": "1", "body": "Just a coding style note: It is customary in SQL to leave no blank lines between elements of a query. Each query should form a \"paragraph\", with blank lines used only to separate one unit of work from another. This will make your code more readable to peers, successors, and StackExchange readers." } ]
[ { "body": "<p>You have three problems that I can see. Two performance, and one logic. In least-to-most significant order:</p>\n<ol>\n<li>Performance: You should no use the <code>NOT LIKE 'NOT FOUND'</code> statement, it should be <code> &lt;&gt; 'NOT FOUND'</code></li>\n<li>Potential logic problem: You should have an order-by clause on the inner select for the TOP 5 ... otherwise, what TOP 5 are you getting?</li>\n<li>Performance: Using <code>declare @table...</code> syntax has different performacne to <code>create table #table ...</code> For example, <a href=\"http://www.sql-server-performance.com/2007/temp-tables-vs-variables/\" rel=\"nofollow noreferrer\">this blog entry shows some real differences</a>. I recommend trying the same query with a #temp table instead.</li>\n</ol>\n<p>Also, read up on this SO Answer: <a href=\"https://stackoverflow.com/a/2219765/1305253\">SQL Server tables: what is the difference between @, # and ##?</a></p>\n<p><strong>Edit:</strong></p>\n<p>It was almost too obvious to ask... but, you have done the two most basic items... right?</p>\n<ol>\n<li>an index on the <code>[PartNumber].[PatternCode]</code></li>\n<li>updated all table statistics</li>\n</ol>\n<p>... right?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:54:00.023", "Id": "76717", "Score": "0", "body": "So, I have replaced the NOT LIKE with <> and modified the query to use #. Please see my updated code. It's still really slow though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:12:44.230", "Id": "76722", "Score": "0", "body": "@Volearix - updated the answer with two more suggestions...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:20:25.400", "Id": "76725", "Score": "0", "body": "Yes on the index (CREATE CLUSTERED INDEX [PartInfo$PatternCode] on #PartInfo ([PatternCode]);), though there might be a better index available? On the second, I'm not familiar with updating table statistics. Unless it's the index or in the code I posted, it didn't happen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:21:46.057", "Id": "76728", "Score": "1", "body": "The index needs to be on `[Web_Service].[dbo].[PartNumber]` not on `#PartInfo` ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:54:59.583", "Id": "76802", "Score": "0", "body": "CREATE NONCLUSTERED INDEX IX_PartNumberInfo_PatternCode ON [PartNumber] (PartNumber);\nIncreased performance 2 seconds. Any better indexing idea? There is already a PK on PattenCode and PartNumber, which I cannot modify." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T14:08:50.503", "Id": "44259", "ParentId": "44256", "Score": "6" } }, { "body": "<h1>RANK()</h1>\n<p>In the past I have found that for these purposes, using <a href=\"http://technet.microsoft.com/en-us/library/ms176102.aspx\" rel=\"noreferrer\"><code>RANK()</code></a> is the way to go.<br />\nIn all honesty, I don't know how cursors perform, in comparison.</p>\n<pre><code>SELECT *\nFROM (\n select *, RANK() OVER (PARTITION BY PatternCode ORDER BY PartNumberInfo.Foo) AS RowRank\n FROM PartNumberInfo\n) AS Bar\nWHERE Bar.RowRank &lt; 5\n</code></pre>\n<p><a href=\"http://sqlfiddle.com/#!6/5a06b/1\" rel=\"noreferrer\">http://sqlfiddle.com/#!6/5a06b/1</a></p>\n<p>This might benefit from indexing.</p>\n<h1>Use nulls instead of <code>NOT FOUND</code></h1>\n<p>You should be using nulls instead of such a default value.</p>\n<h1>nvarchar</h1>\n<p>You should be using nvarchar instead of varchar: <a href=\"https://stackoverflow.com/questions/144283/what-is-the-difference-between-varchar-and-nvarchar\">https://stackoverflow.com/questions/144283/what-is-the-difference-between-varchar-and-nvarchar</a></p>\n<p>If the content of your columns is never user-input, then you can consider exceptions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:07:25.860", "Id": "76743", "Score": "0", "body": "BEAST! I knew about RANK, but wasn't sure how to use it! Took me from around 24 minute execution to 15 seconds! Final code posted. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:35:16.193", "Id": "76798", "Score": "0", "body": "15 seconds still feels too long for such a simple thing. I have a nagging suspicion that you could profit from good indexing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:58:51.567", "Id": "76804", "Score": "0", "body": "CREATE NONCLUSTERED INDEX IX_PartNumberInfo_PatternCode ON [PartNumber] (PartNumber); Exists already. Not good enough? I do not do much indexing, something better that you could suggest?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:12:46.307", "Id": "76809", "Score": "0", "body": "My guess is that it does **not** significantly affect the query - try to \"explain\"/\"check the execution plan of\" the query. I would look into doing a composite index on the two columns that you use in the query: PatternCode and PartNumber (note that the order of the columns in the index is relevant). I suggest you ask a question in StackOverflow about the index." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:54:28.187", "Id": "44267", "ParentId": "44256", "Score": "6" } }, { "body": "<p>On your final and completed code, there is no reason to create a variable for a number that doesn't change.</p>\n<p>So this:</p>\n<pre><code>WHERE [DistinctTop].[RowRank] &lt;= @TopCount\n</code></pre>\n<p>Should become this:</p>\n<pre><code>WHERE [DistinctTop].[RowRank] &lt;= 5\n</code></pre>\n<p>The less variables and things that are created on the database the better, this variable is unneeded.</p>\n<hr />\n<h3>You could use a <a href=\"http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx\" rel=\"nofollow noreferrer\">CTE (Common Table Expression)</a></h3>\n<p>rather than this:</p>\n<pre><code>DECLARE @TopCount int = 5;\n\nSELECT [DistinctTop].[PartNumber]\n ,[DistinctTop].[PatternCode]\n ,[DistinctTop].[LanguageCode]\n \nFROM (SELECT [PartNumber]\n ,[PatternCode]\n ,[LanguageCode]\n ,RANK() OVER \n (PARTITION BY [PatternCode] ORDER BY [PartNumber]) AS RowRank\n FROM PartNumberInfo) AS [DistinctTop]\n \nWHERE [DistinctTop].[RowRank] &lt;= @TopCount\n\nORDER BY [DistinctTop].[PatternCode];\n</code></pre>\n<p>Do this:</p>\n<pre><code>WITH [DistinctTop]\nAS \n(\n SELECT [PartNumber]\n ,[PatternCode]\n ,[LanguageCode]\n ,RANK() OVER (PARTITION BY [PatternCode] ORDER BY [PartNumber]) AS RowRank\n FROM PartNumberInfo\n)\nSELECT [DistinctTop].[PartNumber]\n ,[DistinctTop].[PatternCode]\n ,[DistinctTop].[LanguageCode]\nFROM [DistinctTop]\nWHERE [DistinctTop].[RowRank] &lt;= 5\n</code></pre>\n<p>This is a little cleaner than what you have in the way that it is clear to a coder what you are doing here and doesn't look messy.</p>\n<p>As far as creating variables on the Database, if I remember right this makes the execution plan a little cleaner as well. You would have to test this though.</p>\n<p><em>If you want to post the code with the results, please post a new question.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T17:19:31.590", "Id": "44885", "ParentId": "44256", "Score": "4" } } ]
{ "AcceptedAnswerId": "44267", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:39:25.383", "Id": "44256", "Score": "8", "Tags": [ "performance", "sql", "sql-server", "cursor" ], "Title": "Return the top 5 of each kind of record" }
44256
<p>I'd like comments on the following code, explanations, etc. are given in the javadoc:</p> <pre><code>package ocr.base; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; /** * Handles the checking of a directory at an interval. * * This interval is variable and is to be found in the config file. * The found files get processed via a file consumer. * The config file is only opened if the last modified date has changed. * * @author Frank van Heeswijk */ public abstract class BaseChecker implements Runnable { /** Scheduler to run the file checking on. **/ private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); /** The directory to be checked. **/ private final File directory; /** A consumer that accepts the files in the directory. **/ private final Consumer&lt;File&gt; fileConsumer; /** The configuration file. **/ private final File configFile; /** The runtime sub class of BaseChecker. **/ private final Class&lt;? extends BaseChecker&gt; subClass; /** The current duration, changes only if the file has been modified. **/ private Duration duration; /** The last modified date of the last readout of the config file. **/ private long configLastModified; /** * Constructs this object. * * @param directory The directory to be checked. * @param fileConsumer The consumer that accepts the files. * @param configFile The configuration file. */ public BaseChecker(final File directory, final Consumer&lt;File&gt; fileConsumer, final File configFile) { this.directory = Objects.requireNonNull(directory); this.fileConsumer = Objects.requireNonNull(fileConsumer); this.configFile = Objects.requireNonNull(configFile); this.subClass = this.getClass(); } /** * Checks the directory now and calls innerRun(). */ @Override public void run() { checkDirectory(); } /** * Gets the duration from the config file and schedules one execution of checkDirectory() at that time. * * It only actually opens the config file if it has been modified. */ private void innerRun() { if (configFile.lastModified() != configLastModified) { duration = durationFromConfig(); } scheduler.schedule(this::checkDirectory, duration.period, duration.unit); } /** * Checks the directory and calls the consumer for every file, and then calls innerRun(). */ private void checkDirectory() { Arrays.stream(directory.listFiles()).forEach(fileConsumer); innerRun(); } /** * Returns the duration from the config file. * * @return The duration. */ private Duration durationFromConfig() { try { return durationFromConfigInner(); } catch (IOException ex) { throw new IllegalStateException("The config file (\"" + configFile.getPath() + "\") has not been found."); } } /** * Returns the duration from the config file. * * Searches the log file for the first line indicating the config entry for this instance. * * @return The duration. * @throws FileNotFoundException If the config file has not been found. */ private Duration durationFromConfigInner() throws IOException { String entry = subClass.getSimpleName() + "="; Optional&lt;String&gt; optional = Files.newBufferedReader(configFile.toPath(), Charset.forName("UTF-8")).lines() .filter(s -&gt; s.startsWith(entry)) .map(s -&gt; s.replaceAll(" ", "")) .findFirst(); configLastModified = configFile.lastModified(); if (!optional.isPresent()) { throw new IllegalStateException("Entry (\"" + entry + "\") has not been found in the config file."); } return Duration.of(optional.get().replace(entry, "")); } /** * Record class to hold the duration. */ private static class Duration { /** The period of the duration. **/ public final int period; /** The time unit of the duration. **/ public final TimeUnit unit; /** * Constructs the duration. * * @param period The period. * @param unit The time unit. */ public Duration(final int period, final TimeUnit unit) { this.period = period; this.unit = Objects.requireNonNull(unit); } /** * Returns a duration based on a string value. * * The implementation accepts all strings starting with an integer number and ending on a 's', 'm', 'h' or 'd'. * These characters respectively denote seconds, minutes, hours and days. * * @param value The string value to be converted * @return The duration that the string value represented. */ public static Duration of(final String value) { Objects.requireNonNull(value); if (value.length() &lt; 2) { throw new IllegalArgumentException("Invalid duration (\"" + value + "\")."); } //period int period = Integer.parseInt(value.substring(0, value.length() - 1)); if (period &lt;= 0) { throw new IllegalArgumentException("Invalid period in value (\"" + value + "\")."); } //unit char unit = value.charAt(value.length() - 1); TimeUnit returnUnit; switch (unit) { case 's': returnUnit = TimeUnit.SECONDS; break; case 'm': returnUnit = TimeUnit.MINUTES; break; case 'h': returnUnit = TimeUnit.HOURS; break; case 'd': returnUnit = TimeUnit.DAYS; break; default: throw new IllegalArgumentException("Invalid unit in value (\"" + value + "\")."); } return new Duration(period, returnUnit); } @Override public String toString() { return "Duration(" + period + ", " + unit + ")"; } } } </code></pre>
[]
[ { "body": "<h2>Duration.of</h2>\n\n<p>With switch statements I find it <em>pleasing</em> to return-early, and avoid multiple lines of code. With switch statements especially, the early-return removes the need for an ugly <code>break</code> as well. Consider this method:</p>\n\n<pre><code> public static Duration of(final String value) {\n\n Objects.requireNonNull(value);\n if (value.length() &lt; 2) {\n throw new IllegalArgumentException(\"Invalid duration (\\\"\" + value + \"\\\").\");\n }\n\n //period\n int period = Integer.parseInt(value.substring(0, value.length() - 1));\n if (period &lt;= 0) {\n throw new IllegalArgumentException(\"Invalid period in value (\\\"\" + value + \"\\\").\");\n }\n\n switch (value.charAt(value.length() - 1)) {\n case 's':\n return new Duration(period, TimeUnit.SECONDS);\n case 'm':\n return new Duration(period, TimeUnit.MINUTES);\n case 'h':\n return new Duration(period, TimeUnit.HOURS);\n case 'd':\n return new Duration(period, TimeUnit.DAYS);\n default:\n throw new IllegalArgumentException(\"Invalid unit in value (\\\"\" + value + \"\\\").\");\n }\n }\n</code></pre>\n\n<h2>File vs. Path</h2>\n\n<p>You should try to stick with one, or the other, but changing between them is not cool.</p>\n\n<p>Your <code>BaseChecker</code> class takes Files as inputs, but internally, it does, in places, convert them to Paths, and then processes the Path values.</p>\n\n<p>If you are using Path, then stick with it. Actually, it is not that simple, but you should consider using other features of Path like the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Watchable.html\" rel=\"nofollow\">Watchable interface it implements</a>.... this would remove the need to poll the state of the config file.</p>\n\n<h2>Charsets</h2>\n\n<p>You have:</p>\n\n<blockquote>\n<pre><code>Charset.forName(\"UTF-8\")\n</code></pre>\n</blockquote>\n\n<p>This is most conveniently replaced with:</p>\n\n<pre><code>StandardCharsets.UTF_8\n</code></pre>\n\n<p>which avoids some lookup overhead.</p>\n\n<p>But you can directly use <code>Files.newBufferedReader(configFile.toPath())</code> in your <code>durationFromConfigInner</code> function</p>\n\n<h2>findFirst vs. findLast</h2>\n\n<p>You look for the config value the <em>first</em> time it is specified, but, standard java properties files, and other config systems, typically rely on the last occasion a value is set. Make sure your code is consistent with expectations</p>\n\n<p>This will likely not matter for you, but it may.</p>\n\n<h2>listFiles()</h2>\n\n<p>You have:</p>\n\n<blockquote>\n<pre><code>Arrays.stream(directory.listFiles()).forEach(fileConsumer);\n</code></pre>\n</blockquote>\n\n<p>I am not particularly happy with this structure. It requires a lot of work to build the listFiles Array, and the intention of the method is to filter it before consuming it, if needed.</p>\n\n<p>Perhaps your code is intended to return all files, but, I would expect it to be more sensible to supply a filter for the listFiles, or even better, to use the new stream API method call <a href=\"http://download.java.net/jdk8/docs/api/java/nio/file/Files.html#list-java.nio.file.Path-\" rel=\"nofollow\">Files.list(path)</a></p>\n\n<pre><code>Files.list(path).forEach(pathConsumer);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:02:28.450", "Id": "76885", "Score": "0", "body": "I agree with most, but must add to the watcher services. Watcher services are *not safe* in a production environment, they *will* miss files. Moreover, it is JVM/OS-dependant which is quite a big no-no. In production you will end up making your own emergency poller (possibly 1 min loop on top of the watcher service) anyway, so I decided to just get rid of the watcher altogether." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:01:46.810", "Id": "76909", "Score": "0", "body": "fair point about the watcher..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T03:39:28.663", "Id": "44318", "ParentId": "44257", "Score": "1" } } ]
{ "AcceptedAnswerId": "44318", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T13:56:05.060", "Id": "44257", "Score": "4", "Tags": [ "java" ], "Title": "Implementation of directory checking in Java 8" }
44257
<p>I have a small animation with Raphael using a large amount of code. Is there any way to reduce it?</p> <p><a href="http://jsfiddle.net/V54hR/1/" rel="nofollow">Demo</a></p> <pre><code>window.onload = function () { var elements = document.querySelectorAll('.colbr'); for (i=0; i&lt;elements.length; i++) { var loadSpinner = spinner(elements[i], 7, 12, 10, 3, "#000"); } }; function spinner(holderid, R1, R2, count, stroke_width, colour) { var sectorsCount = count || 12, // color = colour || "#000", color = "#000", width = stroke_width || 15, r1 = Math.min(R1, R2) || 35, r2 = Math.max(R1, R2) || 60, cx = r2 + width, cy = r2 + width, r = Raphael(holderid, r2 * 2 + width * 2, r2 * 2 + width * 2), sectors = [], opacity = [], beta = 2 * Math.PI / sectorsCount, pathParams = {stroke: color, "stroke-width": width, "stroke-linecap": "round"}; Raphael.getColor.reset(); for (var i = 0; i &lt; sectorsCount; i++) { var alpha = beta * i - Math.PI / 2, cos = Math.cos(alpha), sin = Math.sin(alpha); opacity[i] = 1 / sectorsCount * i; sectors[i] = r.path([["M", cx + r1 * cos, cy + r1 * sin], ["L", cx + r2 * cos, cy + r2 * sin]]).attr(pathParams); if (color == "rainbow") { sectors[i].attr("stroke", Raphael.getColor()); } } var tick; (function ticker() { opacity.unshift(opacity.pop()); for (var i = 0; i &lt; sectorsCount; i++) { sectors[i].attr("opacity", opacity[i]); } r.safari(); tick = setTimeout(ticker, 1000 / sectorsCount); })(); return function () { clearTimeout(tick); r.remove(); }; } </code></pre>
[]
[ { "body": "<p>I really like what you wrote there, though I am afraid at this point you ought to expand the code, not reduce it.</p>\n\n<ul>\n<li><code>r</code>, <code>r1</code>, <code>r2</code>, <code>cx</code>, <code>cy</code>, <code>beta</code> are all variables that need better ( more meaningful ) names</li>\n<li>You need to indent your code, just hit <kbd>TidyUp</kbd> in your fiddle and you will see</li>\n<li>This is not part of your core code, but you should not simply assign something to <code>window.onload</code>, you should use <code>addEventListener</code></li>\n<li>Your code had support for using custom colors, and then you took it out, if you really want to take that out, then you should also take out the parameter, the commented out code and the <code>if (color == \"rainbow\"){</code> statement</li>\n<li>in your <code>var</code> statement, you could simply do <code>cy = cx</code></li>\n<li>be consistent in your name, and use lowerCamelCase: <code>stroke_width</code> -> <code>strokeWidth</code></li>\n<li>You did not declare <code>i</code> with <code>var</code></li>\n<li>While straightforward, your code has no comments at all..</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:15:56.553", "Id": "76794", "Score": "1", "body": "You could use `<kbd>` instead of the tag notation, for `tidyup`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:09:59.290", "Id": "44282", "ParentId": "44261", "Score": "2" } } ]
{ "AcceptedAnswerId": "44282", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:03:30.620", "Id": "44261", "Score": "3", "Tags": [ "javascript", "reinventing-the-wheel", "raphael.js", "animation" ], "Title": "Small animation with Raphael" }
44261
<p>Please let me know what you think. Is the code well written? Am I using best practices (like when I chose <code>===</code> over <code>==</code>)? Is my script too verbose?</p> <p>Note: I'm only asking because the tutorial I'm using is a little old.</p> <pre><code>/* A login script to that checks two users and their corresponding passwords and then greets one of them */ var input = '', guess = '', montyPswrd = 'Cheese', montyUser = 'Monty', chipUser = 'Chip', chipPswrd = 'Gadget'; var isMonty = function (name) { if (name === montyUser) { document.write('&lt;h1&gt;Welcome to the site ' + montyUser + '&lt;/h1&gt;'); } else { alert('Your not monty'); } }; var isChip = function (name) { if (name === chipUser) { document.write('&lt;h1&gt;Welcome to the site ' + chipUser + '&lt;/h1&gt;'); } else { alert('Your not chip'); } }; input = prompt('Enter Username:', 'username'); switch (input) { case montyUser: guess = prompt('Enter Password','password'); break; case chipUser: guess = prompt('Enter Password','password'); case null: break; default: alert('wrong useranme!'); break; } paswrdCheck: if (guess === '') { // then the user hit ESC or cancel // no point in asking for password break paswrdCheck; } else { switch (guess) { case montyPswrd: isMonty(input); // makes sure monty is matched with right password break; case chipPswrd: isChip(input); // makes sure chip is matched with right password break; case null: break; default: alert('wrong password!'); break; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:21:41.577", "Id": "76727", "Score": "0", "body": "I would add a bit of information in your post. What are looking for in a review (We do general stuff but is there something specific) ? Having a comment in the code explaining what your code is about is not the best for a question here, could you write an explanation outside of the code block ? IMO, this would help your question a bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:47:46.517", "Id": "76923", "Score": "0", "body": "Can you provide a link to the programming challenge?" } ]
[ { "body": "<p>This is tagged <a href=\"/questions/tagged/programming-challenge\" class=\"post-tag\" title=\"show questions tagged &#39;programming-challenge&#39;\" rel=\"tag\">programming-challenge</a>, but just to be sure it's said: This obviously is <strong>not</strong> secure in any sense; the passwords are in the source.<br>\nAnyway, I'm assuming security isn't the point.</p>\n\n<p>First of all: Spellcheck. \"<em>useranme</em>\" and \"<em>Your</em> not chip/monty\".</p>\n\n<p>Secondly, my question is \"why 2 users?\" What if it's 3? Or 6,123,345? Right now you'd have to duplicate <em>everything</em> in your code to accommodate more users. Obviously that'll be extremely cumbersome.</p>\n\n<p>A much better approach is to write code to check <em>any</em> given user/password against a <em>list</em> of users (rather than named variables).</p>\n\n<p>So, first we'll need a list of users (or, in this case, a JS object):</p>\n\n<pre><code>var users = {\n 'Monty': 'Cheese',\n 'Chip': 'Gadget'\n};\n</code></pre>\n\n<p>Then, some login logic (this can be a function, or several functions, or many other things - this is just a simple implementation)</p>\n\n<pre><code>var username = prompt('Enter Username:', 'username');\nif( !username ) { // if username is blank, null or otherwise false'y\n return; // stop here if no name is given\n}\n\n// alert and stop if the username doesn't exists\nif( !users.hasOwnProperty(username) ) {\n alert('Unknown username');\n return;\n}\n\n// now we can get and check the password\nvar password = prompt('Enter Password:','password');\nif( users[username] === password ) {\n document.write('&lt;h1&gt;Welcome to the site ' + username + '&lt;/h1&gt;');\n} else {\n alert(\"You're not \" + username + \"!\");\n}\n</code></pre>\n\n<p>And done.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:08:07.493", "Id": "44276", "ParentId": "44262", "Score": "7" } }, { "body": "<p>Just wanted to add a bit to <a href=\"https://codereview.stackexchange.com/users/14370/flambino\">Flambino</a> Answer.</p>\n\n<p>His is well written but lets compared to yours as to why since you asked if yours was well written:</p>\n\n<p>1) Spell check please. You are not writing for yourself. You may write code for others that works with you on a larger scale. So please write things without spelling mistakes. Use a IDE that has autocomplete like coda or sublime.</p>\n\n<p>2) Use naming convention that are common. pwd, password are common not pwsrd, it helps legibility. </p>\n\n<p>3) Think portability: will this script work in any situation or just this one. If its just this one, that is fine also but you can broaden it up a bit more so that if you land it in another site you don't need to change it much (like the chip/monty...what if your names are fred and bob?)</p>\n\n<p>4) Extensions: like Flambino said - your limiting it to two people you should use loops and say what if N users needs to be checked on. This will make your code more compact and usable in other projects.</p>\n\n<p>Bonus: Best practice is not about using === or == but formatting code, using conventions that are standard and making sure your code is not spaghetti. Using === and == has different meanings than just best practice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:31:56.883", "Id": "44343", "ParentId": "44262", "Score": "3" } }, { "body": "<p>The code is already well reviewed,</p>\n\n<p>A thing I want to add is <code>document.write</code>, do not use <code>document.write</code>.\nInstead, put tags in your HTML code and update their content.</p>\n\n<p>Another thing is your label <code>paswrdCheck:</code>, do not use labels, they are like GOTO, GOTO is considered harmful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:13:20.490", "Id": "82979", "Score": "0", "body": "GOTO is the devil: http://stackoverflow.com/questions/1900017/is-goto-in-php-evil (please note the xkcd meme lol)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:53:04.550", "Id": "44346", "ParentId": "44262", "Score": "2" } } ]
{ "AcceptedAnswerId": "44276", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:13:15.290", "Id": "44262", "Score": "3", "Tags": [ "javascript", "beginner", "html", "programming-challenge", "authentication" ], "Title": "Login script that checks two users and their corresponding passwords" }
44262
<p>I am making this program that is going to calculate distance from randomly generated dots (with x and y coordinates) to 5 bigger ones and then its going to put each smaller dot into the group with bigger one that is nearest to it. So, i am making this with classes and every dot is made as an object. I made 2 arrays of objects. One holds the bigger dots and other one smaller dots. I also made 2 separate classes. I am not sure if this should be done with nested classes/subclasses or my concept is ok. <img src="https://i.stack.imgur.com/jwLrp.jpg" alt="It should look like this"></p> <p>My classes:</p> <pre><code>class Groups{ int x; int y; int brush; //i use this just for groups to have different color when drawing public Groups(int a, int b, int brush) { this.x = a; this.y = b; this.brush = brush; } public int getX() { return this.x; } public int getY() { return this.y; } public int getBrush() { return this.brush; } } public class Dots{ int x; int y; int group; public Dots(int x, int y) { this.x = x; this.y = y; this.group = 0; } public int getX() {return this.x;} public int getY() {return this.y;} public int getGroup() {return this.group;} public void setGroup(int x) {this.group = x;} } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:25:28.013", "Id": "76729", "Score": "1", "body": "This looks rather like Java. C# has properties, which are quite convenient for what you're doing, and has the convention that public members are PascalCase." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:29:27.080", "Id": "76730", "Score": "0", "body": "Well I am learning OOP, and when teacher was explaining classes he used slideshow with java examples but he said its all the same. Could you maybe link me site with explanation or something please. Ty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:49:54.923", "Id": "76791", "Score": "0", "body": "If possible, you should always write your code in English. That way, you can avoid situations where the code you posted somewhere won't compile, because you forgot to translate constructor from Czech. :-)" } ]
[ { "body": "<p>for OOP practice - its best to go from small to big.</p>\n\n<p>i.e.: a dot is x,y, the group is a collection of dot.</p>\n\n<p>And you are correct - regardless of syntax (ie programming language) this concept of nested/inheritance (aka subclass) is sometimes harder to pick from.</p>\n\n<p>the bottom line of OOP though is that you try and reduce redundancy.</p>\n\n<p>(similar to person -> student / teacher)</p>\n\n<p>Possible solution would be make Dot a class, make Group uses an array of Dot with Brush (because the Group is always 5 dots of x,y)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:43:00.867", "Id": "44280", "ParentId": "44263", "Score": "2" } }, { "body": "<h2>Naming</h2>\n\n<p>Class names in general should be <em>singular</em> - <code>Group</code>, <code>Dot</code>. </p>\n\n<p>If you have a constructor which sets coordinates <code>x</code> and <code>y</code>, call the parameters it gets <code>x</code> and <code>y</code>, not <code>a</code> and <code>b</code>... Also, I would refrain from single letter names, although, in this case, <code>x</code> and <code>y</code> seem ok, since they represent coordinates.</p>\n\n<h2>Scoping</h2>\n\n<p>You declared members, and implemented getters to them which is fine (although you used the wrong idiom for <code>C#</code>), but you failed to declare the members as <code>private</code>. This means that these members are <a href=\"http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx\" rel=\"nofollow\"><code>internal</code></a>, and can be accessed outside the class:</p>\n\n<blockquote>\n <p>Depending on the context in which a member declaration occurs, only\n certain declared accessibilities are permitted. If no access modifier\n is specified in a member declaration, a default accessibility is used.\n Top-level types, which are not nested in other types, can only have\n internal or public accessibility. The default accessibility for these\n types is <strong>internal</strong>.</p>\n</blockquote>\n\n<p><em><strong>Edit</em></strong> - this is, of course, wrong (thanks @Matthew) - I got confused with <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html\" rel=\"nofollow\">java</a>), the default access modifier for members in C# is private. I still stand by my recommendation to be explicit with <code>private</code>, to be more readable, and compliant with coding conventions.</p>\n\n<h2>Object Oriented</h2>\n\n<p>For some reason <code>Dot</code> has a property called <code>Group</code> which is... an <code>int</code>?? What did you intend this property to do? If you want it to hold a <code>Group</code>, its type should be <code>Group</code>:</p>\n\n<pre><code>private Group group;\n\npublic Group getGroup() {\n return group;\n}\n\npublic void setGroup(Group group) {\n this.group = group;\n}\n</code></pre>\n\n<p>I also guess the <code>brush</code> is also an instance of a class (and not an <code>int</code>), and should be declared as such:</p>\n\n<pre><code>private Brush brush;\n\n// exercise for the OP...\n</code></pre>\n\n<p>Also, what is the role of <code>x</code> and <code>y</code> for <code>Group</code>? I should have guessed that <code>Group</code> will hold some <code>Dots</code> instead...</p>\n\n<pre><code>private List&lt;Dot&gt; dots = new List&lt;Dot&gt;();\n\npublic Enumerable&lt;Dot&gt; getDots() {\n return dots;\n}\n\npublic void addDot(Dot dot) {\n dots.Add(dot);\n}\n</code></pre>\n\n<h2>What are nested classes? What are subclasses?</h2>\n\n<p>You ask whether you should use <code>subclasses</code> of <code>nested classes</code>, but your example shows neither.</p>\n\n<p>A <code>subclass</code> is a class which <a href=\"http://msdn.microsoft.com/en-us/library/ms173149.aspx\" rel=\"nofollow\"><em>inherits</em></a> from another class, and then looks and behaves just like it, <em>plus</em> some other functionality, which makes it a special case of its parent:</p>\n\n<pre><code>public class ChangeRequest : WorkItem {\n // ....\n}\n</code></pre>\n\n<p>In OO design this is expressed as an <code>is a</code> relationship - \"ChangeRequest <em>is a</em> WorkItem\"</p>\n\n<p>A nested class is a class which is declared <a href=\"http://msdn.microsoft.com/en-us/library/ms173120.aspx\" rel=\"nofollow\"><em>inside</em></a> another class, it does not inherit anything from it, though it might have special permissions to access its enclosing class:</p>\n\n<pre><code>class Container\n{\n public class Nested\n {\n Nested() { }\n }\n}\n\nContainer.Nested nest = new Container.Nested();\n</code></pre>\n\n<p>As you can see, the relation between <code>Group</code> and <code>Dot</code> doesn't seem to fall under any of these categories, and they should be written as separate classes, each having a property pointing to the other ('Dot <em>has a</em> Group' and 'Group <em>has</em> Dots').</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:11:23.970", "Id": "76817", "Score": "0", "body": "I'm not sure your comment on scoping is correct. Your quote refers to classes. Members by default are private." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:25:33.290", "Id": "76823", "Score": "0", "body": "@MatthewSteeples - apparently, it has been too long since I wrote in C# (http://msdn.microsoft.com/en-us/library/ms173121(v=vs.80).aspx), thanks for clearing this up." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:17:49.243", "Id": "44285", "ParentId": "44263", "Score": "10" } }, { "body": "<p>I am not going to repeat the points of Uri Agassi.</p>\n\n<p>Both of your classes have a considerable amount of common code and both represent some shape that has to be drawn. Therefore I suggest extracting the common code to an abstract base class named <code>Shape</code>.\nA <code>Shape</code> has a center and a brush:</p>\n\n<pre><code>public abstract class Shape\n{\n public Shape(Point center, Brush brush)\n {\n _center = center;\n _brush = brush;\n }\n\n private Point _center;\n public Point Center { get { return _center; } }\n\n protected Brush _brush;\n public Brush Brush { get { return _brush; } }\n}\n</code></pre>\n\n<p>As you can see, I am using a <code>Point</code> structure for the center. The <code>Graphics</code> object supports these points and they can be assigned with just one statement <code>Point p = dot.Center;</code>. The <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.point%28v=vs.110%29.aspx\" rel=\"nofollow\">System.Drawing.Point</a> structure has also a set of useful methods and operator overloads.</p>\n\n<p>The <code>Group</code> class inherits <code>Shape</code> and passes on the center and the brush to the base constructor:</p>\n\n<pre><code>public class Group : Shape\n{\n public Group(Point center, Brush brush)\n : base(center, brush)\n {\n }\n}\n</code></pre>\n\n<p><code>Group</code> adds no more members, as <code>Shape</code> has all it needs.</p>\n\n<p>The <code>Dot</code> class inherits <code>Shape</code> as well and adds a <code>Group</code> property. Since we probably don't know to which group a dot belongs when it is created, we initialize the brush as black.</p>\n\n<p>When we assign a group to the dot, we automatically take over the group's brush, since a dot has always the same color as the group it belongs to. </p>\n\n<pre><code>public class Dot : Shape\n{\n public Dot(Point center)\n : base(center, Brushes.Black)\n {\n }\n\n private Group _group;\n public Group Group {\n get { return _group; }\n set\n {\n _group = value;\n _brush = value == null ? Brushes.Black : value.Brush;\n }\n }\n}\n</code></pre>\n\n<p>I also used properties instead of accessor methods.</p>\n\n<hr>\n\n<p>Possible extensions: You could add a radius to the <code>Shape</code> class. This would allow you to use the same method for drawing the groups as well as the dots. Add an abstract <code>Radius</code> property to <code>Shape</code>:</p>\n\n<pre><code>public abstract int Radius { get; }\n</code></pre>\n\n<p>and implement it in <code>Group</code>:</p>\n\n<pre><code>public override int Radius { get { return 5; } }\n</code></pre>\n\n<p>and in <code>Dot</code>:</p>\n\n<pre><code>public override int Radius { get { return 2; } }\n</code></pre>\n\n<p>Now you can write the drawing method which works for both shapes like this:</p>\n\n<pre><code>private void DrawShape(Graphics g, Shape shape)\n{\n g.FillEllipse(shape.Brush,\n shape.Center.X - shape.Radius, shape.Center.Y - shape.Radius,\n 2 * shape.Radius, 2 * shape.Radius);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:54:31.713", "Id": "44294", "ParentId": "44263", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:14:11.030", "Id": "44263", "Score": "4", "Tags": [ "c#", "object-oriented", "classes" ], "Title": "Nested class or two separate classes?" }
44263
<p>I wanted to avoid running the code <code>HttpContext.Current.Server.MapPath</code> every time <code>file_path_includes</code> is called.</p> <p>Is the below an effective way of doing so?</p> <pre><code>private static string file_path_includes_; public static string file_path_includes { get { if (file_path_includes_ == null) file_path_includes_ = HttpContext.Current.Server.MapPath("/_includes") + @"\"; return file_path_includes_; } } </code></pre> <p>So the better implentation would be a static constructor as such:</p> <pre><code>public static string file_path_includes; static ParentClassName() { file_path_includes = HttpContext.Current.Server.MapPath("/_includes") + @"\"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:53:27.163", "Id": "76736", "Score": "0", "body": "This definitely looks like a valid way to lazily initialize a property, though I'm not a fan of the naming style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:15:00.423", "Id": "76746", "Score": "0", "body": "Yes, that static constructor seems correct. However, I am not sure if HttpContext.Current.Server will be available at the time, the static constructor is called. If so, the earlier lazy option is preferable or you can even do away with the static member variable." } ]
[ { "body": "<p>Is it best to initialize a static member once, in a static constructor. If that is not possible, then a lazy initialization can be done like this. (Similar code to yours, just using the null coalescing operator.)</p>\n\n<pre><code>private static string file_path_includes_;\n\npublic static string file_path_includes\n{\n get\n {\n return \n file_path_includes_ ??\n (file_path_includes_ = HttpContext.Current.Server.MapPath(\"/_includes\") + @\"\\\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:58:54.777", "Id": "76738", "Score": "1", "body": "Please **demonstrate** `static constructor` and `??` is completely novel to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:00:40.847", "Id": "76741", "Score": "0", "body": "A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.\n?? is the null coalescing operator. You can look it up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:10:43.693", "Id": "76777", "Score": "3", "body": "If lazy initialization is desired, it is worth considering the [Lazy<T>](http://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx) class. You may even want to refer to the MSDN page on [Lazy Initialization](http://msdn.microsoft.com/en-us/library/dd997286(v=vs.110).aspx)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:41:32.663", "Id": "76799", "Score": "0", "body": "@DanLyons SharePoint 2010 :(" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:56:20.800", "Id": "44268", "ParentId": "44265", "Score": "3" } }, { "body": "<p>Since the <strong>file_path_includes</strong> remains the same so it makes sense to make it <em>readonly</em>. Instead of using a static constructor you can initalize it inline as it will make loading the variable even lazier.</p>\n\n<pre><code>private static readonly string file_path_includes = HttpContext.Current.Server.MapPath(\"/_includes\") + @\"\\\";\n</code></pre>\n\n<p>As Magus mentioned variable naming convention needs some thought.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T06:56:32.037", "Id": "45468", "ParentId": "44265", "Score": "2" } } ]
{ "AcceptedAnswerId": "44268", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:46:19.397", "Id": "44265", "Score": "2", "Tags": [ "c#" ], "Title": "Is it effective to use get; set; to avoid redundant processes?" }
44265
<p>I have created a small crypto extension and I want a deep review of it, such as possible fixes (for hidden problems) and tweaks...</p> <ul> <li><p>1- Crypto.cs</p> <pre><code>public static class Crypto { public static Salt Salt = new Salt(); public static string GetMd5Hash(this string input) { using (var md5Hash = new HMACMD5(Salt.Key)) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); var sBuilder = new StringBuilder(); foreach (byte t in data) { sBuilder.Append(t.ToString("x2")); } return sBuilder.ToString(); } } public static bool VerifyMd5Hash(this string input, string hash) { string hashOfInput = GetMd5Hash(input); StringComparer comparer = StringComparer.OrdinalIgnoreCase; return 0 == comparer.Compare(hashOfInput, hash); } public static byte[] GenerateKey(int size) { using (var cryptoProvider = new RNGCryptoServiceProvider()) { var buffer = new byte[size]; cryptoProvider.GetBytes(buffer); return buffer; } } public static byte[] AESEncryptBytes(this byte[] message, byte[] sharedSecret) { using (var pdb = new Rfc2898DeriveBytes(Convert.ToBase64String(sharedSecret), Salt.Key)) { using (var ms = new MemoryStream()) { using (Aes aes = new AesManaged()) { aes.Key = pdb.GetBytes(aes.KeySize/8); aes.IV = pdb.GetBytes(aes.BlockSize/8); using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(message, 0, message.Length); } } return ms.ToArray(); } } } public static byte[] AESDecryptBytes(this byte[] message, byte[] sharedSecret) { using (var pdb = new Rfc2898DeriveBytes(Convert.ToBase64String(sharedSecret), Salt.Key)) { using (var ms = new MemoryStream()) { using (Aes aes = new AesManaged()) { aes.Key = pdb.GetBytes(aes.KeySize/8); aes.IV = pdb.GetBytes(aes.BlockSize/8); using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(message, 0, message.Length); } } return ms.ToArray(); } } } public static string AESEncryptString(this string message, byte[] sharedSecret) { return Convert.ToBase64String(AESEncryptBytes(Encoding.UTF8.GetBytes(message), sharedSecret)); } public static string AESDecryptString(this string message, byte[] sharedSecret) { return Encoding.UTF8.GetString(AESDecryptBytes(Convert.FromBase64String(message), sharedSecret)); } } </code></pre></li> <li><p>2- Salt.cs</p> <pre><code>public class Salt { public Salt() { Key = GenerateRandomKey(); } public byte[] Key { get; private set; } public byte[] GenerateRandomKey() { return Crypto.GenerateKey(256); } public Salt Set(string salt) { Key = Encoding.UTF8.GetBytes(salt); return this; } public Salt Set(byte[] salt) { Key = salt; return this; } } </code></pre></li> <li><p>3- Usage</p> <pre><code>static void Main() { #region Cryptography const String message = "ABCDEFGH"; //Message to be encrypted/decrypted String encryptedMessage; Byte[] sharedSecret = {0x01, 0x02, 0x03, 0x04, 0x05}; //Shared secret generated using RSA or DH Key Exchange (or whatever). Crypto.Salt = new Salt(); //Generates a new random dummy key *YOU HAVE TO SAVE THIS SALT FOR FUTURE DECRYPTING*. Crypto.Salt.Set(@"ek]U)/XOdwqP{u&lt;el(K=\DNPR,iM%"); //Or you can specify your own. Console.WriteLine("1- Salted MD5 Hash:-"); Console.Write("Encrypted: "); Console.WriteLine(encryptedMessage = message.GetMd5Hash()); Console.Write("Identical: "); Console.WriteLine(message.VerifyMd5Hash(encryptedMessage)); Console.WriteLine(); Console.WriteLine("2- Salted AES Encryption:-"); Console.Write("Encrypted: "); Console.WriteLine(encryptedMessage = message.AESEncryptString(sharedSecret)); Console.Write("Decrypted: "); Console.WriteLine(encryptedMessage.AESDecryptString(sharedSecret)); Console.WriteLine(); Console.WriteLine("3- Random Key Generation:-"); Console.WriteLine(BitConverter.ToString(Crypto.GenerateKey(16)).Replace("-", "")); Console.WriteLine(); #endregion Console.Read(); } </code></pre></li> <li><p>I think using Encoding here is kinda inappropriate so any ideas for that too ?</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:19:00.403", "Id": "76821", "Score": "0", "body": "I can think of a small enhancement. You could make overloads for `GetMd5Hash()` and any other method that uses hardcoded encodings such as UTF8, hex or base64. You could specify the encodings in a method parameter. This might make your extensions more versatile." } ]
[ { "body": "<p>Lots and lots of badness. Please don't write crypto before you've spend some effort studying crypto. Take a look at jbtule's answer to <a href=\"https://stackoverflow.com/a/10366194/445517\">Encrypt/Decrypt string in .NET</a> for how to symmetric encryption.</p>\n\n<ol>\n<li><p>I don't get the what the goal of <code>GetMd5Hash</code> is. It doesn't compute an MD5 hash. It uses a MAC (HMAC-MD5) so it's name is wrong.</p>\n\n<p>It's not used like a MAC (a MAC is keyed), but somewhat similar to a password hash, but the construction is no password hash. Password hashing should use PBKDF2 (<code>Rfc2898DeriveBytes</code>) not HMAC since the latter is too fast.</p></li>\n<li><p>A global static salt doesn't make much sense. Salts are mainly useful for password hashes, but they should be unique for each call.</p></li>\n<li><p>The hex encoding should be in its own method. That method doesn't have a single purpose.</p></li>\n<li><p><code>VerifyMd5Hash</code> has input dependent runtime. That's a security weakness if it were a MAC, not so much if it's a password hash.</p></li>\n<li><p><code>AESEncryptBytes</code> is using <code>Rfc2898DeriveBytes</code> on the key. Keys are supposed to be uniformly distributed and have high entropy. So this is just a waste of resources. <code>Rfc2898DeriveBytes</code> should be used on passwords, not keys.</p></li>\n<li><p>You pass the same global salt to <code>Rfc2898DeriveBytes</code> and <code>HMAC</code>. That's a bad idea for two reasons: It's fixed, so it misses the point. And it's using the same value as HMAC key and PBKDF2 salt. Keys should only ever be used in one place.</p></li>\n<li><p>You're using a fixed IV. Similarly to a salt, a new IV should be used for each encryption.</p></li>\n<li><p>You're using unauthenticated encryption, so you're vulnerable to padding oracles if you face active attackers.</p></li>\n<li><p><code>TransformFinalBlock</code> is much simpler than all that stream stuff.</p></li>\n<li><p>The per-process salt means that decryption won't work once you restart the application</p></li>\n<li><p>A 256 <em>byte</em> salt is insanely large. 128 <em>bits</em> enough.</p></li>\n<li><p>Prefer a uniformly random salt over a string. (Your <code>Salt.Set(string)</code> isn't a good idea)</p></li>\n<li><p><code>Salt</code> contains global mutable state, that's bad design.</p></li>\n<li><p><code>Salt.Key</code> is a nonsensical expression. Something is either a salt, or a key. Not both.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:29:47.517", "Id": "76825", "Score": "0", "body": "so after you destroyed me with all that notices :D are there any already implemented and verified methods somewhere that do the same as the methods i tried to write above, i want to encrypt/decrypt strings as well as byte[] using AES, also a good way to MD5 hash passwords. I mean at least some implementations that are verified and i can relay on to write my own." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:34:27.497", "Id": "76827", "Score": "0", "body": "@RuneS jbtule's answer I linked looks reasonable to me. For password hashing you shouldn't look at MD5, but rather at `Rfc2898DeriveBytes`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:36:22.260", "Id": "76828", "Score": "0", "body": "You mean that i can simply use Rfc2898DeriveBytes and return .GetBytes as a hashed password ?, also how could i Verify hash then ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:55:00.273", "Id": "76834", "Score": "0", "body": "For number 5 notice, but that is how it was implemented every where on the internet, `Rfc2898DeriveBytes` is commonly use to generate a salted Key, also the sharedSecret variable at my method is supposed to be pre generated using an asymmetric function... RSA or DH for instance. So i don't get point 5, 7, and 8 correctly as that is the conclusion of what i found all over the internet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:02:02.300", "Id": "76836", "Score": "0", "body": "Concerning 5: You need to use `Rfc2898DeriveBytes` if you want to derive a key from a user supplied password. This should only be used in places where you can't generate a high quality random secret. A random key encrypted with RSA can be used directly, a DH shared secret should be hashed with a cheap hash (e.g. `key=sha2(shared-secret)`) or a bit better style using a cheap key-derivation-function (KDF) like HKDF instead of an expensive KDF like PBKDF2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:02:57.787", "Id": "76837", "Score": "0", "body": "Concerning 7: You can derive the key from `Rfc2898DeriveBytes`, but only if you use a distinct salt for each encryption. Salt and IV serve a similar purpose, so it can be redundant to use a random value for both. But since deriving more than 20 bytes with `Rfc2898DeriveBytes` increases the cost for the legitimate user and not the attacker, I wouldn't recommend that. // The problem with searching for info about crypto is that >90% of the tutorials are written by people who don't know what they're doing. Hard to see which are good, and which aren't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:05:07.967", "Id": "76838", "Score": "0", "body": "So i will reconsider everything and re-post a new review request so be prepared :D." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:14:39.967", "Id": "76839", "Score": "0", "body": "Sorry in the example you provided, can you tell me what is the authKey ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:16:24.907", "Id": "76841", "Score": "0", "body": "@RuneS With traditional authenticated encryption, you need one key for the encryption and another independent key for the MAC. Modern authenticated encryption handles this for you and only takes one key in its API." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:22:54.283", "Id": "44297", "ParentId": "44266", "Score": "6" } }, { "body": "<p>You code is readable, your names are meaningful and it seems like you know your way around C#. Keep up the good work :)</p>\n\n<p>Some general non-crypto C# comments:</p>\n\n<ol>\n<li><p><code>using</code> blocks</p>\n\n<p>Your using <code>using</code> a lot and it's good. But try to minimize the code inside them.</p>\n\n<p>If you've got a resource <code>R</code> that needs careful handling - then acquire it, use it and then release it as soon as possible. Especially when using time and synchronization sensitive resources such as DB connections or files - close it the moment you're done with it. It's not a big deal for the classes you're using, but it's a good practice. Also, try not to use control flow directions (such as <code>return</code>) inside it. So I'd rewrite <code>GenerateKey</code>:</p>\n\n<pre><code>public static byte[] GenerateKey(int size)\n{\n var buffer = new byte[size];\n using (var cryptoProvider = new RNGCryptoServiceProvider()) {\n cryptoProvider.GetBytes(buffer);\n }\n return buffer;\n}\n</code></pre></li>\n<li><p>VerifyMd5Hash - I find this form more straight-forward:</p>\n\n<pre><code>public static bool VerifyMd5Hash(this string input, string hash)\n{\n string hashOfInput = GetMd5Hash(input);\n return StringComparer.OrdinalIgnoreCase.Compare(hashOfInput, hash) == 0;\n}\n</code></pre></li>\n<li><p>GenerateRandomKey</p>\n\n<p>This method is redundant - it just calls another (static) function. If you do want to keep it - make it static. A rule of thumb: if there's no reason not to make a method static - make it static.</p></li>\n<li><p>Salt.Set</p>\n\n<p>These kind of method should probably be of type <code>void</code>. Seeing that in order to call them you have to hold a reference to the <code>Salt</code> instance - what's the use of returning another reference?</p>\n\n<p>Maybe what you need is a factory function:</p>\n\n<pre><code>public static Salt Set(string saltString)\n{\n var salt = new Salt(); // calling the default constructor now calls GenerateRandomKey, which is not needed\n salt.Key = Encoding.UTF8.GetBytes(saltString);\n return salt;\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:38:35.813", "Id": "76831", "Score": "0", "body": "There are amazing tips, i will re look the way i am doing things that way then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:49:56.523", "Id": "76833", "Score": "0", "body": "at the last function i can tell that you can't double define `salt`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:33:44.937", "Id": "44299", "ParentId": "44266", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:53:54.173", "Id": "44266", "Score": "3", "Tags": [ "c#", "cryptography" ], "Title": "Cryptographic Extensions" }
44266
<p>Here is a code that guesses the number chosen by the user. I know that using goto is a bad practice, but it seems unavoidable here.</p> <p>that's because using <code>do while</code> doesn't work, for example:</p> <pre><code>do{ scanf("%c",&amp;variable); }while(variable == 'a' || variable = 'b' || variable = 'c'); </code></pre> <p>would accept all letters while I want it to accept only a,b and c, so I think using <code>if/else</code> and <code>goto</code> is better. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; void sleep(unsigned int mseconds) { clock_t goal = mseconds + clock(); while (goal &gt; clock()); } int main() { int guess; int tries=0; char answer; answer='y'; int min =0; int max = 101; int avg; int a =0; int i,j; puts("pick a number between 1 and 100"); puts("if the number is higher than the guess press h"); puts("if it is less than the guess press l "); puts("if my guess is correct press y"); for(i=0; (i&lt; 8); i++) { sleep(600); avg = (min + max)/2; if(!avg) break; printf("is it %d\?\n", avg ); fff: answer = getchar(); if(answer == 'y') { a++; break; } else if(answer == 'h') { min = avg; } else if(answer == 'l') { max = avg; } else goto fff; } int sol = rand() % 4 + 1; if(a) { switch(sol) { case 2: puts("You are not good enough to beat me, human"); break; case 3: puts("Stop wasting my time, your numbers are so easy to guess"); break; case 4: puts("Next"); break; //case 1: default: printf("That was easy your number is : %d ", avg); break; } } else { xa: switch(sol) { case 2: puts("Are you sure about this number"); break; case 3: puts("I don't support imaginary numbers"); break; case 4: puts("Stop playing with me"); break; //case 1: default: puts("I think there is no such number"); } } sleep(2000); getchar(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:15:47.043", "Id": "76747", "Score": "2", "body": "If `goto` is inevitable, a label named `fff:` has to be ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:29:59.220", "Id": "76783", "Score": "0", "body": "Please don't edit your question in a way that will make answers look invalid." } ]
[ { "body": "<p>Bad things happen when you use use GOTO.....</p>\n\n<p><a href=\"http://xkcd.com/292/\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XEmOx.png\" alt=\"Velociraptor\"></a></p>\n\n<p>The problem with your while loop is that you are using <code>=</code> instead of <code>==</code> .... you are assigning the values to the variable inside the loop, and it is successful, thus accepts all characters......</p>\n\n<blockquote>\n<pre><code>do{\n scanf(\"%c\",&amp;variable);\n }while(variable == 'a' || variable = 'b' || variable = 'c');\n</code></pre>\n</blockquote>\n\n<p>Fix it....</p>\n\n<pre><code> do{\n scanf(\"%c\",&amp;variable);\n }while(variable == 'a' || variable == 'b' || variable == 'c');\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Actually, the do-while loop may not be the best it needs to be bigger.... consider the following:</p>\n\n<pre><code>int ok = 1;\n\ndo\n{\n printf(\"is it %d\\?\\n\", avg );\n answer = getchar();\n if(answer == 'y')\n {\n a++;\n ok = 1;\n break;\n }\n else if(answer == 'h')\n {\n ok = 1;\n min = avg;\n }\n else if(answer == 'l')\n {\n ok = 1;\n max = avg;\n }\n else\n {\n ok = 0;\n printf(\"Illegal input %c\\n\", answer);\n }\n} while (!ok)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:29:40.777", "Id": "76759", "Score": "0", "body": "@nathan - edited answer with decent loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T23:58:07.887", "Id": "76850", "Score": "3", "body": "Get back to your Java world! ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:15:35.913", "Id": "44271", "ParentId": "44269", "Score": "11" } } ]
{ "AcceptedAnswerId": "44271", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:57:10.533", "Id": "44269", "Score": "6", "Tags": [ "c" ], "Title": "Mini mind reader" }
44269
<p>I am beyond stuck in a half way point between PHP structural and OOP, but I can never achieve proper SOLID patterns despite reading DI, IOC, and reading about the interfaces.</p> <p>Rather than to read logical examples (i.e. a storage class that takes a book class and you typecast an interface etc...). I want to know how I can take my brain off thinking I got SOLID down but I actually didn't. There is talk about trying to refactor a small chunk but then that small chunk isn't SOLID enough.</p> <p>Here are the code segments - my thought and goals are after:</p> <pre><code>class DataID { protected $_id_array; protected $_storage; public function __construct(StorageInterface $db_conn, $tables = array()) { $this-&gt;_storage = $db_conn; foreach ($tables as $table) { $sql = "SELECT `id` as `id`, `name` as `value` FROM $table ORDER BY `value` ASC"; $result = $this-&gt;_storage-&gt;read($sql); if (!empty($result)) { foreach ($result as $row) { $this-&gt;_id_array[$table][$row['value']] = $row['id']; } } } } public function getID($table, $value) { if (!empty($this-&gt;_id_array[$table])) { if (isset($this-&gt;_id_array[$value])) { return $this-&gt;_id_array[$table][$value]; } } return null; } } </code></pre> <p><strong>Goal:</strong></p> <p>I have tables that has ID vs Value data. I'm going to use this class to run through data (value) and I want to retrieve the ID of it. Best way to avoid too many DB request is to put it inside an array of [value] = ID I believe and then check corresponding index as value and fetch ID.</p> <p>Storage is an container that goes into the DB via SQL and go fetch me all the data over. This way if the method of the storage changes (Mongo, SQL, pod, MySQLi) I can change how I treat my read.</p> <p>Tables is a list of known tables in the DB that I need that Data from. That list will be from an array config file that shall be loaded in a main.</p> <p><strong>Issues:</strong></p> <ol> <li><p>I have a strong feeling that I can make this better but I don't know how - because to me a constructor initialize things and well I'm going into the DB to initialize my array but for some reason i feel that SOLID fails for me here.</p></li> <li><p>If I have tables that have too many values (i.e. let's say if a table look up is more than 50) I want to hit the DB and not store it inside an array.</p></li> </ol> <p>If that's the case, I'll have to make queries inside <code>getID</code> to use storage to go fetch it. How do I maintain SOLID while adding that extra logic?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:06:42.400", "Id": "76775", "Score": "0", "body": "There are lots of options, but this can be a bit tricky to optimize right as it depends a bit on how the class gets used. If you are storing _a lot_ of data, most of which never gets used, getting it all in the constructor (or elsewhere) can be expensive for little gain. Also, if you keep hitting the same few data points over and over, a more limited caching strategy might be appropriate. If you use a lot of this data, caching it all might make sense then. Two quick points I can make are that you can consolidate your SQL calls into one call, and there is a bug in `getID`'s second `if`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:12:24.963", "Id": "76780", "Score": "0", "body": "@cbojar - lets assume the QUERY result itself is cached by the Storage container. They array result itself for the lookup have flexible limit in the sense that I will start with storing only 50, and anything else go fetch into db (as mentioned in #2) if need to I only have about 6 tables to do so. My goal though is not about functionality as I can probably have done a large if statement with condition and just pull everything into this class without injecting the class and just inject the Storage class. I want to know is there a better solution since I dont feel this being SOLID enough." } ]
[ { "body": "<p>Reading through this code and your goals, it seems this class has two responsibilities:</p>\n\n<ul>\n<li>Provide a Key-Value store</li>\n<li>Get data from the database (potentially with caching)</li>\n</ul>\n\n<p>To make it more SOLID, you can pick one of these responsibilities for this class and put the other one somewhere else.</p>\n\n<p>If you wanted to use this class to provide a KV store, you would inject an array pre-filled with all of the data into the constructor rather than injecting DB information. You could then use a factory that takes those parameters to build the DataID object with the data. This removes a dependency on anything database related, simplifies your constructor, and reduces the class to a thin veneer over the underlying array. It cannot, however, get new information by itself, nor can it provide database caching. You could create an adapter class around the database result set and inject that instead of the array. The result set adapter could then handle getting additional information and caching, but this might end up replicating the concerns you have here, just somewhere else.</p>\n\n<p>If you wanted to use this class as an adapter over the <code>StorageInterface</code> class, you would not do all the work in the constructor and simply make calls to the underlying storage object in the <code>getID</code> method. This allows you to simplify the constructor once again, but does not in itself provide caching. You said the <code>StorageInterface</code> implementation provides query-level caching, but you can create a separate adapter wrapper around it that encapsulates your SQL and caches a whole table whenever one element is retrieved from it, and can limit those caches based on table size. Once again you can use a factory method so that your external application does not need to know about this internal adapter. This option seems to fit most closely with what you want to achieve while still having better SOLID-ness.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Here's how this achieves better adherence to the SOLID principles:</p>\n\n<ul>\n<li><strong>S</strong>: This class's responsibilities have been reduced from two to one.</li>\n<li><strong>O</strong>: I can add additional functionality by adding decorators and adapters around the various objects to add additional functionality, without having to change those objects directly.</li>\n<li><strong>L</strong>: <code>StorageInterface</code> uses Liskov Substitution, but an adapted class around the <code>StorageInterface</code> can also follow Liskov Substitution by adding decorators around it to add functionality.</li>\n<li><strong>I</strong>: The adapters are small, client-focused APIs.</li>\n<li><strong>D</strong>: <code>StorageInterface</code> is an abstraction, and your <code>StorageInterface</code> adapters/decorators can also be build as abstractions.</li>\n</ul>\n\n<p><em>Bonus Points:</em></p>\n\n<p>By removing the work out of the constructor, you are adhering more closely to the <strong>Law of Demeter</strong>. Rather than asking for something to get something through it, you are asking for what you really want.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:05:55.200", "Id": "76815", "Score": "0", "body": "thanks for a complete description of your idea. Let me digest and bring out a code to see if I've accomplished your recommendation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:07:27.047", "Id": "44281", "ParentId": "44270", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T15:58:25.663", "Id": "44270", "Score": "3", "Tags": [ "php", "object-oriented", "mysql", "dependency-injection" ], "Title": "Going from Spaghetti PHP OOP to SOLID OOP" }
44270
<blockquote> <p>If we take 47, reverse and add, <code>47 + 74 = 121</code>, which is palindromic.</p> <p>Not all numbers produce palindromes so quickly. For example,</p> <pre><code>349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337 </code></pre> <p>That is, 349 took three iterations to arrive at a palindrome.</p> <p>Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).</p> <p>Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.</p> <p>How many Lychrel numbers are there below ten-thousand?</p> </blockquote> <p>This is my solution:</p> <pre><code>from datetime import datetime candidates = [] def reverse(number): ''' Returns the reverse order of an integer, for example: reverse(123) returns the integer 321 ''' number = str(number) return int(number[::-1]) def is_lychrel(number): ''' Returns True if 'number' is a lychrel candidate, but works only with numbers from 1 to 10000 ''' iterated = number + reverse(number) for i in range(25): rev_iterated = reverse(iterated) if iterated != rev_iterated: iterated = iterated + rev_iterated else: return False return True if __name__ == '__main__': start_time = datetime.now() for number in range(10001): if is_lychrel(number): candidates.append(number) time = datetime.now() - start_time # To get the time of the calculation print('In {} were found {} lychrel candidates'.format(time, len(candidates))) print(' '.join(map(str, candidates)), 'are candidates.') suml = input('Press ENTER to close ') </code></pre> <p>On my PC (with Intel Atom 2GHz), I got it with .4 seconds. Could you offer suggestions on making it run faster?</p>
[]
[ { "body": "<h2>Hints</h2>\n\n<ol>\n<li><p>According to the example in the problem description, 349 is not a Lychrel number. As a hint for speeding things up, I'd like to point out that the example computation might also tell you something about, say, the number 1292.</p>\n\n<p>What I'm trying to say is that when you evaluate 1292, you will be performing part of the same computation that you already did with 349. The same applies to the reversed forms of each number, but there's a catch: the reversal is not symmetric when trailing zeros are present. 210 reversed is 12, but 12 reversed is 21.</p></li>\n<li><p>A single reverse-add operation typically maps multiple numbers to the same number. If you figure out how that works, you can reduce the number of cases you need to consider.</p></li>\n</ol>\n\n<h2>Changes suggested by hint 1</h2>\n\n<ul>\n<li><p>To be able to take timings with <code>timeit</code>, I first rearranged your top-level code to a function. I also changed the ranges to 50 and 10000, for reasons explained in <a href=\"https://codereview.stackexchange.com/a/45078/10916\">Gareth's answer</a>.</p>\n\n<pre><code>def e55():\n candidates = []\n for number in range(10000):\n if is_lychrel(number):\n candidates.append(number)\n return len(candidates)\n</code></pre>\n\n<p>This runs in 158 ms on my computer:</p>\n\n<pre><code>$ python3 -m timeit -s \"from e55_op import e55\" \"e55()\" \n10 loops, best of 3: 158 msec per loop \n</code></pre></li>\n<li><p>The main function could be written more concisely. This one is marginally slower at 161 ms:</p>\n\n<pre><code>def e55():\n return sum(1 for number in range(10000) if is_lychrel(number))\n</code></pre></li>\n<li><p>Now to the performance optimization. I want to avoid following the same sequence of iteration more than once. First, I'll extract the loop from <code>is_lychrel</code> into a recursive function. This in itself does not make it run faster, but neither does it slow it down.</p>\n\n<pre><code>def check(number, depth):\n ''' Returns True if 'number' is neither a palindrome\n nor becomes one in 'depth' iterations of reverse-add.'''\n rev = reverse(number)\n return number != rev and (not depth or check(number + rev, depth-1))\n\ndef is_lychrel(number):\n ''' Returns True if 'number' is a lychrel candidate,\n but works only with numbers from 1 to 10000 '''\n return check(number + reverse(number), 49) \n</code></pre></li>\n<li><p>The speedup comes from making the recursive function cache its return values in a dictionary. I'll also eliminate the <code>is_lychrel</code> function as it is called from only one place.</p></li>\n</ul>\n\n<p>The complete code is below and runs in 36.5 ms. I also timed Gareth's proposal: 54.8 ms.</p>\n\n<pre><code>def reverse(number):\n ''' Returns the reverse order of an integer,\n for example: reverse(123) returns the integer 321 '''\n number = str(number)\n return int(number[::-1])\n\ndef check(number, depth, cache):\n ''' Returns True if 'number' is neither a palindrome\n nor becomes one in 'depth' iterations of reverse-add.'''\n if number not in cache:\n rev = reverse(number)\n cache[number] = (number != rev \n and (not depth or check(number + rev, depth-1, cache)))\n return cache[number]\n\ndef e55():\n cache = {}\n return sum(1 for number in range(10000) \n if check(number + reverse(number), 49, cache))\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>I'm resetting the cache inside <code>e55</code> because <code>timeit</code> runs the function multiple times. Each iteration has to be able to start from the same state.</li>\n<li>Calling <code>check</code> with <code>depth=49</code> causes 50 iterations to be evaluated, because it starts from an already reverse-added number.</li>\n</ul>\n\n<h2>Hint 2: math</h2>\n\n<p>Let's consider all 4-digit numbers. Labeling the digits <code>abcd</code> we can represent the number as </p>\n\n<pre><code>a*1000 + b*100 + c*10 + d\n</code></pre>\n\n<p>Reverse-add results in</p>\n\n<pre><code>(a+d)*1000 + (b+c)*100 + (c+b)*10 + (d+a)\n= (a+d)*1001 + (b+c)*110\n</code></pre>\n\n<p>As <code>a</code> ranges from 1 to 9 and the other digits from 0 to 9, (a+d) can take values from 1 to 18 and (b+c) from 0 to 18. Thus there are 18*19 = 342 possible values for the expression <code>(a+d)*1001 + (b+c)*110</code>. That gives an opportunity to speed up the program if we make it loop over the 342 sums instead of the 9000 4-digit numbers. There is the extra complication that we need to calculate how many numbers map to each reverse-add result, but that is not very complicated. </p>\n\n<p>The 3-, 2- and 1-digit cases can be analyzed in the same way.</p>\n\n<h2>Hint 2: implementation</h2>\n\n<p>I'm using <code>collections.Counter</code> to determine how many ways there are to add two numbers for each sum. I've inlined the <code>reverse</code> function because it is called from only one place.</p>\n\n<p>This code runs in 4.64 ms, which is a 34X speedup from the original.</p>\n\n<pre><code>from collections import Counter\n\ndef check(number, depth, cache):\n ''' Returns True if 'number' is neither a palindrome\n nor becomes one in 'depth' iterations of reverse-add.'''\n if number not in cache:\n rev = int(str(number)[::-1])\n cache[number] = (number != rev \n and (not depth or check(number + rev, depth-1, cache)))\n return cache[number]\n\ndef cases():\n ''' Yields numbers that can result from reverse-adding numbers\n below 10000, and the frequency of each'''\n freqs00_99 = Counter(i % 10 + i // 10 for i in range(100))\n freqs10_99 = Counter(i % 10 + i // 10 for i in range(10,100))\n\n for i in range(10):\n yield 2*i, 1 # from one digit\n for i, f_outer in freqs10_99.items():\n yield 11*i, f_outer # from two digits\n for j in range(10):\n yield 101*i + 20*j, f_outer # from three digits\n for j, f_inner in freqs00_99.items():\n yield 1001*i + 110*j, f_outer*f_inner # from four digits\n\ndef e55():\n cache = {}\n return sum(freq for i, freq in cases() if check(i, 49, cache))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T01:47:03.557", "Id": "77196", "Score": "0", "body": "I just cant see to get a simple approach using this way to think, because doing that is going to require more conditions and probably is going to be the same running time or even worse. What do you think ? Do you have an idea to improve this ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:17:43.647", "Id": "44402", "ParentId": "44272", "Score": "5" } }, { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>Python has a built-in module, <a href=\"http://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a>, for measuring the execution time of small code snippets. So there is no need for all that fussing about with <code>datetime</code>.</p></li>\n<li><p><a href=\"http://projecteuler.net/problem=55\" rel=\"nofollow noreferrer\">Project Euler problem 55</a> says:</p>\n\n<blockquote>\n <p>you are given that for every number below ten thousand, it will either (i) become a palindrome in less than fifty iterations</p>\n</blockquote>\n\n<p>but your code only tries 25 iterations. It happens to be the case that 25 iterations are enough in this case, but how did you figure that out? If you had a mathematical proof that showed that 25 iterations were enough, then that would be fair enough, but I suspect that in fact you re-ran the program with different values for the count of iterations until you found that smallest one that produces the right answer. This seems like cheating to me: if you are willing to do that, why not just replace the whole program with:</p>\n\n<pre><code>print(answer)\n</code></pre>\n\n<p>which would be even faster?</p></li>\n<li><p>The problem statement asks:</p>\n\n<blockquote>\n <p>How many Lychrel numbers are there below ten-thousand?</p>\n</blockquote>\n\n<p>but you test <code>range(10001)</code> which is off by one. Luckily for you, 10,000 is not a Lychrel number, so this doesn't lead to an error.</p></li>\n<li><p>You've made <code>candidates</code> into a global variable, and run some of your code at top level. This makes it hard to test your program from the interactive interpreter. You need something like this:</p>\n\n<pre><code>def problem55(n):\n \"\"\"Return a list of Lychrel candidates below n.\"\"\"\n candidates = []\n for number in range(n):\n if is_lychrel(number):\n candidates.append(number)\n return candidates\n</code></pre>\n\n<p>and then you can test it like this:</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit(lambda:problem55(10000), number=100)\n8.279778157011606\n</code></pre></li>\n</ol>\n\n<h3>2. Speeding it up</h3>\n\n<ol>\n<li><p>The problem statement only asks <em>how many</em> Lychrel numbers there are, so there is no need to construct a list of them.</p></li>\n<li><p>Function calls in Python are moderately expensive, so you can save some time by inlining them. This leads to an implementation like this:</p>\n\n<pre><code>def problem55_1(n, m):\n \"\"\"Return the count of numbers below n that do not lead to a\n palindrome after m iterations of reversal and addition.\n\n \"\"\"\n count = 0\n for i in range(n):\n r = int(str(i)[::-1])\n for _ in range(m):\n i += r\n r = int(str(i)[::-1])\n if i == r:\n break\n else:\n count += 1\n return count\n</code></pre>\n\n<p>which is about 16% faster than yours:</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:problem55_1(10000, 50), number=100)\n6.93482669594232\n</code></pre></li>\n<li><p><a href=\"https://codereview.stackexchange.com/a/44402/11728\">Janne suggested</a> that you could speed things up by caching the numbers already found to be Lychrel and non-Lychrel, and you replied:</p>\n\n<blockquote>\n <p>doing that is going to require more conditions and probably is going to be the same running time or even worse</p>\n</blockquote>\n\n<p>which is a bit of a defeatist attitude. Certainly the code gets more complex when you add caching, but it's not <em>a priori</em> obvious whether this costs more than it saves, or saves more than it costs. The best way to find out is to knuckle down and try it:</p>\n\n<pre><code>def problem55_2(n, m):\n \"\"\"Return the count of numbers below n that do not lead to a\n palindrome after m iterations of reversal and addition.\n\n \"\"\"\n lychrel = set()\n nonlychrel = set()\n count = 0\n for i in range(n):\n j = i\n if i in lychrel:\n count += 1\n continue\n stack = [i]\n r = int(str(i)[::-1])\n for _ in range(m):\n i += r\n if i in lychrel:\n count += 1\n lychrel.update(stack)\n break\n if i in nonlychrel:\n nonlychrel.update(stack)\n break\n stack.append(i)\n r = int(str(i)[::-1])\n if i == r:\n nonlychrel.update(stack)\n break\n else:\n count += 1\n lychrel.update(stack)\n return count\n</code></pre>\n\n<p>I find that this is about twice as fast as your code:</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:problem55_2(10000, 50), number=100)\n3.935654202941805\n</code></pre></li>\n<li><p>One final tweak from me. Now that we are caching, the order in which we check numbers for the Lychrel property matters. As you iterate the reverse-and-add process, the numbers get bigger. So if we start with the larger numbers and proceed downwards, then we are more likely to get cache hits. So I tried replacing the line:</p>\n\n<pre><code> for i in range(n):\n</code></pre>\n\n<p>with</p>\n\n<pre><code> for i in range(n - 1, -1, -1):\n</code></pre>\n\n<p>and got a further small speedup:</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:problem55_3(10000, 50), number=100)\n3.800810826011002\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T02:38:35.920", "Id": "82384", "Score": "0", "body": "I interpret \"below ten thousand\" as < 10000, not ≤ 10000. (But that's splitting hairs about something that makes no difference in this case.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T18:25:49.620", "Id": "82436", "Score": "0", "body": "I interpret that phrase in the same way as you do. Did I make a mistake?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T11:26:38.103", "Id": "45078", "ParentId": "44272", "Score": "6" } } ]
{ "AcceptedAnswerId": "44402", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:32:13.253", "Id": "44272", "Score": "7", "Tags": [ "python", "performance", "programming-challenge", "palindrome" ], "Title": "Lychrel calculator (Project Euler 55)" }
44272
<p>This code was already reviewed, but the reviewer missed many points of my code. Most of the following question is from the previous review.</p> <p>I have written a system for handling the dispatch of events between objects. I need this functionality for a larger project I am working on. <strong>Objects should be able to dispatch events without knowing anything about the objects that will receive them, or vice versa</strong>. (bolded because this is important, and the last person missed it.)</p> <p>If this indicates that there is something seriously wrong with my larger design, please tell me.</p> <p>I currently have two classes: EventHandler and EventListener. (There's a third class in the package, ResolvableEventObject, but it just adds a resolve() method to the basic EventObject that is called once the event is finished with dispatch.)</p> <p>The code is as follows. (imports were skipped) </p> <p>(If you need more explanation, please ask.)</p> <h2>EventManager.class</h2> <pre><code>public final class EventManager //The manager holds all the EventListeners, and dispatches events among them. { private static EventManager INSTANCE = new EventManager(); //Singleton pattern, as multiple managers is nonsensical. private HashMap&lt;Class&lt;? extends EventObject&gt;, LinkedList&lt;EventListener&gt;&gt; listeners; private int lockCount = 0; private LinkedList&lt;ListenerStub&gt; delayedListeners; public static EventManager getInstance() { return INSTANCE; } private EventManager() { listeners = new HashMap(); delayedListeners = new LinkedList(); } /*Adds a listener if there's nothing using the set of listeners, or delays it * until the usage is finished if something is. * Package protected because nothing other than EventListener's registerListener() * should call it. Eqivalent statements apply for removeListener() below. */ void addListener(Class&lt;? extends EventObject&gt; clazz, EventListener listener) { if (lockCount == 0) { realAddListener(clazz, listener); } else { delayListenerOperation(clazz, listener, true); } } private void realAddListener(Class&lt;? extends EventObject&gt; clazz, EventListener listener) { if (!listeners.containsKey(clazz)) { listeners.put(clazz, new LinkedList&lt;EventListener&gt;()); } LinkedList&lt;EventListener&gt; list = listeners.get(clazz); list.add(listener); System.out.println("added"); } void removeListener(Class&lt;? extends EventObject&gt; clazz, EventListener listener) { if (lockCount == 0) { realRemoveListener(clazz, listener); } else { delayListenerOperation(clazz, listener, false); } } private void realRemoveListener(Class&lt;? extends EventObject&gt; clazz, EventListener listener) { LinkedList&lt;EventListener&gt; list = listeners.get(clazz); list.remove(listener); System.out.println("removed"); } private void delayListenerOperation(Class&lt;? extends EventObject&gt; clazz, EventListener listener, boolean add) { delayedListeners.add(new ListenerStub(clazz, listener, add)); System.out.println("delayed"); } public void dispatchEvent(EventObject event) { ListenerLock l = new ListenerLock(); //This odd construction seems to force garbage collection. //Security measure to clean up old objects before dispatching events. System.gc(); try { Thread.sleep(1); } catch (Exception ex) { } //end of odd construction dispatchEvent(event, event.getClass()); //Hiding recursive call from user l.release(); if (event instanceof ResolvableEventObject) { ((ResolvableEventObject) event).resolve(); //ResolvableEventObject is my class, it's just an EventObject with a //resolve() method. } } private void dispatchEvent(EventObject event, Class clazz) { LinkedList&lt;EventListener&gt; list = listeners.get(clazz); if (list != null) { for (EventListener listener : list) { listener.handleEvent(event); } } if (EventObject.class.isAssignableFrom(clazz.getSuperclass())) { dispatchEvent(event, clazz.getSuperclass()); } } private void resolveDelayedListeners() { for (ListenerStub listenerStub : delayedListeners) { if (listenerStub.isAdd()) { realAddListener(listenerStub.getListenerClass(), listenerStub.getListener()); } else { realRemoveListener(listenerStub.getListenerClass(), listenerStub.getListener()); } } } private class ListenerStub /* * This class is used to hold the data of the listeners to be removed * until the lock on the listener set is released. */ { private Class&lt;? extends EventObject&gt; clazz; private EventListener listener; private boolean add; ListenerStub(Class&lt;? extends EventObject&gt; clazz, EventListener listener, boolean add) { this.clazz = clazz; this.listener = listener; this.add = add; } public Class&lt;? extends EventObject&gt; getListenerClass() { return clazz; } public EventListener getListener() { return listener; } public boolean isAdd() { return add; } } public class ListenerLock /* * This is a basic lock that is used to prevent modifications to the list of * listeners. It releases when told, or when finalized if forgotten. */ { boolean released = false; ListenerLock() { lockCount++; } public void release() { if (!released) { lockCount = Math.min(0, lockCount - 1); released = true; if (lockCount == 0) { resolveDelayedListeners(); } } } protected void finalize() throws Throwable { super.finalize(); release(); } } } </code></pre> <h2>EventListener.class</h2> <pre><code>public final class EventListener { /* * An EventListener pairs a class (EventObject or a subtype) with a method on an object. * It can hold either a strong or a weak reference to the object, and defaults weak. * It uses reflection to call the specified method. */ Object source = null; Method handler = null; Class clazz; WeakReference&lt;Object&gt; sourceReference; public EventListener(Class&lt;? extends EventObject&gt; clazz, Object source, String handlingMethod, boolean weakReference) { if (weakReference) { this.source = null; sourceReference = new WeakReference(source); } else { this.source = source; sourceReference = null; } /* * This structure sets up the call to the specified method on the specified * object. If no method is found for the specified class to listen to, * superclasses are tried until either a valid method is found or EventObject * is reached with no match. */ Class C = clazz; while (EventObject.class.isAssignableFrom(C) &amp;&amp; handler == null) { try { this.handler = source.getClass().getMethod(handlingMethod, C); } catch (NoSuchMethodException e) { C = C.getSuperclass(); } } if (handler == null) { throw new IllegalArgumentException("No method with the signature: " + handlingMethod + "(" + clazz.getSimpleName() + ") found."); } this.clazz = clazz; } public EventListener(Class&lt;? extends EventObject&gt; clazz, Object source, String handlingMethod) { this(clazz, source, handlingMethod, true); } void handleEvent(EventObject event) //package protected because it should only be //called by EventManager's dispatchEvent(). { if (source == null) { //source == null iff using weak references. if (sourceReference.get() == null) { //referenced object garbage collected, delete listener. deregisterListener(); return; } try { handler.invoke(sourceReference.get(), event); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } } else { try { handler.invoke(source, event); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } } } public void registerListener() //registers a listener with the manager. Reference to listener //is required to deregister later. { EventManager.getInstance().addListener(clazz, this); } public void deregisterListener() { EventManager.getInstance().removeListener(clazz, this); } } </code></pre> <p>Could you please tell me whether this is proper practice, or if there is a better way to do it? I am knowledgeable about Java, but this is the first time I have done anything like this. </p> <p>Also, is there anything you notice that is hurting performance? I haven't had a chance to test it with regards to speed, but my functionality tests completed almost instantly after compile.</p> <p>If you were wondering, this is intended to be used as part of a library for a larger project, as well as other subsequent projects with complex message passing between unspecified objects that don't reference each other.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:27:06.987", "Id": "76781", "Score": "0", "body": "One performance issue I see is that your `EventManager` uses a single `lockCount` variable, meaning that _every_ list is locked if I'm adding or removing. This would serialize writes to _different lists_ that would not have a race condition, which is unnecessary. A lock per list would be better here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:37:29.140", "Id": "76785", "Score": "0", "body": "@cbojar Good catch. How would you suggest I implement that?" } ]
[ { "body": "<ol>\n<li><p>If I'm right you're planning to use these classes from multiple threads. If that's the case you should do some synchronization or use thread-safe classes to make it thread-safe.</p></li>\n<li><p>There are <a href=\"https://stackoverflow.com/q/10218895/843804\">existing event handling libraries</a>. Don't reinvent the wheel unless you have a really good reason for that.</p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><blockquote>\n<pre><code>private HashMap&lt;Class&lt;? extends EventObject&gt;, LinkedList&lt;EventListener&gt;&gt; listeners;\n</code></pre>\n</blockquote>\n\n<p>could be </p>\n\n<pre><code>private Map&lt;Class&lt;? extends EventObject&gt;, List&lt;EventListener&gt;&gt; listeners;\n</code></pre>\n\n<p>See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<p>Anyway, a <a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained\" rel=\"nofollow noreferrer\">Mulitmap</a> would be a better choice here. It was designed exactly to supersede this structure.</p></li>\n<li><p>The same is true for the <code>delayedListeners</code>:</p>\n\n<blockquote>\n<pre><code>private LinkedList&lt;ListenerStub&gt; delayedListeners;\n</code></pre>\n</blockquote>\n\n<p>The assigment also could be in the same line as the field declaration.</p>\n\n<pre><code>private final Map&lt;Class&lt;? extends EventObject&gt;, List&lt;EventListener&gt;&gt; listeners = new HashMap&lt;&gt;();\nprivate final List&lt;ListenerStub&gt; delayedListeners = new LinkedList&lt;&gt;(); \n</code></pre></li>\n<li><blockquote>\n<pre><code> // Singleton pattern, as multiple managers is nonsensical.\n</code></pre>\n</blockquote>\n\n<p>Singleton is rather an antipattern nowadays. You might need multiple instances in unit and integration tests and later you might have separated modules which will require separate event managers. Consider making it non-singleton. Singletons ussually make unit-testing really hard.</p></li>\n<li><p>Calling <code>System.gc()</code> is a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">code smell</a>. Are you sure that you need that? See also: <a href=\"https://stackoverflow.com/a/2414120/843804\">Why is it a bad practice to call System.gc?</a></p></li>\n<li><blockquote>\n<pre><code>/*\n * This is a basic lock that is used to prevent modifications to the list of listeners. It\n * releases when told, or when finalized if forgotten.\n */\n</code></pre>\n</blockquote>\n\n<p>I'd put a warning log to the <code>finalize</code> to get a notification if the client is broken.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:33:04.413", "Id": "77014", "Score": "2", "body": "After looking into the provided link, it seems like \"EventBus\" from \"guava-libraries\" does the same thing my code does, but is better developed and tested. (It's an existing library) I'll see if I can simply substitute it in place of this ad-hoc solution. If I can't, the other comments were helpful. Also, thank you for not suggesting I use Lock in place of ListenerLock, the behavior of Lock (ie. blocking) is not wanted here. Thanks for the assistance!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T22:28:40.157", "Id": "77067", "Score": "0", "body": "@user3033745: I'm glad that it helped. Guava is a high-quality lib, strongly recommended. Thanks for the feedback!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:51:33.620", "Id": "44345", "ParentId": "44273", "Score": "3" } } ]
{ "AcceptedAnswerId": "44345", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T16:49:38.113", "Id": "44273", "Score": "4", "Tags": [ "java", "event-handling" ], "Title": "Event Handling system in Java - follow-up" }
44273
<p>I've been programming with Python 2.7 for about six months now and if possible, I'd like some critique to see what I might have done better or what I might be doing wrong.</p> <p>My objective was to make a script scraper that finds variables and functions, outputting them to a text file along with their line number. It also organizes the output based on type and string length for readability. It works as intended, but I'd like to know if/how I could have wrote it better, cleaner.</p> <pre><code>import re def change_line(): parse_next['line_count'] += 1 def make_readable(list): fix_order = {} for item in list: fix_order[len(item)] = item return sort_this(fix_order) def sort_this(dict): fixed = dict.keys() fixed.sort() newly_ordered = [] for number in fixed: newly_ordered.append(dict[number]) return newly_ordered def parse_match(match): if '\n' in match: parse_next[match]() elif 'def' in match: parse_next[match] = parse_next['line_count'] funcs.append(match) elif match: parse_next[match] = parse_next['line_count'] varis.append(match) else: print 'error' funcs = [] varis = [] txt_file = open('c:\\code\\test.txt', 'r') output = open('c:\\code\\output.txt', 'w+') found = re.findall(r'\n|def\s.+|.+ = .+', txt_file.read()) parse_next = { '\n': change_line, 'line_count': 1, } for match in found: parse_match(match) funcs = make_readable(funcs) varis = make_readable(varis) output.write('\t:Functions:\n\n') for item in funcs: s_fix = item.replace('def ', '',) to_write = [s_fix, ' Line:', str(parse_next.get(item)), '\n'] output.writelines(to_write) output.write('\n'*2) output.write('\t:Variables:\n\n') for item in varis: to_write = [item.strip(),' Line:', str(parse_next.get(item)), '\n'] output.writelines(to_write) output.close() txt_file.close() </code></pre> <p>To run it, you'll need to edit this filepath:</p> <pre><code>txt_file = open('c:\code\test.txt', 'r') </code></pre> <p>with code from a script of your choice.</p> <p>Be harsh if necessary, I'd really like to get better.</p>
[]
[ { "body": "<p>A couple of suggestions:</p>\n\n<hr>\n\n<p><code>make_readable</code> has a very serious problem - what if two inputs have the same length? A dictionary can only have one value per key; I suggest making it a dictionary of lists of items (or a <code>collections.defaultdict(list)</code>) instead. Also, don't call the argument <code>list</code> - that's a built-in.</p>\n\n<hr>\n\n<p><code>sort_this</code> could be shortened (and the argument shouldn't be called <code>dict</code>):</p>\n\n<pre><code>def sort_this(d):\n return [d[key] for key in sorted(d)]\n</code></pre>\n\n<p>Iterating over a dictionary (e.g. in <code>sorted</code>) automatically iterates over the keys. Also, this will work without modification in Python 3.x (where <code>fixed.sort()</code> will fail).</p>\n\n<hr>\n\n<p>The <code>global</code> variables (e.g. <code>funcs</code>) should either be <em>explicitly global</em> (i.e. put <code>global funcs</code> at the start of functions that use them) or, much better, passed as arguments to the functions: </p>\n\n<pre><code>def parse_match(match, funcs, varis, parse_next):\n</code></pre>\n\n<hr>\n\n<p>One bug you may want to look into - if a variable is defined over multiple lines:</p>\n\n<pre><code>my_list = [1, 2, 3,\n 4, 5, 6]\n</code></pre>\n\n<p>Your code only gets the start of the definition.</p>\n\n<hr>\n\n<p>Finally, it would be neat to not have to change the hard-coded strings to change the files to analyse and output to! Look into taking command line arguments (<code>sys.argv</code>) or using e.g. <code>tkinter</code> to put a GUI in. At the very least, have a higher-level function <code>analyse(input_file, output_file)</code> then call it at the end of your script:</p>\n\n<pre><code>if __name__ == \"__main__\":\n analyse(\"C:\\\\code\\\\test.txt\", \"C:\\\\code\\\\output.txt\")\n</code></pre>\n\n<p>It is not best practice to put the variables you have to change somewhere in the middle of the file - top or bottom is easier to find!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:13:41.027", "Id": "76818", "Score": "0", "body": "Thanks man! I'll post an updated version of the script once i fix everything. Might be a day or so before i get back and post it though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:22:37.753", "Id": "77027", "Score": "0", "body": "Posted an edited version, but I found a major bug. I'll reupdate when it's fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:56:02.377", "Id": "77037", "Score": "0", "body": "Sadly, I don't think I'm going to be able to fix it this time. I fed it a few different inputs and it gave me a different error every time. It would be so much easier to just remake the whole thing with the bug in mind." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:41:15.660", "Id": "44279", "ParentId": "44275", "Score": "2" } } ]
{ "AcceptedAnswerId": "44279", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:06:24.410", "Id": "44275", "Score": "1", "Tags": [ "python", "optimization", "python-2.x" ], "Title": "Script scraper for outputting variables and functions to a text file" }
44275
<p>This is about my first backbone.js application. It is a small directory that fetches data and presents it in a search-like UI. </p> <p><a href="http://nativomorphosis.cl/prui/index.html">Here</a> is a working (minified) example.</p> <p>Here is the file that handles everything</p> <pre><code>window.Directory = function() { "use strict"; // Create the view and listen to main events this.view = new this.AppView().on({ // Main functions that take care of searching and returning results for multiple items. 'Dir.parseForm': function() { this.parseForm() }, 'Dir.parsedTheForm': function(selectedThings) { this.prepareResultsCollection(selectedThings) }, 'Dir.resultsCollectionPrepared': function() { this.collection.fetch() }, 'Dir.fetchingThings': function() {}, // Just here in case we need it 'Dir.doneFetching': function() { this.createArrayOfElements() }, 'Dir.elementsReadyToInsert': function(elementsToInsert) { this.insertIntoTheDOM(elementsToInsert) }, // We're all done. // Functions for handling when a single element wants to be viewed. 'Dir.clickedElement': function(clickEvent) { this.getClickedId(clickEvent) }, 'Dir.gotClickedElementId': function(clickedId) { this.prepareClickedModel(clickedId) }, 'Dir.clickedModelPrepared': function() { this.model.fetch() }, 'Dir.fetchingModel': function() {}, 'Dir.doneFetchingModel': function() { this.createModelElement(); }, 'Dir.modelReadyToInsert': function(modelElement) { this.insertModelElementInDOM(modelElement) }, // A little spinner 'Dir.spinnerOn': function(spinnerMessage) { switch(spinnerMessage) { case 'wait': var spinnerHTML = '&lt;b class="glyphicon glyphicon-time"&gt;&lt;/b&gt;'; break; case 'load': var spinnerHTML = '&lt;b class="glyphicon glyphicon-refresh"&gt;&lt;/b&gt;'; break; default: var spinnerHTML = spinnerMessage; } jQuery('#ai-info').html(spinnerHTML); }, 'Dir.spinnerOff': function() { jQuery('#ai-info').empty() } }); } Directory.prototype.AppView = Backbone.View.extend({ el: '[data-main]', results_area: '[data-results]', events: { // Switches that trigger the search action 'change [name="type"]': function() { this.trigger('Dir.parseForm') }, 'keyup [name="keyword"]': function() { this.trigger('Dir.parseForm') }, 'change [name="specialization"]': function() { this.trigger('Dir.parseForm') }, 'change [name="sector"]': function() { this.trigger('Dir.parseForm') }, 'change [name="size"]': function() { this.trigger('Dir.parseForm') }, 'change [name="startswith"]': function() { this.trigger('Dir.parseForm') }, // On click a single element 'click [data-id]': function(clickedElement) { this.trigger('Dir.clickedElement', clickedElement) } }, // We set a timeout here so that this trigger is done asynchronously, and the event bindings can be ready. initialize: function() { setTimeout(function(){ this.trigger('Dir.parseForm')}.bind(this) )}, /*** * Returns an array of the selected form elements using * Backbone.Syphon.serialize(). Additionally, sets a timer * function to avoid submitting when the user is typing. */ parseForm: function() { // Set our spinner to 'waiting' this.trigger('Dir.spinnerOn', 'wait'); // To avoid multiple requests when typing we set a timeout that clears itself under 500ms clearTimeout(this.safeType); this.safeType = setTimeout(function () { // Create object of items based on the selected items from the filters form. var selectedThings = Backbone.Syphon.serialize(this); // Let the event handler know we're ready. this.trigger('Dir.parsedTheForm', selectedThings); }.bind(this), 500); }, /*** * Creates a collection object to store the objects that * will be shown. It is called when 'Dir.parsedTheForm' is * triggered. * @param selectedThings */ prepareResultsCollection: function(selectedThings) { // We set the URL our Backbone.Collection is going to use. switch (selectedThings.type) { case "product": var url = '/api/category';break; case "service": var url = '/api/category';break; default: var url = '/api/company'; } // Create a little Backbone collection and bind a few events this.collection = new Backbone.Collection(); this.collection.url = url; this.collection.type = selectedThings.type; // For templating this.collection.comparator = 'name'; this.collection.on({ 'request': function() { this.trigger('Dir.spinnerOn', 'load') this.trigger('Dir.fetchingThings') }, 'sync': function() { this.trigger('Dir.doneFetching'); this.trigger('Dir.spinnerOff'); } }, this); // Note that we're binding the view as the 'this' variable. // Let the event handler know we're done. this.trigger('Dir.resultsCollectionPrepared'); }, /*** * Creates an array of elements ready to be inserted in the DOM * from the results provided in the this.collection.models array. * Creates the array 'elements', fires up Dir.elementsReadyToInsert * and is fired up with Dir.doneFetching. */ createArrayOfElements: function() { // First let's determine what template we're using switch (this.collection.type) { case "product": case "service": var templateTagId = 'template-category';break; default: var templateTagId = 'template-company'; } // Go through the models contained in the collection and generate an HTML for each one var elementsToInsert = []; this.collection.models.forEach(function(littleModel) { // Find the template in the HTML that has the id #template-{collection type} var templateTag = document.getElementById(templateTagId), template = _.template( templateTag.innerHTML.trim() ), html = template( littleModel.toJSON() ); elementsToInsert.push(html); }.bind(this)); // And let the event handler know we're ready. this.trigger('Dir.elementsReadyToInsert', elementsToInsert); }, /*** * This function takes the array of elements built by #createArrayOfElements * and inserts them into the DOM. Fired by 'Dir.elementsReadyToInsert'. * @param elementsToInsert */ insertIntoTheDOM: function(elementsToInsert) { // Create a wrapper element to collect each one, and insert the wrapper in the results area. switch (this.collection.type) { case "product": var wrapperHTML = '&lt;div class="categories"&gt;&lt;/div&gt;';break; case "service": var wrapperHTML = '&lt;div class="categories"&gt;&lt;/div&gt;';break; default: var wrapperHTML = '&lt;table class="table table-hover table-condensed companies"&gt;&lt;/table&gt;'; } var $wrapper = jQuery(wrapperHTML); jQuery(this.results_area).html($wrapper); // Insert each element into the wrapper. elementsToInsert.forEach(function(elementHTML) { $wrapper.append(elementHTML) }.bind(this)) }, /*** * This function just finds the clicked element id when there's a click event * on an element with a [data-id] attribute. It's fired by the Dir.clickedElement * event and sends Dir.gotClickedElementId when it's done. * @param clickEvent */ getClickedId: function(clickEvent) { // This comes from a click event // Find the [data-id] attribute using jQuery var clickedElement = clickEvent.currentTarget, clickedId = jQuery(clickedElement).attr('data-id'); // This is a little patch that does no harm, to avoid looping when seeing companies inside categories this.collection.type = jQuery(clickedElement).attr('data-type') || this.collection.type; // Let the event handler know we have it. this.trigger('Dir.gotClickedElementId', clickedId); }, /*** * This function takes the clicked element's id and forms a little model from it, * with the url set to properly fetch its data. When it's done, it fires * Dir.clickedModelPrepared. The function itself is fired by Dir.prepareClickedModel. * @param clickedId */ prepareClickedModel: function(clickedId) { // Let's set the URL that the model is going to use. Using switch instead of getting it from this.collection.url to allow configuration afterwards. switch (this.collection.type) { case "product": var url = '/api/category';break; case "service": var url = '/api/category';break; default: var url = '/api/company'; } // Create a little model associated with the given Id through the url parameter, and register a few events. this.model = new Backbone.Model(); this.model.url = url + '/' + clickedId; this.model.on({ 'request': function() { this.trigger('Dir.spinnerOn', 'load'); this.trigger('Dir.fetchingModel') }, 'sync': function() { this.trigger('Dir.doneFetchingModel'); this.trigger('Dir.spinnerOff'); } }, this); // Let the event handler know we're done. this.trigger('Dir.clickedModelPrepared'); }, /*** * Creates the HTML element for the clicked model, and dispatches it ready * to be inserted in the DOM. Fires up Dir.modelReadyToInsert, and * it's fired up by Dir.doneFetchingModel. */ createModelElement: function() { // Based on the collection we came from, we can determine the template switch (this.collection.type) { case "product": case "service": var templateTagId = 'template-category-single';break; default: var templateTagId = 'template-company-single'; } // Find the template in the HTML that has corresponding id. var templateTag = document.getElementById(templateTagId), template = _.template( templateTag.innerHTML.trim() ), modelElement = template( this.model.toJSON() ); // Let the event handler know we're done. this.trigger('Dir.modelReadyToInsert', modelElement); }, /*** * Inserts the clicked model element into the DOM. Fired up by Dir.modelReadyToInsert. * @param modelElement */ insertModelElementInDOM: function(modelElement) { jQuery(this.results_area).html(modelElement); } }); var dir = new Directory(); </code></pre> <p>My main concerns are: </p> <ul> <li><p>I have not used any module loading library.</p></li> <li><p>I am more or less <em>freestyling</em> in respect to code structure. </p></li> <li><p>I'm using jQuery just for a few functions like <code>$.attr()</code> and <code>$.html()</code>.</p></li> <li><p>I'm <em>kind of</em> using backbone.js in a way that (I think) it's not really intended for.</p></li> <li><p>Things like</p> <pre><code>this.view = new this.AppView().on({ </code></pre> <p></p> <pre><code>case "service": var templateTagId = 'template-category-single';break; </code></pre></li> <li><p>Initializing models and collections on the go.</p></li> </ul> <p>Things I feel proud of but are probably bad news:</p> <ul> <li><p>Using events for everything instead of chaining functions.</p></li> <li><p>So many comments</p></li> </ul> <p>Could someone offer a code review on patterns, structure, style, and general quality of the solution?</p>
[]
[ { "body": "<p>Interesting code. As you might have guessed, there's a lot wrong with it.</p>\n\n<ul>\n<li>Events instead of chaining. Makes it harder to follow the code, makes it harder on IDE's that know how to jump to a function, no added benefits. You have <code>this</code> basically as a holder of global variables instead of calling functions with parameters</li>\n<li><p>Comments -> I like it, but be careful with things like this:</p>\n\n<pre><code>/***\n * Inserts the clicked model element into the DOM. Fired up by Dir.modelReadyToInsert.\n * @param modelElement\n */\ninsertModelElementInDOM: function(modelElement) {\n jQuery(this.results_area).html(modelElement);\n}\n</code></pre>\n\n<p>I understand you call this function with the clicked model element, but really you want to document what the function does, not with what it is called.</p></li>\n<li><code>this.view = new this.AppView().on({</code> -> Oh my goodness, because you are abusing events, that parts looks terrible with the lack of newlines, I am not sure you can salvage it without keeping only the <em>real</em> events.</li>\n<li>Regardless, <code>'Dir.parseForm': function() { this.parseForm() },</code> could be <code>'Dir.parseForm': this.parseForm,</code></li>\n<li><code>Backbone.View.extend({</code>, the <code>events</code> part, has a ton of copy pasted <code>function() { this.trigger('Dir.parseForm') },</code>, you should do something about that</li>\n<li>You are not using a module loading library -> I think that's ok</li>\n<li>Except for abuse of chaining, I think your code structure is fine</li>\n<li>jQuery -> better than writing and maintaining <code>attr</code> &amp; <code>html</code> yourself I would think</li>\n<li>Creating Models on the fly -> yeah, it looks wrong to me, you are supposed to declare your model once and then get instances.</li>\n</ul>\n\n<p>All in all, I am sorry to say that most of this code should be rewritten to stop abusing events/listeners.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:08:04.337", "Id": "76963", "Score": "0", "body": "Thank you for the comments! Actually, this is version 2 of the code. Version one was a mess. I will apply your recommendations and probably make an update of the results. Thanks again !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T02:50:59.057", "Id": "77081", "Score": "0", "body": "@AlainJacometForte Just a note: If you edit your code and want a new review of it, please post it as a completely new question to avoid confusion." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:27:03.767", "Id": "44342", "ParentId": "44283", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:11:55.933", "Id": "44283", "Score": "10", "Tags": [ "javascript", "backbone.js" ], "Title": "Directory Searcher" }
44283
<p>Is there a better way to pass variables into a class?</p> <pre><code>public class Truck { private int _wheels; private string _color; private bool _loaded; public int wheels { get { return _wheels; } } public string color { get { return _color; } } public bool loaded { get { return _loaded; } } public Truck(int wheels, string color, bool loaded) { this._wheels = wheels; this._color = color; this._loaded = loaded; } } Truck dumpTruck = new Truck(6, "yellow", false); </code></pre> <p>I have learned C# by error code and there has got to be a better way to do this. I am stuck on Framework 2.0.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:49:38.537", "Id": "76800", "Score": "2", "body": "This is a very effective way to make an immutable `Truck` class. What is it that you have a problem with?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:51:06.733", "Id": "76801", "Score": "0", "body": "@Magus When building classes I seem to repeat this method over and over again. Seems like there should be a shortcut when passing variables identical to the object's properties." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:12:20.103", "Id": "76808", "Score": "0", "body": "So, are you saying that you have both `Truck` and `Car` and want to be able to assign them both in a loop, or that you want to be able to make the call `Truck dumpTruck = (6, \"yellow\", false)`? In the second case, you're out of luck, but you can at least reduce it to `var dumpTruck = new Truck(6, \"yellow\", false)`. The main reason for this is that you could also have a `class UltraTruck : Truck { }` and use it instead. The compiler can't tell the difference without a name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:37:19.713", "Id": "76829", "Score": "0", "body": "C# version 6.0 may have Primary Constructors (inspired by F#) while will make such class initialization more idiomatic and easy to code.\nhttp://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated" } ]
[ { "body": "<p>A few observations.</p>\n\n<ol>\n<li><p>Properties should be PascalCase.</p>\n\n<pre><code>public class Truck\n{\n // ...\n public int Wheels { get {return _wheels; } }\n\n // ...\n}\n</code></pre></li>\n<li><p>The <code>this</code> keyword is not needed here. by having the '_' in front of your class variables, you are differentiating them from the local variables.</p></li>\n</ol>\n\n<p>Now, to answer your question, you could use <a href=\"http://msdn.microsoft.com/en-us/library/bb384054.aspx\">Automatic Properties</a>, which would change your class to be something like:</p>\n\n<pre><code>public class Truck\n{\n public int Wheels { get; private set; }\n public string Color { get; private set; }\n public bool Loaded { get; private set; }\n\n public Truck(int wheels, string color, bool loaded)\n {\n Wheels = wheels;\n Color = color;\n Loaded = loaded;\n }\n}\n</code></pre>\n\n<p>As for your question of having a better way: the only other way to set them is to make the property's <code>set</code> method public and set them through that. Personally, I like passing them through the constructor better, it makes it easier to make the the class immutable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:08:25.310", "Id": "76806", "Score": "2", "body": "ThisIsPascalCase and thisIsCamelCase." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:11:19.430", "Id": "76807", "Score": "0", "body": "Thanks @Magus I get the names confused regularly :) Edit made" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:49:54.283", "Id": "76832", "Score": "0", "body": "`public int Wheels { get; private set; }` throws `...Truck.Wheels.get' must declare a body because it is not marked abstract or extern`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:15:03.777", "Id": "76840", "Score": "0", "body": "What are you trying to do @iambriansreed?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:53:32.800", "Id": "44288", "ParentId": "44286", "Score": "10" } }, { "body": "<ol>\n<li><p>Depending on your implementation and needs of this program you may want to look into the <code>Color</code> <code>struct</code> it represents colors and there is a <code>Colors</code> <code>class</code> which has many predefined colors created already. This would be usedful if your program is a visual program and you have to render the specified color on screen. Otherwise a <code>string</code> is just fine.</p></li>\n<li><p>To elaborate more on <a href=\"https://codereview.stackexchange.com/users/15324/jeff-vanzella\">Jeff Vanzella</a>'s <a href=\"https://codereview.stackexchange.com/a/44288/38054\">answer</a> when he said </p>\n\n<blockquote>\n <p>As for your question of having a better way: the only other way to set them is to make the property's set method public and set them through that.</p>\n</blockquote>\n\n<p>This is of-course changing your program in a way that you really may not want, but it is good to know about.</p>\n\n<pre><code>public class Truck\n{\n public int Wheels { get; set; }\n public string Color { get; set; }\n public bool Loaded { get; set; }\n}\n</code></pre>\n\n<p>...Somewhere else, when declaring Truck</p>\n\n<pre><code>var truck = new Truck() { Wheels = 4, Color = \"Blue\", Loaded = true };\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var truck = new Truck();\ntruck.Wheels = 4;\ntruck.Color = \"Blue\";\ntruck.Loaded = true;\n</code></pre>\n\n<p>the above two method do the exact same thing, the former is just shorthand for the latter</p>\n\n<p><strong>Edit</strong>: Added point #3</p></li>\n<li>You don't need to say <code>this._wheels = wheels</code>, in your case there are no variables in your constructor that conflict with <code>_wheels</code> so you can just say <code>_wheels = wheels;</code> In-fact that is partially the reason <code>private</code> <code>class</code> scoped variables are often named with an underscore prefix. In some conventions, that underscore prefix isn't used, so the <code>class</code> scoped <code>private</code> members are named something like <code>wheels</code>, and then in the constructor you do have to say <code>this.wheels = wheels;</code>, the former referring to the <code>class</code> level <code>wheels</code>, and the latter referring to the constructor level <code>wheels</code>. This is confusing when people do that, which is why I prefer to do it the way you did it, and have all my private <code>class</code> level members prefixed with an underscore. Note that I did specify <code>private</code>, if a variable is <code>public</code> is should be Capitalized, with no underscores in the beginning(preferably none in the rest of the name), and a property, meaning it has the <code>{get; set;}</code> or the more lengthy getters and setters you used in the OP.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:14:50.097", "Id": "76820", "Score": "0", "body": "@SamLeach It will show up with IntelliSense, however if the `set` accessor is private, it will result in a compile error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-18T05:36:36.673", "Id": "282571", "Score": "0", "body": "Using underscores in variable names is actually against the recommended guidelines set forth by Microsoft for variable naming in .NET. [MSDN](https://msdn.microsoft.com/en-us/library/ms229045(v=vs.110))." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:20:56.337", "Id": "44290", "ParentId": "44286", "Score": "7" } }, { "body": "<p>Maybe the word \"better\" needs to be elaborated. </p>\n\n<p>As it was suggested - public setter will help make it so that you can reuse the object.\nFor a stand alone class - there is not much you can add - if it had dependencies then it would have been another matter and also how you retrieve the parameters.</p>\n\n<p>That's when having less parameters receiving by the constructor will be important as for example wheel can be its own class with its own dimension (like rim size and number).</p>\n\n<p>But Jeff's solution of at least putting the public setter available should be sufficient for your needs for now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:18:35.560", "Id": "44304", "ParentId": "44286", "Score": "2" } } ]
{ "AcceptedAnswerId": "44290", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:43:25.013", "Id": "44286", "Score": "5", "Tags": [ "c#", "object-oriented" ], "Title": "Truck class constructor" }
44286
<p>I have the following code which basically takes a list of sorted integer arrays and merges them together removing the duplicates. </p> <p>I have tried to do the complexity analysis and came to a rough conclusion that it may be O(n<sup>2</sup>) order. Could you please see if my understanding is correct here. </p> <p>Also, if you could suggest ways to make the code better in terms of its running time, I would really be grateful.</p> <p>If you need the implementation of <code>PrioQueue</code>, please let me know.</p> <pre><code>public ArrayList MergeMultiple(Object[] input) { ArrayList result = new ArrayList(); int activeArrayIndex = -1; int inputArrayCount = input.Count(); // Keep track of indices of the arrays int[] indices = new int[inputArrayCount]; // Keep track of whether the end has been reached for each array bool[] endOfArray = new bool[inputArrayCount]; // Heap PrioQueue heap = new PrioQueue(); while (endOfArray.Contains(false)) // O(N) { for (int i = 0; i &lt; inputArrayCount; i++) // O(N) { int[] active = (int[])input[i]; int index = indices[i]; if (activeArrayIndex == -1 || (i == activeArrayIndex &amp;&amp; !endOfArray[i])) { int value = active[index]; // Add value to the heap heap.Enqueue(i + "|" + value, value); // O(N)?? } } // Add to result if (!heap.IsEmpty()) { activeArrayIndex = activeArrayIndex == -1 ? 0 : activeArrayIndex; string activeArrayIndexWithVal = (string)heap.Dequeue(); // O(1) string[] activeArrayObject = activeArrayIndexWithVal.Split('|'); // Identifying active array activeArrayIndex = Convert.ToInt32(activeArrayObject[0]); int[] activeArray = (int[])input[activeArrayIndex]; // Adding value to result object if not already in the array list if (!result.Contains(activeArrayObject[1])) // O(N) { result.Add(activeArrayObject[1]); } // Update index list with active array indices[activeArrayIndex]++; // update end of array count list for current array endOfArray[activeArrayIndex] = activeArray.Length == (indices[activeArrayIndex]); } } return result; } </code></pre>
[]
[ { "body": "<p>If <code>N == number of input arrays</code> and <code>M == length of the longest input array</code> then your outer while loop will run <code>M</code> times with the check condition being <code>O(N)</code> so your outer loop is O(M<em>N)<code>. The inner loop runs</code>N<code>times and the heap insert is</code>O(log(N))<code>so your inner body is</code>O(N</em>log(N)). Resulting in a total complexity of <code>O(M * N^2 * log(N))</code></p>\n\n<p>Some review:</p>\n\n<p>I find the entire code very confusing and hard to read. You keep track of different properties for the same array in disjoint helper arrays (<code>indices</code> and <code>endOfArray</code>) while they should be combined in a single state object.</p>\n\n<p>Also your input is <code>Object[]</code> while obviously you expect a list of <code>int[]</code> so why not express that in your parameter directly like: <code>List&lt;int[]&gt; input</code>.</p>\n\n<p>Your result is a non-generic <code>ArrayList</code> so it's really hard to know what the exact return type of the elements is. Reading through the code it looks like the elements get returned as strings which is probably very confusing for the user - why on earth would a method to which I pass a list of integer arrays return the merged result as an array of strings?</p>\n\n<p>If I read your intention correctly then you want to merge the input arrays, remove all duplicates and return the result ordered. You can write that very nicely with LINQ:</p>\n\n<pre><code>public List&lt;int&gt; MergeLists(List&lt;int[]&gt; lists)\n{\n return lists.SelectMany(l =&gt; l) // flatten into single collection\n .Distinct() // remove duplicates\n .OrderBy(x =&gt; x) // sort the result\n .ToList(); // build result list\n}\n</code></pre>\n\n<p>Assuming all <code>N</code> arrays have the same maximum length <code>M</code> then <a href=\"https://stackoverflow.com/questions/2799427/what-guarantees-are-there-on-the-run-time-complexity-big-o-of-linq-methods\">the complexity should be</a>:</p>\n\n<ul>\n<li><code>Distinct()</code> is in the order of <code>O(N * M)</code></li>\n<li><code>OrderBy()</code> is in the order of <code>O(N * M * log(N * M))</code></li>\n<li><code>ToList()</code> is in the order of <code>O(N * M)</code></li>\n</ul>\n\n<p>Which means the resulting complexity is <code>O(N * M * log(N * M)</code> so you have cut it down to linear in terms of number of input arrays and the code is significantly shorter, easier to read and maintain and very likely to contains fewer bugs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:20:25.717", "Id": "76822", "Score": "0", "body": "Linq is inherently a .NET object. I just wanted to play around with something more generic. Three questions: First, shouldn't M be the *total* length of all the arrays combined, because, in the worst case the outer loop goes through all elements in all arrays. Second, How would I take into consideration the check for if the item already exists in the results array list? Third, is select many in the order of O(1), same as select?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:56:34.047", "Id": "44295", "ParentId": "44287", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:51:36.280", "Id": "44287", "Score": "4", "Tags": [ "c#", "queue", "complexity" ], "Title": "Big-O complexity calculation for a merge and sort function" }
44287
<p>I'm writing a simple remote PC app (mouse-keyboard). Android is the client and is connected with WiFi to Java PC Server. I'm using TCP but I see a bit of latency compared to other remote apps. I'm sending a String to Server like these: "a","B","2".</p> <p>Why am I getting latency sometimes? When I press any key, sometimes something doesn't happen for 1 sec, and then coming (pressing key) when I press the key. How can improve it for low latency? </p> <p><a href="https://codereview.stackexchange.com/questions/44189/latency-problem-for-keyboard-remoting-from-android-phone">Original question is here</a>.</p> <p>Client on Android (TCP):</p> <pre><code> public class SendFile extends Activity { Socket sockClient; PrintWriter out; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); } public void commandto(String sip, int port ,String byt) { try { sockClient = new Socket(sip,port); //sockClient.connect(new InetSocketAddress(sip,port),9000); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sockClient.getOutputStream())),true); out.println(byt); out.flush(); Log.w("Client", "Client sent message"); sockClient.close(); }catch (final UnknownHostException e) { Toast.makeText(getBaseContext(),"Hata UnknownHostException"+e.getMessage(), Toast.LENGTH_LONG).show(); }catch (final IOException e) { // Toast.makeText(getBaseContext(),"Hata IOException"+e.getMessage(), Toast.LENGTH_LONG).show(); } } @Override public boolean dispatchKeyEvent(KeyEvent KEvent) { int keyaction = KEvent.getAction(); if(keyaction == KeyEvent.ACTION_DOWN) { int keycode = KEvent.getKeyCode(); int keyunicode = KEvent.getUnicodeChar(KEvent.getMetaState() ); char character = (char) keyunicode; if(keycode != 82){ if(keycode!=59){ commandto("192.168.2.195",9512,String.valueOf(character)); } } } return super.dispatchKeyEvent(KEvent); } } </code></pre> <p>TCP Server Codes: </p> <pre><code> import java.awt.AWTException; public class MainForma extends JFrame { private ServerSocket ss= null; private Socket s =null; private BufferedReader br=null; public Thread thread; Robot robo; String command; ObjectInputStream ois; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { frame.setVisible(true); btnCheckUpdate.doClick(); } catch (Exception e) { e.printStackTrace(); } } }); } private void cAccept (int portt) throws AWTException { try{ if(ss==null){ ss = new ServerSocket(portt);} }catch (IOException e){ lblInf.setText("Could not listen on port :"+portt+" "+e.getMessage()); } btnStop.setEnabled(true);btnStart.setEnabled(false); lblInf.setText("Server is started!"); } while(true){ try{ s = ss.accept(); br = new BufferedReader(new InputStreamReader(s.getInputStream())); command =br.readLine(); System.out.println(command+"\n"); type(command); s.close(); br.close(); }catch (IOException e){ try { if(s!=null) s.close(); if(br!=null) br.close(); } catch (IOException es) { // TODO Auto-generated catch block es.printStackTrace(); } lblInf.setText("Server is stopped!"); lblInf2.setText(""); } } } public void type(String character){ try { robo = new Robot(); if(character!=""){ switch (character) { case "a": robo.keyPress(KeyEvent.VK_A); break; case "b": robo.keyPress(KeyEvent.VK_B); break; case "c": robo.keyPress(KeyEvent.VK_C); break; case "d": robo.keyPress(KeyEvent.VK_D); break; case "A": robo.keyPress(KeyEvent.VK_SHIFT); robo.keyPress(KeyEvent.VK_A); robo.keyRelease(KeyEvent.VK_SHIFT);break; case "B": robo.keyPress(KeyEvent.VK_SHIFT); robo.keyPress(KeyEvent.VK_B); robo.keyRelease(KeyEvent.VK_SHIFT);break; case "C": robo.keyPress(KeyEvent.VK_SHIFT); robo.keyPress(KeyEvent.VK_C); robo.keyRelease(KeyEvent.VK_SHIFT);break; case "D": robo.keyPress(KeyEvent.VK_SHIFT); robo.keyPress(KeyEvent.VK_D); robo.keyRelease(KeyEvent.VK_SHIFT);break; case "E": robo.keyPress(KeyEvent.VK_SHIFT); robo.keyPress(KeyEvent.VK_E); robo.keyRelease(KeyEvent.VK_SHIFT);break; case "F": robo.keyPress(KeyEvent.VK_SHIFT); case "0": robo.keyPress(KeyEvent.VK_0); break; case "1": robo.keyPress(KeyEvent.VK_1); break; case "2": robo.keyPress(KeyEvent.VK_2); break; case "3": robo.keyPress(KeyEvent.VK_3); break; default: System.out.println("fucj"+"/ "+character); } } } catch (AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } } btnStart = new JButton("Start"); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnStart.setEnabled(false); btnStop.setEnabled(true); thread = new Thread() { public void run(){ try { cAccept(9512); } catch (AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; thread.start(); } }); </code></pre> <p>I'm waiting for any idea for improving latency. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T23:39:28.417", "Id": "76849", "Score": "0", "body": "Please do not remove the code that was originally posted. The below answer corresponds to that code, so it should remain." } ]
[ { "body": "<p>The performance problem is still related to creating a socket each time you want to send data.</p>\n\n<p>Here is a revised version of your code... note how the socket is kept open all the time (unless there is a failure, at which point it will re-connect....):</p>\n\n<pre><code>Socket sockClient = null;\nString remoteHost = null;\nint remotePort = 0;\nPrintWriter remoteOut;\n\n@Override\npublic void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.test);\n\n}\n\nprivate synchronized final PrintWriter checkSocket(String sip, int port) throws IOException {\n if (sockClient != null &amp;&amp; (sockClient.isOutputShutdown() || sockClient.isClosed())) {\n sockClient.close();\n sockClient = null;\n }\n if (sockClient != null &amp;&amp; !(remoteHost.equals(sip) &amp;&amp; remotePort == port)) {\n sockClient.close();\n sockClient = null;\n }\n if (sockClient == null) {\n remoteHost = sip;\n remotePort = port;\n sockClient = new Socket(remoteHost, remotePort);\n remoteOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sockClient.getOutputStream())));\n }\n return remoteOut;\n}\n\npublic void commandto(String sip, int port, String byt) {\n boolean ok = false;\n try {\n\n PrintWriter out = checkSocket(sip, port);\n\n out.println(byt);\n out.flush();\n Log.w(\"Client\", \"Client sent message\");\n ok = true;\n } catch (final UnknownHostException e) {\n\n Toast.makeText(getBaseContext(),\n \"Hata UnknownHostException\" + e.getMessage(),\n Toast.LENGTH_LONG).show();\n\n } catch (final IOException e) {\n //\n Toast.makeText(getBaseContext(),\n \"Hata IOException\" + e.getMessage(), Toast.LENGTH_LONG)\n .show();\n } finally {\n if (!ok) {\n // there was a problem on the network.....\n // force a re-connect on the next message.\n synchronized(this) {\n sockClient = null;\n }\n }\n }\n}\n</code></pre>\n\n<p>Using this system, the socket STAYS OPEN ALL THE TIME... do not close it!</p>\n\n<p>This is the way that TCP is designed to work.</p>\n\n<p>NOTE, you need to make the corresponding changes on the server side as well....</p>\n\n<p>The server cannot keep closing the socket after every transmission... it needs to read a line, process it, and wait for the next line <strong>without</strong> closing the socket.</p>\n\n<p><strong>Read up on the <a href=\"http://docs.oracle.com/javase/tutorial/networking/sockets/\" rel=\"nofollow\">Java Socket Tutorial</a>....</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:55:50.157", "Id": "76812", "Score": "0", "body": "I've get NullPointerException at \"checkSocket\". SS : http://i.imgur.com/lAeAwUg.png" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:57:28.607", "Id": "76813", "Score": "1", "body": "@sallamaniaa repaired I think. Edited/fixed code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:02:43.693", "Id": "76814", "Score": "0", "body": "I'm tried this. But It's working for a time. So It's just once press and does'nt happing until when I restart activity. And my log is working in \"commandto\", \"Client sent message\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:37:47.163", "Id": "76830", "Score": "0", "body": "I've fixed the issue. I added this \"remotePort = 0;\" in dispatchKeyEvent. :) little wrong. Meanwhile it's working good. I'm learning what you do. Thank you again. If you want anything of me say it. You have a good ideo." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T11:49:29.087", "Id": "78599", "Score": "0", "body": "When I've test it where a bit far of my Wi-Fi modem then I see some latency sometime. I'm testing latency with this. ( like this start-end = System.currentTimeMillis(); ) I see all time normal latency (3-5) but sometimes I see 1000-2000 ms, after It's coming normal-not normal... It's just happining only when I far of my Wi-fi modem. I'm testing other applications they are not same problem." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:30:39.107", "Id": "44293", "ParentId": "44289", "Score": "4" } }, { "body": "<p>Another thing you can try, to reduce latency, is to use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#setTcpNoDelay%28boolean%29\" rel=\"nofollow\">setTcpNoDelay</a> to disable the <a href=\"http://en.wikipedia.org/wiki/Nagle%27s_algorithm\" rel=\"nofollow\">Nagle algorithm</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T00:11:38.940", "Id": "44312", "ParentId": "44289", "Score": "1" } }, { "body": "<p>Two quick notes:</p>\n\n<ol>\n<li><p>You should format the code. Eclipse (and I guess other IDEs) support autoformat, they do a really good job here, use them. They give the code a more professional look and costs you only a keypress. Code is read more than written, so it's worth to optimize for reading. (It would also help reviewers on this site.)</p></li>\n<li><p>Instead of a big switch-case you could use a <code>Map&lt;Character, List&lt;Integer&gt;&gt; keyMapping</code> (untested code):</p>\n\n<pre><code>Map&lt;Character, List&lt;Integer&gt;&gt; keyMapping = new HashMap&lt;&gt;();\nkeyMapping.put('a', newArrayList(KeyEvent.VK_A));\n...\nkeyMapping.put('A', newArrayList(KeyEvent.VK_SHIFT, KeyEvent.VK_A, KeyEvent.VK_SHIFT));\n</code></pre>\n\n<p>and use this map:</p>\n\n<pre><code>List&lt;Integer&gt; keys = keyMapping.get(character);\nfor (int keyCode: keys) {\n robot.keyPress(keyCode);\n}\n</code></pre>\n\n<p>You might also be able to use the fact that value of <code>VK_A</code> is <code>65</code> which is the ASCII code of <code>A</code>.</p>\n\n<p>(A <a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained\" rel=\"nofollow\">Multimap</a> would be better here. <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Lists.html#newArrayList%28E...%29\" rel=\"nofollow\"><code>newArrayList</code></a> is from <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Google Guava</a>. It has a quite simple <a href=\"https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/Lists.java#87\" rel=\"nofollow\">implementation</a> which you can copy-paste to your project if you don't want to include a new jar only for that.)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:07:38.400", "Id": "76911", "Score": "1", "body": "1. I tried Source Format (ctrl+shift+f) in Eclipse. Thanks. 2. But I see error \"newArrayList(KeyEvent.VK_A)\". Should I create a method name is \"newArrayList\". How can i use it? There is error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:36:33.547", "Id": "76917", "Score": "0", "body": "@sallamaniaa: I've updated the answer, check it please." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T07:29:54.717", "Id": "44325", "ParentId": "44289", "Score": "1" } } ]
{ "AcceptedAnswerId": "44293", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:05:01.760", "Id": "44289", "Score": "5", "Tags": [ "java", "android", "networking", "tcp" ], "Title": "Latency problem for keyboard remoting from Android phone - follow up" }
44289
<p>This is just some test code I'm doing to learn C++11. It compiles and runs consistently. But is anything wrong that will eventually (or under slightly different circumstances) fail?</p> <p>Besides additional refactoring for sheer cleverness, are there any notable improvements that can be made to remove lines (like unnecessary type conversion chains)? Are there memory leaks or uninitialized memory? Some questions are noted in comments.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;memory&gt; #include &lt;Windows.h&gt; #include &lt;WinDNS.h&gt; #include &lt;iomanip&gt; #include &lt;string&gt; // I keep specifying wstring and wcout. I could macro it, but I don't want to. Is it normal to specify w everywhere? #include &lt;sstream&gt; #include &lt;exception&gt; using namespace std; struct DnsRAII { PDNS_RECORD p; DnsRAII() : p(NULL) { } ~DnsRAII() { if (p != NULL) DnsRecordListFree(p); } private: // disallowing copy and assignment, right, because by default they would exist and if I allowed them I'd have to worry about shared references more, right? DnsRAII(const DnsRAII &amp;p) { } DnsRAII &amp; operator= (const DnsRAII &amp; p) { } }; static wstring ipv4tos(IP4_ADDRESS addr) { wstringstream ss; in_addr ip4; ip4.S_un.S_addr = addr; ss &lt;&lt; to_wstring(ip4.S_un.S_un_b.s_b1) &lt;&lt; "." &lt;&lt; to_wstring(ip4.S_un.S_un_b.s_b2) &lt;&lt; "." &lt;&lt; to_wstring(ip4.S_un.S_un_b.s_b3) &lt;&lt; "." &lt;&lt; to_wstring(ip4.S_un.S_un_b.s_b4); return ss.str(); } static wstring ipv4toptrq(IP4_ADDRESS addr) { wstringstream ss; in_addr ip4; ip4.S_un.S_addr = addr; ss &lt;&lt; to_wstring(ip4.S_un.S_un_b.s_b4) &lt;&lt; "." &lt;&lt; to_wstring(ip4.S_un.S_un_b.s_b3) &lt;&lt; "." &lt;&lt; to_wstring(ip4.S_un.S_un_b.s_b2) &lt;&lt; "." &lt;&lt; to_wstring(ip4.S_un.S_un_b.s_b1) &lt;&lt; ".IN-ADDR.ARPA"; return ss.str(); } static wstring ipv6tos(IP6_ADDRESS addr) { wstringstream ss; auto group = [&amp;](int group) { if (!(addr.IP6Byte[group * 2] == 0 &amp;&amp; addr.IP6Byte[group * 2] == addr.IP6Byte[(group * 2) + 1])) ss &lt;&lt; hex &lt;&lt; setfill(L'0') &lt;&lt; setw(2) &lt;&lt; (int)addr.IP6Byte[group * 2] &lt;&lt; setw(2) &lt;&lt; (int)addr.IP6Byte[(group * 2) + 1]; }; group(0); ss &lt;&lt; ":"; group(1); ss &lt;&lt; ":"; group(2); ss &lt;&lt; ":"; group(3); ss &lt;&lt; ":"; group(4); ss &lt;&lt; ":"; group(5); ss &lt;&lt; ":"; group(6); ss &lt;&lt; ":"; group(7); ss &lt;&lt; ":"; return ss.str(); } static wstring rrtos(wstring &amp;query, DnsRAII &amp;results) { wstringstream ss; for (auto current = results.p; current != NULL; current = current-&gt;pNext) { switch (current-&gt;wType) { case DNS_TYPE_MX: ss &lt;&lt; query &lt;&lt; " -&gt; MX " &lt;&lt; current-&gt;Data.Mx.pNameExchange &lt;&lt; "\n"; break; case DNS_TYPE_A: ss &lt;&lt; query &lt;&lt; " -&gt; A " &lt;&lt; ipv4tos(current-&gt;Data.A.IpAddress) &lt;&lt; "\n"; break; case DNS_TYPE_AAAA: ss &lt;&lt; query &lt;&lt; " -&gt; AAAA " &lt;&lt; ipv6tos(current-&gt;Data.AAAA.Ip6Address) &lt;&lt; "\n"; break; case DNS_TYPE_PTR: ss &lt;&lt; query &lt;&lt; " -&gt; PTR " &lt;&lt; current-&gt;Data.PTR.pNameHost &lt;&lt; "\n"; break; default: ss &lt;&lt; query &lt;&lt; " -&gt; Record type " &lt;&lt; current-&gt;wType &lt;&lt; " unhandled\n"; break; } } return ss.str(); } static wstring topmx(DnsRAII &amp;results) { DNS_MX_DATA top; top.pNameExchange = 0; top.wPreference = ~0; // maxint - find ANYTHING lower than this for (auto current = results.p; current != NULL; current = current-&gt;pNext) { switch (current-&gt;wType) { case DNS_TYPE_MX: if (current-&gt;Data.MX.wPreference &lt; top.wPreference) top = current-&gt;Data.Mx; break; default: break; } } if (top.pNameExchange != 0) return wstring(top.pNameExchange); throw exception("MX record not found"); } int main(int argc, char **argv) { cout &lt;&lt; "Searching ... \n"; auto options = DNS_QUERY_BYPASS_CACHE | DNS_QUERY_NO_LOCAL_NAME | DNS_QUERY_NO_HOSTS_FILE; in_addr dnsServer; dnsServer.S_un.S_un_b.s_b1 = 8; // Google's DNS dnsServer.S_un.S_un_b.s_b2 = 8; dnsServer.S_un.S_un_b.s_b3 = 8; dnsServer.S_un.S_un_b.s_b4 = 8; IP4_ARRAY dnsServers; dnsServers.AddrCount = 1; dnsServers.AddrArray[0] = IP4_ADDRESS(dnsServer.S_un.S_addr); // I'm not sure I'm allocating this correctly auto name = wstring(L"stackoverflow.com"); wcout &lt;&lt; "\nDomain: " &lt;&lt; name &lt;&lt; " ... \n"; DnsRAII results; if (0 == DnsQuery((PCWSTR)name.c_str(), DNS_TYPE_MX, options, &amp;dnsServers, &amp;results.p, NULL)) { wcout &lt;&lt; rrtos(name, results); } else { wcout &lt;&lt; "Host not found"; getchar(); return 1; } wstring mx; try { mx = topmx(results); } catch (exception ex) { wcout &lt;&lt; ex.what(); getchar(); return 1; } wcout &lt;&lt; "\nMX: " &lt;&lt; mx &lt;&lt; " ... \n"; DnsRAII results2; if (0 == DnsQuery((PCWSTR)mx.c_str(), DNS_TYPE_A, options, &amp;dnsServers, &amp;results2.p, NULL)) { wcout &lt;&lt; rrtos(mx, results2); } else { wcout &lt;&lt; "Host not found"; getchar(); return 1; } wcout &lt;&lt; "\nIP: " &lt;&lt; ipv4tos(results2.p-&gt;Data.A.IpAddress) &lt;&lt; " ... \n"; wstring reverse = ipv4toptrq(results2.p-&gt;Data.A.IpAddress); DnsRAII results3; if (0 == DnsQuery((PCWSTR)reverse.c_str(), DNS_TYPE_PTR, options, &amp;dnsServers, &amp;results3.p, NULL)) { wcout &lt;&lt; rrtos(reverse, results3); } else { wcout &lt;&lt; "PTR not found"; getchar(); return 1; } wcout &lt;&lt; "\nSo \"" &lt;&lt; name &lt;&lt; "\" is run by \"" &lt;&lt; results3.p-&gt;Data.PTR.pNameHost &lt;&lt; "\"\n"; wcout &lt;&lt; "\nDone.\n"; getchar(); return 0; } </code></pre> <p>Output is below:</p> <pre><code>Searching ... Domain: stackoverflow.com ... stackoverflow.com -&gt; MX ASPMX2.GOOGLEMAIL.com stackoverflow.com -&gt; MX ASPMX3.GOOGLEMAIL.com stackoverflow.com -&gt; MX ASPMX.L.GOOGLE.com stackoverflow.com -&gt; MX ALT1.ASPMX.L.GOOGLE.com stackoverflow.com -&gt; MX ALT2.ASPMX.L.GOOGLE.com MX: ASPMX.L.GOOGLE.com ... ASPMX.L.GOOGLE.com -&gt; A 173.194.68.26 IP: 173.194.68.26 ... 26.68.194.173.IN-ADDR.ARPA -&gt; PTR qa-in-f26.1e100.net So "stackoverflow.com" is run by "qa-in-f26.1e100.net" Done. </code></pre> <p>("qa-in-f26.1e100.net" is a Google mail server)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T18:04:08.067", "Id": "77147", "Score": "0", "body": "Is this really working code? [`DnsRecordListFree`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682021.aspx) is documented to take two parameters, but you only pass one in `DnsRAII`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T19:01:47.597", "Id": "77154", "Score": "0", "body": "Yes it does work with only one. I think it's a default argument?" } ]
[ { "body": "<p>As it stands, the code is somewhat fragile. It only builds as a wide-character build (i.e., with UNICODE and/or _UNICODE defined). I'd prefer to see code explicitly define things that need to be wide characters as wide characters.</p>\n\n<p>I'm also seeing the same problem with <code>DnsFree</code> that @Michael Urman mentioned in his comment: I need to pass a second parameter (<code>DnsFreeRecordList</code>) to <code>DnsRecordListFree</code> to get the compiler to accept the code.</p>\n\n<p>I'm not overly fond of your DnsRAII class. First of all, I dislike the name. RAII is an implementation technique of which the client should be able to remain unaware. To the client, it should be something on the order of a <code>DnsRecordCollection</code> or (probably preferable) a <code>DnsIterator</code>.</p>\n\n<p>Second, I don't like defining a private copy constructor and assignment operator to prevent copying and assignment. I'd prefer to either derive from <code>Boost::noncopyable</code>, or else (if you can use C++11) specify <code>=delete</code> for those two member functions:</p>\n\n<pre><code>DnsRAII(const DnsRAII &amp;p) = delete;\nDnsRAII &amp;operator=(const DnsRAII &amp;) = delete;\n</code></pre>\n\n<p>I'll repeat though: rather than changing the syntax for making those unavailable, I'd prefer to start with a different class. Lacking a reason to do otherwise, a <code>DnsIterator</code> seems like what I'd probably prefer.</p>\n\n<p>To go with that, I think I'd create an <code>IpAddress</code> class with a few constructors to let the rest of the code create an IP address in a usable format a little more easily. As a first attempt at it, I'd consider something like this:</p>\n\n<pre><code>class IPAddress {\n IP4_ADDRESS addr;\npublic:\n IPAddress(char a, char b, char c, char d);\n IPAddress(IP4_ADDRESS addr) : addr(addr) {}\n explicit operator IP4_ADDRESS() const { return addr; } \n};\n</code></pre>\n\n<p>With this, the mainstream code to specify the IP Address of Google's server would looks something like:</p>\n\n<pre><code>IPAddress google{8, 8, 8, 8};\n</code></pre>\n\n<p>Then the <code>DnsIterator</code> class would take an instance of that (along with a domain to search for and an optional DWORD specifying search options):</p>\n\n<pre><code>DnsIterator(IPAddress server, std::string domain, DWORD options = DNS_QUERY_STANDARD) {\n</code></pre>\n\n<p>Using these, the complete code to retrieve and display the preferred MX record would look something like this:</p>\n\n<pre><code>auto options = DNS_QUERY_BYPASS_CACHE | DNS_QUERY_NO_LOCAL_NAME | DNS_QUERY_NO_HOSTS_FILE;\n\nIPAddress google(8, 8, 8, 8);\nstd::string name{ \"stackoverflow.com\" };\n\nDnsIterator&lt;DNS_TYPE_MX&gt; begin(google, name, options);\nDnsIterator&lt;DNS_TYPE_MX&gt; end;\n\n\nstd::cout &lt;&lt; std::min_element(begin, end, \n [](DNS_RECORD const &amp;a, DNS_RECORD const &amp;b){ \n return a.Data.MX.wPreference &lt; b.Data.MX.wPreference; \n })\n -&gt;Data.MX.pNameExchange;\n</code></pre>\n\n<p>Likewise, listing all the A records for an address would look something like this:</p>\n\n<pre><code>DnsIterator&lt;DNS_TYPE_A&gt; b2(google, name);\nDnsIterator&lt;DNS_TYPE_A&gt; e2;\n\nstd::transform(b2, e2, \n std::ostream_iterator&lt;std::string&gt;(std::cout, \"\\n\"), \n [&amp;name](DNS_RECORD const &amp;r) { return rrtos(name, r); });\n</code></pre>\n\n<p>Of course, defining the classes to implement that would be a little extra work up-front, but honestly the amount of extra work is really quite minimal, and the payoff in simpler, neater code afterwards is pretty serious.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T03:25:34.357", "Id": "78690", "Score": "0", "body": "Wow, this is really meaningful feedback. Thanks! I'll work through it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:28:10.200", "Id": "45177", "ParentId": "44291", "Score": "5" } } ]
{ "AcceptedAnswerId": "45177", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T19:24:15.560", "Id": "44291", "Score": "6", "Tags": [ "c++", "c++11", "memory-management", "winapi" ], "Title": "WinAPI code for DNS queries" }
44291
<p><a href="https://projecteuler.net/problem=3">Project Euler problem 3</a> asks for the largest prime factor of 600851475143.</p> <p>I have gone from 96 lines to 17 lines taking hits at this one. This is what I am left with after all of that effort:</p> <pre><code>public class IntegerFactoriseFive { public static void main(String[] args) { long n = 600851475143L; for (long i = 2; i &lt;= n; i++) { if (n % i==0) { System.out.println(i); n = n / i; i = 2; } } } } </code></pre> <p>Is there any way to make it faster?</p> <p>I'm not suggesting that it isn't quick enough already, but for the sake of it and for improving the way I tackle problems in the future. My other solutions were taking forever. I was using recursion, and I even only iterated up to the square root of the numbers I was checking (from early school maths I know to only check up to the square root, it is a lot quicker), but it was still to slow. In the end, iterating by one and dividing this huge number was the wrong way to go about it, so instead, I figured that dividing the number as much as possible was the only way I could do it in any good time.</p> <p>Please offer suggestions. As you can see by the class name, it is my fifth official solution for it that is the quickest of the ones I came up with.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:35:35.743", "Id": "76897", "Score": "0", "body": "How has no one mentioned the upper bound of the search space is much lower: `i<(int)Math.sqrt(n);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:42:59.453", "Id": "76903", "Score": "0", "body": "Even though trial division can tackle this one in reasonable time with any non-braindead implementation, consider using a faster integer factorization algorithm. [Pollard Rho](http://en.wikipedia.org/wiki/Pollard's_rho_algorithm) is very accessible and is considerably faster than trial division (its running time is asymptotically O(sqrt p) where p is the smallest prime factor of the input). A favourite for finding prime factors up to 50-60 bits." } ]
[ { "body": "<p>Reduce the number of System.out.println calls may give a little speedup:</p>\n\n<pre><code>public class IntegerFactoriseFive {\n\n public static void main(String[] args)\n {\n StringBuilder sb= new StringBuilder();\n long n = 600851475143L;\n for (long i = 2; i &lt;= n; i++)\n {\n if (n % i==0)\n {\n sb.append(i).append('\\n');\n n /= i;\n i = 2;\n }\n }\n System.out.println(sb.toString);\n }\n\n}\n</code></pre>\n\n<p><strong>You can also modify your algorithm.</strong></p>\n\n<ol>\n<li>If a number can not be divided by 2 it can also not be divided by any even number. So you can check2 and than only the odd numbers.</li>\n<li>you can make a list of all <em>little</em> prime numbers and check these and from the point where you have not the primes, try all odd numbers</li>\n<li>you can stop checking at sqrt(n) but that is quite expensive to calculate. Not so good, but still halves the work, stop at <code>n/2</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T02:43:10.263", "Id": "76855", "Score": "0", "body": "How do you know sqrt(n) is expensive to calculate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T05:23:49.200", "Id": "76866", "Score": "0", "body": "@NowIGetToLearnWhatAHeadIs: experience. In general an iterative algorithm is used that converge against the sqrt. (sometimes additional to a look up table with some starting points). For big n it may be faster to calculate sqrt(n) than checking up to n/2 but you have to profile where the break even point is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T05:41:00.533", "Id": "76868", "Score": "0", "body": "Ok. I was just asking because when I did this problem on project euler, I thought the same thing you are saying, but then I tried it with doing square roots and it was way faster. My processor has an FSQRT instruction, and I think java takes advantage of it when it does the square root. So its actually not so slow. But I am not 100% sure that java is doing the square root in hardware, but it certainly could be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:43:29.223", "Id": "76904", "Score": "0", "body": "How do you know sqrt (n) is expensive to calculate? Did you measure it? I bet you didn't. You tell someone to profile to find out whether they should use sqrt, but you haven't done any profiling yourself to find whether you should avoid it. This being 2014, a single square root is more expensive than most operations, but it is _one_ square root and nowhere near as expensive as half a billion iterations through a loop if you look for prime factors of a number > one billion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:13:04.913", "Id": "76913", "Score": "0", "body": "@gnasher729: You lost the bed. I profiled it years ago, and the result was that it was the bottle neck in my case. In my case an alternative implementation without sqrt was much faster. Therfore I wrote that only profiling can show if the costs of sqrt is higher than the alternative implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T00:07:38.240", "Id": "77075", "Score": "0", "body": "To be fair, performance testing a feature a decade ago doesn't really qualify as sufficient evidence when dealing with modern technology." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T15:07:26.873", "Id": "84165", "Score": "0", "body": "@Jeff Gohlke: It still depends on the hardware your VM runs on and the implementation of the VM. I would not avoid profiling only because I think on my platform may be a hardware acceleration which might be used by the VM." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:54:35.653", "Id": "44302", "ParentId": "44300", "Score": "3" } }, { "body": "<p>By inspection, <code>n</code> has no even factors. You only need to try odd factors.</p>\n\n<p>Whenever you find an <code>i</code> that is a divisor of <code>n</code>, you should factor out <em>all</em> powers of <code>i</code>. There is also no need for <code>i</code> to start from scratch — your hunt for divisors should proceed monotonically upward.</p>\n\n<p>Your search can end when <code>i</code> reaches or surpasses the square root of <code>n</code>. At that point, <code>n</code> is the answer to the challenge.</p>\n\n<p>(A reasonable algorithm should obtain the answer within milliseconds.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T22:04:51.620", "Id": "76845", "Score": "0", "body": "will give this a go" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:10:52.273", "Id": "44303", "ParentId": "44300", "Score": "8" } }, { "body": "<p>The <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a> is one of the most efficient prime-finding algorithms out there. If you really want a program with good performance, make sure to Google the clever methods that have already been devised. \"Don't reinvent the wheel\" is a common programming mantra.</p>\n\n<p>As far as your implementation, there are a couple of simple logical notes (which I believe are covered by the other answers): don't check even numbers at all (increment with <code>i += 2</code> rather than <code>i++</code>), and don't print until/unless it's absolutely necessary.</p>\n\n<p>To address issues in the comments below: Division into the constant value is computationally trivial compared to the process of actually finding the primes. It's the finding that we want to speed up. After all the primes have been found which are less than the desired number, we can iterate over them from highest to least and find the largest one. It's pretty straightforward.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T04:56:54.950", "Id": "76864", "Score": "0", "body": "The Sieve of Eratosthenes will find many prime numbers. But which of those is the largest prime factor of 600851475143? Trial division is the way to go for this problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:38:10.763", "Id": "76898", "Score": "0", "body": "Sieve of Eratosthenes is good for finding all prime numbers in some range, let's say all prime number up to a million, or all prime numbers from 13.1 billion to 13.2 billion. It is useless for checking if a single number is a prime, and it is useless for finding the largest prime factor of a number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T13:39:15.727", "Id": "76932", "Score": "0", "body": "@gnasher729 It's far from useless to find the largest prime factor of a number. The efficiency hit comes from finding all the primes, not dividing them into the constant. So you find all the primes up to the desired number, then perform the division (iterating in reverse, from highest to lowest) to find the greatest one. The division is trivial, computationally, compared to the finding of the primes. (I also think there's some math which says you only need to find primes up to sqrt(num) or num/2 or something, but I don't remember well enough.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:07:59.687", "Id": "76942", "Score": "2", "body": "The time that is needed to create the sieve far surpasses that which is needed to just perform the trial division. Even with a fast sieve creation. See my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:39:35.717", "Id": "44305", "ParentId": "44300", "Score": "5" } }, { "body": "<p>You're looking for the largest prime factor, right? And you know that the maximum for any factor will be the square root of n?</p>\n\n<p>Why not run the loop from sqrt(n) backwards and break on the first result?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T22:05:49.390", "Id": "76846", "Score": "0", "body": "Come to think of it, this will also find factors that are not prime, so you'll probably want to run a probabilistic test on candidate results. Still faster than printing in order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T22:06:48.227", "Id": "76847", "Score": "0", "body": "yes it will find numbers that are not prime, I was aiming more for speed on this particular example, rather than something generic" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T06:09:01.480", "Id": "76870", "Score": "0", "body": "`n` is huge! Your best best is to optimistically hope to eliminate a few small factors quickly. For example, if `n` were divisible by 3, you would immediately reduce your search space by 66%. As it turns out, the smallest factor of `n` is 71, but that's still quite good: after 35 trial divisions, you reduce your search space by 98%! And when you're done, you _know_ that the result is prime, with no further checking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:54:48.927", "Id": "76907", "Score": "1", "body": "The maximum for any factor is _not_ the square root of n. Take 38 = 2 x 19. The largest factor is 19, much bigger than the square root of 38. What you mean is: If you haven't find any factor up to the square root of n, then you know it is a prime number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:34:12.483", "Id": "77029", "Score": "0", "body": "Thanks, it's been a long time since I did prime-number things and I misremembered. Shame on me!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T21:41:43.343", "Id": "44306", "ParentId": "44300", "Score": "4" } }, { "body": "<p>Since you're increasing i from below, each time you find a factor it's actually a prime factor so you don't need to reset i to 2 after each finding:</p>\n\n<ol>\n<li>check for n % 2 == 0 first and set n /= 2 in this case and jump to 1</li>\n<li>Initialize i with 3</li>\n<li>Initialize n_sqrt with sqrt(n)</li>\n<li>if i > n_sqrt you're done. n is your highest prime factor</li>\n<li>If n % i == 0 you found a prime factor, set n /= i and jump to 3</li>\n<li>Increment i by 2 and jump to 4</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T07:12:11.797", "Id": "44324", "ParentId": "44300", "Score": "1" } }, { "body": "<p>There are some things you can do without resorting to a sieve to find all primes.</p>\n\n<ol>\n<li>No even number besides '2' can be a prime so skip all even numbers in your iteration after removing all factors of '2'.</li>\n<li>Limit your search range to the largest possible factor of n, i.e. <code>Math.sqrt(n)</code></li>\n</ol>\n\n<p>Like this:</p>\n\n<pre><code>public class IntegerFactoriseFive {\n public static void main(String[] args) {\n { // Original trial division\n long startTime = System.nanoTime();\n {\n long n = 600851475143L;\n for (long i = 2; i &lt;= n; i++) {\n if (n % i == 0) {\n System.out.println(i);\n n = n / i;\n i = 2;\n }\n }\n }\n long stopTime = System.nanoTime();\n System.out.println(\"ns: \" + (stopTime - startTime));\n }\n { // Optimised Trial division\n long startTime = System.nanoTime();\n long n = 600851475143L;\n while (n % 2 == 0) {\n n = n / 2;\n }\n long largest = 0;\n for (long i = 3; i &lt;= Math.sqrt(n); i += 2) {\n if (n % i == 0) {\n largest = i;\n while (n % i == 0) {\n n = n / i;\n }\n }\n }\n System.out.println(Math.max(largest, n));\n\n long stopTime = System.nanoTime();\n System.out.println(\"ns: \" + (stopTime - startTime));\n }\n { // Optimised sieve+test\n long startTime = System.nanoTime();\n long n = 600851475143L;\n final int maxFactor = (int) Math.sqrt(n);\n boolean[] primes = new boolean[maxFactor + 1];\n\n for (int i = 0; i &lt;= maxFactor; i++) {\n primes[i] = true;\n }\n\n long largest = 0;\n for (int i = 2; i &lt;= maxFactor; ++i) {\n if (!primes[i])\n continue;\n for (long j = ((long) i) * i; j &lt;= maxFactor; j += i) {\n primes[(int) j] = false;\n }\n if (n % i == 0) {\n largest = i;\n while (n % i == 0) {\n n = n / i;\n }\n if(n==1)\n break;\n }\n }\n\n System.out.println(Math.max(largest, n));\n long stopTime = System.nanoTime();\n System.out.println(\"ns: \" + (stopTime - startTime));\n }\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>71\n839\n1471\n6857\nns: 530011 (0.5ms)\n6857\nns: 71469 (0.07ms)\n6857\nns: 15287751 (15ms)\n</code></pre>\n\n<p><strong>Summary:</strong>\nWith a sieve based method, you need to spend so much time at generating the primes that it actually is slower than the original. If you need to test many numbers, then the sieve is going to overtake trial division as you only pay the setup once.</p>\n\n<p>The optimized trial division is the fastest of them all by almost a factor 10. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T14:09:40.903", "Id": "44352", "ParentId": "44300", "Score": "2" } } ]
{ "AcceptedAnswerId": "44305", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:33:48.110", "Id": "44300", "Score": "6", "Tags": [ "java", "performance", "primes", "project-euler" ], "Title": "Speeding up my implementation of Project Euler #3" }
44300
<p>Someone asked if their singleton is good for OOP:</p> <p><a href="https://codereview.stackexchange.com/questions/39382/using-a-singleton-class-to-get-and-set-program-wide-settings/44298#44298">Using a singleton class to get and set program wide settings</a>.</p> <p>However, the answer just provides tweaks to his existing code - but the question wasn't entirely answered. What is the best practice to use for configuration files so that it doesn't become spaghetti code?</p> <p>All apps need configuration settings so that it saves time and it looks neat.</p> <p>I currently use something similar to what was proposed but not a singleton. However, I have a long array that feeds into different constructors. I feel that this is improper or maybe it is.</p> <pre><code>namespace App; class Config { protected static $config = array(); public static function get($name, $default = null) { return isset(self::$config[$name]) ? self::$config[$name] : $default; } public static function add($parameters = array()) { self::$config = array_merge(self::$config, $parameters); } } App\Config::add( array( 'database' =&gt; array( 'default' =&gt; array( 'driver' =&gt; 'mysql', 'host' =&gt; '127.0.0.1', 'username' =&gt; 'user', 'password' =&gt; '', 'database' =&gt; 'database', 'charset' =&gt; 'utf8', 'collation' =&gt; 'utf8_unicode_ci' ), 'tracking' =&gt; array( 'driver' =&gt; 'mysql', 'host' =&gt; '192.168.0.1', 'username' =&gt; 'tracking', 'password' =&gt; '123456', 'database' =&gt; 'tracking', 'charset' =&gt; 'utf8', 'collation' =&gt; 'utf8_unicode_ci' ), 'data' =&gt; array( 'driver' =&gt; 'mysql', 'host' =&gt; '192.168.0.11', 'username' =&gt; 'data', 'password' =&gt; 'abcder', 'database' =&gt; 'data_info', 'charset' =&gt; 'utf8', 'collation' =&gt; 'utf8_unicode_ci' ) ), 'pheanstalk' =&gt; array( 'default' =&gt; array( 'host' =&gt; 'localhost', 'port' =&gt; 11400, 'queue_name' =&gt; 'queue' ) ), 'app_worker' =&gt; array( 'log_files_path' =&gt; ROOT.'/logs', 'file_size_limit' =&gt; 542880, //5MB 'file_name_extension' =&gt; 'w_log', ), 'memcache' =&gt; array( 'default' =&gt; array( array( 'host' =&gt; 'localhost', 'port' =&gt; '11211' ), array( 'host' =&gt; 'localhost', 'port' =&gt; '11211' ), array( 'host' =&gt; 'localhost', 'port' =&gt; '11211' ) ) ) ) ); </code></pre> <p>Then in my main program:</p> <pre><code>$db_config = App\Config::get('database'); </code></pre> <p>Now it's ok for me to add extra configuration needs for different object I might create and etc and I can load up a controller or piece of code to fetch it from. However, I feel that this configuration file that adds all these settings will be terribly long in the long wrong.</p> <p>I would like to know if there something better, and what. I tried to use inheritance or DI but my configuration file is still long.</p>
[]
[ { "body": "<p>I personally use defines for for settings rather than utilising arrays. </p>\n\n<p>A singleton is the correct route to go down and to help reduce your code and array you may want to use external files. </p>\n\n<p>This is my config loader class with some simple caching that supports both database and file;</p>\n\n<pre><code>&lt;?php\n/**\n * Config loader \n */\nfinal class Config extends Singleton{\n public static $loadedConfigs = array();\n\n /**\n * Get specific config value\n * \n * @param String $scope Configuration scope, used to determine config location\n * @param String $module Specific config module name\n * @param String $param (optional) Specific config option\n * \n * @return Mixed Requested parameter value if requested, otherwise associative array or configuration key:pair values unless config file couldn't be loaded, then false\n * @author Dean Whitehouse\n * @copyright Dean Whitehouse 2014\n * @todo verify the config name is a valid one \n */\n public static function get($scope, $module, $param = null){\n if($param !== null &amp;&amp; $param != ''){\n $const = strtoupper((string)$param);\n }\n\n $errorAppend = '; requested scope `'.$scope.'` with module `'.$module.'`;'.($param !== null ? 'Parameter requested `'.$param.'`' : '');\n\n if(isset(static::$loadedConfigs[$scope][$module])){\n $config = static::$loadedConfigs[$scope][$module];\n\n if(isset($const)){\n if(!isset($config[$const])){\n error_log('Constant `'.$const.'` undefined'.$errorAppend);\n return false;\n }\n else\n $config = $config[$const];\n }\n return $config;\n }\n else{\n if($scope == 'core'){\n $file = '_app/core/config/'.$module.'.config.php';\n\n if(!file_exists($file)){\n error_log('Config file doesn\\'t exist at `'.$file.'`'.$errorAppend);\n return false;\n }\n else{\n $consts = get_defined_constants(true);\n $consts = isset($consts['user']) ? $consts['user'] : array();\n\n require_once $file;\n\n $new = get_defined_constants(true);\n $new = $new['user'];\n $diff = array_diff_assoc($new, $consts);\n static::$loadedConfigs[$scope][$module] = $diff;\n\n if(isset($const)){\n if(defined($const))\n return constant($const);\n else{\n error_log('Constant `'.$const.'` undefined'.$errorAppend);\n return false;\n }\n }\n\n return static::$loadedConfigs[$scope][$module];\n }\n }\n elseif($scope == 'coreDB'){\n $check = db\\sqli::query(\"SHOW TABLES LIKE '\".db\\sqli::escape($module).\"'; -- Database check\");\n\n if($check-&gt;num_rows == 0){\n error_log('Config table doesn\\'t exist'.$errorAppend);\n return false;\n }\n else{\n $query = 'SELECT `key`, `value` FROM `'.db\\sqli::escape($module).'`';\n if($param !== null){\n $query .= ' WHERE `key` = '.db\\sqli::escape($param).' LIMIT 1';\n }\n\n $query = db\\sqli::query($query);\n\n if($query-&gt;num_rows &gt; 0){\n\n $consts = get_defined_constants(true);\n $consts = isset($consts['user']) ? $consts['user'] : array();\n\n while($config = $query-&gt;fetch_assoc()){\n define($config['key'], $config['value']);\n }\n\n $new = get_defined_constants(true);\n $new = $new['user'];\n $diff = array_diff_assoc($new, $consts);\n static::$loadedConfigs[$scope][$module] = $diff;\n\n if(isset($const)){\n if(defined($const))\n return constant($const);\n }\n\n return static::$loadedConfigs[$scope][$module];\n }\n else{\n error_log('Constant `'.$const.'` undefined'.$errorAppend);\n return false;\n }\n\n }\n }\n else{\n error_log('Config scope `'.$scope.'` isn\\'t recognised'.$errorAppend);\n return false;\n }\n }\n }\n\n /**\n * Load configuration module\n * \n * @param String $scope Configuration scope, used to determine config location\n * @param String $module Specific config module name\n * \n * @return Mixed False if configuration couldn't be loaded, otherwise associative array or configuration key:pair values\n * @author Dean Whitehouse\n * @copyright Dean Whitehouse 2014\n */\n public static function load($scope, $module){\n return static::get($scope, $module);\n }\n}\n?&gt;\n</code></pre>\n\n<p>I call it like:</p>\n\n<pre><code>Config::load('core', 'env');\nConfig::load('core', 'db');\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>Sample config file 'env.config.php'</p>\n\n<pre><code>&lt;?php \ndefine('AUTO_REPAIR', true);\n\ndefine('APP_ROOT', rtrim($_SERVER['SCRIPT_NAME'], '/index.php')); //folder the root of the site is in - only if in a directory\n\ndefine('SECURE', true);\n\ndefine('LOG_DIR', '_app/logs/');\n\ndefine('SECURE_KEY', ''); //used for CSRF, NONCE and Cookies\n?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T12:33:34.593", "Id": "77334", "Score": "1", "body": "Can you include the structure of your define so that we can correlate your class and the call. Tks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T13:17:59.520", "Id": "77340", "Score": "0", "body": "Updated to include this" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T12:09:22.187", "Id": "44563", "ParentId": "44301", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T20:47:02.820", "Id": "44301", "Score": "8", "Tags": [ "php", "object-oriented", "mysql" ], "Title": "How is OOP achieved with configuration files in PHP?" }
44301
<p>This draws blocks on the screen from a grid to make a background for my game. I am wondering if anyone has any suggestions on optimizing it for speed.</p> <pre><code>int blockwidth=blocksize-2; //Draw coloured blocks for (int x=0;x&lt;sizex;x++){ int screenx=-(int)camerax+(x*blocksize); if (screenx&gt;-blocksize &amp;&amp; screenx&lt;gamewidth){ for (int y=0;y&lt;sizey;y++){ int screeny=-(int)cameray+(y*blocksize); if (screeny&gt;-blocksize &amp;&amp; screeny&lt;gameheight){ if (tiles[x][y][0]&gt;0){ g.setColor(new Color( tiles[x][y][1])); //g.fillRect(screenx,screeny,blockwidth,blockwidth); g.drawImage(Iloader.Imagelist.get(0), screenx,screeny, screenx+blockwidth,screeny+blockwidth, graphicsize,0,graphicsize*2,graphicsize, null); } else { //g.setColor(new Color( tiles[x][y][1] | 0xFFFF0000)); g.setColor(new Color( tiles[x][y][1])); g.fillRect(screenx,screeny,blockwidth,blockwidth); } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T07:41:44.107", "Id": "76877", "Score": "0", "body": "In which method is this? I assume `paintComponent` or similar? Have you checked how often that method is called? How often does the tiles actually change?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T07:54:50.780", "Id": "76879", "Score": "0", "body": "I include it in my render method so every frame update" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T07:55:55.113", "Id": "76880", "Score": "0", "body": "Therefore I could pop it in another method to copy to an offscreen image and only call it if it changes BUT have the render method copy the whole other image each frame update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T08:03:15.740", "Id": "76881", "Score": "1", "body": "How often does the value of a specific `tiles[x][y][1]` or `tiles[x][y][0]` change?" } ]
[ { "body": "<p>There are a few optimizations I can see in your code.</p>\n\n<ol>\n<li><p>creating a new Color every time is a little severe. You can do a few things here, for example, if your color palette is limited, then cache the individual Color instances. I know it sounds petty right now, but, when you add it up there are a lot of new Color instances created.</p>\n\n<p>What you should at minimum do, is track your last Color used, and only create a new one if it is different.</p></li>\n<li><p>Pull the <code>Iloader.Imagelist.get(0)</code> outside the loop, and have <code>Image image = Iloader.Imagelist.get(0)</code></p></li>\n<li><p>Pull calculations outside the loops where you can... and continue/break when you can too.</p>\n\n<pre><code>Image image = Iloader.Imagelist.get(0);\nint screenx=-(int)camerax - blocksize;\nfor (int x = 0; x &lt; sizex; x++){\n screenx += blocksize;\n if (screenx &lt;= -blocksize) {\n continue;\n }\n if (screenx &gt;= gamewidth) {\n break;\n }\n int screeny= -(int)cameray - blocksize;\n for (int y = 0; y &lt; sizey; y++){\n screeny += blocksize;\n if (screeny &lt;= -blocksize)\n continue;\n }\n if (screeny &gt;= gameheight) {\n break;\n } \n if (tiles[x][y][0] &gt; 0) {\n // need to set the color here? g.setColor(new Color( tiles[x][y][1]));\n g.drawImage(image, screenx, screeny, screenx + blockwidth,\n screeny + blockwidth, graphicsize, 0, graphicsize * 2,\n graphicsize, null);\n } else {\n //g.setColor(new Color( tiles[x][y][1] | 0xFFFF0000));\n g.setColor(new Color( tiles[x][y][1]));\n g.fillRect(screenx,screeny,blockwidth,blockwidth); \n\n }\n }\n}\n</code></pre></li>\n</ol>\n\n<p>The above code does not have the mechanism for caching the color. You should figure one out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T07:25:17.003", "Id": "76876", "Score": "0", "body": "Thanks, will try ALL of that; I have not come across using continue break in this way either so you have taught me something significant." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T02:49:13.387", "Id": "44317", "ParentId": "44307", "Score": "2" } } ]
{ "AcceptedAnswerId": "44317", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T22:51:49.050", "Id": "44307", "Score": "2", "Tags": [ "java", "game", "graphics" ], "Title": "Drawing blocks for a 2D game background" }
44307
<p>For practicing reasons I would like to write a method which inserts a character into a string.</p> <p>I would like to know:</p> <ol> <li><p>What is the best practice concerning placement of a comment within methods? For example, is the way that I commented about what raises an exception fine, or are there better practices? Would I need more comments, and if so, where? </p></li> <li><p>In this particular example, are throwing unchecked exceptions preferred or checked?</p></li> <li><p>How can I make this method more reliable?</p></li> <li><p>How can I make this method more scalable?</p></li> <li><p>While dealing with immutable strings there are always discussions around performance. Can I make this method run faster?</p></li> <li><p>Is this code thread safe?</p></li> </ol> <p></p> <pre><code>/** * Inserts the character ch at the location index of string st * @param st * @param ch * @param index * @return a new string */ public static String insertCharAt(String st, char ch, int index){ //1 Exception if st == null //2 Exception if index&lt;0 || index&gt;st.length() if (st == null){ throw new NullPointerException("Null string!"); } if (index &lt; 0 || index &gt; st.length()) { throw new IndexOutOfBoundsException("Try to insert at negative location or outside of string"); } return st.substring(0, index)+ch+st.substring(index, st.length()); } </code></pre>
[]
[ { "body": "<ol>\n<li><p>The Javadoc style headers you have provided for this method are already more than enough. If you are adding comments to your method it should only be either for API documentation, or where the code is sufficiently complex to warrant an explanation that you cannot provide by simplifying or more appropriately naming the variables.</p>\n\n<p>You should however make it clear that your method throws these two exceptions by including them in the method definition, e.g.</p>\n\n<pre><code>public static String insertCharAt(String str, char ch, int index) throws NullPointerException, IndexOutOfBoundsException\n</code></pre>\n\n<p>This way it will be obvious from reading the method definition that these exceptions can be thrown, and your comment will be unnecessary when we read the line above each exception-throwing statement and see the logic that causes it to be thrown.</p>\n\n<p>In general, if your comment is telling us nothing more than what the code already does, make your code as simple and readable as possible and delete the comment. At best it will add noise to the code file and at worst it will get out of sync with the code and become misleading.</p></li>\n<li><p>In this example, presumably prefer to use a checked exception so that the method calling <code>insertCharAt</code> and can catch these exceptions and handle them in some way. See also <a href=\"https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions\">https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions</a></p></li>\n<li><p>This depends what you mean by more reliable. Do you mean robust in regards error cases?</p></li>\n<li><p>This also depends on what you mean by more scalable. What do you mean?</p></li>\n<li><p>This method is very simple and there isn't a great deal of room for performance improvement that I can see.</p>\n\n<p>Edit:</p></li>\n<li><p>This method is thread safe as it does not modify any parameters passed to it (and strings are immutable anyway) and does not modify any class-local variables. Even if you had assigned the return value to a temporary variable before returning it, it would not be shared between threads as method level variables belong to each thread's stack.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T23:51:42.673", "Id": "44310", "ParentId": "44309", "Score": "5" } }, { "body": "<ol>\n<li><p><em><strong>Comments</em></strong> - in methods are only useful if they tell you something that is not immediately obvious when you read the code. Your code is immediately obvious, and thus the comments <em>inside</em> the method are completely redundant. I have a note a little later about your JavaDoc though....</p></li>\n<li><p><em><strong>Exceptions</em></strong> - In many ways the difference between when checked and unchecked exceptions are useful, is easy to determine:</p>\n\n<ul>\n<li>If something fails because the programmer using your code is an idiot (or needs a smack to the side of the head), then throw an unchecked exception.</li>\n<li>If something fails because of an environmental situation beyond the control of the programmer, then throw a checked exception.</li>\n</ul>\n\n<p>In your case, if the programmer gives you garbage, throw an unchecked exception.... and there is essentially nothing environmental that can go wrong. So, no checked exceptions from your method.</p></li>\n<li><p><em><strong>Reliability</em></strong> - what can go wrong? In this case, <strong><em>right now</em></strong>, nothing. If something goes wrong it is either because the person using the method is an idiot, or you are an idiot. in either case, you will immediately be aware of that. Your code is simple, and works. For larger functions, it may not be so clear...</p>\n\n<p>But, reliability is about more than what is happening now. Reliability is making sure that things work in the future too. So, to improve reliability, write tests. Make the tests run every conceivable condition through the code. Run the tests every time you change the code.</p>\n\n<p>That is what makes code reliable. Tests. Tests, tests, and more tests. Then Regression tests, and compatibility tests. There is a common theme here, can you spot it?</p></li>\n<li><p><em><strong>Scalability</em></strong> - this is a buzz-word that that you threw in because right now it is popular. What influences could introduce scalability problems in your code. In essence, only one thing: very large Strings. With current and older versions of Java (less than 3 or 4 months old), the memory is shared between String values. In your case, doing <code>String.substring(....)</code> does not take much more memory (about 24 to 64 bytes depending on the JVM). In newer versions of Java (recent Java7 fic-packs and Java8), the substring command will copy the relevant inner memory of the String, and thus will take much more memory. Your code could have scalability problems since it will require a large amount of additional memory each time you do an insert.</p>\n\n<p>Now, whether that is a thing you should worry about.... no, I don't think so. If you have Strings that large, you will have other problems first.</p></li>\n<li><p><em><strong>Performance</em></strong> - Yes, it can be faster. Is the improvement meaningful, I doubt it, but, for the record:</p>\n\n<ul>\n<li><p>you are checking your input values for nulls, and index constraint violations. These exceptions will be thrown anyway, but with default messages. If you remove the explicit checks, you will not actually lose any functionality (except for less meaningful exception messages), and you will gain performance.</p></li>\n<li><p>The String concatenation in this line here:</p>\n\n<blockquote>\n<pre><code>st.substring(0, index)+ch+st.substring(index, st.length())\n</code></pre>\n</blockquote>\n\n<p>is creating a new StringBuilder instance, two new String objects, concatenating them, and then converting the result to a String. By my count that is three Strings, and a StringBuilder.</p>\n\n<p>You can do better by having just two char[] arrays, and a String.</p>\n\n<pre><code>char[] chars = str.toCharArray();\nchars = Arrays.copyOf(chars, chars.length + 1);\nSystem.arrayCopy(chars, index, chars, index + 1, chars.length - index - 1);\nchars[index] = ch;\nreturn new String(chars);\n</code></pre>\n\n<p>Whether the marginal improvement will help you or not is uncertain....</p></li>\n</ul></li>\n<li><p><em><strong>Thread-Safety</em></strong> - no problems.... there are no external references, and it is fully 'A-OK'.</p></li>\n</ol>\n\n<p><strong>other</strong>:</p>\n\n<p>I am a firm believer in JavaDoc. Depending on your circumstances, JavaDoc can be less important. Any time I wrote code that is more 'serious' (I expect anyone to have to maintain), I write comprehensive JavaDoc. IDE's make this relatively easy. Your JavaDoc is not complete.</p>\n\n<p>You do not describe the input values appropriately, and there is not enough detail in the <code>return</code> section.</p>\n\n<p>As for declaring the thrown unchecked exceptions.... no. Don't do it... see this <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html\">Exception Tutorial here</a>, but, you <strong>should</strong> document them anyway in the JavaDoc.</p>\n\n<p>The JavaDoc is your communication with other programmers. Help them by giving good documentation.</p>\n\n<p>Similarly, your actual exceptions are your communication with other programmers... help them too. Currently your exceptions are poor... consider these changes:</p>\n\n<pre><code>throw new NullPointerException(\"Null String input value: st\");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>throw new IndexOutOfBoundsException(\"No such index \" + index\n + \" in a String of size \" + st.length()\n + \". Expect index value 0 &lt;= index &lt;= \" + st.length());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:30:09.520", "Id": "77054", "Score": "0", "body": "The two char array approach might have some insignificant performance increase but think of the poor future programmers who have to come along and understand that code! The readability and maintainability tradeoffs are surely worth keeping it simple." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:35:24.320", "Id": "77056", "Score": "0", "body": "@willh - yeah, that is why I reluctantly suggested it. There are times when the performance difference makes a difference. I have no idea of whether this is the time, or not." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T02:10:07.513", "Id": "44315", "ParentId": "44309", "Score": "5" } }, { "body": "<p>Shifting bytes on insertion is always costly. What you do up there creates a StringBuilder and copies bytes using System.arraycopy(), which is a native method and is the fastest known way in Java to copy arrays.</p>\n\n<p>But, if you are really interested in high performance, you will have to make your own helper class. If you check, even StringBuilder does a stupid System.arraycopy() on insert. \nA faster way to do this is to maintain a tree of char[], so insertion is done in logarithmic time. Of course then you have to check for the possibility of the previous char[] array having some extra space in it (or reallocate on deletion to save space), and of course build() would be somewhat costly. But if you expect lots of small manipulative operations, StringBuilder is really ineffective.</p>\n\n<p>I believe though that if you look around in Apache/Guava libraries, you'll find an existing implementation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-21T10:35:49.333", "Id": "78203", "ParentId": "44309", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T23:30:10.823", "Id": "44309", "Score": "6", "Tags": [ "java", "strings", "exception", "immutability" ], "Title": "Insert a character into a string" }
44309
<p>I'm creating a location-based reminder application in Android using proximity alerts, geocoder, Google Maps API and their Places API.</p> <p>Currently there is a default <code>ListView</code> using a Cardlibs library and a button for a new reminder, which then asks for the 'subject' and 'location'. There is a button for a map to allow the user to select a location from the map instead. </p> <p>Then there is a "submit" button which sends a custom object called <code>Reminder</code> to the activity with the <code>ListView</code>.</p> <p>The <code>ListView</code> Activity (<code>MainActivity</code>) is however separated into two fragments <code>HomeFragment</code> and <code>WorkFragmen</code> for respective 'profiles'. So far I haven't thought of a way to save the data, but I'm most likely heading to use SQLite.</p> <p>Anyhow, this means that I'm questioning any use for this custom <code>Reminder</code> object if I'm just going to be inputting the metadata into a database anyway.</p> <p>Is there a better way I could do this, and to quickly look over my code for the <code>Reminder</code> object and profiles (as I think the fragments could just extend a standard 'base' fragment as I'm duplicating code)?</p> <p><strong>Reminder:</strong></p> <pre><code>public class Reminder implements Parcelable { public double latitude; public double longitude; public String subject; public String locationName; public String profile; public Reminder() { } public Reminder(Parcel in) { String[] data = new String[5]; in.readStringArray(data); this.subject = data[0]; this.locationName = data[1]; this.latitude = Double.parseDouble(data[2]); this.longitude = Double.parseDouble(data[3]); this.profile = data[4]; } public String getProfile() { return profile; } public double getLatitude() { return latitude; } public String getLocationName() { return locationName; } public double getLongitude() { return longitude; } public String getSubject() { return subject; } public void setProfile(String profile) { this.profile = profile; } public void setLatitude(double latitude) { this.latitude = latitude; } public void setLocationName(String locationName) { this.locationName = locationName; } public void setLongitude(double longitude) { this.longitude = longitude; } public void setSubject(String subject) { this.subject = subject; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeStringArray(new String[] { this.subject, this.locationName, String.valueOf(this.latitude), String.valueOf(this.longitude), this.profile }); } public static final Parcelable.Creator&lt;Reminder&gt; CREATOR = new Parcelable.Creator&lt;Reminder&gt;() { public Reminder createFromParcel(Parcel source) { // TODO Auto-generated method stub return new Reminder(source); // using parcelable constructor } public Reminder[] newArray(int size) { // TODO Auto-generated method stub return new Reminder[size]; } }; } </code></pre> <p><strong>List using a fragment:</strong></p> <pre><code>public class HomeFragment extends Fragment { public static ArrayList&lt;Card&gt; cards = new ArrayList&lt;Card&gt;(); Reminder reminder; public HomeFragment() { } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); reminder = getActivity().getIntent().getParcelableExtra("reminder"); Card card = new Card(getActivity()); CardHeader cardHeader = new CardHeader(getActivity()); if (reminder != null) { cardHeader.setTitle(reminder.getSubject()); card.addCardHeader(cardHeader); card.setTitle(reminder.getLocationName()); cards.add(card); } CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(getActivity(), cards); CardListView listView = (CardListView) getActivity().findViewById(R.id.card_list); mCardArrayAdapter.notifyDataSetChanged(); if (listView != null) listView.setAdapter(mCardArrayAdapter); } </code></pre>
[]
[ { "body": "<h2>Reminder</h2>\n\n<ul>\n<li><p>there is no reason to have your Reminder fields <code>latitude</code>, <code>longitude</code>, .... as public fields, and there are good reasons to keep them private. You already have the getters and setters for them.</p></li>\n<li><p>The Parcelable constructor should also be private. It will never be called from outside your class (unless you have tests, or something, but that can be solved in a different way).</p></li>\n<li><p>In the Parcelable constructor you pre-define the size of the String array then call <code>readStringArray(...)</code>. You should instead be using <code>createStringArray()</code>.</p>\n\n<p>The reality is that you should actually be doing the following:</p>\n\n<pre><code>@Override\npublic void writeToParcel(Parcel dest, int flags) {\n\n dest.writeString(this.subject);\n dest.writeString(this.locationName);\n dest.writeDouble(this.latitude);\n dest.writeDouble(this.longitude);\n dest.writeString(this.profile);\n}\n</code></pre>\n\n<p>then, in the Parcel constructor you should have:</p>\n\n<pre><code>public Reminder(Parcel in) {\n this.subject = in.readString();\n this.locationName = in.readString();\n this.latitude = in.readDouble();\n this.longitude = in.readDouble();\n this.profile = in.readString();\n}\n</code></pre></li>\n</ul>\n\n<h2>Data Storage</h2>\n\n<p>The best way to store your data will depend on the system you choose to store it in.</p>\n\n<p>Right now you are undecided. That's OK.</p>\n\n<p>Your Reminder class is flexible enough for it not to matter right now. You can adapt at the time it happens.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T04:49:48.657", "Id": "76862", "Score": "0", "body": "I didn't see createStringArray - Thanks. But currently whenever the application is destroyed, the data is removed - The proximity alerts seem to stay but I'm hoping to save the data so they can then further edit each reminder if need be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T04:51:03.477", "Id": "76863", "Score": "0", "body": "@abstrakt I am not suggesting that you don't need to store the data. I am suggesting that the best way to store the data depends on where you want to store it.... and, until you decide, I can't help." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T02:29:48.617", "Id": "44316", "ParentId": "44314", "Score": "3" } } ]
{ "AcceptedAnswerId": "44316", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T01:40:59.220", "Id": "44314", "Score": "4", "Tags": [ "java", "object-oriented", "android", "database" ], "Title": "Location-based reminder application" }
44314
<p>I have a method that reverse each word in a string. I want to know how I can increase it's performance and memory efficiency. Ideas I had in mind were simply using <code>char[]</code> instead of strings being that strings are immutable and each time I concatenate the Strings, I am creating a new String object which is not efficient at all.</p> <p>Example:</p> <pre><code>hi there cow --&gt; ih ereht woc </code></pre> <p>Code:</p> <pre><code>public static String reverseWord(String str) { int len = str.length(); String strResult = ""; String strBuffer = ""; for (int i = 0; i &lt; len; i++) { if (str.charAt(i) != ' ') { strBuffer = str.charAt(i) + strBuffer; } else if (str.charAt(i) == ' ') { strResult += strBuffer + " "; strBuffer = ""; } } strResult += strBuffer; return strResult; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T06:05:24.130", "Id": "76869", "Score": "0", "body": "possible duplicate of [Reversing words in a string](http://codereview.stackexchange.com/questions/37364/reversing-words-in-a-string)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T06:12:09.907", "Id": "76871", "Score": "0", "body": "@JamesKhoury This question seeks to reverse the characters within each word. The other question seeks to reverse the words within a sentence." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T06:14:54.037", "Id": "76872", "Score": "0", "body": "@200_success You're right. I had missed that distinction." } ]
[ { "body": "<ol>\n<li><blockquote>\n <p>Ideas I had in mind were simply using char[] instead of strings being that strings are immutable and each time I concatenate the Strings, I am creating a new String object which is not efficient at all.</p>\n</blockquote>\n\n<p>Yes, that will be faster. Go ahead and write it :-)</p></li>\n<li><p>Instead of <code>String</code>s like <code>strResult</code> and <code>strBuffer</code> you could use <code>StringBuilder</code>s (although using char is probably faster). <code>StringBuilder</code> is mutable and would be faster than using <code>String</code>s. <code>StringBuilder</code> also supports <code>insert(offset, char)</code> but also has a <code>reverse</code> method.</p></li>\n<li><p>I'd rename <code>strResult</code> to <code>result</code> (to avoid Hungarian notation) and <code>strBuffer</code> to the more descriptive <code>currentWord</code>.</p></li>\n<li><blockquote>\n<pre><code>if (str.charAt(i) != ' ') {\n ...\n}\nelse if (str.charAt(i) == ' ') {\n ...\n}\n</code></pre>\n</blockquote>\n\n<p>The following is the same, you don't need the second, inverted condition:</p>\n\n<pre><code>if (str.charAt(i) != ' ') {\n ...\n} else {\n ...\n}\n</code></pre></li>\n<li><p>You might want to use a more another check for spaces. Currently it handles tabs (<code>\\t</code>) as normal characters and</p>\n\n<pre><code>\"hi\\tthere\\tcow\"\n</code></pre>\n\n<p>will be</p>\n\n<pre><code>\"woc\\tereht\\tih\"\n</code></pre></li>\n</ol>\n\n<p>Here is a slightly improved version with <code>StringBuilder</code>s:</p>\n\n<pre><code>public static String reverseWord(String str) {\n int len = str.length();\n StringBuilder result = new StringBuilder();\n StringBuilder currentWord = new StringBuilder();\n for (int i = 0; i &lt; len; i++) {\n if (str.charAt(i) != ' ') {\n currentWord.insert(0, str.charAt(i));\n } else {\n result.append(currentWord).append(\" \");\n currentWord.setLength(0);\n }\n }\n result.append(currentWord);\n return result.toString();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T06:18:50.727", "Id": "44322", "ParentId": "44320", "Score": "6" } }, { "body": "<p>Your instincts are correct: the current solution is terribly inefficient. You'll do approximately one string concatenation for each character in the input string. Each such concatenation would involve allocating a new string and copying the previous characters. The running time is O(<em>m n</em>), where <em>m</em> is the average word length and <em>n</em> is the total number of characters.</p>\n\n<p>That said, your algorithm has the advantage of being easy to understand. For a short string such as \"hi there cow\", efficiency doesn't really matter. Sometimes a simple but inefficient algorithm is preferable.</p>\n\n<p><code>strBuffer</code> is an unfortunately confusing name for a <code>String</code>, as it suggests that it would be a <code>StringBuffer</code>.</p>\n\n<p>Converting your algorithm to use a <code>StringBuilder</code> or <code>StringBuffer</code> would be a slight improvement, but it would still be inefficient, since <code>stringBuilder.insert(0, …)</code> would result in a lot of characters having to be shifted over. It would still be O(<em>m n</em>).</p>\n\n<p>For efficiency, swapping characters within a <code>char[]</code> array is definitely the way to go. To implement that, I suggest defining a helper function</p>\n\n<pre><code>/**\n * Reverses the characters of buf, resulting in the characters between\n * start (inclusive) and end (exclusive) get swapped.\n */\nprivate static void reverseChar(char[] buf, int start, int end) {\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T14:37:54.253", "Id": "76939", "Score": "0", "body": "Quick note for OP: `StringBuffer` is for multithread accessing and `StringBuilder` is single thread operation. Synchronization have a good impact on performance, so `StringBuilder` is normally preferred in single thread environment." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T06:51:03.030", "Id": "44323", "ParentId": "44320", "Score": "5" } }, { "body": "<p>I literally fell asleep with an answer mostly built.... and now that 200_success and palacsint have covered pretty much my complete answer.</p>\n\n<p>I have to reiterate though that the use of <code>strBuffer = str.charAt(i) + strBuffer;</code> will be your worst performance culprit.</p>\n\n<p>Also, (as I learned recently), your code will not handle surrogate Unicode characters well (it will reverse and thus break them). So, I had put together some code which I believe will be much faster than yours, it will handle space and punctuation in a very different way to yours, and it will correctly <em>not</em> reverse surrogate pairs in the text.</p>\n\n<p>The reason this code will be faster is because it converts the input String to a single char array, and it does not create any other objects until the end, when it converts the array back to the output String.</p>\n\n<pre><code>public class WordRev {\n\n public static void main(String[] args) {\n String[] phrases = { \"Hello World!!\", \" Bilbo Bagginses\",\n \"Pair\\uD800\\uDC00Pair\" };\n\n for (String p : phrases) {\n System.out.print(p + \" -&gt; \");\n System.out.println(wordReverse(p));\n }\n }\n\n private static final boolean isWordChar(final char ch) {\n return Character.isLetterOrDigit(ch) || Character.isSurrogate(ch);\n }\n\n private static final String wordReverse(final String p) {\n char[] chars = p.toCharArray();\n int wordstart = 0;\n while (wordstart &lt; chars.length) {\n while (wordstart &lt; chars.length &amp;&amp; !isWordChar(chars[wordstart])) {\n wordstart++;\n }\n int wordend = wordstart + 1;\n boolean hasSurrogate = false;\n while (wordend &lt; chars.length &amp;&amp; isWordChar(chars[wordend])) {\n if (Character.isSurrogate(chars[wordend])) {\n hasSurrogate = true;\n }\n wordend++;\n }\n if (wordend - 1 &gt; wordstart) {\n // reverse between.\n int mid = wordstart + (wordend - wordstart - 1) / 2;\n int midoff = (wordend - wordstart - 1) &amp; 1;\n for (int i = mid - wordstart; i &gt;= 0; i--) {\n char tmp = chars[mid - i];\n chars[mid - i] = chars[mid + midoff + i];\n chars[mid + midoff + i] = tmp;\n }\n if (hasSurrogate) {\n for (int i = wordstart + 1; i &lt; wordend; i++) {\n if (Character.isLowSurrogate(chars[i - 1])\n &amp;&amp; Character.isHighSurrogate(chars[i])) {\n char tmp = chars[i];\n chars[i] = chars[i - 1];\n chars[i - 1] = tmp;\n }\n }\n }\n }\n wordstart = wordend + 1;\n }\n return new String(chars);\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:56:39.920", "Id": "76960", "Score": "0", "body": "wow you really went over the top with this and i appreciate it! i thought about surrogate pairs but decided to ignore these cases due to my lack of understanding in concepts." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:56:59.667", "Id": "44339", "ParentId": "44320", "Score": "4" } } ]
{ "AcceptedAnswerId": "44339", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T05:28:10.453", "Id": "44320", "Score": "7", "Tags": [ "java", "performance", "strings" ], "Title": "Reverse word by word efficiency" }
44320
<p>Could you please see if they are no bugs in this implementation? I am especially interested in knowing if there could be here any multithreading problems (such as race conditions).</p> <p>It is written in C# for .NET 3.5.</p> <pre><code>public interface IAsyncOperation { OperationToken Token { get; } bool IsCompleted { get; } Exception Exception { get; } bool Wait(int timeout); } public interface IAsyncOperation&lt;out TResult&gt; : IAsyncOperation { TResult Result { get; } } /// &lt;summary&gt; /// Asynchronous operation that may be executed on a separate thread. /// IsCompleted and Exception would be synchronized after invoking Wait. /// &lt;/summary&gt; public abstract class AsyncOperation : IAsyncOperation { protected readonly object CompletionLock = new object(); private volatile bool isCompleted; // volatile in order not to change the order of writing Exception and Result protected AsyncOperation(bool isCompleted = false) { IsCompleted = isCompleted; Token = OperationToken.New(); } public OperationToken Token { get; protected set; } public bool IsCompleted { get { return isCompleted; } protected set { isCompleted = value; } } public Exception Exception { get; protected set; } public bool Wait(int timeout) { if (!IsCompleted) { lock (CompletionLock) { if (!IsCompleted) { // when migrated to .NET 4.5 then implement with ManualResetEventSlim Monitor.Wait(CompletionLock, timeout); } } } return IsCompleted; } protected void Complete() { if (IsCompleted) { throw new InvalidOperationException("The operation was already completed"); } lock (CompletionLock) { if (IsCompleted) { throw new InvalidOperationException("The operation was already completed"); } IsCompleted = true; Monitor.PulseAll(CompletionLock); } } protected void Complete(Exception exception) { if (!IsCompleted) { lock (CompletionLock) { if (!IsCompleted) { Exception = exception; IsCompleted = true; Monitor.PulseAll(CompletionLock); } } } } } public abstract class AsyncOperation&lt;TResult&gt; : AsyncOperation, IAsyncOperation&lt;TResult&gt; { protected AsyncOperation(bool isCompleted = false) : base(isCompleted) { } public TResult Result { get; private set; } protected void Complete(TResult result) { if (!IsCompleted) { lock (CompletionLock) { if (!IsCompleted) { Result = result; IsCompleted = true; Monitor.PulseAll(CompletionLock); } } } } } /// &lt;summary&gt; /// Invokes the action on the ThreadPool. /// &lt;/summary&gt; public class PooledOperation : AsyncOperation { private readonly Action&lt;OperationToken&gt; action; private bool isStarted; public PooledOperation(Action&lt;OperationToken&gt; action) { this.action = action; ThreadPool.QueueUserWorkItem(Execute); } public static IAsyncOperation&lt;TResult&gt; Run&lt;TResult&gt;(Func&lt;OperationToken, TResult&gt; function) { var result = new PooledOperation&lt;TResult&gt;(function); result.Start(); return result; } public static IAsyncOperation Run(Action&lt;OperationToken&gt; action) { var result = new PooledOperation(action); result.Start(); return result; } public void Start() { if (!isStarted) { isStarted = ThreadPool.QueueUserWorkItem(Execute); } } private void Execute(object state) { try { action(Token); Complete(); } catch (Exception ex) { Complete(ex); } } } public class PooledOperation&lt;TResult&gt; : AsyncOperation&lt;TResult&gt; { private readonly Func&lt;OperationToken, TResult&gt; function; public PooledOperation(Func&lt;OperationToken, TResult&gt; function) { this.function = function; } public void Start() { if (!IsCompleted) { ThreadPool.QueueUserWorkItem(Execute); } } private void Execute(object state) { try { TResult result = function(Token); Complete(result); } catch (Exception ex) { Complete(ex); } } } /// &lt;summary&gt; /// Used in own ThreadPool-like implementation. /// &lt;/summary&gt; internal class AsyncCommand : AsyncOperation { private readonly Action&lt;OperationToken&gt; command; public AsyncCommand(Action&lt;OperationToken&gt; command) { command.ThrowIfNull("command"); this.command = command; } public void Execute() { if (IsCompleted) { throw new InvalidOperationException("The operation was already completed"); } try { command(Token); Complete(); } catch (Exception ex) { Complete(ex); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T14:35:11.427", "Id": "76937", "Score": "0", "body": "As far as you can tell, does the code seem to work as expected?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:33:15.367", "Id": "76949", "Score": "2", "body": "Yes, it looks like it is working fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:39:23.370", "Id": "76952", "Score": "2", "body": "Good! I was just making sure, since the site's scope isn't to *debug non-working code* (see [help/on-topic] for more info)." } ]
[ { "body": "<ol>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>protected void Complete()\n{\n if (!IsCompleted)\n {\n lock (CompletionLock)\n {\n if (!IsCompleted)\n {\n IsCompleted = true;\n Monitor.PulseAll(CompletionLock);\n }\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>I guess if a client/subclass calls <code>Complete()</code> twice it's an error in the client code. You may want to fail early and throw an exception. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p>\n\n<p>Inverting the first condition and <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow\">using a guard clause</a> also would make the code more flatten:</p>\n\n<pre><code>protected void Complete()\n{\n if (IsCompleted)\n {\n throw new ...;\n }\n lock (CompletionLock)\n {\n if (IsCompleted)\n {\n throw new ...;\n }\n IsCompleted = true;\n Monitor.PulseAll(CompletionLock);\n }\n}\n</code></pre>\n\n<p>You could extract a <code>CheckNotCompleted</code> method here to remove some duplicateion:</p>\n\n<pre><code>protected void Complete()\n{\n CheckNotCompleted();\n lock (CompletionLock)\n {\n CheckNotCompleted();\n IsCompleted = true;\n Monitor.PulseAll(CompletionLock);\n }\n}\n\nprivate void CheckNotCompleted() \n{\n if (IsCompleted)\n {\n throw new ...;\n }\n}\n</code></pre></li>\n<li><p>I'd consider using composition instead of inheritance. <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em> is a good resource about that. </p></li>\n<li><p>The code reminds me <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html\" rel=\"nofollow\"><code>Future</code></a>s and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html\" rel=\"nofollow\"><code>Executor</code></a>s from Java.</p>\n\n<p>In Java, you can create an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html\" rel=\"nofollow\"><code>ExecutorService</code></a> with <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html\" rel=\"nofollow\"><code>Executors.newFixedThreadPool()</code></a> (and with many other methods).</p>\n\n<pre><code>int threadNumber = 1;\nExecutorService executorService = Executors.newFixedThreadPool(threadNumber);\n</code></pre>\n\n<p>Then you can submit a <code>task</code> instance which implements <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html\" rel=\"nofollow\"><code>Runnable</code></a> or <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html\" rel=\"nofollow\"><code>Callable</code></a> which will be run on another thread and you get a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html\" rel=\"nofollow\"><code>Future</code></a> instance immediately:</p>\n\n<pre><code>Future future = executorService.submit(task);\n</code></pre>\n\n<p><code>Future</code> has <code>isDone()</code> and <code>get(timeout, timeUnit)</code> methods which are very similar to your <code>IsCompleted</code> and <code>Wait</code> methods.</p>\n\n<p>I feel that I've lost a little bit in the C# classes (I'm not too familiar with C#) but I hope the design of <code>Future</code> could give you some ideas.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T22:09:32.090", "Id": "77063", "Score": "0", "body": "Thanks for good comments!\n1. I was thinking of it by my own and now I am sure that it is a good idea.\n2. I agree with the concept but I do not know how I could implement it using composition with having good encapsulation (I do not want the `Complete` method to be public). I have subclasses that for example has an additional generic `TResult Result` property or implementation using Thread, ThreadPool, custom own ThreadPool. Do you want me to post more code for the review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T22:18:50.697", "Id": "77066", "Score": "1", "body": "@Pellared: Feel free to share more code. `public` does not hurt, you can have an instance in a private field which is not known by any other class, so noone could call its public methods (so it's safe)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T21:04:05.827", "Id": "77452", "Score": "1", "body": "I have added the code. Thanks for involvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T22:04:42.697", "Id": "77466", "Score": "1", "body": "@Pellared: Answer updated, I hope it helps." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:41:12.403", "Id": "44365", "ParentId": "44326", "Score": "5" } } ]
{ "AcceptedAnswerId": "44365", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T07:52:05.843", "Id": "44326", "Score": "6", "Tags": [ "c#", "multithreading" ], "Title": "Simple asynchronous operation implementation" }
44326
<p>I've been programming for about 4 months now, just trying to learn by myself. I've tried my way with coding the Game of Life here, would like some general feedback as well as some pointers on how I can speed it up because right now it seems to run incredibly slowly. Keep in mind I'm a newbie so I would like some easy ways to optimize it.</p> <p>Both positive and negative feedback are very welcome.</p> <p>Here's the complete code:</p> <pre><code>public partial class MainFom : Form { Grid formGrid; CancellationTokenSource tokenSrc = new CancellationTokenSource(); public MainFom() { InitializeComponent(); } private void MainFom_Load(object sender, EventArgs e) { formGrid = new Grid(); } private void MainFom_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawImage(formGrid.toBitmap(), 0, 0); e.Graphics.Dispose(); } private void startBtn_Click(object sender, EventArgs e) { Task tempTask = Task.Factory.StartNew( (x) =&gt; { while (!tokenSrc.IsCancellationRequested) { formGrid.UpdateGrid(); Graphics graphics = this.CreateGraphics(); graphics.Clear(this.BackColor); graphics.DrawImage(formGrid.toBitmap(), 0, 0); graphics.Dispose(); } }, tokenSrc); startBtn.Hide(); Button stopBtn = new Button() { Text = "Stop", Location = startBtn.Location, Size = startBtn.Size }; this.Controls.Add(stopBtn); stopBtn.Click += new EventHandler( (x, y) =&gt; { tokenSrc.Cancel(); stopBtn.Hide(); startBtn.Show(); tempTask.Wait(); tokenSrc = new CancellationTokenSource(); }); } } </code></pre> <hr> <pre><code>class Grid { #region Properties/Fields const int MAX_CELLS_X = 41*2;//41; const int MAX_CELLS_Y = 35*2;//35; Random RNG = new Random(); CellCollection cells; #endregion public Grid() { //Initialize grid (both frontend and backend) cells = new CellCollection(); for (int x = 0; x &lt; MAX_CELLS_X; x++) { int XCord = 10 * (x + 1); for (int y = 0; y &lt; MAX_CELLS_Y; y++) { int YCord = 10 * (y + 1); Point point = new Point(XCord, YCord); if (RNG.Next(100) &lt; 7) { // 10% chance of initial seed creating a live cell cells.Add(new Cell(new Rectangle(point, new Size(10, 10)), point) { isAlive = true }); } else { cells.Add(new Cell(new Rectangle(point, new Size(10, 10)), point)); } } } } public void UpdateGrid() { //Create copy of cells since all changes must be done simultaneously CellCollection copy = cells; for (int i = 0; i &lt; copy.Count; i++) { //Rule 1: Any live cell with fewer than two live neighbours dies, as if caused by under-population. if (cells[i].isAlive &amp;&amp; cells.GetNeighbours(cells[i]).Length &lt; 2) { copy[i].Kill(); } //Rule 2: Any live cell with more than three live neighbours dies, as if by overcrowding. if (cells[i].isAlive &amp;&amp; cells.GetNeighbours(cells[i]).Length &gt; 3) { copy[i].Kill(); } //Rule 3: Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. if (!cells[i].isAlive &amp;&amp; cells.GetNeighbours(cells[i]).Length == 3) { cells[i].Alive(); } } // Now that all cells are changed we can copy those changes simulatenously by copying the copy back to the original cells = copy; } public Bitmap toBitmap() { Bitmap gridBmp = new Bitmap(1000, 1000); // TODO: Find optimal size for bmp using (Graphics gfxObj = Graphics.FromImage(gridBmp)) { // Draw grid here and Dispose() on Pen, gfxObj is implicitly disposed Pen myPen = new Pen(Color.LightGray); SolidBrush myBrush = new SolidBrush(Color.Black); foreach (var cell in cells) { if (!cell.isAlive) { gfxObj.DrawRectangle(myPen, cell.rect); } else { gfxObj.FillRectangle(myBrush, cell.rect); } } myPen.Dispose(); } return gridBmp; } } </code></pre> <hr> <pre><code>class CellCollection : List&lt;Cell&gt; { public Cell[] GetNeighbours(Cell cell) { List&lt;Cell&gt; neighbours = new List&lt;Cell&gt;(); foreach (Cell entry in this) { //Top row if(entry.point.Y.Equals(cell.point.Y - 10)) { if (entry.point.X.Equals(cell.point.X-10) || entry.point.X.Equals(cell.point.X) || entry.point.X.Equals(cell.point.X+10)) { if (entry.isAlive) { neighbours.Add(entry); } } } // Middle row if (entry.point.Y.Equals(cell.point.Y)) { if (entry.point.X.Equals(cell.point.X - 10) || entry.point.X.Equals(cell.point.X + 10)) { if (entry.isAlive) { neighbours.Add(entry); } } } //Bottom row if (entry.point.Y.Equals(cell.point.Y + 10)) { if (entry.point.X.Equals(cell.point.X - 10) || entry.point.X.Equals(cell.point.X) || entry.point.X.Equals(cell.point.X + 10)) { if (entry.isAlive) { neighbours.Add(entry); } } } } return neighbours.ToArray(); } } </code></pre> <hr> <pre><code>class Cell { public bool isAlive { get; set; } public Rectangle rect { get; set; } public readonly Point point; public Cell(Rectangle rect, Point point) { this.rect = rect; this.point = point; } public void Alive() { isAlive = true; } public void Kill() { isAlive = false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:10:52.610", "Id": "76912", "Score": "0", "body": "I updated my answer after you accepted it, to point out another bug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:19:00.670", "Id": "76943", "Score": "2", "body": "If you want to improve your performance iteratively, use a profiler, find the slowest thing, optimize that. If you want to improve your performance *massively*, use Gosper's Algorithm, but keep in mind that Gosper's Algorithm is hard to understand and implement unless you have a good grasp on immutable types and memoization. Gosper's Algorithm can easily do boards of a quadrillion cells and calculate trillions of generations per second, which sounds impossible but it is not!" } ]
[ { "body": "<p>It looks well-written.</p>\n\n<hr>\n\n<p>You're hard-coding <code>10</code> in several places. What if you want to change it to <code>12</code>, or (worse) to <code>12.33333</code>? Instead of storing <code>Rect</code> and <code>Point</code> in <code>Cell</code>, I'd suggest storing the zero-based <code>x</code> and <code>y</code> grid coordinate of the cell: that makes your <code>UpdateGrid</code> calculation easier. <code>point</code> and <code>rect</code> can be a property of <code>Cell</code>, calculated on-the-fly ...</p>\n\n<pre><code>Point point { get { return new Point(this.x * 10, this.y * 10); } }\n</code></pre>\n\n<p>... or initialized in the Cell constructor:</p>\n\n<pre><code>Point point;\nint x;\nint y;\npublic Cell(int x, int y)\n{\n this.x = x;\n this.y = y;\n this.point = new Point(this.x * 10, this.y * 10);\n}\n</code></pre>\n\n<hr>\n\n<p>In C# the convention is to use PascalCase instead of camelCase: so <code>IsAlive</code> instead of <code>isAlive</code> etc.</p>\n\n<hr>\n\n<p>To make it faster, currently you are calling the GetNeighbours method several times for each cell, which is a waste:</p>\n\n<pre><code> for (int i = 0; i &lt; copy.Count; i++)\n {\n //Rule 1: Any live cell with fewer than two live neighbours dies, as if caused by under-population.\n if (cells[i].isAlive &amp;&amp; cells.GetNeighbours(cells[i]).Length &lt; 2)\n {\n copy[i].Kill();\n }\n //Rule 2: Any live cell with more than three live neighbours dies, as if by overcrowding.\n if (cells[i].isAlive &amp;&amp; cells.GetNeighbours(cells[i]).Length &gt; 3)\n {\n copy[i].Kill();\n }\n //Rule 3: Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n if (!cells[i].isAlive &amp;&amp; cells.GetNeighbours(cells[i]).Length == 3)\n {\n cells[i].Alive();\n }\n }\n</code></pre>\n\n<p>It would be better to call that method only once:</p>\n\n<pre><code> for (int i = 0; i &lt; copy.Count; i++)\n {\n int countNeighbours = cells.GetNeighbours(cells[i]).Length;\n //Rule 1: Any live cell with fewer than two live neighbours dies, as if caused by under-population.\n if (cells[i].isAlive &amp;&amp; countNeighbours &lt; 2)\n {\n copy[i].Kill();\n }\n //Rule 2: Any live cell with more than three live neighbours dies, as if by overcrowding.\n if (cells[i].isAlive &amp;&amp; countNeighbours &gt; 3)\n {\n copy[i].Kill();\n }\n //Rule 3: Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n if (!cells[i].isAlive &amp;&amp; countNeighbours == 3)\n {\n cells[i].Alive();\n }\n }\n</code></pre>\n\n<p>Your GetNeighbours returns a List but it only needs to return an integer count.</p>\n\n<p>Your GetNeighbours searches the whole grid for neighbours; it could just find them instead:</p>\n\n<pre><code>// position of this cell\nint x = cell.x;\nint y = cell.y;\nreturn\n // row above\n IsAlive(x - 1, y - 1) +\n IsAlive(x, y - 1) +\n IsAlive(x + 1, y - 1) +\n // left and right on this row\n IsAlive(x - 1, y) +\n IsAlive(x + 1, y) +\n // row below\n IsAlive(x - 1, y + 1) +\n IsAlive(x, y + 1) +\n IsAlive(x + 1, y + 1);\n\nbool IsAlive(int x, int y)\n{\n // x and/or y might be off the board\n if ((x &lt; 0) || (y &lt; 0) || (x &gt;= MAX_CELLS_X) || (y &gt;= MAX_CELLS_Y))\n // no cell here therefore not alive\n return false;\n // find the cell at (x,y)\n int index = (y * MAX_CELLS_X) + x;\n Cell found = this[index];\n return found.isAlive;\n}\n</code></pre>\n\n<hr>\n\n<p>It would be more conventional to model the Grid as a two-dimensional array than as a one-dimensional list.</p>\n\n<p>Grid probably shouldn't be a subclass of (i.e. inherit from) List: at most it should contain a List as a data member.</p>\n\n<hr>\n\n<p>You should Dispose your SolidBrush as well as your Pen: do that with further <code>using</code> statements.</p>\n\n<hr>\n\n<p>This doesn't create a copy:</p>\n\n<pre><code>//Create copy of cells since all changes must be done simultaneously\nCellCollection copy = cells;\n</code></pre>\n\n<p>It creates a variable named <code>copy</code> which is a reference to the same CellCollection as <code>cells</code>.</p>\n\n<p>To create a copy, given that CellCollection is a List, define a 'copy constructor' ...</p>\n\n<pre><code>CellCollection(CellCollection copyFrom)\n // invoke this List constructor:\n // http://msdn.microsoft.com/en-us/library/fkbw11z0(v=vs.110).aspx\n : base(copyFrom)\n{\n}\n</code></pre>\n\n<p>... and invoke it e.g. like this:</p>\n\n<pre><code>CellCollection copy = new CellCollection(cells);\n</code></pre>\n\n<p>There's a typo in your rule #3 processing: you set aliveness of <code>cell</code> instead of <code>copy</code>.</p>\n\n<hr>\n\n<p>Beware making all your properties settable; for example, your API allows callers to set the isAlive and rect properties:</p>\n\n<pre><code>public bool isAlive { get; set; }\npublic Rectangle rect { get; set; }\n</code></pre>\n\n<p>Why have Alive and Kill methods if callers can also/instead set the isAlive property directly? And do you want callers to change the rect property after the cell has been constructed?</p>\n\n<p>Some people (e.g. people who use scripting languages) like a permissive API which allows you to do as much as possible; conversely there's also something to be said for a restrictive API which lets you do as little as possible i.e. only what is necessary and no more: for example if I have no need to change the rect after the Cell is constructed then I don't define an API which permits that.</p>\n\n<hr>\n\n<p>I just noticed that even making a copy of the grid isn't enough: because the copied list would contain the same Cell instances as the original list. You can fix that:</p>\n\n<ul>\n<li>By making a copy (using <code>new Cell</code>) of each Cell as you copy it into the new List</li>\n<li>Or by saying that Cell is a struct instead of a class</li>\n<li>Or by giving up on the idea of copying Cells, and adding a new property like <code>bool NextGenerationAliveness</code> which you initialize in UpdateGrid: a) walk through the grid using IsAlive to set NextGenerationAliveness b) walk through the list again to set IsAlive = NextGenerationAliveness.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:59:23.070", "Id": "44334", "ParentId": "44327", "Score": "7" } }, { "body": "<p>Some quick comments:</p>\n\n<ul>\n<li>Syntax: coord[inate], not \"cord\".</li>\n<li>PascalCase is for public properties/fields, local variables should use camelCase: <code>int xCoord = 9001;</code></li>\n</ul>\n\n<h1>I spot a bug</h1>\n\n<pre><code>//Create copy of cells since all changes must be done simultaneously\nCellCollection copy = cells;\n</code></pre>\n\n<p>I do not think this does what you think it does.</p>\n\n<h1>Cache calculations</h1>\n\n<p>Don't redo this 3 times, once for each of the successive ifs: <code>cells.GetNeighbours(cells[i]).Length</code>.</p>\n\n<h1>Make CellCollection a <code>Cell[][]</code></h1>\n\n<p>Instead of a <code>List&lt;Cell&gt;</code>. Because:</p>\n\n<ol>\n<li>It would make the structure match better the format of the data;</li>\n<li>It allows you to find the neighbours directly by index (x-1;y-1, x;y-1, etc) instead of travelling the whoooole list like you are doing - what if the board has <strong><a href=\"http://www.youtube.com/watch?v=cKKHSAE1gIs\">1 million</a></strong> cells?</li>\n</ol>\n\n<h1>Outdated comment...</h1>\n\n<pre><code>if(RNG.Next(100) &lt; 7)\n{ // 10% chance of initial seed creating a live cell\n</code></pre>\n\n<p>10%? Or 6?</p>\n\n<h1>Simplifications</h1>\n\n<p>instead of</p>\n\n<pre><code>for (int x = 0; x &lt; MAX_CELLS_X; x++)\n{\n int xCoord = 10 * (x + 1);\n</code></pre>\n\n<p>i'd do</p>\n\n<pre><code>for (int x = 1; x &lt;= MAX_CELLS_X; x++)\n{\n int xCoord = 10 * x;\n</code></pre>\n\n<hr>\n\n<p>And:</p>\n\n<pre><code>var cell = new Cell(new Rectangle(point, new Size(10, 10)), point);\nif (RNG.Next(100) &lt; 7)\n{\n cell.IsAlive = true;\n}\ncells.Add(cell);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>cells.Add(new Cell(new Rectangle(point, new Size(10, 10)), point) { IsAlive = RNG.Next(100) &lt; 7 });\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:14:51.010", "Id": "44336", "ParentId": "44327", "Score": "10" } } ]
{ "AcceptedAnswerId": "44334", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T08:19:08.333", "Id": "44327", "Score": "7", "Tags": [ "c#", "object-oriented", "beginner", "game-of-life" ], "Title": "Feedback on my Conway's Game of Life" }
44327
<p>To learn tree traversal i implemented <a href="http://docs.python.org/2/library/os.html#os.walk" rel="nofollow noreferrer"><code>os.walk</code></a>, <a href="http://en.wikipedia.org/wiki/Tail_call" rel="nofollow noreferrer">tail-recursive</a> and stack-based. Unfortunately Python doesn't support tail call optimization. How do i rewrite my function so that it is maximally <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="nofollow noreferrer">functional paradigm</a> compliant? I want to keep side-effects to minimum yet not dive into deep recursions.</p> <pre><code>def walk_rec(path): def i(result, stack): if not stack: return result else: path = stack.pop() with cd(path): ds, fs = partition(isdir, listdir(path)) stack.extend(join(path, d) for d in ds) result.append((path, ds, fs)) return i(result, stack) return i([], [expanduser(path)]) def walk_iter(path): stack = [expanduser(path)] result = [] while stack: path = stack.pop() with cd(path): ds, fs = partition(isdir, listdir(path)) stack.extend(join(path, d) for d in ds) result.append((path, ds, fs)) return result </code></pre> <p>See: <a href="https://stackoverflow.com/a/13197763/596361"><code>cd</code></a>, <a href="https://stackoverflow.com/a/4578605/596361"><code>partition</code></a>.</p> <p>I could get rid of <code>cd</code>, but this is not critical.</p> <pre><code>with cd(path): ds, fs = partition(isdir, listdir(path)) # can be replaced with ds, fs = partition(lambda d: isdir(join(path, d)), listdir(path)) </code></pre>
[]
[ { "body": "<p>Does this help? In your walk_iter, instead of using pop, grab the first element of the stack. Then do something like this ...</p>\n\n<pre><code>if first_element_has_sub_elements:\n new_stack = stack[0][1]\n new_stack.extend(stack[1:])\n stack = new_stack[:]\nelse:\n stack = stack[1:]\n</code></pre>\n\n<p>This was my experiment, in case it's helpful ...</p>\n\n<pre><code>TREE = [\n (\"L1A\", [(\"L1A2A\",), \n (\"L1A2B\", [(\"L1A2B3A\", )])]),\n (\"L1B\", [(\"L1B2A\", [(\"L1B2A3A\", )])]),\n (\"L1C\",),\n (\"L1D\", [(\"L1D2A\",), \n (\"L1D2B\", [(\"L1D2B3A\", ),\n (\"L1D2B3B\",)])]),\n ]\n\nEXPECTED = [\"L1A\", \"L1A2A\", \"L1A2B\", \"L1A2B3A\",\n \"L1B\", \"L1B2A\", \"L1B2A3A\", \"L1C\", \n \"L1D\", \"L1D2A\", \"L1D2B\", \"L1D2B3A\", \"L1D2B3B\"]\n\ndef traverse_tree(TREE):\n chopped_tree = TREE[:]\n results = []\n while chopped_tree:\n results.append(chopped_tree[0][0])\n if len(chopped_tree[0]) &gt; 1:\n new_tree = chopped_tree[0][1]\n new_tree.extend(chopped_tree[1:])\n chopped_tree = new_tree[:]\n else:\n chopped_tree = chopped_tree[1:]\n\n return results\n\nif __name__ == \"__main__\":\n results = traverse_tree(TREE)\n if results == EXPECTED:\n print \"OK\"\n else:\n print \"MISMATCH\"\n print \"Expected: \"\n print EXPECTED\n print \"Results: \"\n print results\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T20:42:09.910", "Id": "44398", "ParentId": "44328", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T08:34:11.007", "Id": "44328", "Score": "6", "Tags": [ "python", "functional-programming", "recursion", "tree", "stack" ], "Title": "Functional, but not recursive, tree traversal" }
44328
<p>I have a navigation controller set up with a user code and password and a log in button. When the user clicks on the Log In button or the return key on the keyboard on the password text box - the program checks if the user code and / or password is blank. It then goes off and calls a Web API running on a server to see if the user and password are valid. If it is, it goes to the next view controller - I created a segue between the two view controllers and named it.</p> <p>This now works for me but because I'm new to this I'd love if someone could have a quick look at my code and see if I am doing anything I shouldn't be doing. I'm worried about memory problems and is it good practice to disable the screen while the system waits for the web service to return.</p> <p>Any guidance would be much appreciated:</p> <pre><code> // when the user clicks the return key on the user code - the focus goes to the password - (IBAction)txtUserDidEndOnExit:(id)sender { [sender resignFirstResponder]; [_txtPassword becomeFirstResponder]; } // when the user clicks the return key on the password - it performs the click on the log in button - (IBAction)txtPasswordDidEndOnExit:(id)sender { [sender resignFirstResponder]; [_butLogin sendActionsForControlEvents:UIControlEventTouchUpInside]; } - (IBAction)butLoginClick:(id)sender { [self logIn]; } - (void) logIn { // check if the user code is blank - if it is - tell the user and stop the log in if ([self.txtUser.text length] == 0) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:@"User Required" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; alert.tag = TAG_USER; [alert show]; return; } // check if the password is blank - if it is - tell the user and stop the log in if ([self.txtPassword.text length] == 0) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:@"Password Required" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; alert.tag = TAG_PWD; // save = false; [alert show]; return; } // read the web service url from settings - if its blank tell the user and stop the log in NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString *webService = [userDefaults stringForKey:@"keyURLWebService"]; if ([webService length] == 0) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Settings Error" message:@"The settings for the Web Service URL is blank" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; return; } // disable the current view so the user can not enter in another user id / password or click on the log in button [self.view setUserInteractionEnabled:NO]; NSString *usercode = self.txtUser.text; NSString *password = self.txtPassword.text; // generate the complete url here NSString *urllink = [NSString stringWithFormat:@"%@/API/Users/GetValidateUser/?usercode=%@&amp;&amp;password=%@", webService, usercode, password]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:urllink] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSString* webresponse = [NSString stringWithUTF8String:[data bytes]]; dispatch_async(dispatch_get_main_queue(), ^(void){ if ([webresponse isEqual: @"OK"]) { [self.view setUserInteractionEnabled:YES]; [self performSegueWithIdentifier: @"PMenu" sender: self]; } else { [self.view setUserInteractionEnabled:YES]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:webresponse delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; alert.tag = TAG_USER; [alert show]; } }); }]; [dataTask resume]; } - (void)alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if (alertView.tag == TAG_USER) { [self.txtUser becomeFirstResponder]; } if (alertView.tag == TAG_PWD) { [self.txtPassword becomeFirstResponder]; } } </code></pre> <p>I've made all the suggested changes - new code below</p> <pre><code>// // ProfileAccountsViewController.m // ProfileAccounts // // Created by Profile on 12/03/2014. // Copyright (c) 2014 Profile Technology Ltd. All rights reserved. // #import "ProfileAccountsViewController.h" @interface ProfileAccountsViewController () @end @implementation ProfileAccountsViewController #define TAG_USER 1 #define TAG_PWD 2 #define TAG_SETTINGS 3 - (void)viewDidLoad { [super viewDidLoad]; self.butLogin.layer.cornerRadius = 7; [self registerForKeyboardNotifications]; [_txtUser becomeFirstResponder]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(IBAction)textFieldDidEndOnExit:(id)sender { if (sender == _txtUser) [_txtPassword becomeFirstResponder]; else if (sender == _txtPassword) { [sender resignFirstResponder]; [self logIn]; } } - (IBAction)butLoginClick:(id)sender { [self logIn]; } - (void) logIn { // check if the user code is blank - if it is - tell the user and stop the log in // If the user forgot a field int returnval = [self textFieldsAreValid]; if (returnval != 0) { NSString *alertMessage = (returnval == 1) ? @"User required" : @"Password required"; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:alertMessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; alert.tag = (_txtUser.text.length == 0) ? TAG_USER : TAG_PWD; } else { // read the web service url from settings - if its blank tell the user and stop the log in NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString *webService = [userDefaults stringForKey:@"keyURLWebService"]; if ([webService length] == 0) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Settings Error" message:@"The settings for the Web Service URL is blank" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } else { [self.activityInd startAnimating]; // disable the current view so the user can not enter in another user id / password or click on the log in button [self.view setUserInteractionEnabled:NO]; NSString *usercode = self.txtUser.text; NSString *password = self.txtPassword.text; NSString *urllink = [NSString stringWithFormat:@"%@/API/Users/GetValidateUser/?usercode=%@&amp;&amp;password=%@", webService, usercode, password]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:urllink] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSString* webresponse = [NSString stringWithUTF8String:[data bytes]]; if (error != nil) { [self handleError:error]; } dispatch_async(dispatch_get_main_queue(), ^(void){ [self.activityInd stopAnimating]; if ([webresponse isEqualToString: @"OK"]) { [self.view setUserInteractionEnabled:YES]; [self performSegueWithIdentifier: @"ProfileMenu" sender: self]; } else { [self.view setUserInteractionEnabled:YES]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:webresponse delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; alert.tag = TAG_USER; [alert show]; } }); }]; [dataTask resume]; } } } -(int)textFieldsAreValid { int wh = 0; if (_txtUser.text.length == 0){ wh = 1; } else { if (_txtPassword.text.length == 0) wh = 2; } return wh; } /** Handle errors in the download by showing an alert to the user. */ - (void)handleError:(NSError *)error { [self.activityInd stopAnimating]; NSString *errorMessage = [error localizedDescription]; NSString *alertTitle = NSLocalizedString(@"Error", @"Log In Error"); NSString *okTitle = NSLocalizedString(@"OK ", @"Log In OK"); UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle message:errorMessage delegate:nil cancelButtonTitle:okTitle otherButtonTitles:nil]; [alertView show]; } - (void)alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if (alertView.tag == TAG_USER) { [self.txtUser becomeFirstResponder]; } if (alertView.tag == TAG_PWD) { [self.txtPassword becomeFirstResponder]; } } #pragma mark - event of keyboard relative methods - (void)registerForKeyboardNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; } -(void)unregisterForKeyboardNotifications { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; // unregister for keyboard notifications while not visible. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; } - (void)keyboardWillShown:(NSNotification*)aNotification { NSDictionary* info = [aNotification userInfo]; CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; CGRect frame = _scrollView.frame; if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) { frame.size.height -= kbSize.height; }else{ frame.size.height -= kbSize.width; } CGPoint fOrigin = _activeField.frame.origin; fOrigin.y -= _scrollView.contentOffset.y; fOrigin.y += _activeField.frame.size.height; if (!CGRectContainsPoint(frame, fOrigin) ) { CGPoint scrollPoint = CGPointMake(0.0, _activeField.frame.origin.y + _activeField.frame.size.height - frame.size.height); [_scrollView setContentOffset:scrollPoint animated:YES]; } } - (void)keyboardWillBeHidden:(NSNotification*)aNotification { //[_scrollView setContentOffset:CGPointMake(0, _scrollView.contentInset.top) animated:YES]; //[_scrollView setContentOffset:CGPointZero animated:YES]; } @end </code></pre>
[]
[ { "body": "<p>Here is what I see in your code :</p>\n\n<h2>In <code>-(IBAction)txtUserDidEndOnExit:(id)sender</code></h2>\n\n<p>You don't need to <code>resignFirstResponder</code> before you make another view become first responder. Right now, the keyboard probably quickly hides/shows when you press the return key when the focus is on the first field.</p>\n\n<h2>In <code>-(IBAction)txtPasswordDidEndOnExit:(id)sender</code></h2>\n\n<p>Why use <code>sendActionsForControlEvents:</code> ? This will only trigger the method associated with the login button, which is <code>[self logIn];</code>. Simply call this, you will certainly avoid confusion if your code changes.</p>\n\n<h2>About the 2 above methods</h2>\n\n<p>You could merge those methods into a single one :</p>\n\n<pre><code>-(IBAction)textFieldDidEndOnExit:(id)sender {\n if (sender == _txtUser)\n [_txtPassword becomeFirstResponder];\n else if (sender == _txtPassword) {\n [sender resignFirstResponder];\n [self login];\n }\n}\n</code></pre>\n\n<p>You would of course need to link both your <code>UITextView</code>s to this method instead of a different method for each one. This does not reduce the line count, but it groups your actions together. Note that I didn't test it, so it <em>might</em> not work straightaway.</p>\n\n<h2>In <code>-(void)logIn</code></h2>\n\n<p><strong>Text fields checking</strong> :</p>\n\n<p>This :</p>\n\n<pre><code>// check if the user code is blank - if it is - tell the user and stop the log in\nif ([self.txtUser.text length] == 0)\n{\n UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@\"Log In Error\" message:@\"User Required\" delegate:self cancelButtonTitle:@\"OK\" otherButtonTitles:nil];\n\n alert.tag = TAG_USER;\n [alert show];\n return;\n}\n\n// check if the password is blank - if it is - tell the user and stop the log in\nif ([self.txtPassword.text length] == 0)\n{\n UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@\"Log In Error\" message:@\"Password Required\" delegate:self cancelButtonTitle:@\"OK\" otherButtonTitles:nil];\n\n alert.tag = TAG_PWD;\n // save = false;\n [alert show];\n return;\n}\n</code></pre>\n\n<p>should be in a dedicated method, like this :</p>\n\n<pre><code>-(BOOL)textFieldsAreValid {\n\n if (_txtUser.text.length == 0 || _txtPassword.text length == 0) return NO;\n\n return YES;\n}\n</code></pre>\n\n<p>so if in the future, you want to add more verifications before the login, it will be easy to do. This would make the beginning of logIn look like :</p>\n\n<pre><code>- (void) logIn {\n\n // If the user forgot a field\n if (![self textFieldsAreValid]) {\n\n NSString *alertMessage = (_txtUser.text.length == 0) ? @\"User required\" : @\"Password required\";\n\n UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@\"Log In Error\" message:alertMessage delegate:self cancelButtonTitle:@\"OK\" otherButtonTitles:nil];\n\n alert.tag = (_txtUser.text.length == 0) ? TAG_USER : TAG_PWD;\n }\n\n [...]\n</code></pre>\n\n<p>You could also imagine returning an <code>NSInteger</code> from <code>textFieldsAreValid</code>, which could be 0->fields are ok, 1->user empty, 2-> password empty, so you don't have to check <code>_txtUser.text.length == 0</code> multiple times.</p>\n\n<p><strong>Rest of the logIn method</strong></p>\n\n<p>The rest of the method should be in an <code>else { }</code> clause. It's not a good practice to <code>return</code> from a void method. You should use <code>if-else</code> in place of your <code>if-return</code>. Place the rest of the code in an <code>else</code>, and it won't be executed if a field is empty. Same goes when you test the webservice address length: use an <code>if-else</code>, don't use <code>return</code>.</p>\n\n<p>Calling <code>[self.view setUserInteractionEnabled:NO];</code> may not be the best option here. You should probably call <code>_textField.enabled = NO;</code> on each of your text fields rather than disabling the whole view.</p>\n\n<p>Also, I don't think you're providing any UI information to the user while the app is validating the credentials. This is not good, you have to let the user know that something is happening. Have a look at iOS' <a href=\"https://developer.apple.com/library/ios/documentation/userexperience/conceptual/UIKitUICatalog/UIActivityIndicatorView.html\" rel=\"nofollow noreferrer\"><code>UIActivityIndicator</code></a> class.</p>\n\n<p>Next, <code>[webresponse isEqual: @\"OK\"]</code> should be <code>[webresponse isEqualToString: @\"OK\"]</code>. There is not a big difference here, but the second one is much faster. As it says on <a href=\"https://stackoverflow.com/questions/1292862/nsstring-isequal-vs-isequaltostring\">this thread</a> :</p>\n\n<blockquote>\n <p><code>isEqual:</code> compares a string to an object, and will return NO if the object is not a string.\n <code>isEqualToString:</code> is faster if you know both objects are strings</p>\n</blockquote>\n\n<p>This will most certainly make <strong>no</strong> performance improvement here considering the strings you use, but it's a better practice to use the <code>isEqualTo&lt;Class&gt;:</code> if you know that the two objects you are comparing are from the same class. In the case of <code>isEqualToArray:</code>, you may see a big performance difference.</p>\n\n<hr>\n\n<p>Happy coding ! And if you have any questions, let me know in the comments ! :]</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:40:27.293", "Id": "76902", "Score": "1", "body": "`You could also imagine returning an NSInteger from textFieldsAreValid, which could be 0->fields are ok, 1->user empty, 2-> password empty, so you don't have to check _txtUser.text.length == 0 multiple times.` How about an enum? Or perhaps better, an `NSString`, where `nil` represents okay, and anything else is the string that represents the error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:43:05.600", "Id": "76921", "Score": "0", "body": "@nhgrif : yes, an enum would be the best here. I didn't have enough time to explain it, that's why I said an NSInteger (enums are just wrappers for this). Not sure about the NSString though, I'd say it's a bit too much for the situation.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:55:21.670", "Id": "76924", "Score": "0", "body": "@rdurand - thank you so much for your very helpful comments. Some of them - like having the one method for the did end on exit - very obvious and something I should have seen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:55:49.277", "Id": "76925", "Score": "0", "body": "@nhgrif - I made the change you suggested too - hopefully I have it right" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:30:46.120", "Id": "44337", "ParentId": "44329", "Score": "7" } }, { "body": "<p>When you have something like this in your code:</p>\n\n<pre><code>- (void)didReceiveMemoryWarning\n{\n [super didReceiveMemoryWarning];\n // Dispose of any resources that can be recreated.\n}\n</code></pre>\n\n<p>You can simply delete all 5 of these lines. The only reason to include the the stub for <code>- (void)didReceiveMemoryWarning</code> is if you're actually going to add code to the method.</p>\n\n<hr>\n\n<pre><code>int returnval\n</code></pre>\n\n<p>This variable should be renamed as <code>returnVal</code>.</p>\n\n<hr>\n\n<pre><code>#define TAG_USER 1\n#define TAG_PWD 2\n#define TAG_SETTINGS 3\n</code></pre>\n\n<p>There's no reason why this shouldn't be an enum:</p>\n\n<pre><code>typedef NS_ENUM(NSInteger, UITAGS) {\n TAG_USER 1,\n TAG_PWD 2,\n TAG_SETTINGS 3\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T01:12:34.743", "Id": "44542", "ParentId": "44329", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T09:30:14.603", "Id": "44329", "Score": "6", "Tags": [ "beginner", "objective-c", "ios", "validation", "cocoa-touch" ], "Title": "iOS App - Interface for user log in using a call to a web service API" }
44329
<p>I've created a program to calculate Pascal's triangle:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void pascal(int limit) { int *begin; begin=(int*)malloc(2*sizeof(int)); *begin=1; *(begin+1)=1; int* p,q,s,t; int row=2,n=3,x; p=begin; q=begin+1; for(n=3;n&lt;=limit+1;n++) { if(n==4) { free(begin); } x=1; printf("Row (%d) : ",row); for(int* i=p;i&amp;lt;=q;i=i+1) { printf("%d ",*i); } putchar('\n'); s=(int*)malloc(n*sizeof(int)); t=s+n-1; *s=*p; *t=*q; for(int* g=p;g&amp;lt;q;g=g+1) { *(s+x)=*g+*(g+1); x++; } p=s; q=t; row++; } } int main(void) { int i; printf("Till which row would you like to calculate the Pascal Triangle?\n\n"); printf("Type your answer:\t"); scanf("%d",&amp;i); putchar('\n'); if(i&lt;n) printf("Nope, you can't do that\n"); else { printf("Row (1) : 1\n"); pascal(i); } } </code></pre> <p>My idea was to work with 2 arrays at the same time, but there is still a problem in my algorithm. How am I supposed to free the memory I allocated before? The first 8 bytes of begin are easy to free, but what should I do so I can free the memory I allocated through the pointers?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:04:21.440", "Id": "76886", "Score": "0", "body": "Please format your code!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:09:08.350", "Id": "76887", "Score": "0", "body": "Can someone please explain to me what does \"format your code\" mean? Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:10:03.077", "Id": "76888", "Score": "0", "body": "Indent blocks, remove empty lines (if they are not needed for better reading) ... You can e.g use http://prettyprinter.de/module.php?name=PrettyPrinter" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:25:05.977", "Id": "76891", "Score": "1", "body": "Thank you so much.This is webseit is really useful.By the way is it good this way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:48:34.077", "Id": "76894", "Score": "0", "body": "How to format a code is a matter of taste, every developer likes it a bit different. But the main reason is, that the code is easier to read when the code is formatted." } ]
[ { "body": "<ul>\n<li><p>you don't free <code>s</code> which means you have a memory leak</p></li>\n<li><p><code>*(begin+1)</code> can be rewritten as <code>begin[1]</code>, which is much clearer</p></li>\n<li><p>1 char variable names are very hard to get into, use longer/descriptive names where needed</p></li>\n</ul>\n\n<p>the entire function can be rewritten as</p>\n\n<pre><code>void pascal(int limit)\n{\n\n int *row;\n row=(int*)malloc(2*sizeof(int));\n row[0]=1;\n row[1]=1;\n\n for(int n=3;n&lt;=limit+1;n++){\n\n printRow(buffer,n);\n\n int* nextRow = (int*)malloc((1+n)*sizeof(int));\n nextRow[0]=row[0];\n nextRow[n]=row[n-1];\n\n for(int i=1;i&lt;n;i++){\n nextRow[i]=row[i-1]+row[i];\n }\n free(row);\n row=nextRow;\n\n }\n}\n</code></pre>\n\n<p>instead of the malloc->assign->free sequence I could have used realloc and then worked backwards:</p>\n\n<pre><code>row = (int*)realloc(row,(1+n)*sizeof(int));\nrow[n]=0;\n\nfor(int i=n;i&gt;0;i--){\n row[i]+=row[i-1];\n}\n</code></pre>\n\n<p>but this is less clear</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T10:53:44.150", "Id": "44333", "ParentId": "44330", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T09:44:32.723", "Id": "44330", "Score": "10", "Tags": [ "c", "array", "memory-management", "pointers" ], "Title": "Pascal Triangle program in C" }
44330
<p>Just a slug generator. I'm wondering if this can be simplified any further.</p> <p>Many thanks.</p> <pre><code>&lt;?php function slug($string) { // Replace all non letters, numbers, spaces or hypens $string = preg_replace('/[^\-\sa-zA-Z0-9]+/', '', mb_strtolower($string)); // Replace spaces and duplicate hyphens with a single hypen $string = preg_replace('/[\-\s]+/', '-', $string); // Trim off left and right hypens $string = trim($string, '-'); return $string; } echo slug('-- This is an example of an ------ article - @@@ ..,.:~&amp;**%$£%$^*'); // outputs "this-is-an-example-of-an-article" </code></pre> <p>Updated version based on feedback:</p> <pre><code>&lt;?php function createSlug($slug) { $lettersNumbersSpacesHyphens = '/[^\-\s\pN\pL]+/u'; $spacesDuplicateHypens = '/[\-\s]+/'; $slug = preg_replace($lettersNumbersSpacesHyphens, '', $slug); $slug = preg_replace($spacesDuplicateHypens, '-', $slug); $slug = trim($slug, '-'); return mb_strtolower($slug, 'UTF-8'); } echo createSlug('-- This is an example ű of an ------ article - @@@ ..,.%&amp;*£%$&amp;*(*'); ?&gt; </code></pre>
[]
[ { "body": "<ol>\n<li><p>You could create a few explanatory local variables:</p>\n\n<pre><code>$lettersNumbersSpacesHypens = '/[^\\-\\sa-zA-Z0-9]+/';\n$spacesAndDuplicateHyphens = '/[\\-\\s]+/';\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$lettersNumbersSpacesHypens = '/[^\\-\\sa-zA-Z0-9]+/';\n$slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug));\n\n$spacesAndDuplicateHyphens = '/[\\-\\s]+/';\n$slug = preg_replace($spacesAndDuplicateHyphens, '-', $slug);\n</code></pre>\n\n<p>These would eliminate the comments. (I haven't checked the regexps, other names might be more appropriate.)</p>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler:</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote>\n\n<p>And <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p></li>\n<li><p><code>slug</code> could be renamed to <code>cleanSlug</code> (contains a verb) to describe what the function does.</p></li>\n<li><p>I'd rename the <code>$string</code> variable to <code>$slug</code> It would be more descriptive, it would express the intent of the variable.</p></li>\n<li><p>I'd use a whitelist instead of the blacklist. Defining the allowed characters (A-Z, 0-9 etc) would create proper URLs from URLs which contain special characters like <code>é</code> or <code>ű</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:28:34.203", "Id": "76944", "Score": "0", "body": "Thanks. I've updated my original question with some changes. Didn't notice the problem with different characters before, this has now been fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:38:49.580", "Id": "76951", "Score": "0", "body": "@AlexGarrett: You're welcome. I've updated the answer a little bit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:59:27.053", "Id": "44347", "ParentId": "44335", "Score": "5" } }, { "body": "<p>Just a small extension to what has been written. If your slug generator is not for an assignment but for actual deployment a lot of frameworks use slug helpers already. I use Laravel, however Laravel has an entire class so that might be messy.</p>\n\n<p>Before Laravel, Codeigniter was the rapid deploy system and their slug system is pretty robust.</p>\n\n<p>Take a look at the slug file. Now mind you they have formatted it into a class with a lot of comments - but if you omit everything you can compare their's and yours and see where the middle ground can be.</p>\n\n<p><a href=\"https://github.com/ericbarnes/CodeIgniter-Slug-Library/blob/master/Slug.php\" rel=\"nofollow\">Codeigniter Slug Class</a></p>\n\n<p>Note - I'm adding this extra bit because as always you shouldn't re-engineer code if its been done and done well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:30:19.850", "Id": "76947", "Score": "0", "body": "Great, thanks for the advice. I actually adapted this code from the Laravel framework. It's for education purposes, so wanted to simplify it so it's easier for beginners to grasp. But I completely agree, good hardened code shouldn't be rewritten if not necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:31:56.690", "Id": "76948", "Score": "0", "body": "I recommend the codeigniter's version instead because i had to reverse engineer it for legacy non MVC code and it works better as as stand-alone function rather than a class (once you take out the clutter)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:27:40.273", "Id": "44356", "ParentId": "44335", "Score": "2" } } ]
{ "AcceptedAnswerId": "44347", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:05:13.510", "Id": "44335", "Score": "4", "Tags": [ "php", "strings" ], "Title": "Slug URL Generator" }
44335
<p>I have a list of months in which users are required to update some data. I want to determine at what date they should have updated their data. They must update in March, May and August. If today is March, I want to get back the 1st of March. If today is February, I want to get back last year's August. In reality the list wouldn't be hardcoded.</p> <p>I do have some working code, but I wonder if there is a simpler / more elegant of writing this (the <code>GetCheckDate</code> method).</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; internal class Program { private static void Main() { var listOfMonths = new List&lt;int?&gt; {3, 5, 8}; Console.WriteLine(GetCheckDate(listOfMonths, new DateTime(2014, 2, 1))); // expect 2013-08-01 Console.WriteLine(GetCheckDate(listOfMonths, new DateTime(2014, 3, 1))); // expect 2014-03-01 Console.WriteLine(GetCheckDate(listOfMonths, new DateTime(2014, 7, 1))); // expect 2014-05-01 Console.WriteLine(GetCheckDate(null, new DateTime(2014, 7, 1))); // expect 2013-07-1 Console.WriteLine(GetCheckDate(new List&lt;int?&gt;(), new DateTime(2014, 7, 1))); // expect 2013-07-1 } private static DateTime GetCheckDate(IEnumerable&lt;int?&gt; listOfMonths, DateTime curDate) { DateTime result = curDate.AddYears(-1); if (listOfMonths == null) return result; listOfMonths = listOfMonths.ToList(); if (!listOfMonths.Any()) return result; listOfMonths = listOfMonths.OrderByDescending(m =&gt; m).ToList(); var greatestSmallerThan = listOfMonths.FirstOrDefault(m =&gt; m &lt;= curDate.Month) ?? listOfMonths.FirstOrDefault(m =&gt; m &gt; curDate.Month); result = new DateTime( greatestSmallerThan.Value &lt;= curDate.Month ? curDate.Year : curDate.Year - 1, greatestSmallerThan.Value, 1); return result; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:56:41.963", "Id": "76908", "Score": "0", "body": "What if list of months is empty?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:19:57.047", "Id": "76914", "Score": "0", "body": "This is not complete code. If the list is empty, I'll return `curDate.AddYears(-1)` (edited). What I'd like to know is how to efficiently determine the date." } ]
[ { "body": "<p>You could use <a href=\"http://msdn.microsoft.com/en-us/library/system.datetime.addmonths%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>DateTime.AddMonths</code></a> to simplify the code:</p>\n\n<pre><code>for (int i = 0; i &lt; 12; i++) {\n var checkDate = curDate.AddMonths(-i))\n if (listOfMonths.Contains(checkDate.Month)) {\n return new DateTime(checkDate.Year, checkDate.Month, 1);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:14:31.227", "Id": "44340", "ParentId": "44338", "Score": "4" } }, { "body": "<p>I suggest you to improve naming: </p>\n\n<ul>\n<li><code>months</code> instead of <code>listOfMonths</code> because its not list, and its better not to include variable type description into name </li>\n<li><code>date</code> instead of <code>curDate</code> - its better to avoid abbreviations, also current method should not care whether moth is current or not - it just search previous month from given months</li>\n<li>Possibly I would rename method to something like <code>GetPreviousMonth</code></li>\n</ul>\n\n<p>Also I don't see any need to have nullable type for months sequence. It should have integers. If month exist in list, then you can avoid sorting - so do this check first. Thus you are not going to add/remove month, then saving ordered sequence to array is little better:</p>\n\n<pre><code>public static DateTime GetCheckDate(IEnumerable&lt;int&gt; months, DateTime date)\n{\n if (month == null || !months.Any() || months.Contains(date.Month))\n return date.AddDays(1 - date.Day);\n\n var orderedMonths = months.OrderByDescending(m =&gt; m).ToArray();\n if (date.Month &gt; orderedMonths.First())\n return new DateTime(date.Year, orderedMonths.First(), 1);\n\n if (date.Month &lt; orderedMonths.Last()) \n return new DateTime(date.Year - 1, orderedMonths.First(), 1);\n\n return new DateTime(date.Year, orderedMonths.First(m =&gt; m &lt; date.Month), 1);\n}\n</code></pre>\n\n<p>But I also prefer readability on first place (performance should be improved only if its a problem) so I would go with Max and Min month instead of sorting them and keeping in mind what is Last and what is First:</p>\n\n<pre><code>public static DateTime GetCheckDate(IEnumerable&lt;int&gt; months, DateTime date)\n{\n if (month == null || !months.Any() || months.Contains(date.Month)) \n return date.AddDays(1 - date.Day); \n\n if (months.Max() &lt; date.Month)\n return new DateTime(date.Year, months.Max(), 1);\n\n if (date.Month &lt; months.Min()) \n return new DateTime(date.Year - 1, months.Max(), 1);\n\n return new DateTime(date.Year, months.Where(m =&gt; m &lt; date.Month).Max(), 1);\n}\n</code></pre>\n\n<p>If I would continue making it more readable, then following extension methods would be useful:</p>\n\n<pre><code>public static DateTime FirstDayOfMonth(this DateTime date, int month = 0)\n{\n return new DateTime(date.Year, month == 0 ? date.Month : month, 1);\n}\n\npublic static DateTime PreviousYear(this DateTime date)\n{\n return date.AddYears(-1);\n}\n</code></pre>\n\n<p>Now whole method is very easy to understand:</p>\n\n<pre><code>public static DateTime GetCheckDate(IEnumerable&lt;int&gt; months, DateTime date)\n{\n if (month == null || !months.Any() || months.Contains(date.Month))\n return date.FirstDayOfMonth();\n\n if (months.Max() &lt; date.Month)\n return date.FirstDayOfMonth(months.Max());\n\n if (date.Month &lt; months.Min())\n return date.PreviousYear().FirstDayOfMonth(months.Max());\n\n return date.FirstDayOfMonth(months.Where(m =&gt; m &lt; date.Month).Max());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:37:19.283", "Id": "76918", "Score": "0", "body": "Because I originally posted my question on StackOverflow, I simplified the code. In reality, it's not a `List<int>`, it's a list of an anonymous type containing the month and a number of months of slack time. The list is created from an xml string. If March is the month determined, it's ok if they've updated their data in the indicated number of months before that date. Should I write sample code that reflects the real code more?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:56:48.080", "Id": "76927", "Score": "0", "body": "Also, if `date` is 2014-09-01, your (first) method returns 2014-03-01 where I'd expect 2014-08-01. The second method doesn't have this problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:59:30.733", "Id": "76928", "Score": "0", "body": "@comecme hold on, I'll check. Also do you have some problems to apply this code to anonymous types?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:50:12.737", "Id": "77033", "Score": "0", "body": "I've updated my question to be more like my real code. I'm using a class `MonthSlack` here. In my code it's an anonymous type, but I don't think that would make a difference. I can't use `months.Max()` now. Could use `months.Max(m => m.Month)`, but I'd still need the actual `MonthSlack` where Month has that max value. If you want to rewrite my new code, I guess you'd better do that in a new answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:21:38.247", "Id": "44341", "ParentId": "44338", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T11:50:49.473", "Id": "44338", "Score": "6", "Tags": [ "c#", "algorithm", "linq", "datetime" ], "Title": "Determining expiration date based on list of months in which to refresh" }
44338
<pre><code>var root = this; root.node = function(path, type) { root.type = type; this.type = type; this.parents = []; this.children = []; var components = path.split('/'); this.parents = parseParents(components); this.name = components[components.length - 1]; this.addChild = function(path, type){ if(this.type === 'file'){ throw new Error('A file node cannot have any children'); } this.children.push(new root.node(path, type)); } function parseParents(components){ var parents = []; if(components.length &gt; 0){ for(var i = (components.length - 1); i &gt; 0; i--){ if(components[i] !== "") if(parents.length === 0){ var currentParent = new node(components[i], 'dir'); currentParent.children.push(new node(components[0], root.type)); parents.push(currentParent); } else{ var newParent = new node(components[i], 'dir'); var curretnChild = new node(components[i - 1], 'dir'); currentParent.parents.push(newParent); currentParent = newParent; } } return parents; } return []; } return this; } var a = new node('/usr/local/foo', 'dir'); a.addChild('test', 'file'); console.log(a); </code></pre> <p>2 way linked list, works great besides that the the 'leaf' items are not populated currently, since in the current structure it will result in an infinite loop.</p> <p>You thoughts please.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:56:25.673", "Id": "76926", "Score": "1", "body": "If leaf items are not populated and it goes into an infinite loop, then your code does not work and hence does not belong on CR." } ]
[ { "body": "<p>Not sure this question is valid, but there is reviewable code:</p>\n\n<ul>\n<li><code>node</code> is a constructor, it should be named with an uppercase <code>N</code></li>\n<li><code>curretnChild</code> is not properly spelled, and not used anywhere, drop it</li>\n<li>Since you set <code>parents</code> to <code>[]</code>, you might as well return <code>parents</code> when <code>if(components.length &gt; 0){</code> is not true</li>\n<li>You should declare your <code>var</code>s on top in <code>parseParents</code>, the scope of <code>newParent</code> and <code>currentParent</code> is the whole function anyway</li>\n<li>Your reliance on <code>root.type</code> is a bug in waiting, find a better way to figure out what the type should be. </li>\n<li><code>addChild</code> should be part of <code>Node.prototype</code>, it does not make sense for every instance of <code>Node</code> to have it's own version of this function</li>\n<li>Your code in <code>addChild</code> does not take care of dupes, that should be addressed</li>\n</ul>\n\n<p>For fun, I wrote this, it creates a double linked list and takes most of my comments in to consideration, except for the last one ( does not take care of dupes ).</p>\n\n<pre><code>function Node( path , type )\n{\n var parts = this.cleanPathParts( path.split(\"/\") ),\n part = parts.pop();\n //Set the basics\n this.name = part;\n this.type = type;\n //Do we still have parts left ?\n if( parts.length ){\n this.parent = new Node( parts.join('/'), this.DIR );\n this.parent.children = [ this ];\n }\n}\n//Ignore blanks and `..` strings\nNode.prototype.cleanPathParts = function( parts )\n{\n return parts.filter( function(part){\n return !!part &amp;&amp; part != \"..\";\n });\n};\n//Get the ultimate parent, usefull for adding path children\nNode.prototype.getRoot = function()\n{\n var root = this;\n while( root.parent )\n root = root.parent;\n return root;\n};\n//Add a child, either a simple node or a path\nNode.prototype.addChild = function( part , type )\n{\n if( this.type != this.DIR ){\n throw new Error('A file node cannot have any children');\n }\n var node = (new Node( part, type )).getRoot();\n node.parent = this;\n this.children = this.children || [];\n this.children.push( node );\n};\n//Constants\nNode.prototype.DIR = 'dir'; \nNode.prototype.FILE = 'file'; \n\nvar a = new Node('/usr/local/foo', 'dir');\na.addChild('1/2/test', 'file');\na.addChild('test', 'file');\nconsole.log(a);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T14:07:23.150", "Id": "77116", "Score": "0", "body": "It's not 2 ways list though, if the children don't point back to the father :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T17:39:26.297", "Id": "77144", "Score": "0", "body": "the property `parent` should do the trick?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T13:08:14.527", "Id": "44348", "ParentId": "44344", "Score": "2" } } ]
{ "AcceptedAnswerId": "44348", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:51:00.680", "Id": "44344", "Score": "2", "Tags": [ "javascript", "linked-list", "file-system" ], "Title": "Directory tree representation with double linked list" }
44344
<p>I'm extremely new to Python, and the Twitter API, but I found an example online that walked me through the process. Now that I've been playing around with it for awhile, I've begun to push the limits of what my laptop can handle in terms of processing power with my current code. I was hoping someone here could check over it and make recommendations on optimizing it. </p> <p>Goal: Take JSON output from the Twitter streaming API and print out specific fields to a CSV file. (The sysarg is used to pass the input and output filenames).</p> <pre><code># import necessary modules import json import sys # define a new variable for tweets tweets=[] # import tweets from JSON for line in open(sys.argv[1]): try: tweets.append(json.loads(line)) except: pass # print the name of the file and number of tweets imported print "File Imported:", str(sys.argv[1]) print "# Tweets Imported:", len(tweets) # create a new variable for a single tweets tweet=tweets[0] # pull out various data from the tweets tweet_id = [tweet['id'] for tweet in tweets] tweet_text = [tweet['text'] for tweet in tweets] tweet_time = [tweet['created_at'] for tweet in tweets] tweet_author = [tweet['user']['screen_name'] for tweet in tweets] tweet_author_id = [tweet['user']['id_str'] for tweet in tweets] tweet_language = [tweet['lang'] for tweet in tweets] tweet_geo = [tweet['geo'] for tweet in tweets] #outputting to CSV out = open(sys.argv[2], 'w') print &gt;&gt; out, 'tweet_id, tweet_time, tweet_author, tweet_author_id, tweet_language, tweet_geo, tweet_text' rows = zip(tweet_id, tweet_time, tweet_author, tweet_author_id, tweet_language, tweet_geo, tweet_text) from csv import writer csv = writer(out) for row in rows: values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row] csv.writerow(values) out.close() # print name of exported file print "File Exported:", str(sys.argv[2]) </code></pre>
[]
[ { "body": "<ul>\n<li><p>Put all <code>import</code> statements at the top.</p></li>\n<li><p>You might leak a file descriptor, since you call <code>open(sys.argv[1])</code> without closing it. (Whether a leak actually occurs depends on the garbage collector of your Python implementation.) Best practice is to use a <code>with</code> block, which automatically closes the resources when it terminates.</p>\n\n<pre><code>with open(sys.argv[1]) as in_file, \\\n open(sys.argv[2]) as out_file:\n …\n</code></pre></li>\n<li><p>It would be better to define your variables in the same order as they will appear in the CSV output.</p></li>\n<li><p>Rather than creating an empty array and appending to it in a loop, use a list comprehension.</p>\n\n<pre><code>tweets = [json.loads(line) for line in in_file]\n</code></pre></li>\n<li><p>You read all the tweets into an array of JSON objects, then slice the data \"vertically\" by attribute, then re-aggregate the data \"horizontally\". That's inefficient in terms of memory usage as well as cache locality.</p></li>\n<li><p>Unless you have a good reason, just transform one line of input at a time. (A good reason might be that you want to produce no output file at all if an error occurs while processing any line.)</p></li>\n</ul>\n\n\n\n<pre><code>import json\nimport sys\nfrom csv import writer\n\nwith open(sys.argv[1]) as in_file, \\\n open(sys.argv[2], 'w') as out_file:\n print &gt;&gt; out_file, 'tweet_id, tweet_time, tweet_author, tweet_author_id, tweet_language, tweet_geo, tweet_text'\n csv = writer(out_file)\n tweet_count = 0\n\n for line in in_file:\n tweet_count += 1\n tweet = json.loads(line)\n\n # Pull out various data from the tweets\n row = (\n tweet['id'], # tweet_id\n tweet['created_at'], # tweet_time\n tweet['user']['screen_name'], # tweet_author\n tweet['user']['id_str'], # tweet_authod_id\n tweet['lang'], # tweet_language\n tweet['geo'], # tweet_geo\n tweet['text'] # tweet_text\n )\n values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]\n csv.writerow(values)\n\n# print the name of the file and number of tweets imported\nprint \"File Imported:\", str(sys.argv[1])\nprint \"# Tweets Imported:\", tweet_count\nprint \"File Exported:\", str(sys.argv[2])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T23:29:21.753", "Id": "77304", "Score": "0", "body": "Thanks for the awesome review. I only had to make one very small change and it works perfectly. FYI, I changed the json import process to:\n\n try:\n tweet = json.loads(line)\n except:\n pass\n\nThanks again for the review!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T06:05:27.030", "Id": "77320", "Score": "0", "body": "@Curtis Putting a try-except around every `json.loads(line)` may or may not be a good idea. That's your decision to make. However, swallowing exceptions silently is almost always a very bad idea. At the very least, print a complaint to `sys.stderr`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T14:44:34.380", "Id": "77349", "Score": "0", "body": "thanks again for all your help, it's all greatly appreciated it. I'm obviously very new to this, but the reason I thought I needed try-except is so that it won't blow up if it hits a incomplete record. Maybe this is incorrect, but it wouldn't run without it, so I guess I'll have to keep it in there until I learn of a better way. I'll look into `sys.stderr` and see what that can tell me. Thanks again for your help!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T22:31:02.823", "Id": "44410", "ParentId": "44349", "Score": "8" } } ]
{ "AcceptedAnswerId": "44410", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T13:27:35.613", "Id": "44349", "Score": "7", "Tags": [ "python", "beginner", "csv", "twitter" ], "Title": "Printing out JSON data from Twitter as a CSV" }
44349
<p>I have recently forked/rewritten a SEDE query (<a href="http://data.stackexchange.com/codereview/query/174384/avid-users-rep-score-targets" rel="nofollow noreferrer">here</a>) that aims at figuring out where a site stands in terms of avid users and distribution of reputation scores, compared to a specific target (number of avid users in each major rep cluster).</p> <pre><code>declare @target_20k float declare @target_10k float declare @target_3k float declare @target_2k float set @target_20k = 3.0 set @target_10k = 10.0 set @target_3k = 80.0 set @target_2k = 120.0 /* only look at users that visited the site recently */ declare @lastActiveDays int set @lastActiveDays = 60 select [20K], [10K], [3K], [2K], [TotalSiteRep], [UsersCount], round([TotalSiteRep]/cast([UsersCount] as float),2) [AvgRep], [AvidUsersRep], round([AvidUsersRep]/cast([TotalSiteRep] as float),2) [%AvidRep], [AvidUsersCount], round([AvidUsersCount]/cast([UsersCount] as float),2) [%AvidUsers], round([AvidUsersRep]/cast(AvidUsersCount as float),2) [AvgAvidRep] from ( select round(sum([20K])/@target_20k, 2) [20K], round(sum([10K])/@target_10k,2) [10K], round(sum([3K])/@target_3k,2) [3K], round(sum([2K])/@target_2k,2) [2K], sum(Reputation) [TotalSiteRep], count(*) [UsersCount], sum(AvidRep) [AvidUsersRep], sum(AvidUser) [AvidUsersCount] from ( select Reputation, case when Reputation &gt;= 20000 then 1 else 0 end [20K], case when Reputation &gt;= 10000 then 1 else 0 end [10K], case when Reputation &gt;= 3000 then 1 else 0 end [3K], case when Reputation &gt;= 2000 then 1 else 0 end [2K], case when Reputation &gt;= 150 then Reputation else 0 end [AvidRep], case when Reputation &gt;= 150 then 1 else 0 end [AvidUser] from Users where datediff(d, LastAccessDate, getdate()) &lt;= @lastActiveDays ) q ) r </code></pre> <p>I'm not crazy about the <code>case when ... then .. else ... end</code> part and about the sub-querying, but it seems to get the job done.</p> <p>Is there a better way to aggregate conditional sums? (feel free to review everything else, ...except the broken indentation of the <code>q</code> query - that's already something I know I have to fix ;)</p> <hr> <p>Here are the query's results for Code Review, as of the latest SEDE update:</p> <p><img src="https://i.stack.imgur.com/S83eo.png" alt="enter image description here"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T14:31:11.510", "Id": "76936", "Score": "4", "body": "you should fix the indentation of the `q` query" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:58:12.713", "Id": "76998", "Score": "0", "body": "What is the rationale for those target numbers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:00:47.943", "Id": "77000", "Score": "0", "body": "@200_success They are the targets Doorknob has determined for [PCG's \"mission\"](http://meta.codereview.stackexchange.com/questions/1628/the-race-has-started-are-you-running). I think they're just arbitrary numbers." } ]
[ { "body": "<p>It's a good habit to end each statement with an explicit semicolon.</p>\n\n<hr>\n\n<p>The innermost query <code>q</code> generates one row for each recent user. Since you have no interest in individual users, and only want counts and sums, you can collapse the two innermost queries <code>q</code> and <code>r</code> — both poorly named, by the way — into one. <a href=\"https://stackoverflow.com/a/1400115/1157100\">Use <code>COUNT()</code> for counting.</a></p>\n\n<hr>\n\n<p>The <code>lastActiveDays</code> filtering is being done inefficiently:</p>\n\n<pre><code>where datediff(d, LastAccessDate, getdate()) &lt;= @lastActiveDays\n</code></pre>\n\n<p>To accomplish that, the server would have to run <code>datediff()</code> on every single row in the <code>Users</code> table. Instead, you should calculate the cutoff date just once:</p>\n\n<pre><code>where LastAccessDate &gt;= cast(dateadd(day, -@lastActiveDays, getdate()) as Date)\n</code></pre>\n\n<p>(The cast truncates the result to midnight.)</p>\n\n<hr>\n\n<p>I prefer to use Common Table Expressions for readability. Since you are not running a correlated subquery, a top-down layout is better than nesting.</p>\n\n<p>The <code>UserStats</code> CTE below is roughly equivalent to subquery <code>q</code>. I've deferred the <code>… / @target…</code> divisions for readability and rearranged the columns in a more logical order. It <em>could</em> be written as just one <code>SELECT</code>, but I think that splitting it up with a CTE makes it easier to understand.</p>\n\n<hr>\n\n<pre><code>declare @target_20k float;\ndeclare @target_10k float;\ndeclare @target_3k float;\ndeclare @target_2k float;\n\nset @target_20k = 3.0;\nset @target_10k = 10.0;\nset @target_3k = 80.0;\nset @target_2k = 120.0;\n\ndeclare @lastActiveDays int;\nset @lastActiveDays = 60;\n\nwith UserStats as (\n select\n count(case when Reputation &gt;= 20000 then 1 else null end) [20KUsersCount],\n count(case when Reputation &gt;= 10000 then 1 else null end) [10KUsersCount],\n count(case when Reputation &gt;= 3000 then 1 else null end) [3KUsersCount],\n count(case when Reputation &gt;= 2000 then 1 else null end) [2KUsersCount],\n count(case when Reputation &gt;= 150 then 1 else null end) [AvidUsersCount],\n count(Id) [UsersCount],\n sum(case when Reputation &gt;= 150 then Reputation else 0 end) [AvidUsersRep],\n sum(Reputation) [TotalSiteRep]\n from Users\n where LastAccessDate &gt;= cast(dateadd(day, -@lastActiveDays, getdate()) as Date)\n)\nselect\n round([20KUsersCount] / @target_20k, 2) [20K],\n round([10KUsersCount] / @target_10k, 2) [10K],\n round([3KUsersCount] / @target_3k, 2) [3K],\n round([2KUsersCount] / @target_2k, 2) [2K],\n [TotalSiteRep],\n [UsersCount],\n round([TotalSiteRep] / cast([UsersCount] as float), 2) [AvgRep],\n [AvidUsersRep],\n round([AvidUsersRep] / cast([TotalSiteRep] as float), 2) [%AvidRep],\n [AvidUsersCount],\n round([AvidUsersCount] / cast([UsersCount] as float), 2) [%AvidUsers],\n round([AvidUsersRep] / cast(AvidUsersCount as float), 2) [AvgAvidRep]\n from UserStats;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:13:49.207", "Id": "77003", "Score": "2", "body": "I like that. I need more CTE's in my life ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:55:40.480", "Id": "44374", "ParentId": "44353", "Score": "4" } } ]
{ "AcceptedAnswerId": "44374", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T14:20:58.623", "Id": "44353", "Score": "7", "Tags": [ "performance", "sql", "sql-server", "t-sql", "stackexchange" ], "Title": "Aggregating Conditional Sums" }
44353
<p>We have two C-strings and for their concatenation we need to know the size of resulting string. And we want to calculate it at compilation stage. How can I improve this solution? </p> <pre><code>char s1[] = "string1"; char s2[] = "string2"; constexpr auto SIZE = sizeof(s1) / sizeof(*s1) + sizeof(s2) / sizeof(*s2) + 2; // + for space and \0 char ss[SIZE]; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:27:44.603", "Id": "76971", "Score": "0", "body": "In what way do you want to improve it? What's wrong with `char ss[] = \"string1 string2\";`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:32:50.467", "Id": "76972", "Score": "1", "body": "I want to change `s1` and `s2` only, so as `ss` is determined automatically." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:36:03.780", "Id": "76973", "Score": "0", "body": "Can you please post an example of some code which 'changes' `s1` and `s2`? And is this all happening when you define global variables, or is it happening inside a function/method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:42:01.547", "Id": "76976", "Score": "0", "body": "I mean I change them manually." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:49:01.203", "Id": "76980", "Score": "0", "body": "I do not understand why you have to divide by sizeof(*s1) and s2. You are allocating the same type (char) for ss too. That could be wrong if char is not one byte wide, or useless if it is always 1 byte." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:52:07.613", "Id": "76982", "Score": "0", "body": "Are you aware that it's normal to use the `strlen` function? For example, if you're doing this calculation inside a function, where arbitrary string values are passed-in via pointer parameters?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:55:05.787", "Id": "76984", "Score": "0", "body": "I specify the sizes (number of elements) of `s1` and `s2`. Either char is one byte or not, I get its sizes by the dividing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:58:25.220", "Id": "76985", "Score": "0", "body": "@ChrisW, but `strlen()` works at runtime. I think it is more correctly to calculate such things at compilation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T17:25:49.807", "Id": "77143", "Score": "0", "body": "Note: `sizeof(s1) / sizeof(*s1)` already includes the `\\0` character. Thus `+ 2` is adding unneeded space." } ]
[ { "body": "<p>You could use a macro, for example <a href=\"https://stackoverflow.com/q/4415524/49942\">one of these ones</a>.</p>\n\n<p>And you shouldn't need to add <code>2</code>: because <code>sizeof</code> should already include the terminating <code>'\\0'</code> of each string. However you could add a comment to explain why you don't add anything: you have two strings each with an implicit terminating <code>'\\0'</code> ... one of them terminates the concatenated string, and the other is room for the intervening \"space\": that is, if you think that concatenating strings should add a space, e.g. \"string1\" plus \"string2\" becomes \"string1 string2\". Note that normally, concatenation means that the result is \"string1string2\", in which case you need to subtract 1.</p>\n\n<p>Your question isn't very clear. You should provide some test cases which demonstrate the expected result and actual result.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:49:28.157", "Id": "76994", "Score": "0", "body": "yeah, thx, I mixed it up with `strlen()`. Why should I use macros instead of `sizeof`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:58:46.737", "Id": "76999", "Score": "0", "body": "You don't have to; but if you're going to be doing it a lot, `ARRAY_SIZE(s1) + ARRAY_SIZE(s2) - 1` might be easier to read than `sizeof(s1) / sizeof(*s1) + sizeof(s2) / sizeof(*s2) - 1`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:38:12.160", "Id": "44372", "ParentId": "44354", "Score": "2" } }, { "body": "<p>This is one case where using the preprocessor may be worthwhile (despite the lack of namespace awareness). In the code below, <code>ss[]</code> not only gets an appropriate size without any effort on your part, it's actually populated with the concatenated text at compile time.</p>\n\n<pre><code>#define S1 \"string1\"\n#define S2 \"string2\"\n\n// optionally, create real character arrays so you can modify them etc.\nchar s1[] = S1;\nchar s2[] = S2;\n\n// now the magic - automatic concatenation of adjacent string literals\nchar ss[] = S1 S2;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T23:14:18.977", "Id": "44415", "ParentId": "44354", "Score": "4" } } ]
{ "AcceptedAnswerId": "44372", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:02:14.477", "Id": "44354", "Score": "0", "Tags": [ "c++", "c", "strings", "c++11" ], "Title": "Handling C-like strings in C++11" }
44354
<p>I have written a method that checks if <code>n</code> number of <code>true</code> <code>booleans</code> are present in a <code>boolean[]</code> array. Then I improved it to var args format which is as follows:</p> <pre><code>public static boolean checkNTrue(int n, boolean... args) { assert args.length &gt; 0; int count = 0; for( boolean b : args ) { if(b) count++; if( count &gt; n ) return false; } return ( count == n ); } </code></pre> <p>I implement it to check if <strong><em>only one</em></strong> of all those <code>boolean</code>s is true by using:</p> <pre><code>boolean result = checkNTrue(1, false, true, false, false); </code></pre> <p>The above returns <code>true</code> confirming the required case. But what if there are <em>only two</em> <code>boolean</code> arguments? A simple <strong>XOR</strong> could return the right result.</p> <p>And in the case of <em>3 <code>booleans</code></em>, <code>return (a ^ b ^ c) ^ (a &amp;&amp; b &amp;&amp; c);</code> works fine too. So, my question is:</p> <p><strong>Do I need to write separate methods to check in cases with 2 and 3 variables?</strong></p> <p>Or will this one method do fine? I invite every kind of criticism through downvotes and comments, but please enlighten me! :-)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T03:49:56.227", "Id": "77082", "Score": "2", "body": "Why assert that `args.length > 0`? If `args`has zero length, why not just return `n == 0`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:21:06.737", "Id": "78582", "Score": "1", "body": "Please don't edit the code in the question in a way that invalidates existing answers. I've rolled it back to Rev 2." } ]
[ { "body": "<p>Premature optimization is a bad idea. Before you try to optimize anything, run a profiler to measure where your bottlenecks are. Unless you are running this function in a tight loop, it's unlikely that this function will be a bottleneck.</p>\n\n<p>The special cases that you would introduce don't come for free:</p>\n\n<ul>\n<li>The more line of code you write, the more bugs you are likely to have, statistically.</li>\n<li>Your unit tests also have to address the special cases.</li>\n<li>There is a bit of overhead in checking whether your special cases apply.</li>\n</ul>\n\n<p>Taking all that into consideration, it's almost certainly not worthwhile to add special cases.</p>\n\n<hr>\n\n<p>The assertion <code>assert args.length &gt; 0</code> might be inappropriate. Considering this code in a vacuum, there is nothing to guarantee that that assertion is logically true. Rather, it's a runtime validation check. Validation failures should throw an <code>IllegalArgumentException</code>. They shouldn't be assertion failures. (Assertions can be disabled, defeating your check.)</p>\n\n<p>If this were a non-public method, and you are sure that you've written your code such that all call sites have at least two arguments, then an assertion might be appropriate.</p>\n\n<p>Here's a philosophical question: should <code>checkNTrue(0)</code> be <code>true</code> or <code>false</code>? I think it should be <code>true</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T13:27:37.250", "Id": "77341", "Score": "1", "body": "@ambigram_maker You changed the assert to `args.length > -1`. Is that really useful? Is it even technically possible for the length of an array to become negative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:24:36.430", "Id": "78583", "Score": "0", "body": "Sorry... Now I understand that the `assert` is useless." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:56:38.480", "Id": "44358", "ParentId": "44357", "Score": "11" } }, { "body": "<ol>\n<li><p><code>assert</code> statements can be disabled, so I'd throw an exception instead:</p>\n\n<pre><code>if (args.length &lt; 1) {\n throw new IllegalArgumentException(\"must have at least one boolean parameter\");\n}\n</code></pre></li>\n<li><blockquote>\n<pre><code>if(b) count++;\n</code></pre>\n</blockquote>\n\n<p>I'd put the <code>count++</code> statement to a separate line. From <em>Code Complete, 2nd Edition</em>, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead of top to bottom and left to right. When you’re looking for a specific line of code, your eye should be able to follow the left margin of the code. It shouldn’t have to dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>I'd rename the method to <code>checkExactlyNTrue</code> for easier understanding. (It would have answered my initial question: what does it do if I have more than <code>n</code> <code>true</code> parameters?)</p></li>\n<li><blockquote>\n <p>Do I need to write separate methods to check in cases with 2 and 3 variables?</p>\n</blockquote>\n\n<p>If you don't have a concrete reason why would you do it? Keep it simple. The method in the question works with two and three parameters too, I would use that.</p></li>\n<li><blockquote>\n <p>And in the case of 3 booleans, return (a ^ b ^ c) ^ (a &amp;&amp; b &amp;&amp; c); works fine too. So, my question is:</p>\n</blockquote>\n\n<p>This would be really hard to read and understand, the method in the question expresses the intent/purpose of the method better.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:23:08.313", "Id": "76970", "Score": "1", "body": "According to best practices, all `if` statements should have braces, and `count++` should be on its own line. However, if the author insists on omitting the braces, then [treating `if (b) count++;` as one statement on one line is safer](http://programmers.stackexchange.com/a/16530/51698)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:09:20.950", "Id": "77001", "Score": "0", "body": "I would argue that the check for at least 1 `boolean` is not needed. The method is still correct without it, no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T22:16:08.983", "Id": "77065", "Score": "0", "body": "@DannyMo: Yes, it as far as I see it is. (I didn't want to change the original behaviour.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T05:33:58.843", "Id": "77085", "Score": "0", "body": "@DannyMo: I'm not _checking_ my method with 1 `boolean`, but I'm _implementing_ it! That's what I wanted to know... is it _Okay_ if I use it to check only **ONE** boolean? :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:00:37.217", "Id": "44359", "ParentId": "44357", "Score": "7" } }, { "body": "<p>At the moment, your code is simple enough so that it's quite easy to understand what it does and to be convinced quite easily that is does correctly. One of the main principle of programming is <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">Keep it simple</a>.</p>\n\n<p>Adding special cases will give you more code to maintain and potentially introduce bugs. This is probably not something you want.</p>\n\n<p>If you want to be sure that your function returns the same thing as <code>xor</code>, you might want to use this in your unit test (<em>you were about to add unit tests, weren't you?)</em></p>\n\n<p>If your reasoning to add special cases was performances, I guess you shouldn't be too worried about that as it corresponds to a situation which would have been super fast anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:10:01.313", "Id": "76965", "Score": "0", "body": "Using xor in unit tests reminds me [Production Logic in Test](http://xunitpatterns.com/Conditional%20Test%20Logic.html#Production%20Logic%20in%20Test)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:02:45.413", "Id": "44360", "ParentId": "44357", "Score": "2" } }, { "body": "<pre><code>if(b) count++;\nif( count &gt; n )\n return false;\n</code></pre>\n\n<p>...can be improved as...</p>\n\n<pre><code>if (b &amp;&amp; ++count &gt; n)\n return false;\n</code></pre>\n\n<p>...which uses \"short circuit evaluation\" so the stuff after <code>&amp;&amp;</code> doesn't run if <code>b</code> if false, i.e. it doesn't bother to check <code>count</code> when it hasn't just been modified. I wouldn't bet on an optimiser understanding this relationship well enough to eliminate the extra check in <code>!b</code> situations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T23:19:06.267", "Id": "77071", "Score": "1", "body": "Your observation about efficiency is valid. However, it would be clearer to write it as a nested statement. `if (b) { count++; if (count > n) { return false; }}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T23:38:20.513", "Id": "77073", "Score": "0", "body": "@200_success: I considered that, but I think programmers reading this should either already know how short-circuit evaluation and pre- vs post-increment work and be entirely comfortable with them, or make the time to learn. :^) This is pretty basic stuff, and if they're not 100% clear, they'll be guessing at what a lot of existing code does. But then I'm a C++ programmer at heart... bread and butter ;-)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T03:54:07.297", "Id": "77083", "Score": "0", "body": "@TonyD: Short-circuit evaluation is great for dealing with cases where the latter tests might give exceptions or undefined behavior should the earlier ones fail... using it to control side effects is rather strange. (shell scripting aside... but then shell scripting is always strange!) If I saw code like that in real life, and noticed the effect, I would be far more likely to think \"oh, the author made a mistake\" before anything else." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T23:04:52.963", "Id": "44414", "ParentId": "44357", "Score": "4" } }, { "body": "<p>If you <strong><em>really</em></strong> want this to be fast — like smokingly, freakingly, astonishingly fast — then throw everything out that you've go so far and rewrite the whole thing to be an O(1) implementation instead of an O(n) implementation.</p>\n\n<p>Always remember the first rule of optimization: The fastest way to do something is to not do it. And the thing you want to avoid here is looping through the array to count values. Memory accesses are expensive, especially if they result in L1 or L2 cache misses or VM page faults.</p>\n\n<p>So here's what I would do: Create a wrapper class for the boolean array. Provide read and write methods for accessing elements of the array. Maintain a count <code>c</code> of true values. When an element is set (e.g., true or false value being stored at some index), compare the new value against the old value. If the value is transitioning from false to true, increment <code>c</code> by 1; if the value is transitioning from true to false, decrement <code>c</code> by 1. Then, in the method which checks if <code>n</code> true boolean values are present, simply compare <code>n</code> to <code>c</code> and you're done. Extremely minimal overhead, and extremely fast checking with no looping.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T07:41:57.230", "Id": "77089", "Score": "2", "body": "I think you've just described [`Bitset.cardinality()`](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html#cardinality\\(\\)) (assuming it is efficiently implemented)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T14:41:50.620", "Id": "77236", "Score": "0", "body": "Yes, I understand that _storing_ the required values on creation is definitely faster... but I'm applying this in a `static` method, so I don't know how much _practical_ it would be. Would'nt using a wrapper add additional overhead every time I call it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T16:09:08.923", "Id": "77251", "Score": "0", "body": "@ambigram_maker — Using a wrapper class would add additional overhead, yes. If you are doing tons of updates and relatively few counting queries, then it may not be worth it; but if you are doing relatively few updates and tons of counting queries, then it will pay for itself easily — especially if there are millions of elements. It's hard to know which way would be best without knowing more about the problem domain... but you may find that the overhead is minimal anyway." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T07:36:32.953", "Id": "44423", "ParentId": "44357", "Score": "2" } } ]
{ "AcceptedAnswerId": "44358", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:34:04.140", "Id": "44357", "Score": "12", "Tags": [ "java", "optimization", "design-patterns" ], "Title": "Optimizing boolean checking method" }
44357
<p>Bit of background info first - I've been struggling with a problem for a while now. How could you have one single event handler to handle every control (or all of a particular type of control) on a form? I've never been able to find a complete solution online either. The two 'easy' methods have glaring issues. For sake of example, let's say we want every text box to change its border color when it gains focus. The code for changing <em>one</em> text box border on focus is easy:</p> <pre><code>Private Sub TextBox0_GotFocus() TextBox0.BorderColor = vbBlue End Sub </code></pre> <p>But doing this for every single text box causes a problem. The brute-force option would be to manually add a handler to every text box, and have them all call a master handler (<a href="http://sharetext.org/SWek">http://sharetext.org/SWek</a>). That creates a <em>lot</em> of duplicate code, fast. And it's time-consuming, boring, easy to forget to do... and as a programmer I'm too lazy to do it like this.</p> <p>The other option is to set the handler for every text box to a constant expression in the form designer (eg <code>=AnyTextBox_HandleGotFocus()</code>), but doing so makes you lose which text box actually got the focus:</p> <pre><code>Private Sub AnyTextBox_HandleGotFocus() ' ??? Which text box just fired this? I have no way of knowing! End Sub </code></pre> <p>I'd need to loop through the form's entire control collection every single time this thing fires. I also lose the ability to grant specific behaviour to an individual control. Unless I whack a massive <code>Switch</code> statement inside the loop or something. <em>Shudder.</em></p> <p>After a long time rolling it around in my head, I <em>think</em> I have a solution. It isn't perfect, but the caveats of this are much smaller than the caveats of the above.</p> <hr> <p>First off, we want to build a collection of the controls we want to use. We can then loop through it and assign all of their event handlers to a single handler programatically. This is the only loop in this code.</p> <pre><code>Private iTextBoxes As Collection Private Sub Form_Load() BuildControlCollection Me, iTextBoxes, eTextBox Dim lTextBox As TextBox For Each lTextBox In iTextBoxes lTextBox.OnGotFocus = "=AnyTextBox_GotFocus(" &amp; lTextBox.Name &amp; ")" Next lTextBox End Sub </code></pre> <p>Not relevant to the question, but <code>BuildControlCollection</code> here turns <code>iTextBox</code> into a collection of all the text boxes on the form. Don't worry about the details of my Hungarian notation either.</p> <p>Next, let's add the 'master' event handler:</p> <pre><code>Public Function AnyTextBox_GotFocus(ByRef mpTextBox As TextBox) mpTextBox.BorderColor = RGB(100, 150, 215) FireControlSingleEvent mpTextBox, "GotFocus" End Function </code></pre> <p>That <code>FireControlSingleEvent</code> is the important part (the name is a bit awkward, suggestions welcome!) - this fires the control's 'unique' event handler, so I can add handling for a specific control.</p> <pre><code>Private Function FireControlSingleEvent(ByRef mpControl As Control, _ ByVal ipEventProcName As String) Try: On Error GoTo Catch Dim iProcName As String iProcName = Me.Controls(mpControl.Name).EventProcPrefix &amp; "_" &amp; ipEventProcName Select Case ipEventProcName Case "Click", "AfterUpdate", "Change", "GotFocus", "LostFocus", "Enter": CallByName Me, iProcName, VbMethod Case "KeyPress": CallByName Me, iProcName, VbMethod, mLastKeyPressedAscii Case Else: Debug.Print "Multi event handling cannot support the " &amp; ipEventProcName &amp; " event." End Select GoTo Finally Catch: If Err.Number = 2465 Then Debug.Print "Procedure " &amp; Forms("Form1").Controls(mpControl.Name).EventProcPrefix &amp; "_" &amp; ipEventProcName &amp; _ " does not exist or is private" Else Err.Raise Err.Number End If Finally: On Error GoTo 0 End Function </code></pre> <p>This attempts to call a method named with the standard convention, according to the control and event procedure name it's given. For example, if it's handed <code>TextBox0</code> and <code>GotFocus</code>, it will attempt to call <code>TextBox0_GotFocus()</code>. The error handling stops it crashing if <code>TextBox0_GotFocus()</code> doesn't exist, removing the necessity for having empty handlers for every single control.</p> <p>The <code>Select</code> statement is there as I haven't worked out how to handle every single event yet - only events that don't need arguments work with this code, so things like mouse events are currently out.(<code>KeyPress</code> is a special case - by turning <code>Key Preview</code> on at the form level, I can capture the KeyAscii required into <code>mLastKeyPressedAscii</code> in the form's <code>Form_KeyPress</code> event, and pass that)</p> <hr> <p><strong>Known caveats</strong></p> <ul> <li>As mentioned above, event handlers that take arguments - such as <code>MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)</code> - aren't compatible without losing the data that would be passed to the parameters.</li> <li>The <code>TextBox0_GotFocus()</code>-type handlers must be altered to <code>Public</code> rather than <code>Private</code> - <code>CallByName</code> can't find <code>Private</code> handlers.</li> </ul> <p>Any suggestions or improvements on this code? There's a few bits I'm iffy about - always nervous about using errors as an intentional part of the code structure, for eg. Feedback welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:20:18.767", "Id": "76968", "Score": "1", "body": "If anyone's wondering what the hungarian notation means: `i` this variable shouldn't be changed once initially set ('immutable'); `m` this variable is expected to be changed ('mutable'); `p` parameter; `l` index / object for a loop; `e` Enum value. It's experimental, just been trying it on for size recently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:42:10.230", "Id": "76977", "Score": "0", "body": "this looks exciting, I will have to see what happens by the time I get home tonight. you are missing some indentation on your case statement too by the way" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:10:11.720", "Id": "77002", "Score": "0", "body": "That's the way the VBA IDE forces it to appear - kinda funny that it's one of very few places it attempts to auto-indent, and it does it in a strange way :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:14:00.463", "Id": "77004", "Score": "0", "body": "I am still trying to Learn VBA as I go. we only use it sparingly for certain things pertaining to a third party application. we create and maintain certain small pieces that are needed in the application and they are coded in VBScript, kind of VBA I still can't figure out what the difference is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:28:46.367", "Id": "77028", "Score": "1", "body": "This post has just taught me about `CallByName` - and now there's a whole new world of refactoring possibilities that have just appeared right before my eyes... I'm so upvoting this, the minute I get votes back (out of ammo right now..)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T00:29:00.570", "Id": "77190", "Score": "0", "body": "@Mat'sMug Yeah, figuring this code was a bit of Rollercoaster Of Discovery (tm). Bad: No way to get the address to a function. Good: `Eval()` lets you call a function by name! Bad: `Eval` doesn't work for `Sub`s. Good: `CallByName` does!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T09:22:25.200", "Id": "77324", "Score": "0", "body": "I put up my implementation of `BuildControlCollection` for review if anyone's interested in seeing how that works: http://codereview.stackexchange.com/questions/44555/generating-a-collection-of-controls" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T22:43:24.650", "Id": "171206", "Score": "1", "body": "I know this is over a year old, but if you're around, you might be interested in this Q & A. http://codereview.stackexchange.com/q/68221/41243" } ]
[ { "body": "<p>I don't have lots of time, so I'll just make a couple of points:</p>\n\n<ul>\n<li>Drop the \"Hungarian\" notation altogether, it's not doing you any good. Instead declare variables close to their usage, and strive to keep procedures &lt; 25 lines.</li>\n<li>If you <em>have to</em> stick to that notation, <em>seriously</em> reconsider the lowercase \"L\" prefix. There's practically zero difference between \"l\" and \"1\" in <em>Courier New</em>, the IDE's default font.</li>\n</ul>\n\n<p>But those are merely nitpicks. The main thing that bothers me is your <code>try/catch/finally</code> emulation. Obviously you're coming from a language that handles errors with exceptions. VB6/VBA doesn't have that.</p>\n\n<blockquote>\n<pre><code>GoTo Finally\n</code></pre>\n</blockquote>\n\n<p>Why use <code>GoTo</code> instead of restructuring the flow?</p>\n\n<p><img src=\"https://i.stack.imgur.com/OVpny.png\" alt=\"goto-spawns-raptors\"></p>\n\n<pre><code>Sub DoSomething()\n On Error GoTo ErrHandler\n\n 'do something\n\nErrHandler: \n 'this part runs regardless of error state\n If Err.Number &lt;&gt; 0 Then\n 'handle specific and/or general error cases\n End If\n 'single exit point\nEnd Sub\n</code></pre>\n\n<p>The <strong>only</strong> recommendable usage for <code>GoTo</code> is when it immediately follows an <code>On Error</code> statement.</p>\n\n<p>Error number 2465 should have a comment that says what it is, or even better, a properly named constant that conveys its meaning:</p>\n\n<pre><code>If Err.Number = HELL_BROKE_LOOSE Then\n</code></pre>\n\n<p>Lastly, <code>On Error GoTo 0</code> is not needed, since <code>On Error GoTo ErrHandler</code> is scoped to the method; however <strong>it would be necessary</strong> if you had <code>On Error Resume Next</code> somewhere in there.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:46:23.807", "Id": "44390", "ParentId": "44361", "Score": "8" } } ]
{ "AcceptedAnswerId": "44390", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:15:04.223", "Id": "44361", "Score": "11", "Tags": [ "vba", "ms-access" ], "Title": "Form controls - Single event handler for multiple controls, without sacrifices" }
44361
<p>The following code is for mapping a dataRecord to a class. I don't like this solution since it requires to duplicate the logic of mapping for each field in every method which access to the same table.</p> <p>What do you think about? What about using automapper?</p> <pre><code>public IEnumerable&lt;Model.Accounts.User&gt; GetUsers(int IDUser) { using (var sqlClient = CreateSqlManagerInstance("ListUser", CommandType.StoredProcedure)) { sqlClient.AddParameterWithValue("IDUser", IDUser); return sqlClient.ExecuteResultSet().Select( dataRecord =&gt; new GModel.Accounts.User { IDUser = dataRecord.GetInt("IdUtente"), FirstName = dataRecord.GetString("Nome"), LastName = dataRecord.GetString("Cognome"), //[...] }).ToArray(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:53:57.187", "Id": "76983", "Score": "1", "body": "`Avoiding code duplication in mapping layer between dataRecord and` and what ?" } ]
[ { "body": "<p>I believe the easiest way to avoid duplication each time you read from the database is to create a <code>constructor</code> which receives a <code>DataRecord</code> as a parameter, and does the heavy lifting:</p>\n\n<pre><code>public class User {\n\n public User() {}\n\n public User(DataRecord dataRecord) {\n IDUser = dataRecord.GetInt(\"IdUtente\");\n FirstName = dataRecord.GetString(\"Nome\");\n LastName = dataRecord.GetString(\"Cognome\");\n //[...]\n }\n\n //...\n}\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>public IEnumerable&lt;Model.Accounts.User&gt; GetUsers(int IDUser)\n{\n using (var sqlClient = CreateSqlManagerInstance(\"ListUser\", CommandType.StoredProcedure))\n {\n sqlClient.AddParameterWithValue(\"IDUser\", IDUser);\n return sqlClient.ExecuteResultSet().Select(\n dataRecord =&gt; new GModel.Accounts.User(dataRecord)).ToArray();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You could also use an automatic mapping library, but before you choose to do that, you might want to look at some <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow\">O/R mapping</a> library, like <a href=\"http://nhforge.org\" rel=\"nofollow\">NHibernate</a> for <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged &#39;c#&#39;\" rel=\"tag\">c#</a>, which should replace the mapping in your code altogether.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:38:33.947", "Id": "76974", "Score": "0", "body": "What about using framework like AutoMapper?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:49:55.717", "Id": "76981", "Score": "1", "body": "see my edit about O/R mapping" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:33:46.570", "Id": "44363", "ParentId": "44362", "Score": "3" } }, { "body": "<p>Instead of using a lambda to do the mapping, you can pass in a function reference. Now the same function is uses for everytime the class need to create a <code>User</code> from a <code>DataRecord</code>.</p>\n\n<pre><code>public GModel.Accounts.User mapRecord(DataRecord dataRecord) {\n // code\n}\n\npublic IEnumerable&lt;Model.Accounts.User&gt; GetUsers(int IDUser)\n{\n using (var sqlClient = CreateSqlManagerInstance(\"ListUser\", CommandType.StoredProcedure))\n {\n sqlClient.AddParameterWithValue(\"IDUser\", IDUser);\n return sqlClient.ExecuteResultSet().Select(mapRecord).ToArray();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:39:08.483", "Id": "76975", "Score": "0", "body": "Is there a way to make mapping selective for only the field which are returned by the store?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:43:46.397", "Id": "76978", "Score": "1", "body": "@Revious: If each of your `DataRecord`s does not have all the fields of a `User`, this will make a consistent mapping more complicated. However, you can always write the method so it checks if a field exists before setting the object property. You just have to be careful handing `User` instances to the rest of your code, as all the fields might not be initialized." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:35:21.727", "Id": "44364", "ParentId": "44362", "Score": "3" } } ]
{ "AcceptedAnswerId": "44363", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:20:09.473", "Id": "44362", "Score": "1", "Tags": [ "c#" ], "Title": "Avoiding code duplication in mapping layer between dataRecord and" }
44362
<p>I'm working on Google Book API to post a book's basic information. I notice that some of the books will always miss a value or two under <code>volumeInfo</code>, like this book <strong>(<a href="http://jsfiddle.net/KU7Zx/21/" rel="nofollow">Fiddle</a>)</strong> that has no publisher value. Do I need to repeat <code>if [object] undefined</code> statement several times for the missing values (e.g Publisher,Average Rating,Rating Count)? Can I do it in a more concise way? </p> <pre><code> $.ajax({ url: 'http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22https%3A%2F%2Fwww.googleapis.com%2Fbooks%2Fv1%2Fvolumes%3Fq%3Disbn%3A1879505215%22&amp;format=json&amp;diagnostics=true&amp;callback=?', dataType: 'json', success: function (data) { $(data.query.results.json.items).each(function (index, item) { var isbn10; $.each(item.volumeInfo.industryIdentifiers, function(index, item) { if (item.type === "ISBN_10") { isbn10 = item.identifier; return false; } }); var Rating = item.volumeInfo.averageRating; var RatingCount = item.volumeInfo.ratingsCount; var item_html = ''; item_html += ' &lt;li&gt;&lt;img src="' +item.volumeInfo.imageLinks.thumbnail+'&lt;/li&gt; &lt;li&gt;&lt;span&gt;Author:&lt;/span&gt; ' + item.volumeInfo.authors + '&lt;/li&gt; &lt;li&gt;&lt;span&gt;Publisher&lt;/span&gt; ' + item.volumeInfo.publisher + '&lt;/li&gt; &lt;li&gt;&lt;span&gt;PublishDate:&lt;/span&gt; '+item.volumeInfo.publishedDate+'&lt;/li&gt; &lt;li&gt;&lt;span&gt;Category:&lt;/span&gt; ' + item.volumeInfo.categories + '&lt;/li&gt; &lt;li&gt;&lt;span&gt;Page Count:&lt;/span&gt; ' + item.volumeInfo.pageCount +' &lt;/li&gt; &lt;li&gt;&lt;span&gt;ISBN:&lt;/span&gt; ISBN10_' + isbn10 +' &lt;/li&gt; &lt;li&gt;&lt;span&gt;Description: &lt;/span&gt; ' + item.volumeInfo.description +' &lt;/li&gt;'; if (Rating != undefined) { item_html += '&lt;li&gt;&lt;span&gt;Average Rating:' + Rating +'&lt;/span&gt;&lt;/li&gt;'; } if (RatingCount != undefined) { item_html += '&lt;li&gt;&lt;span&gt;Rating Count:' + RatingCount +'&lt;/span&gt;&lt;/li&gt;'; } var title_html ='' +item.volumeInfo.title + ''; $('#bookhead').append(title_html); $('#bookdetail ul').append(item_html); }); }, error: function () {} }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:14:02.360", "Id": "77005", "Score": "0", "body": "Please indent your code properly. In it's current form it's unreadable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:26:39.140", "Id": "77009", "Score": "0", "body": "@ReneSaarsoo edited. I hope it's better now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:39:04.963", "Id": "77018", "Score": "0", "body": "Not really. The indentation should reflect the structure of your code - which statements are nested inside which statement. Just indenting all lines by the same amount is not much help. See: http://stackoverflow.com/questions/18841450/proper-indentation-in-javascript" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:41:10.483", "Id": "77020", "Score": "0", "body": "Also, don't use line breaks inside strings. That's not supported cross-browser and not part of the ECMAScript spec." } ]
[ { "body": "<p>You can define a hash of the possible field names and loop through them:</p>\n\n<pre><code>var fieldTitles = {\n description: \"Description\",\n Rating: \"Average Rating\",\n RatingCount: \"Rating Count\"\n};\n\nvar volumeInfo = item.volumeInfo;\nfor (var key in fieldTitles) {\n if (volumeInfo[key]) {\n item_html += '&lt;li&gt;&lt;span&gt;' + fieldTitles[key] + ':' + volumeInfo[key] +'&lt;/span&gt;&lt;/li&gt;';\n }\n}\n</code></pre>\n\n<p>Additional notes:</p>\n\n<ul>\n<li><p>store <code>item.volumeInfo</code> to a local variable so you don't have to access it through <code>item</code> object all the time.</p></li>\n<li><p>Most of the time it's better and simpler to check for existence of a value with <code>if (someVar)</code> rather than comparing directly with undefined.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:29:13.263", "Id": "44382", "ParentId": "44366", "Score": "2" } }, { "body": "<p>There are a few way to approach this:</p>\n\n<ul>\n<li><p>You can use the <code>||</code> shortcut</p>\n\n<pre><code>&lt;li&gt;&lt;span&gt;Publisher&lt;/span&gt; ' + ( item.volumeInfo.publisher || '' )+ '&lt;/li&gt;'\n</code></pre></li>\n<li><p>You could default all the values prior to building your HTML</p>\n\n<pre><code>item.volumeInfo.publisher = item.volumeInfo.publisher || 'Publisher unknown';\n</code></pre></li>\n</ul>\n\n<p>Other than that;</p>\n\n<ul>\n<li><p>You should use a shortcut for <code>item.volumeInfo</code>, like <code>info</code>:</p>\n\n<pre><code>item_html += ' \n &lt;li&gt;&lt;img src=\"' + info.imageLinks.thumbnail+'&lt;/li&gt;\n &lt;li&gt;&lt;span&gt;Author:&lt;/span&gt; ' + info.authors + '&lt;/li&gt;\n &lt;li&gt;&lt;span&gt;Publisher&lt;/span&gt; ' + info.publisher + '&lt;/li&gt;\n &lt;li&gt;&lt;span&gt;PublishDate:&lt;/span&gt; '+ info.publishedDate+'&lt;/li&gt;\n &lt;li&gt;&lt;span&gt;Category:&lt;/span&gt; ' + info.categories + '&lt;/li&gt;\n &lt;li&gt;&lt;span&gt;Page Count:&lt;/span&gt; ' + info.pageCount +' &lt;/li&gt;\n &lt;li&gt;&lt;span&gt;ISBN:&lt;/span&gt; ISBN10_' + isbn10 +' &lt;/li&gt;\n &lt;li&gt;&lt;span&gt;Description: &lt;/span&gt; ' + info.description +' &lt;/li&gt;';\n</code></pre></li>\n<li>Your <code>success</code> function should have been separate from the <code>$.ajax({</code> call for easier reading</li>\n<li>Indent better, it's a mess</li>\n<li><code>var Rating =</code> -> <code>var rating =</code>. Only constructor functions should start with an uppercase letter</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:12:00.123", "Id": "44386", "ParentId": "44366", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:43:06.070", "Id": "44366", "Score": "1", "Tags": [ "javascript", "jquery", "parsing", "json" ], "Title": "How to handle JSON's undefined value in a better way?" }
44366
<p>Is there any way to simplify the following C# helper class to numerate a string for Json.Net?</p> <pre><code>internal static string CreateContact(string title) { var createContact = new {Title = title}; string output = JsonConvert.SerializeObject(createContact); return output; } [JsonProperty(PropertyName = "9")] public string Title { get { return _title; } set { _title = value; _title = GetTitleId(Title).ToString(); } } public static int? GetTitleId(string title) { //remove "." var titleRemoveDots = title.Replace(".", ""); var titleLowerCase = titleRemoveDots.Trim().ToLower(); switch(titleLowerCase) { case "dir": return 1; case "dr": case "doctor": return 4; case "mag": case "magister": return 5; case "ing": return 6; case "dipling": case "dipl": return 7; case "prof": case "professor": return 8; case "dkfm": return 9; case "prok": return 12; default: return null; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:26:41.830", "Id": "76990", "Score": "0", "body": "How is the class named? Is there more to it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T08:34:16.950", "Id": "77091", "Score": "1", "body": "I don't get what you're trying to do in the `Title` setter. First you're assigning `value` to `_title`, then you are assigning the result of `GetTitleId` to `_value`. And you're passing the `Title` property in the method call. Also, I would normally expect the value of a property to have the value I've just set. Finally, the Title property doesn't contain a Title, but contains a TitleId." } ]
[ { "body": "<p>Just a quick point, regarding readability; the <code>switch</code> block would be better off written like this:</p>\n\n<pre><code>//remove \".\"\nvar titleRemoveDots = title.Replace(\".\", \"\");\nvar titleLowerCase = titleRemoveDots.Trim().ToLower();\nswitch(titleLowerCase)\n{\n case \"dir\":\n return 1;\n case \"dr\": \n case \"doctor\":\n return 4;\n case \"mag\": \n case \"magister\":\n return 5;\n case \"ing\":\n return 6;\n case \"dipling\": \n case \"dipl\":\n return 7;\n case \"prof\": \n case \"professor\":\n return 8;\n case \"dkfm\":\n return 9;\n case \"prok\":\n return 12;\n default:\n return null;\n}\n</code></pre>\n\n<p>The absence of <code>break;</code> between cases (/ the presence of <code>return</code> in all cases) can make it harder to refactor the <code>switch</code> block later. I think it would be better to separate the concept of <em>figuring out the return value</em> and that of <em>returning a value</em>:</p>\n\n<pre><code>int? result;\n\n//remove \".\"\nvar titleRemoveDots = title.Replace(\".\", \"\");\nvar titleLowerCase = titleRemoveDots.Trim().ToLower();\nswitch(titleLowerCase)\n{\n case \"dir\":\n result = 1;\n break;\n case \"dr\": \n case \"doctor\":\n result = 4;\n break;\n case \"mag\": \n case \"magister\":\n result = 5;\n break;\n case \"ing\":\n result = 6;\n break;\n case \"dipling\": \n case \"dipl\":\n result = 7;\n break;\n case \"prof\": \n case \"professor\":\n result = 8;\n break;\n case \"dkfm\":\n result = 9;\n break;\n case \"prok\":\n result = 12;\n break;\n default:\n break;\n}\n\nreturn result;\n</code></pre>\n\n<p>Now, call me a <code>switch</code>-hater, I'd probably end up with something like this:</p>\n\n<pre><code>public enum PersonTitle\n{\n Director = 1,\n Doctor = 4,\n Magister = 5,\n Ingineer = 6,\n Dipling = 7,\n Professor = 8,\n Dkfm = 9, // todo: give readable name\n Prok = 12 // todo: give readable name\n}\n\nprivate static _titleIds = new Dictionary&lt;string, PersonTitle&gt; {\n { \"dir\", PersonTitle.Director },\n { \"dr\", PersonTitle.Doctor },\n { \"doctor\", PersonTitle.Doctor },\n { \"mag\", PersonTitle.Magister },\n { \"magister\", PersonTitle.Magister },\n { \"ing\", PersonTitle.Ingineer },\n { \"dipl\", PersonTitle.Dipling },\n { \"dipling\", PersonTitle.Dipling },\n { \"prof\", PersonTitle.Professor },\n { \"professor\", PersonTitle.Professor },\n { \"dkfm\", PersonTitle.Dkfm },\n { \"prok\", PersonTitle.Prok }\n };\n</code></pre>\n\n<p>And then <code>GetTitleId</code> could look like this:</p>\n\n<pre><code>public static int? GetTitleId(string title)\n{\n var cleanTitle = title.Replace(\".\", string.Empty).Trim().ToLower();\n PersonTitle result;\n\n if (_titleIds.TryGetValue(cleanTitle, out result))\n {\n return (int)result;\n }\n else\n {\n return null;\n }\n}\n</code></pre>\n\n<p>One issue is that <code>Title</code> is actually a <code>string</code> representation of the <code>int</code> value, which can be allowed to be <code>null</code> - I might be mistaken, but it looks like the setter for <code>Title</code> would throw a <code>NullReferenceException</code> if/when that is the case, because it's calling <code>ToString()</code> on <code>null</code>:</p>\n\n<blockquote>\n<pre><code>[JsonProperty(PropertyName = \"9\")]\npublic string Title\n{\n get\n {\n return _title;\n }\n set\n {\n _title = value;\n _title = GetTitleId(Title).ToString();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>I'd expect a null-check there:</p>\n\n<pre><code> set\n {\n _title = value;\n _title = (GetTitleId(Title) ?? string.Empty).ToString();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T14:02:54.560", "Id": "81734", "Score": "0", "body": "If anything this code is more complex than the code in my original question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T14:11:29.387", "Id": "81738", "Score": "2", "body": "@user2151345 indeed, a `switch` block with hard-coded magic numbers and strings is simpler *to code*. I find the dictionary simpler *to maintain*." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:09:31.780", "Id": "44377", "ParentId": "44369", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:13:09.363", "Id": "44369", "Score": "5", "Tags": [ "c#", "strings", "serialization", "json.net" ], "Title": "Helper class to change property of string when serializing for Json.Net" }
44369
<p>I'm currently developing a method which performs an update of some data; much like the following simplified logic:</p> <pre><code>boolean updateRequired = (currentValue == null &amp;&amp; newValue != null); boolean deleteRequired = (currentValue != null &amp;&amp; newValue == null); if(updateRequired || deleteRequired) { // ... } </code></pre> <p>Which probably is fine enough by itself. However, I can't loose the feeling that I'm somehow re-inventing the wheel. The above is just simplified, current/new-Value are <code>string</code>s if that matters.</p> <p>Is there any way to make this more neat?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:24:50.003", "Id": "76989", "Score": "1", "body": "Is it c#, java or php? Your question is off-topic too, you need working and complete code to be that you want reviewed. You can have a language independent answer even if you specified which language you're using" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:40:31.097", "Id": "76991", "Score": "0", "body": "If this is tagged with different language, then it may imply that it's example code. Such code is off-topic here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:48:30.183", "Id": "76992", "Score": "0", "body": "This question appears to be off-topic because it is about example code, not the actual code you wrote. This question would be more suitable for 'Programmers'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:49:51.977", "Id": "76995", "Score": "0", "body": "I've edited the question to be specified to Java. I thought to make the question as broad as possible (as this isn't really language specific). Stackoverflow-damaged ;-)." } ]
[ { "body": "<p>You could always condense it as follows:</p>\n\n<pre><code>boolean needToDoSomething = currentValue == null ? newValue != null : newValue == null;\n\nif(needToDoSomething) {\n // ...\n}\n</code></pre>\n\n<p>This is probably less clear than what you have, and gains you very little. Also, if you later branch based off of the individual values, you'd have to calculate them at that point anyway. In other words, probably best to leave it alone.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:19:40.853", "Id": "44378", "ParentId": "44370", "Score": "1" } }, { "body": "<h2>Just a thought I just had, what happens if both are false??</h2>\n\n<hr>\n\n<p>it looks like you have two separate Boolean variables that are meant to indicate two totally different things</p>\n\n<ul>\n<li>Update</li>\n<li>Delete</li>\n</ul>\n\n<p>so really if this is the case you should leave the variables the way that they are and show us the rest of the code. </p>\n\n<p>I imagine it looks something like this</p>\n\n<pre><code>boolean updateRequired = (currentValue == null &amp;&amp; newValue != null);\nboolean deleteRequired = (currentValue != null &amp;&amp; newValue == null);\n\nif (updateRequired) {\n object.Update();\n} else if (deleteRequired) {\n object.Delete();\n}\n</code></pre>\n\n<p>or maybe as two separate if statements altogether</p>\n\n<pre><code>if (updateRequired) {\n object.Update();\n}\n\nif (deleteRequired) {\n object.Delete();\n}\n</code></pre>\n\n<p>I am betting you probably want to delete first and then insert the new data/object/whatever.</p>\n\n<hr>\n\n<p>I looked at the question and it looks like you might want to delete first and then update/insert, if that is the case then you just need to flippy floppy the update and delete code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:35:21.573", "Id": "77015", "Score": "3", "body": "You're assuming that he performs different operations whether it's an update or a delete. That isn't necessarily true (but it probably is :))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:38:16.883", "Id": "77017", "Score": "0", "body": "there is a major structure issue here if OP is doing the same thing when one or the other are true. if both are false what happens?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:28:04.937", "Id": "44380", "ParentId": "44370", "Score": "1" } }, { "body": "<p>Those few lines of code are very confusing</p>\n\n<ul>\n<li><p>If the value was <code>null</code> and now not <code>null</code>, you are really creating or inserting, not updating. I would call it <code>insertRequired</code> </p>\n\n<pre><code>boolean updateRequired = (currentValue == null &amp;&amp; newValue != null);\n</code></pre></li>\n<li><p>Why would you have an <code>if</code> condition that triggers for both inserting and deleting, it would not make any sense. It should be </p>\n\n<pre><code>if( insertRequired ){\n //doSomething\n}\nelse if( deleteRequired ){\n //doSomething else\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:49:54.670", "Id": "77023", "Score": "0", "body": "Actually, since this is Java, that doesn't necessarily work. `String a = \"String\"; String b = \"String\"; a != b == true;` `==` and `!=` compare references, which may be different for equivalent string content. You would use `.equals()` but you'd still have to do null checks to make sure at least one wasn't null." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:56:47.383", "Id": "77024", "Score": "1", "body": "Actually I just checked that and the example I gave does seem to give the same reference, but if you change it to `String a = \"String\"; String b = new String(\"String\");`, then it has the expected effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T07:42:39.390", "Id": "77090", "Score": "0", "body": "@cbojar - Yep, Java uses the same instance for identical static strings." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:45:35.027", "Id": "44383", "ParentId": "44370", "Score": "3" } }, { "body": "<p>I think I know what you are looking for. you only want to do stuff if</p>\n\n<ul>\n<li>x = false and y = true</li>\n<li>x = true and y = false</li>\n</ul>\n\n<p>and not when </p>\n\n<ul>\n<li>x = false and y = false</li>\n<li>x = true and y = true</li>\n</ul>\n\n<p>in that case I would think that what you want is an <code>XOR</code> or an <code>Exclusive Or</code>\n</p>\n\n<pre><code>boolean isNewValueAssigned = newvalue != null;\nboolean isCurrentValueAssigned = currentValue != null;\nif (isNewValueAssigned ^ isCurrentValueAssigned) {\n //Play more Galaga\n //do More Work\n}\n</code></pre>\n\n<p>I think that this makes it more clear what you are trying to do.</p>\n\n<p>Reference to this <a href=\"https://stackoverflow.com/questions/726652/creating-a-logical-exclusive-or-operator-in-java#comment538455_726665\">Comment</a> and this <a href=\"https://stackoverflow.com/a/726665/1214743\">Answer</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T20:13:51.840", "Id": "77041", "Score": "1", "body": "The XOR operator in Java `^` is inended for use as a bitwise XOR, not a logical XOR of booleans. For a logical check, use `!=` like `if (updateRequired != deleteRequired) {....}`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:54:17.083", "Id": "44385", "ParentId": "44370", "Score": "2" } }, { "body": "<p>Depending on your use case, I recommend two options. Both of them are based on a separate function for checking things....</p>\n\n<p>At its simplest, have a function:</p>\n\n<pre><code>private static final boolean needToDoSomething(String currentValue, String newValue) {\n return currentValue == null &amp;&amp; newValue != null || currentValue != null &amp;&amp; newValue == null;\n}\n</code></pre>\n\n<p>Then you can just have:</p>\n\n<pre><code>if (needToDoSomething(currentValue, newValue)) {\n ....\n}\n</code></pre>\n\n<p>If you need to do something more special than just the 'needs modification' test, for example, you need to distinguish inside the <code>if</code> block between these conditions, then I would recommend an Enum with a static method, for example:</p>\n\n<pre><code>public enum EditState {\n ADDED, DELETED, MODIFIED, UNCHANGED;\n\n public static getState(String currentValue, String newValue) {\n if (currentValue == newValue) {\n // this covers null == null too\n return UNCHANGED;\n }\n if (currentValue != null &amp;&amp; newValue == null) {\n return DELETED;\n }\n if (newValue != null &amp;&amp; currentValue == null) {\n return ADDED;\n }\n return currentValue.equals(newValue) ? UNCHANGED : MODIFIED;\n }\n\n\n public boolean isStateChanging() {\n return this != UNCHANGED;\n }\n}\n</code></pre>\n\n<p>Then, with this Enum class, you can be more specific:</p>\n\n<pre><code>EditState state = EditState.getState(currentValue, newValue);\n\nswitch (state) {\n case UNCHANGED :\n .....\n case DELETED :\n .....\n ....\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T00:00:52.907", "Id": "77074", "Score": "0", "body": "Nice, I really liked the `enum` solution; perhaps a bit overkill in my scenario, but nice. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:38:06.757", "Id": "44388", "ParentId": "44370", "Score": "10" } }, { "body": "<p>In my opinion, you haven't included enough code to make this a good Code Review question, but I'll try to answer anyway.</p>\n\n<p>If <code>currentValue == null</code> and <code>newValue != null</code>, then it seems to me that <code>createRequired</code> would be a better name than <code>updateRequired</code>.</p>\n\n<p>You appear to be checking to see if exactly one of <code>currentValue</code> or <code>newValue</code> is <code>null</code>.</p>\n\n<pre><code>if ((currentValue == null) != (newValue == null)) {\n // ...\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T22:51:24.903", "Id": "44412", "ParentId": "44370", "Score": "4" } } ]
{ "AcceptedAnswerId": "44388", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:21:16.587", "Id": "44370", "Score": "7", "Tags": [ "java" ], "Title": "To update or to delete? That is the Query" }
44370
<p>I picked the first test (Tape Equilibrium) from Codility <a href="https://codility.com/train/">here</a>. </p> <p>Question:</p> <blockquote> <p>A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape. Any integer P, such that <code>0 &lt; P &lt; N</code>, splits this tape into two non−empty parts:</p> <pre><code> A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1]. </code></pre> <p>The difference between the two parts is the value of:</p> <pre><code> |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])| </code></pre> <p>In other words, it is the absolute difference between the sum of the first part and the sum of the second part.For example, consider array A such that:</p> <pre><code> A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 </code></pre> <p>We can split this tape in four places:</p> <pre><code>P = 1, difference = |3 − 10| = 7 P = 2, difference = |4 − 9| = 5 P = 3, difference = |6 − 7| = 1 P = 4, difference = |10 − 3| = 7 </code></pre> <p>Write a function: <code>int solution(int A[], int N);</code> that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.</p> </blockquote> <p>This is how I implemented it. I got 50% with complexity N*N. How could I make it cleaner?</p> <pre><code>// you can also use imports, for example: import java.math.*; import java.util.*; import java.lang.*; class Solution { public int solution(int[] A) { // write your code in Java SE 7 int sizeOfArray = A.length; int smallest = Integer.MAX_VALUE; int result = 0; for(int i=1;i&lt;sizeOfArray;i++){ int difference = Math.abs(sumOfArray(subArray(0,i,A))- sumOfArray(subArray(i,sizeOfArray,A))); //System.out.println("difference"+difference); result = Math.min(smallest,difference); smallest = result; } return result; } public int sumOfArray(int[] arr) { int sum=0; for(int i:arr) { sum += i; } return sum; } public int[] subArray(int begin, int end, int[] array) { return Arrays.copyOfRange(array, begin, end); } } </code></pre>
[]
[ { "body": "<p><strong>Naming</strong></p>\n\n<p>The Java naming convention for arguments is camelCase. You should rename this argument <code>A</code> here: </p>\n\n<blockquote>\n<pre><code>public int solution(int[] A) \n</code></pre>\n</blockquote>\n\n<p>It would be best to make it look like the following code, or use a better name that would fit your needs:</p>\n\n<pre><code>public int solution(int[] arrayA) \n</code></pre>\n\n<p>I don't have anything against a variable named <code>arr</code> for an <code>int []</code>, but you're using <code>arr</code> and <code>array</code> in different methods. I would recommend to stick to one name, or try to find less generic name if they mean different things.</p>\n\n<p><strong>Formatting</strong></p>\n\n<p>Your formatting is very good in general, and you're consistent. Some times, you could use a little bit of white-space.</p>\n\n<blockquote>\n<pre><code>for(int i=1;i&lt;sizeOfArray;i++)\n</code></pre>\n</blockquote>\n\n<p>You could add some spaces to clearly define the three part of the for-loop:</p>\n\n<pre><code>for(int i=1; i&lt;sizeOfArray; i++)\n</code></pre>\n\n<p>I will not evaluate your algorithm, since this is not my forte.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:51:15.243", "Id": "76996", "Score": "1", "body": "I would have gone for `array`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:48:31.683", "Id": "44373", "ParentId": "44371", "Score": "15" } }, { "body": "<p>From a once over,</p>\n\n<p>you seem to call <code>sumofArray</code> a number of times, you should only have to call it once.</p>\n\n<p>At the very beginning, you call it once for the entire array, results should be <code>13</code><br>\nThen for position 0 (value 3), you substract <code>3</code> and get <code>3</code> and <code>10</code> ( 13 - 10)<br>\nThen for position 1 (value 1). you add <code>1</code> to <code>3</code> and subtract <code>1</code> from <code>10</code> giving <code>4</code> and <code>9</code><br>\nThen for position 2 (value 2), you add <code>2</code> to <code>4</code> and substract <code>2</code> from <code>9</code> giving <code>6</code> and <code>7</code><br></p>\n\n<p>etc. ad nauseum.</p>\n\n<p>This way you access all elements twice, if I count correctly.</p>\n\n<p>As I mentioned in a comment, I would rename <code>arr</code> -> <code>array</code></p>\n\n<p>I am no Java expert, but JavaScript is close enough that you should be able to follow:</p>\n\n<pre><code>var A = [3,1,2,4,3];\n\nfunction sumArray( array )\n{\n var sum = 0, index = array.length;\n while(index--)\n sum += array[index];\n return sum;\n}\n\nfunction tapeEquilibrium( array )\n{\n var left = sumArray( array ),\n right = 0,\n smallest = left,\n index = array.length,\n difference;\n\n while( index-- )\n {\n right += array[index];\n left -= array[index];\n difference = Math.abs( right-left );\n if( difference &lt; smallest )\n smallest = difference; \n }\n return smallest;\n}\n\nconsole.log( tapeEquilibrium( A ) );\n</code></pre>\n\n<p>The added advantage is that very little extra memory is required when very large arrays need to be examined.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:59:33.380", "Id": "44375", "ParentId": "44371", "Score": "11" } }, { "body": "<p>The trick to this problem is in the algorithm. A solution of \\$O(n)\\$ complexity is available if you process the data in a 'clever' way. Consider the following algorithm:</p>\n\n<ul>\n<li>create a new array of the same size, call it <code>sum</code></li>\n<li>populate the <code>sum</code> array with the sum of all values to the left in the original data array</li>\n<li>Once the <code>sum</code> array is fully populated, you will know what the total sum is for the array.</li>\n<li>this allows you to determine what the balance-point-sum is, it will be half of the total.</li>\n<li>you may be tempted to just binary search the sum array for the place that is half the total, but this will fail if there are negative values in the input array.</li>\n<li>the only solution is to scan the sums looking for half the value, with some short-circuit if there is an exact half found.</li>\n</ul>\n\n<p>Putting it together as code, it looks like:</p>\n\n<pre><code>public static final int tapeEquilibrium(int[] data) {\n if (data.length &lt; 3) {\n // rules indicate 0 &lt; P &lt; N which implies at least 3-size array\n throw new IllegalStateException(\"Need minimum 3-size array input\");\n }\n int[] sums = new int[data.length];\n for (int i = 1; i &lt; sums.length; i++) {\n sums[i] = sums[i - 1] + data[i - 1];\n }\n int total = sums[sums.length - 1] + data[data.length - 1];\n int min = Integer.MAX_VALUE;\n for (int i = 0; i &lt; sums.length; i++) {\n int diff = Math.abs((total - sums[i]) - sums[i]);\n if (diff == 0) {\n return 0;\n }\n if (diff &lt; min) {\n min = diff;\n }\n }\n return min;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:08:51.670", "Id": "44376", "ParentId": "44371", "Score": "8" } }, { "body": "<p>You should be able to do it in \\$O(n)\\$ time and \\$O(1)\\$ space. Keep a running total of the left sum and the right sum. As you test each \\$p\\$, deduct a number from one side and credit it to the other.</p>\n\n<pre><code>public static int minDiff(int[] a) {\n int leftSum = 0, rightSum = 0;\n for (int ai : a) {\n leftSum += ai;\n }\n int minDiff = Integer.MAX_VALUE;\n for (int p = a.length - 1; p &gt;= 0; p--) {\n rightSum += a[p];\n leftSum -= a[p];\n\n int diff = Math.abs(leftSum - rightSum);\n if (diff == 0) {\n return 0;\n } else if (diff &lt; minDiff) {\n minDiff = diff;\n }\n }\n return minDiff;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:31:14.237", "Id": "77010", "Score": "0", "body": "Basically, the same solution as @konijn's." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:31:19.580", "Id": "77011", "Score": "0", "body": "This solution will not work when the input contains negative values... The sum of the two sides will not be increasing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:32:48.400", "Id": "77013", "Score": "0", "body": "@rolfl Could you provide a counterexample?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:37:09.877", "Id": "77016", "Score": "0", "body": "Never mind, I misread your description vs your implementation. Your description says 'keep a running total of the left sum', but that is not what your code does, your code calculates the complete total of all values, and then subtracts things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:39:21.993", "Id": "77019", "Score": "0", "body": "Except that my last Java code was in 1.4, so I wrote some JavaScript ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T01:55:33.790", "Id": "77078", "Score": "0", "body": "@200_success loved it thanks!keeping a running sum was the key." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:28:13.973", "Id": "44381", "ParentId": "44371", "Score": "12" } }, { "body": "<p>Just a minor note to add about the original code which was not mentioned earlier:</p>\n\n<p>The code uses <code>subArray</code> only for summarizing:</p>\n\n<blockquote>\n<pre><code>int difference = Math.abs(sumOfArray(subArray(0,i,A))-\nsumOfArray(subArray(i,sizeOfArray,A)));\n</code></pre>\n</blockquote>\n\n<p>It would be faster with the original array:</p>\n\n<pre><code>public int sumOfArray(int[] array, int begin, int end) {\n int sum = 0;\n for (int i = begin; i &lt; end; i++) {\n sum += array[i];\n }\n return sum;\n}\n</code></pre>\n\n<p>+1: An extra tab in the second line above the would make it clear that it's one statement:</p>\n\n<pre><code>int difference = Math.abs(sumOfArray(subArray(0,i,A))-\n sumOfArray(subArray(i,sizeOfArray,A)));\n</code></pre>\n\n<p>This makes the code easier to read (and maintain).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T13:28:40.067", "Id": "44442", "ParentId": "44371", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T17:26:58.943", "Id": "44371", "Score": "27", "Tags": [ "java", "algorithm", "programming-challenge" ], "Title": "Tape Equilibrium" }
44371
<p>I am currently using this code (and more) to deal with 2D matrices. I am not very proficient in C, so I am not quite sure, if this is a good way of doing it. I've seen other people in similar situations using pointers to a struct, but I didn't want to complicate things... </p> <pre><code>typedef struct CMatrix { double *m; uint32_t width; uint32_t height; } CMatrix; </code></pre> <p>-</p> <pre><code>CMatrix newCMatrix(uint32_t width, uint32_t height) { CMatrix rtn; rtn.m = malloc(width * height * sizeof(double)); bzero(rtn.m, width * height * sizeof(double)); rtn.width = width; rtn.height = height; return rtn; } </code></pre> <p>-</p> <pre><code>CMatrix ma = newCMatrix(2, 2); </code></pre> <p>All ideas are welcome!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:39:10.043", "Id": "77031", "Score": "0", "body": "What is the use of this `bzero` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:45:25.813", "Id": "77032", "Score": "0", "body": "because the memory returned by malloc() is not initialized, I'm setting it to all zeros." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:51:18.137", "Id": "77034", "Score": "0", "body": "Use `memset` instead of `bzero`. But it is better to use `calloc` than using `malloc` + `memset`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T00:45:18.523", "Id": "77076", "Score": "0", "body": "You are not using signed integers to represent sizes/indices (Well done), but note that the standard library provide an specific type for this purpose: `size_t`" } ]
[ { "body": "<p><em>This answer replaces poor advice in a previous answer.</em></p>\n\n<p>You can use <code>calloc()</code> instead of <code>malloc()</code> and <code>bzero()</code>.</p>\n\n<p>Your <code>newCMatrix()</code> is otherwise fine. If you write a <code>newCMatrix(uint32_t, uint32_t)</code>, though, you should also provide a corresponding <code>freeCMatrix(CMatrix)</code> to deallocate the array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T20:20:12.320", "Id": "77042", "Score": "0", "body": "Thanks! I actually have a freeCMatrix() function, but I didn't include it in this post." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T20:15:03.020", "Id": "44394", "ParentId": "44387", "Score": "1" } }, { "body": "<p>Pointers seem more complicated, but they're usually faster and more correct.</p>\n\n<h2>Faster</h2>\n\n<p>For example, perhaps you have a function like this:</p>\n\n<pre><code>CMatrix add(CMatrix left, CMatrix right)\n{\n ... add the matrices ...\n}\n</code></pre>\n\n<p>In the above you're passing matrix parameters by value instead of by pointer. That means that you're passing a copy of each matrix (instead of a pointer to each matrix).</p>\n\n<p>Assuming you have 32-bit pointers, each matrix is 12 bytes in size (4 bytes for the pointer and 4 bytes for each integer), so you're passing 24 bytes (for two matrices) instead of 8 bytes (for two pointers-to-matrices).</p>\n\n<p>That (24 bytes instead of 8 bytes) is not a big difference (i.e. not much slower); but it's a bigger difference when your structs are larger and more complicated.</p>\n\n<h2>More correct</h2>\n\n<p>Another problem is that subroutines are operating on a private, local copy of the matrix; for example:</p>\n\n<pre><code>void transpose(CMatrix matrix)\n{\n ... height becomes width and vice versa ...\n uint32_t oldWidth = matrix.width;\n uint32_t oldHeight = matrix.height;\n matrix.width = oldHeight;\n matrix.height = oldWidth;\n ... and transpose the data ...\n}\n</code></pre>\n\n<p>This function changes the width and height of its local copy of the matrix, not the width and height of the caller's copy of the matrix.</p>\n\n<h2>Summary</h2>\n\n<p>Your code happens to work because:</p>\n\n<ul>\n<li>You have a simple structure</li>\n<li>You don't alter height and width in a subroutine, after you create the matrix</li>\n<li>The data itself within the matrix (i.e. the <code>double *m</code> pointer) is a pointer (and is therefore shared between subroutines)</li>\n</ul>\n\n<p>However it's bad practice: if you're coding in C, you should become familiar with using pointers.</p>\n\n<p>There's nothing wrong with the <code>newCMatrix</code> function you showed in the OP. What I'm criticizing is your statement that pointers complicate things, because they're usually necessary, e.g. for other functions; for example, the 'add' function above should (in order to be idiomatic) be declared more like the following:</p>\n\n<pre><code>CMatrix add(const CMatrix *left, const CMatrix *right)\n{\n ... add the matrices ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:07:13.977", "Id": "77049", "Score": "0", "body": "Presumably, `transpose(const CMatrix)` would return the result in a new `CMatrix`. The caller would have to remember to free a lot of stuff, which could get tricky." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:19:12.643", "Id": "77051", "Score": "0", "body": "Yes, transpose would have to return a new CMatrix if it couldn't alter the existing one: `CMatrix transposed = transpose(matrix);`. Perhaps pass-by-value works well for the OP, given the peculiar nature of the CMatrix struct (i.e. logically const height and width properties, with the mutable data located in a pointer-type member); I hoped to warn that C code doesn't always/generally work correctly without using pointers, and that pointers are idiomatic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T22:07:04.450", "Id": "77062", "Score": "0", "body": "Thanks! I didn't even think about the whole call by value / call by reference issue, because so far I didn't have any functions that manipulate the matrices..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T20:45:37.803", "Id": "44399", "ParentId": "44387", "Score": "4" } } ]
{ "AcceptedAnswerId": "44399", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:35:24.993", "Id": "44387", "Score": "11", "Tags": [ "c", "beginner", "matrix", "pointers" ], "Title": "C struct or pointer to struct?" }
44387
<p>I've found myself wanting an easy way to implement chat into various apps, so I developed a set of classes for the firebase.com backend that make it easy for me to quickly set up the nuts and bolts of a chat system. To implement this, I have three classes:</p> <h3>FSPresenceManager</h3> <p>Current Connection / Other User's Connection</p> <h3>FSChannelManager</h3> <p>Send / Receive Alerts From users</p> <h3>FSChatManager</h3> <p>Create Chat / Send &amp; Receive Messages / Light "Queries" (hoping to improve)</p> <p>These classes act as sort of a notification center where you can register observers for callbacks and the class distributes the information when it comes in from firebase. For this reason, I used singletons in all cases. I decided to wrap all of these classes into a greater class, which is also a Singleton that I called FireSuite.</p> <p>This allows me to set things like URL, and CurrentUserId for all managers at once in a few lines.</p> <h3>FireSuite.h</h3> <pre><code>#import "FSChatManager.h" #import "FSPresenceManager.h" #import "FSChannelManager.h" @interface FireSuite : NSObject + (FireSuite *) suiteManager; // Singleton @property (strong, nonatomic) NSString * firebaseURL; @property (strong, nonatomic) NSString * currentUserId; @property (strong, nonatomic) FSChatManager * chatManager; @property (strong, nonatomic) FSPresenceManager * presenceManager; @property (strong, nonatomic) FSChannelManager * channelManager; @end </code></pre> <h3>FireSuite.m</h3> <pre><code>#import "FireSuite.h" @implementation FireSuite @synthesize firebaseURL, currentUserId, presenceManager, chatManager, channelManager; + (FireSuite *) suiteManager { static dispatch_once_t pred; static FireSuite *shared = nil; dispatch_once(&amp;pred, ^{ shared = [[FireSuite alloc] init]; }); return shared; } #pragma mark SETTERS - (void) setFirebaseURL:(NSString *)firebaseURLsetter { if (![firebaseURLsetter hasSuffix:@"/"]) { firebaseURLsetter = [NSString stringWithFormat:@"%@/", firebaseURLsetter]; } // Set Our Tools [FSChatManager singleton].urlRefString = firebaseURLsetter; [FSPresenceManager singleton].urlRefString = firebaseURLsetter; [FSChannelManager singleton].urlRefString = firebaseURLsetter; firebaseURL = firebaseURLsetter; } - (void) setCurrentUserId:(NSString *)currentUserIdToSet { // Set Our Tools [FSChatManager singleton].currentUserId = currentUserIdToSet; [FSPresenceManager singleton].currentUserId = currentUserIdToSet; [FSChannelManager singleton].currentUserId = currentUserIdToSet; currentUserId = currentUserIdToSet; } #pragma mark GETTERS - (FSPresenceManager *) presenceManager { FSPresenceManager * manager = [FSPresenceManager singleton]; return manager; } - (FSChatManager *) chatManager { FSChatManager * manager = [FSChatManager singleton]; return manager; } - (FSChannelManager *) channelManager { FSChannelManager * manager = [FSChannelManager singleton]; return manager; } @end </code></pre> <p>Everything is still fairly "Stream Of Thought Programming" so there's a bit of inconsistency and things I'd prefer to implement differently, but before I proceed I wanted to get a second opinion on this.</p> <p>The main reason is that it allows me to easily update firebaseURL / currentUserId one time without having to worry about it being up to date everywhere.</p> <p>Aside from general preferences, is this going to create unforeseen problems?</p> <p>Second opinions and alternative strategies are also welcome! Also, if there's problems with something about my post, please elaborate when downvoting. This is my first codeReview post and I might just not understand something!</p> <h3>Usage</h3> <p>Step 1: Create suiteManager and assign URL / CurrentUser</p> <pre><code>FireSuite * fireSuite = [FireSuite suiteManager]; fireSuite.firebaseURL = @"https://someFirebase.firebaseIO.com/"; fireSuite.currentUserId = @"currentUserId"; </code></pre> <p>Step 2: Monitor Our Connection / Other User's Connection</p> <pre><code>FSPresenceManager * presenceManager = fireSuite.presenceManager; // Start Monitor [presenceManager startPresenceManager]; // Monitor Current User's Connection [presenceManager registerConnectionStatusObserver:self withSelector:@selector(isConnected:)]; // Monitor Other Users (for instance, a chat opponent) [presenceManager registerUserStatusObserver:self withSelector:@selector(userStatusDidUpdateWithId:andStatus:) forUserId:@"userId1"]; [presenceManager registerUserStatusObserver:self withSelector:@selector(userStatusDidUpdateWithId:andStatus:) forUserId:@"userId2"]; // Receive Presence Manager Notifications - (void) isConnected:(BOOL)isConnected { NSLog(@"Current User %@ firebase", isConnected ? @"Connected To": @"Disconnected From"); } // Use this to monitor chat partners or whoever to see if they're online - (void) userStatusDidUpdateWithId:(NSString *)userId andStatus:(BOOL)isOnline { NSLog(@"%@ is currently: %@", userId, isOnline ? @"Online": @"Offline"); } </code></pre> <p>Step 3: Channel Manager</p> <pre><code>// Get Channel Manager FSChannelManager * channelManager = fireSuite.channelManager; // Observe Current User's Alert's Channel [channelManager registerUserAlertsObserver:self withSelector:@selector(receivedAlert:)]; // To Send An Alert NSMutableDictionary * alertData = [NSMutableDictionary new]; alertData[@"some"] = @"random"; alertData[@"data"] = @"here"; // Received Via - (void) receivedAlert:(NSDictionary *)alert { NSString * alertType = alert[kAlertType]; id alertData = alert[kAlertData]; double timestamp = [alert[kAlertTimestamp] doubleValue] / 1000; NSDate * sentAt = [NSDate dateWithTimeIntervalSince1970:timestamp]; NSLog(@"Received alert sentAt: %@ alertType: %@ withData: %@", sentAt, alertType, alertData); } // alertData can be any %@ object [channelManager sendAlertToUserId:@"currentUserId" withAlertType:@"someAlertType" andData:alertData withCompletion:^(NSError * error) { if (!error) { NSLog(@"Alert Sent"); } else { NSLog(@"ERROR: %@", error); } }]; </code></pre> <p>Step 4: Use Chat Manager</p> <pre><code>FSChatManager * chatManager = fireSuite.chatManager; // Create A New Chat // Set CustomId to nil for AutoId [chatManager createNewChatForUsers:@[@"user1id", @"user2id"] withCustomId:nil andCompletionBlock:^(NSString *newChatId, NSError *error) { NSLog(@"Created New Chat With Id: %@", newChatId); [self launchNewChatSessionForChatId:newChatId]; }]; // Launch New Session - (void) launchNewChatSessionForChatId:(NSString *)chatId { FireSuite * fireSuite = [FireSuite suiteManager]; FSChatManager * chatManager = fireSuite.chatManager; chatManager.chatId = chatId; // chat id of new session chatManager.delegate = self; // who to send the messages chatManager.maxCount = [NSNumber numberWithInt:50]; // number of initial recent messages to receive [chatManager loadChatSessionWithCompletionBlock:^(NSArray *messages, NSError *error) { if (!error) { // Will receive the 50 most recent messages from firebase (maxCount) NSLog(@"Open with recent messages: %@", messages); // receivedNewMessage: will begin running now. } else { NSLog(@"Error: %@", error); } }]; } // Chat Session Delegate Call - (void) newMessageReceived:(NSMutableDictionary *)newMessage { NSLog(@"Received new message: %@", newMessage); } // To Send Message: [chatManager sendNewMessage:@"Some message to send to the chat!"]; // To End Chat Session - (void) endChat { [[FireSuite suiteManager].chatManager endChatSessionWithCompletionBlock:^{ NSLog(@"Closed Current Chat Session"); }]; } </code></pre> <p>Full Code Here: <a href="https://github.com/LoganWright/FireSuite" rel="nofollow">GitHub</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:16:13.917", "Id": "77050", "Score": "0", "body": "Generally speaking, singletons should be avoided where they can. With that said, there's not enough code here to determine whether or not the singletons are avoidable. There's not much code here to actually review. I understand you've posted a link to the entire project in GitHub, but you should post the code you want the review to be focused on here and post the link only as a means of giving us some context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:23:27.220", "Id": "77052", "Score": "0", "body": "Hi, @nhgrif, the reason I've implemented singletons in my case is so that each singleton can register observers on various levels of my app and distribute information from firebase without having to create / destroy / keep track of multiple connections. I'll reevaluate my question to see if I can explain some usage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:37:01.380", "Id": "77057", "Score": "0", "body": "@nhgrif, is this a better explanation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-03T06:34:18.847", "Id": "149360", "Score": "0", "body": "@Logan, I've been thinking about similar structure recently, and probably instead of class names of subsingletons (in addition to instancetype for \"outer\" singleton) it would be better to have id<ProtocolName> so that you can swap the whole singleton.\n\nAlso, did you make any changes in this setup and/or found some bad usecases?" } ]
[ { "body": "<p>There's very little code here to review, and I made some points in my comment to the question regarding this, however, on what is posted, here are some notes...</p>\n\n<hr>\n\n<p>First of all, Xcode now autosynthesizes, so you can eliminate this line:</p>\n\n<pre><code>@synthesize firebaseURL, currentUserId, presenceManager, chatManager, channelManager;\n</code></pre>\n\n<p>This does mean you'll have to refer to <code>firebaseURL</code> as <code>_firebaseURL</code> instead, but this actually makes it more clear that you're referring to a private instance variable and not a method variable. Xcode while highlight it properly for you either way, which helps you distinguish, but when posted outside of Xcode, such as Github or Codereview, the highlighting isn't done, so it's easy to miss.</p>\n\n<hr>\n\n<p>Second, you can slightly improve performance and save some lines of code by putting your three singletons into a collection. Once you've done that (suppose a NSDictionary, so you can use keys to determine what's what), try out this line of code:</p>\n\n<pre><code>[someArray makeObjectsPerformSelector:@selector(setUrlRefString:) \n withObject:firebaseURLsetter];\n</code></pre>\n\n<hr>\n\n<p>Third, in your getters for your singletons, you can simply write:</p>\n\n<pre><code>return [FSPresenceManager singleton];\n</code></pre>\n\n<p>Rather than setting a variable then returning the variable.</p>\n\n<hr>\n\n<p>Fourth, you should be sure to override the setters for the singletons to be instance variables aren't created for them.</p>\n\n<pre><code>- (void)setPresenceManager {\n return;\n}\n</code></pre>\n\n<hr>\n\n<p>Fifth, you've put a lot of work into giving yourself convenience methods for synching these three singletons. But what prevents me from doing this:</p>\n\n<pre><code>[FireSuite suiteManager].chatManager.urlRefString = @\"SomethingDifferentFromTheOtherTwo\";\n</code></pre>\n\n<p>The answer is, nothing.</p>\n\n<p>You might consider making the inner singletons all private, and giving this suite manager a bunch of method wrappers.</p>\n\n<hr>\n\n<p>Finally, your singleton's return type is <code>FireSuite</code>. I imagine you've done similar for the three inner singletons. If you ever want to subclass any of these for any reason, you're going to run into trouble. If you keep this return type, you're preventing subclassing, which may be something you want to do (see <code>NSNumber</code>, for example). But I don't see any particular reason for preventing subclassing.</p>\n\n<p>But wait, before you switch the return type to <code>id</code>... hold on. If you switch to <code>id</code>, you can't do the following:</p>\n\n<pre><code>[FireSuite suiteManager].chatManager\n</code></pre>\n\n<p>Instead, you'll have to do this:</p>\n\n<pre><code>((FireSuite*)[FireSuite suiteManager].chatManager\n</code></pre>\n\n<p>So instead of a return type of <code>id</code>, we're going to want to use <code>instancetype</code> as our return type.</p>\n\n<p>This is some Xcode magic which will assures the type you're returning is the type that's calling the method, even if you subclass. <code>[FireSuite suiteManager]</code> returns a <code>FireSuite</code> object, and <code>[FireSuiteSubclass suiteManager]</code> returns a <code>FireSuiteSubclass</code> object.</p>\n\n<hr>\n\n<p><strong>Addendum:</strong> Why does the chat manager have a delegate and methods that take block arguments?</p>\n\n<p>Couldn't we have two methods to whatever protocol chat manager delegates conform to, one for success and one for error?</p>\n\n<pre><code>@protocol YourChatManagerDelegate\n@required - (void)chatSessionLoadDidFailWithError:(NSError*)error;\n@required - (void)chatSessionDidFinishLoadWithMessages:(NSArray*)messages;\n</code></pre>\n\n<p>Now our delegate simply implements these methods, and the chat manager calls these methods rather than executing the completion block which will no longer be passed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:47:32.807", "Id": "77059", "Score": "0", "body": "Thanks, there's a lot of stuff here for me to digest and work on! How do I add instanceType? I tried to put instancetype where I would put 'id', but it is calling errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:48:45.900", "Id": "77060", "Score": "0", "body": "In both the `.h` and `.m` files, change from this: `+ (FireSuite *) suiteManager` ........................ to this: `+ (instancetype) suiteManager` And don't forget to check the addendum I addended." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:39:19.187", "Id": "44406", "ParentId": "44391", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T19:52:01.683", "Id": "44391", "Score": "4", "Tags": [ "objective-c", "ios", "singleton" ], "Title": "Singleton With Sub-Singletons" }
44391
<p>This code review is inspired by the <a href="https://stackoverflow.com/questions/22411299/sort-files-in-numeric-order">this StackOverflow question</a> and written in Java 8.</p> <p>The code is supposed to:</p> <ol> <li>Order all files, with syntax <code>jobXXX.script</code>, where <code>XXX</code> is a number, by the number.</li> <li>Write the contents of the files in that ordering to one file.</li> </ol> <p>I am asking for a general code review and there are two things that are bugging me:</p> <ul> <li>I need to wrap <code>Exception</code>s inside lambda expressions.</li> <li>The file that is being written to, has an imperfect unnecessary annoying OCD-triggering newline at the end.</li> </ul> <hr> <pre><code>package testproject4; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import java.util.stream.Stream; /** * * @author Beheerder */ public class TestProject4 { private void init() throws IOException { Path directory = Paths.get("C:\\Users\\Frank\\Downloads\\testjob"); try (BufferedWriter writer = Files.newBufferedWriter(directory.resolve("masterjob.script"))) { Files.list(directory) .filter(path -&gt; Files.isRegularFile(path)) .filter(path -&gt; path.getFileName().toString().matches("job\\d+.script")) .sorted(Comparator.comparingInt(this::pathToInt)) .flatMap(this::wrappedLines) .forEach(string -&gt; wrappedWrite(writer, string)); } } private int pathToInt(final Path path) { return Integer.parseInt(path.getFileName() .toString() .replaceAll("job(\\d+).script", "$1") ); } private Stream&lt;String&gt; wrappedLines(final Path path) { try { return Files.lines(path); } catch (IOException ex) { //swallow return null; } } private void wrappedWrite(final BufferedWriter writer, final String string) { try { writer.write(string); writer.newLine(); } catch (IOException ex) { //swallow } } public static void main(String[] args) throws IOException { new TestProject4().init(); } } </code></pre>
[]
[ { "body": "<h2>NewLine</h2>\n\n<p>The newline at the end is correct... at least according to your code.</p>\n\n<p><code>Files.lines(...)</code> ignores the last line of input files if it has no characters. This is a standard system to have for most operating systems (the last character in a text file is a newline).</p>\n\n<p>Your code is perpetuating this process, and it always adds a newline after each line printed.</p>\n\n<p>Thus, your file always ends up with a newline at the end. This is a good thing.</p>\n\n<h2>Exceptions</h2>\n\n<p>Java Lambdas cannot contain expressions that throw caught exceptions. This is a weakness. The weakness is so sever that as part of Java8, there is the new Exception <a href=\"http://download.java.net/jdk8/docs/api/java/io/UncheckedIOException.html\" rel=\"nofollow\"><code>UncheckedIOException</code></a> so that IO-based operations can throw an unchecked exception.</p>\n\n<p>The easiest way to use it is to change your catch blocks to:</p>\n\n<pre><code>private Stream&lt;String&gt; wrappedLines(final Path path) {\n try {\n return Files.lines(path);\n } catch (IOException ioe) {\n throw new UncheckedIOException(ioe);\n }\n}\n</code></pre>\n\n<p>The alternative is to wrap the exception inside the lambda with:</p>\n\n<pre><code> try (BufferedWriter writer = Files.newBufferedWriter(directory.resolve(\"masterjob.script\"))) {\n Files.list(directory)\n .filter(path -&gt; Files.isRegularFile(path))\n .filter(path -&gt; path.getFileName().toString().matches(\"job\\\\d+.script\"))\n .sorted(Comparator.comparingInt(this::pathToInt))\n .flatMap(try { this::wrappedLines } catch(IOException ioe) {throw new UncheckedIOException(ioe)})\n .forEach(string -&gt; try {wrappedWrite(writer, string)} catch(IOException ioe) {throw new UncheckedIOException(ioe)});\n }\n</code></pre>\n\n<h2>General</h2>\n\n<p>The Java8 side of this otherwise looks OK, and works fine for me too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:06:30.993", "Id": "44401", "ParentId": "44392", "Score": "2" } } ]
{ "AcceptedAnswerId": "44401", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T20:10:13.670", "Id": "44392", "Score": "6", "Tags": [ "java", "io", "lambda" ], "Title": "Combining contents of files by reading them in a human ordering" }
44392
<p>For the implementation of the Playfair encryption I needed a custom struct called Cell. This is because I not only need an array of characters I also want to get Elements in a matrix based on their "cartesian" position.</p> <pre><code>public struct Cell { public char character; public int X; public int Y; public Cell(char _character,int _X, int _Y) { this.character = _character; this.X = _X; this.Y = _Y; } } </code></pre> <p>Then I implement the method which calculates the cipher.</p> <pre><code>public static string PlayfairCipher(string keyWord,string plainText) { //Define alphabet //There is no J in the alphabet instead I is used char[] alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ".ToCharArray(); #region Adjust Key keyWord = keyWord.Trim(); keyWord = keyWord.Replace(" ", ""); keyWord = keyWord.Replace("J", "I"); keyWord = keyWord.ToUpper(); StringBuilder keyString = new StringBuilder(); foreach(char c in keyWord) { if(!keyString.ToString().Contains(c)) { keyString.Append(c); alphabet = alphabet.Where(val =&gt; val != c).ToArray(); } } #endregion #region Adjust plain text plainText = plainText.Trim(); plainText = plainText.Replace(" ", ""); plainText = plainText.Replace("J", "I"); plainText = plainText.ToUpper(); //If the Length of the plain text is odd add X if((plainText.Length % 2 &gt; 0)) { plainText += "X"; } List&lt;string&gt; plainTextEdited = new List&lt;string&gt;(); //Split plain text into pairs for (int i = 0; i &lt; plainText.Length;i += 2) { //If a pair of chars contains the same letters replace one of them with X if (plainText[i].ToString() == plainText[i + 1].ToString()) { plainTextEdited.Add(plainText[i].ToString() + 'X'); } else { plainTextEdited.Add(plainText[i].ToString() + plainText[i + 1].ToString()); } } #endregion #region Create 5 x 5 matrix List&lt;Cell&gt; matrix = new List&lt;Cell&gt;(); int keyIDCounter = 0; int alphabetIDCounter = 0; //Fill the matrix. First with the key characters then with the alphabet for (int x = 0; x &lt; 5;x++) { for (int y = 0; y &lt; 5; y++) { if (keyIDCounter &lt; keyString.Length) { Cell cell = new Cell(keyString[keyIDCounter],x,y); matrix.Add(cell); keyIDCounter++; } else { Cell cell = new Cell(alphabet[alphabetIDCounter], x, y); matrix.Add(cell); alphabetIDCounter++; } } } #endregion #region Write cipher StringBuilder cipher = new StringBuilder(); foreach(string pair in plainTextEdited) { int indexA = matrix.FindIndex(c =&gt; c.character == pair[0]); Cell a = matrix[indexA]; int indexB = matrix.FindIndex(c =&gt; c.character == pair[1]); Cell b = matrix[indexB]; //Write cipher if (a.X == b.X) { cipher.Append(matrix[matrix.FindIndex(c =&gt; c.X == (a.X + 1)%5 &amp;&amp; c.Y == a.Y)].character); cipher.Append(matrix[matrix.FindIndex(c =&gt; c.X == (b.X + 1)%5 &amp;&amp; c.Y == b.Y)].character); } else if(a.Y == b.Y) { cipher.Append(matrix[matrix.FindIndex(c =&gt; c.X == a.X &amp;&amp; c.Y == (a.Y + 1) % 5)].character); cipher.Append(matrix[matrix.FindIndex(c =&gt; c.X == b.X % 5 &amp;&amp; c.Y == (b.Y + 1) % 5)].character); }else { cipher.Append(matrix[matrix.FindIndex(c =&gt; c.X == a.X &amp;&amp; c.Y == b.Y)].character); cipher.Append(matrix[matrix.FindIndex(c =&gt; c.X == b.X % 5 &amp;&amp; c.Y == a.Y)].character); } } #endregion return cipher.ToString(); } </code></pre> <p>Should I split this into more separate methods? Do I really need the Cell struct or is there another way to get an element's coordinates? Also how is the overall implementation and code readability? What should I improve regarding future implementations?</p>
[]
[ { "body": "<ol>\n<li><p>Your <code>Cell</code> struct should be immutable - you can achieve that by making all the fields <code>readonly</code>.</p></li>\n<li><p>In <code>Cell</code> <code>character</code> should be <code>PascalCase</code>. </p></li>\n<li><p>You repeat the code for trimming and replacing characters for they key and plain text. This should be moved into a method.</p></li>\n<li><p>There is some convoluted code which iterates of the <code>keyWord</code> and adds stuff to a <code>keyString</code>. If I read it correctly then what this is doing is: Build a list of all unique characters and remove those from the alphabet. LINQ is perfect for doing that in a concise way:</p>\n\n<pre><code>var uniqueKeyChars = keyWord.Distinct().ToList();\nalphabet = alphabet.Except(uniqueKeyChars).ToArray(); \n</code></pre></li>\n<li><p>I would consider moving the whole pad-to-even-length and then split into pairs business into a separate methods as well. Also using a <code>Tuple</code> to represent pairs of characters seems to be more appropriate.</p>\n\n<pre><code>public static IEnumerable&lt;Tuple&lt;char, char&gt;&gt; GetPairs(this IEnumerable&lt;char&gt; input)\n{\n while (input.Any())\n {\n var pair = input.Take(2);\n char first = pair.First();\n char second = pair.Skip(1).Any() ? pair.Last() : 'X';\n yield return Tuple.Create(first, second);\n input = input.Skip(2);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var plainTextPairs = plainText.GetPairs();\n</code></pre></li>\n<li><p>If you have followed the suggestions above you will now have a <code>uniqueKeyChars</code> array as well as the <code>alphabet</code> with the <code>uniqueKeyChars</code> removed. This should make building the matrix easier:</p>\n\n<pre><code>var cellAlphabet = new Queue&lt;char&gt;(uniqueKeyChars.Concat(alphabet));\nfor (int x = 0; x &lt; 5; x++)\n{\n for (int y = 0; y &lt; 5; y++)\n {\n var cell = new Cell(cellAlphabet(cellAlphabet.Dequeue()), x, y);\n matrix.Add(cell);\n }\n}\n</code></pre></li>\n<li><p>When creating the cipher if you split the index finding from the appending then the code becomes slightly more readable (below assuming you use the extension method shown above):</p>\n\n<pre><code>foreach(string pair in plainTextPairs)\n{\n int indexA = matrix.FindIndex(c =&gt; c.character == pair.Item1);\n Cell a = matrix[indexA];\n\n int indexB = matrix.FindIndex(c =&gt; c.character == pair.Item2);\n Cell b = matrix[indexB];\n\n int cipherCellIndexA;\n int cipherCellIndexB;\n\n //Write cipher\n if (a.X == b.X)\n {\n cipherCellIndexA = matrix.FindIndex(c =&gt; c.X == (a.X + 1) % 5 &amp;&amp; c.Y == a.Y);\n cipherCellIndexB = matrix.FindIndex(c =&gt; c.X == (b.X + 1)%5 &amp;&amp; c.Y == b.Y);\n }\n else if(a.Y == b.Y)\n {\n cipherCellIndexA = matrix.FindIndex(c =&gt; c.X == a.X &amp;&amp; c.Y == (a.Y + 1) % 5);\n cipherCellIndexB = matrix.FindIndex(c =&gt; c.X == b.X % 5 &amp;&amp; c.Y == (b.Y + 1) % 5);\n }else\n {\n cipherCellIndexA = matrix.FindIndex(c =&gt; c.X == a.X &amp;&amp; c.Y == b.Y);\n cipherCellIndexB = matrix.FindIndex(c =&gt; c.X == b.X % 5 &amp;&amp; c.Y == a.Y);\n }\n\n cipher.Append(matrix[cipherCellIndexA].Character);\n cipher.Append(matrix[cipherCellIndexB].Character);\n}\n</code></pre>\n\n<p>Of course of you would make your matrix an actual 2d array then you could skip the whole <code>FindIndex</code> shebang and just pick the cell by the index which should speed up things a bit.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T03:12:04.867", "Id": "44419", "ParentId": "44396", "Score": "3" } } ]
{ "AcceptedAnswerId": "44419", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T20:37:13.917", "Id": "44396", "Score": "4", "Tags": [ "c#", "cryptography" ], "Title": "How to optimize this Playfair encryption?" }
44396
<p>I created a class to prevent the default delay which happens when holding down the key on Windows Forms. It seems like the class is working correctly but I don't know if I'm using the best practice.</p> <p>KeyboardController class;</p> <pre><code>class KeyboardController { public event EventHandler kbEvent; private DispatcherTimer timer; private HashSet&lt;Key&gt; keyPressed; public KeyboardController(Window c, EventHandler function) { c.KeyDown += WinKeyDown; c.KeyUp += WinKeyUp; kbEvent = function; keyPressed = new HashSet&lt;Key&gt;(); timer = new DispatcherTimer(); timer.Tick += new EventHandler(kbTimer_Tick); timer.Interval = new TimeSpan(0, 0, 0, 0, 10); timer.Start(); } public bool KeyDown(Key key) { if (keyPressed.Contains(key)) { return true; } else { return false; } } private void WinKeyDown(object sender, KeyEventArgs e) { keyPressed.Add(e.Key); } private void WinKeyUp(object sender, KeyEventArgs e) { keyPressed.Remove(e.Key); } private void kbTimer_Tick(object sender, EventArgs e) { kbEvent(null, null); } } </code></pre> <p>MainWindow.xaml.cs;</p> <pre><code>public MainWindow() { EventHandler eh = new EventHandler(KeyboardFunction); kbc = new KeyboardController(this, eh); } private void KeyboardFunction(object sender, EventArgs e) { if (kbc.KeyDown(Key.Right)) { // do something. } else { // do something. } } </code></pre>
[]
[ { "body": "<ol>\n<li><p><strike>The main issue is that the key event handler and the timer tick will run on different threads which means that someone could press a key while the timer tick fires - in which case the <code>HashSet</code> could be modified while you are trying to read it from another thread. You will need to safeguard against that by protecting the access to the <code>HashSet</code> with a <code>lock</code></strike> You can probably get away with it because the <code>DispatcherTimer</code> runs on the UI thread where the <code>KeyDown</code>/<code>KeyUp</code> events are also being raised. </p></li>\n<li><p>The idiomatic way of subscribing to event handler is to let the user subscribe to the event rather than passing the event handler via the constructor. What happens if the user has shorter lifetime than the event provider? In your case it would keep it alive because you can't unsubscribe.</p></li>\n<li><p>When raising the event you need to check if the vent handler is null - subscriptions to an event are considered optional which means no subscriber might exist. Also you should not pass null as sender or EventArgs. The idiomatic pattern in C# goes like this:</p>\n\n<pre><code>private void kbTimer_Tick(object sender, EventArgs e)\n{\n var handler = kbEvent;\n if (handler != null)\n handler(this, EventArgs.Empty);\n}\n</code></pre></li>\n<li><p>The <code>KeyDown</code> method can be reduced to 1 line of code:</p>\n\n<pre><code>return keyPressed.Contains(key);\n</code></pre></li>\n<li><p>The name for the event is a bit non-descriptive. How about <code>keyboardTick</code>?</p></li>\n<li><p>Standard naming convention in C# for public fields/properties/methods is <code>PascalCase</code> (so the event should be <code>KeyboardTick</code>).</p></li>\n</ol>\n\n<p>In summary the final code could look like this:</p>\n\n<pre><code>class KeyboardController\n{\n public event EventHandler KeyboardTick;\n private DispatcherTimer timer;\n private HashSet&lt;Key&gt; pressedKeys;\n private readonly object pressedKeysLock = new object();\n\n public KeyboardController(Window c)\n {\n c.KeyDown += WinKeyDown;\n c.KeyUp += WinKeyUp;\n pressedKeys = new HashSet&lt;Key&gt;();\n\n timer = new DispatcherTimer();\n timer.Tick += kbTimer_Tick;\n timer.Interval = new TimeSpan(0, 0, 0, 0, 10);\n timer.Start();\n }\n\n public bool KeyDown(Key key)\n {\n lock (pressedKeysLock)\n {\n return pressedKeys.Contains(key);\n }\n }\n\n private void WinKeyDown(object sender, KeyEventArgs e)\n {\n lock (pressedKeysLock)\n {\n keyPressed.Add(e.Key);\n }\n }\n\n private void WinKeyUp(object sender, KeyEventArgs e)\n {\n lock (pressedKeysLock)\n {\n keyPressed.Remove(e.Key);\n }\n }\n\n private void kbTimer_Tick(object sender, EventArgs e)\n {\n var handler = keyboardTick;\n if (handler != null)\n {\n handler(this, EventArgs.Empty);\n }\n }\n}\n</code></pre>\n\n<p>and the usage:</p>\n\n<pre><code>public MainWindow()\n{\n kbc = new KeyboardController(this);\n kbc.KeyboardTick += HandleKeyboardTick;\n}\n\nprivate void HandleKeyboardTick(object sender, EventArgs e)\n{\n if (kbc.KeyDown(Key.Right))\n {\n // do something.\n }\n else\n {\n // do something.\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T10:08:57.093", "Id": "77097", "Score": "0", "body": "How do we know they run on different threads? All events run on different threads?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T18:02:34.900", "Id": "77146", "Score": "0", "body": "@Cem, hm looking at it again you might get away without a lock because the `DispatcherTimer` runs on the UI thread where the `KeyDown` and `KeyUp` events are also likely being raised on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T19:06:48.100", "Id": "77156", "Score": "0", "body": "Are there any tool like debug that I can watch threads?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:35:53.873", "Id": "77176", "Score": "0", "body": "In Visual Studio take a look at the Debug/Windows.. menu when debugging. You can view parallel stacks. That will show things running in parallel, in any loaded assembly." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T02:45:57.850", "Id": "44418", "ParentId": "44404", "Score": "2" } } ]
{ "AcceptedAnswerId": "44418", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T21:30:03.540", "Id": "44404", "Score": "4", "Tags": [ "c#", "wpf", "event-handling" ], "Title": "Preventing keydown delay" }
44404
<p>As a first little Python exercise, I wrote an analyzer/summarizer for my nginx accesslogs. The code works fine but I'm not sure if I used the different types of sequences properly or made some other stupid things which could lead to bugs etc.</p> <hr> <p>Steps:</p> <ol> <li>read in access.log and heavily poke around to fetch the wanted data (requests, IPs and user agents till now)</li> <li>sum the occurrences</li> <li>sort the sums desc and write the top x sums into a file</li> </ol> <hr> <p>Example generalized log (I don't know if that's helpful):</p> <pre><code>1.1.1.1 - - [21/Feb/2014:06:35:45 +0100] "GET /robots.txt HTTP/1.1" 200 112 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 1.1.1.1 - - [21/Feb/2014:06:35:45 +0100] "GET /blog.css HTTP/1.1" 200 3663 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 2.2.2.2 - - [21/Feb/2014:06:52:04 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 2.2.2.2 - - [21/Feb/2014:06:52:04 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 3.3.3.3 - - [21/Feb/2014:06:58:14 +0100] "/" 200 1664 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 4.4.4.4 - - [21/Feb/2014:07:22:03 +0100] "/" 200 1664 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 5.5.5.5 - - [21/Feb/2014:07:32:48 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 5.5.5.5 - - [21/Feb/2014:07:32:48 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 6.6.6.6 - - [21/Feb/2014:08:13:01 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 6.6.6.6 - - [21/Feb/2014:08:13:01 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 7.7.7.7 - - [21/Feb/2014:08:51:25 +0100] "GET /main.php HTTP/1.1" 200 3681 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461)" 7.7.7.7 - - [21/Feb/2014:08:51:34 +0100] "-" 400 0 "-" "-" 7.7.7.7 - - [21/Feb/2014:08:51:48 +0100] "GET /tag/php.php HTTP/1.1" 200 4673 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461)" 8.8.8.8 - - [21/Feb/2014:08:53:43 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 8.8.8.8 - - [21/Feb/2014:08:53:43 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 9.9.9.9 - - [21/Feb/2014:09:18:40 +0100] "-" 400 0 "-" "-" 9.9.9.9 - - [21/Feb/2014:09:18:40 +0100] "GET /main HTTP/1.1" 200 3681 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 9.9.9.9 - - [21/Feb/2014:09:18:41 +0100] "GET /phpMyAdmin/scripts/setup.php HTTP/1.1" 404 27 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 9.9.9.9 - - [21/Feb/2014:09:18:42 +0100] "GET /pma/scripts/setup.php HTTP/1.1" 404 27 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 10.10.10.10 - - [21/Feb/2014:09:21:29 +0100] "-" 400 0 "-" "-" 10.10.10.10 - - [21/Feb/2014:09:21:29 +0100] "GET /main.php HTTP/1.1" 200 3681 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 10.10.10.10 - - [21/Feb/2014:09:21:30 +0100] "GET /about.php HTTP/1.1" 200 2832 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 10.10.10.10 - - [21/Feb/2014:09:21:30 +0100] "GET /tag/nginx.php HTTP/1.1" 200 3295 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 10.10.10.10 - - [21/Feb/2014:09:21:31 +0100] "GET /how-to-setup.php HTTP/1.1" 200 2637 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117" 1.1.1.1 - - [21/Feb/2014:09:27:27 +0100] "GET /robots.txt HTTP/1.1" 200 112 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 1.1.1.1 - - [21/Feb/2014:09:27:27 +0100] "GET /tag/tor.php HTTP/1.1" 200 2041 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 5.5.5.5 - - [21/Feb/2014:10:14:37 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 5.5.5.5 - - [21/Feb/2014:10:14:37 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 8.8.8.8 - - [21/Feb/2014:10:55:19 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 8.8.8.8 - - [21/Feb/2014:10:55:19 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 1.1.1.1 - - [21/Feb/2014:11:19:05 +0100] "GET /robots.txt HTTP/1.1" 200 112 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 1.1.1.1 - - [21/Feb/2014:11:19:06 +0100] "GET /robots.txt HTTP/1.1" 200 112 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 1.1.1.1 - - [21/Feb/2014:11:19:06 +0100] "GET / HTTP/1.1" 200 3649 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 6.6.6.6 - - [21/Feb/2014:12:16:14 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 6.6.6.6 - - [21/Feb/2014:12:16:15 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 5.5.5.5 - - [21/Feb/2014:14:17:52 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 5.5.5.5 - - [21/Feb/2014:14:17:52 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 6.6.6.6 - - [21/Feb/2014:14:58:04 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 6.6.6.6 - - [21/Feb/2014:14:58:04 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 5.5.5.5 - - [21/Feb/2014:15:38:46 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 5.5.5.5 - - [21/Feb/2014:15:38:47 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 2.2.2.2 - - [21/Feb/2014:18:20:36 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 2.2.2.2 - - [21/Feb/2014:18:20:37 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 5.5.5.5 - - [21/Feb/2014:19:42:00 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 5.5.5.5 - - [21/Feb/2014:19:42:00 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 2.2.2.2 - - [21/Feb/2014:20:22:13 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 2.2.2.2 - - [21/Feb/2014:20:22:13 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 6.6.6.6 - - [21/Feb/2014:21:02:55 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 6.6.6.6 - - [21/Feb/2014:21:02:55 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 8.8.8.8 - - [22/Feb/2014:01:05:37 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 8.8.8.8 - - [22/Feb/2014:01:05:38 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 8.8.8.8 - - [22/Feb/2014:04:28:10 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 8.8.8.8 - - [22/Feb/2014:04:28:10 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 2.2.2.2 - - [22/Feb/2014:05:49:34 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 2.2.2.2 - - [22/Feb/2014:05:49:34 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" 5.5.5.5 - - [22/Feb/2014:06:29:47 +0100] "GET /main/rss HTTP/1.1" 301 178 "-" "Motorola" 5.5.5.5 - - [22/Feb/2014:06:29:47 +0100] "GET /feed/atom.xml HTTP/1.1" 304 0 "-" "Motorola" </code></pre> <hr> <p>This is my code:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path class LogAnalyzer(): """ Parses and summarizes nginx logfiles """ def __init__(self, readfile, writefile, topcount=5): """ Initializing """ self.summary = { "requests": {}, "ips": {}, "useragents": {} } self.topcount = topcount self.reafile = readfile self.writefile = writefile def analyze(self): """ Reads and splits the access-log into our dictionary """ #is file? if not os.path.isfile(self.reafile): print(self.reafile, "does not exist! exiting") exit(1) log = open(self.reafile, 'r') lines = log.readlines() log.close() loglist = [] for s in lines: line = s.strip() tmp = line.split(' ') ip = tmp[0] #not the finest way...get indices of double quotes doublequotes = LogAnalyzer.find_chars(line, '"') #get the starting/ending indices of request &amp; useragents by their quotes request_start = doublequotes[0]+1 request_end = doublequotes[1] useragent_start = doublequotes[4]+1 useragent_end = doublequotes[5] request = line[request_start:request_end] useragent = line[useragent_start:useragent_end] #writing a dictionary per line into a list...huh...dunno loglist.append({ "ip": ip, "request": request, "useragent": useragent }) self.summarize(loglist) self.write_summary() def summarize(self, cols): """ count occurences """ for col in cols: if not col['request'] in self.summary['requests']: self.summary['requests'][col['request']] = 0 self.summary['requests'][col['request']] += 1 if not col['ip'] in self.summary['ips']: self.summary['ips'][col['ip']] = 0 self.summary['ips'][col['ip']] += 1 if not col['useragent'] in self.summary['useragents']: self.summary['useragents'][col['useragent']] = 0 self.summary['useragents'][col['useragent']] += 1 def write_summary(self): """ sorts and writes occurences into file """ summary = open(self.writefile, 'w') summary.write("Log summary\n") for key in self.summary: list = sorted(self.summary[key].items(), key=lambda x: x[1], reverse=True) list = list[:self.topcount] summary.write("\nTop "+key+":\n") for l in list: summary.write(l[0]+": "+str(l[1])+" times\n") summary.close() @staticmethod def find_chars(string, char): """ returns a list of all indices of char inside string """ return [i for i, ltr in enumerate(string) if ltr == char] if __name__ == '__main__': logfile = './access.log' summaryfile = './access_summary.log' summary = LogAnalyzer(logfile, summaryfile, 5) summary.analyze() </code></pre> <hr> <p>Notes:</p> <p>Regex: I know it may would be "better" if I simply used regular expressions, but:</p> <ol> <li><p>I really have problems creating the patterns .</p></li> <li><p>I wanted to get some experiences with Python's sequence functions. But that leads to the ugly part in the analyze-function, because I need</p> <ul> <li>split-function with whitespaces for dividing each line into parts (I may want to fetch the date-times and status codes as well later)</li> <li>for-loop to find out the request and user agent, because they are embedded in double-quotes and usually contain whitespaces.</li> </ul></li> </ol> <p>Could that be made better? Are there some other things to improve?</p>
[]
[ { "body": "<p>I find your <code>find_chars()</code> method amusingly creative. I'll comment on the big picture instead.</p>\n\n<ul>\n<li><p><strong>Class design:</strong> Passing all the parameters into the constructor makes the class less versatile. Those parameters don't need to be part of the object's state. Consider this outline instead:</p>\n\n<pre><code>class LogAnalyzer():\n def __init__(self):\n self.summary = …\n\n def analyze(self, logfile):\n …\n\n def summarize(self, topcount=5):\n …\n</code></pre>\n\n<p>Then you have the flexibility to summarize several log files at once:</p>\n\n<pre><code>analysis = LogAnalyzer()\nanalysis.analyze('access_log.0')\nanalysis.analyze('access_log.1')\nanalysis.analyze('access_log.2')\nprint(analysis.summarize('access_summary.txt'))\n</code></pre>\n\n<p>Consider making it the caller's responsibility to write the result to a file. I don't think that it's essential to the business of log analysis. </p></li>\n<li><p>Take advantage of <a href=\"http://docs.python.org/3.3/library/collections.html#collections.Counter\"><strong><code>collections.Counter</code></strong></a>.</p></li>\n<li><p>Open files using <strong><code>with</code> blocks</strong>. Then you never have to worry about closing them.</p></li>\n<li><p><strong>Avoid reading everything into memory at once.</strong> Read a line at a time, use it to update the cumulative statistics, and don't hold on to <code>lines</code>. If possible, avoid keeping <code>loglist</code> as well.</p></li>\n</ul>\n\n\n\n<pre><code>from collections import defaultdict, Counter\n\nclass LogAnalyzer():\n def __init__(self):\n self.linecount = 0\n self.counters = defaultdict(Counter)\n\n def analyze(self, logfile):\n with open(logfile) as f:\n for line in f:\n self._update(**self._parse(line))\n\n def summarize(self, topcount=5):\n …\n\n @staticmethod\n def _parse(line):\n …\n return {'ip': …, 'request': …, 'useragent': … }\n\n def _update(self, **kwargs):\n self.linecount += 1\n for key, value in kwargs.items():\n self.counters[key][value] += 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T12:45:47.150", "Id": "77109", "Score": "0", "body": "the find_chars-body is taken from a stackoverflow-question ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T12:46:37.480", "Id": "77110", "Score": "0", "body": "thanks for your tips, particularly the collections.Counter sounds quite helpful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T00:28:18.823", "Id": "44417", "ParentId": "44413", "Score": "5" } }, { "body": "<p>Everything that @200_success wrote was good advice. As for the actual parsing of the file, there is actually a better way:</p>\n\n<pre><code> with open(logfile, \"rb\") as f:\n for line in csv.reader(f, delimiter=' '):\n self._update(**self._parse(line))\n</code></pre>\n\n<p>Python's csv module contains code the read CSV files, but you can also use it to read files with a similar format, such as this one. This uses spaces instead of commas to seperate the values, but follows the same quoting rules as CSV. The code above will get each line as list of the columns like this:</p>\n\n<pre><code>['1.1.1.1', '-', '-', '[21/Feb/2014:06:35:45', '+0100]', 'GET /robots.txt HTTP/1.1', '200', '112', '-', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)']\n</code></pre>\n\n<p>Thus all the hard working of parsing is already done, you should be able to easily pull the information you want. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:35:45.300", "Id": "44475", "ParentId": "44413", "Score": "4" } } ]
{ "AcceptedAnswerId": "44417", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T23:01:38.290", "Id": "44413", "Score": "4", "Tags": [ "python", "beginner", "parsing", "logging" ], "Title": "Diving into Python sequences: analyze an access.log" }
44413
<p>I've coded branch and bound to solve the knapsack problem, and use a <strong>greedy linear relaxation</strong> to find an upper bound on a node I'm currently exploring. What I mean by this is that I first sort the items by their respective <em>value density</em> (computed <code>value/weight</code>, for each item) and then fill the bag according to a greedy algorithm, using a fraction of the last item that would put us over the bag's capacity. This solution is unattainable (we can't take half an item) but provides an upper bound on the maximum value we <em>can</em> attain from considering an item <code>j</code>:</p> <pre><code>def _linear_relaxation(self, j, cp, cw): # we consider how well we can do to increase our current profit (cp) # by looking at items beyond the item that we either just took or left behind weight = cw value = cp for (v, w), index in self.ordered: if index &gt; j: if w + weight &lt;= self.capacity: value += v weight += w else: return value + (v * (self.capacity - w)/float(w)) return value </code></pre> <p>My code works great to solve small problems using this relaxation, but starts slowing down when the problem size increases. One optimization (or <strong>reduction on a node's upper bound</strong>) is to avoid taking items of <a href="http://www8.cs.umu.se/~jopsi/dinf504/chap13.shtml" rel="noreferrer">high value density</a> whose weight exceeds the leftover weight we're trying to fill. </p> <p>Think about it this way: our greedy linear relaxation bound takes items in decreasing order according to their density, <code>value/weight</code>. If the <code>residual</code> or remaining weight in the bag is less than the item we're considering adding to the bound, it is much better to take items further down our density list. Consider, for example, <code>residual = 1</code>, <code>weight = 2</code>. Wouldn't it be great if we found a small <code>value</code>, so that we could add to our estimate <code>value/2</code>, rather than <code>2 * value</code>? We'd get a much better estimate on the least upper bound than if we considered the last item with the greatest density, with no regard as to its relative effect on our upper bound. </p> <p>With this in mind, a better bound can be found as follows:</p> <pre><code>def _linear_relaxation(self, j, cp, cw): weight = cw value = cp for (v, w), index in self.ordered: if index &gt; j: if w + weight &lt;= self.capacity: value += v weight += w else: if w &gt; self.capacity - (w + weight): continue return value + (v * (self.capacity - w)/float(w)) return value </code></pre> <p>This bound is great for a list of no more than 1000 items (around 11 seconds compared to no solution) but fails on a problem with 10,000 items. My question, how can we we do better? Can the bound be improved on? Or can we more smartly consider what nodes are worth adding, based on the best solution discovered so far. </p> <p>My question/goal of the review:</p> <p>To provide some context, the code I've written is included below. Please let me know if you have improvements on its structure (for example, is it better practice to make <code>TreeNode</code> a truly recursive object and give it <code>left</code> and <code>right</code> attributes? Do we gain anything by doing this?). What I'm really looking for, though, is how we can improve the current <strong>depth first search</strong> implementation (please don't provide a solution that uses a heap, for example, unless you can demonstrate it is an all around better algorithm than what I've written). If you'd like to provide code, that would be great, but I'm really just looking for some ideas on how my current code might be optimized. I'm kind of new to optimization and don't really know where to look for improvements or really how to think about the problem as might a person with a speciality in optimization. </p> <p>While searching, if we include an item, do we need to recalculate the bound on this node (or would it just be the value of its parent--this solution is still attainable)?</p> <p>One optimization I should make: put the right node on after putting on the left node. The order in which we consider expanding a path matters, here!</p> <pre><code>class TreeNode: def __init__(self, level, V, W, taken): self.level = level self.V = V self.W = W self.taken = taken def __str__(self): return str((self.level, self.V, self.W, self.taken)) class KP: def __init__(self, cap, values, weights): self.capacity = cap self.values = values self.weights = weights # sort the items according to their value per weight self.ordered = sorted([((v, w), i) for i, (v, w) in enumerate(zip(self.values, self.weights))], key = lambda tup: float(tup[0][0])/tup[0][1], reverse = True) # our best initial solution will be the greedy solution def _greedy_solution(self): weight = 0 value = 0 taken = [] for (v, w), index in self.ordered: if w + weight &lt;= self.capacity: # take items of highest value per unit weight, while we still can value += v weight += w taken.append(index) else: return TreeNode(index, value, weight, taken) return TreeNode(index, value, weight, taken) def solve(self): best = self._greedy_solution() root = TreeNode(0, 0, 0, []) stack = [root] while len(stack) &gt; 0: current = stack.pop() index = current.level if current.V &gt;= best.V: # consider whether we can immediately improve our best best = current if index &lt; len(self.values): # there are items left to consider # we have two branches to consider: if we have room, we take the item # if we don't have room, we continue our solution to the next iteration # where we consider the next item if current.W + self.weights[index] &lt;= self.capacity: taken = list(current.taken) # update path of items taken taken.append(index) # create the right node right = TreeNode( index + 1, current.V + self.values[index], current.W + self.weights[index], taken ) if right.V &gt; best.V: # update our best, if possible best = right bound = self._linear_relaxation(index, right.V, right.W) # only continue exploring if # we're guaranteed something better if bound &gt;= best.V: stack.append(right) # create the left node, continue # solution of the parent, without # taking the item left = TreeNode( index + 1, current.V, current.W, list(current.taken) ) bound = self._linear_relaxation(index, left.V, left.W) # only continue exploring if # we're guaranteed something better if bound &gt;= best.V: stack.append(left) return best </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T13:57:06.070", "Id": "77583", "Score": "0", "body": "Isn't `solve` supposed use the sorted list of items?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T14:01:47.790", "Id": "77586", "Score": "0", "body": "@JanneKarila It does. Look at how it the solution using `_linear_relaxation`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T14:07:25.690", "Id": "77588", "Score": "0", "body": "Yes, but it creates the next node at `index+1` where `index` refers to the unsorted list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T14:16:05.817", "Id": "77591", "Score": "0", "body": "@JanneKarila I see what you're saying. That's a good point. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-18T15:16:47.100", "Id": "77619", "Score": "0", "body": "@JanneKarila If I'm correct, I should create `right` as follows (and apply similar changes elsewhere):\n\n`right = TreeNode( index + 1, current.V + self.ordered[index][0][0], current.W + self.ordered[index][0][1], taken )`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T11:40:53.010", "Id": "77789", "Score": "0", "body": "Yes, and remember to change `_linear_relaxation` to use right index. Also, I suppose the optimization you added to `_linear_relaxation` becomes redundant then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:44:16.453", "Id": "78186", "Score": "0", "body": "As you state that you want to use depth first search, would this approach be of any interest? [Iterative Deepening Depth First Search](https://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search). If it applies, you can use your existing depth first search program so it might not require much additional code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T11:30:37.357", "Id": "84281", "Score": "0", "body": "This is going to sound dense, because it dense, but how to you input your data?" } ]
[ { "body": "<h2>Your first upper bound is buggy</h2>\n\n<pre><code>return value + (v * (self.capacity - w)/float(w))\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>return value + (v * (self.capacity - weight)/float(w))\n</code></pre>\n\n<p>If <code>w_i &lt;&lt; W</code> you are overestimating the upper bound by heaps, which causes your branch and bound to never \"bound\".</p>\n\n<h2>Your second relaxation is not an upper bound</h2>\n\n<p>I'm assuming your linear relaxation is for the upper bound. As such your first function to calculate the upper bound is good (bar the bug above). The second function is no longer an upper bound because you are essentially taking a greedy solution as the upper bound. </p>\n\n<p>Example that triggers faulty upper bound:</p>\n\n<p>Define the value and weight of item i as: <code>v_i</code> and <code>w_i</code> respectively.\nDefine the ratio of value to weight for item i as: <code>r_i = v_i / w_i</code>.\nThe knapsack can carry at most <code>W</code> units of mass. </p>\n\n<p>We have three items as follows:</p>\n\n<pre><code>r_0 = k\nr_1 = r_2 = k - dk\nw_0 = W - dw\nw_1 = w_2 = W/2\n</code></pre>\n\n<p>where <code>k</code> is an arbitrary constant, <code>dk</code> is a small value and <code>dw</code> is a value strictly smaller than <code>W/2</code> i.e: <code>dw &lt; W/2</code>.</p>\n\n<p>Your upper bound algorithm would pick i=0 first and then be unable to add any other items to the knapsack and the achieved value is:</p>\n\n<pre><code> V_ub = r_0*w_0 = k*(W-dw) = k*W - dw*K\n</code></pre>\n\n<p>However the highest attainable value is achieved by taking r_1 and r_2 but not r_0:</p>\n\n<pre><code> V_optimal = r_1*w_1 + r_2*w_2 = 2*r_1*w_1 = 2*(k-dk)*W/2 = k*W - dk*W\n</code></pre>\n\n<p>It is clear that when <code>dw*K &gt; dk*W</code> then <code>V_ub &lt; V_optimal</code> and your algorithm will cause your branch and bound algorithm to prune sections of the graph that could contain the optimum.</p>\n\n<p>If you are uncertain of the above inequality you can let <code>dw</code> approach <code>W/2</code> from <code>0</code> and let <code>dk</code> approach <code>0</code> from <code>k</code> and see that the limit is trivially:</p>\n\n<pre><code> W/2*K &gt; 0\n</code></pre>\n\n<p>which proves that this scenario is possible and likely to happen when you get enough items.</p>\n\n<p>In comparison, the first upper bound would achieve:</p>\n\n<pre><code>V_ub = r_0*w_0 + r_1*(W-w0) = k*(W-dw) + (k-dk)*(W-(W-dw)) = k*W - dw*K + dw*k - dk*dw\n = k*W -dk*dw\n</code></pre>\n\n<p>As <code>dw &lt; W/2</code> then <code>V_ub &gt; V_opt</code> and it is proved that this is an upper bound.</p>\n\n<h2>Edit/Addendum: Improve your lower bound</h2>\n\n<p>You initialize a <code>best</code> node with a greedy solution at the start here:\nThen you update the <code>best</code> solution here (similarly for left node):</p>\n\n<pre><code> if right.V &gt; best.V: # update our best, if possible \n best = right\n</code></pre>\n\n<p>Then you calculate the upper bound with the linear relaxation method:</p>\n\n<pre><code> bound = self._linear_relaxation(index, right.V, right.W)\n</code></pre>\n\n<p>And then only if a branch has a upper bound that is better than the best solution's <em>partial</em> value do you continue evaluating the branch:</p>\n\n<pre><code> if bound &gt;= best.V:\n stack.append(right)\n</code></pre>\n\n<p>This efficiently make the <code>best</code> solution's <em>partial</em> value your lower bound. The lower and upper bounds should as tightly as possible bound the best achievable value in that branch. Taking the partial value in the branch this far, grossly underestimates the lower bound. Making your search space larger. Remember, your search space grows with your bounds. </p>\n\n<p>You set the lower bound here (similarly for the left case):</p>\n\n<pre><code> right = TreeNode( index + 1, current.V + self.values[index],\n current.W + self.weights[index], taken )\n</code></pre>\n\n<p>Right.V is used as a lower bound which it technically is, albeit a poor one.</p>\n\n<p>Instead of: </p>\n\n<pre><code> if right.V &gt; best.V: # update our best, if possible \n best = right\n</code></pre>\n\n<p>You should do:</p>\n\n<pre><code> # Somewhere earlier,\n best = self._greedy_solution()\n best_lb = best.V; # Here V is a lower bound on the whole search space. Good!\n\n # Later on...\n right = TreeNode( index + 1, current.V + self.values[index],\n current.W + self.weights[index], taken )\n lowerBound = greedy_solution_on_remaining_items(right)\n if lowerBound &gt; best_lb: # update our best, if possible \n best = right\n best_lb = lowerBound \n</code></pre>\n\n<p>And similar checks for the left case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T15:14:31.830", "Id": "77835", "Score": "0", "body": "This is great, great work. Do you have any suggestions for further reducing the search space? Can we get a tighter bound, or somehow apply [forward checking](http://en.wikipedia.org/wiki/Look-ahead_(backtracking))? This is really what I was after." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T15:21:12.937", "Id": "77839", "Score": "0", "body": "I'm not very good with python, in fact I've never written anything in it. So it would help me greatly if you commented your code a bit. But right now I cannot see anywhere where you are discarding branches that have an upper bound that is lower than the highest lower bound. Meaning that your branch and bound could be incorrectly implemented and you're erroneously searching large parts of the search space." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T15:25:08.743", "Id": "77840", "Score": "0", "body": "Why do you say that? We selectively branch when we decide whether or not to put an item on the stack: `if bound >= best.V: stack.append(right)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T15:35:44.843", "Id": "77843", "Score": "1", "body": "Comments added!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T15:39:24.790", "Id": "77844", "Score": "0", "body": "My fault, as I said I'm not used to python. So `bound` is your upper bound and `best.V` is the best lower bound? And you're calculating the lower bound here: `current.V + self.values[index]`? If this is the lower bound, it is very loose. In fact you should strive to make it much tighter to prune more candidates earlier. I would try re-using your greedy solver on the partial solutions to get a tighter lower bound." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T15:55:11.987", "Id": "77847", "Score": "0", "body": "The lower bound is the current best solution: If our estimate of what we can get (computed from `_linear_relaxation`) is not better than our best so far, what good is it to continue? I don't think we can improve this. \n\nOur upper bound would be the fractional solution to the knapsack problem (i.e. when we take a fraction of the highest item ranked by value per unit weight: `return value + (v * (self.capacity weight)/float(w))`. The true solution will always be lower than this, since we can't take a fraction of an item. Does this make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T17:12:37.517", "Id": "77872", "Score": "0", "body": "No, your lower bound (in the code right now) is the value of the best *partial* solution this far. You need to *estimate* a lower bound that is as high as possible for the *entire branch*. See here: `if right.V > best.V: best = right` the higher `right.V` is here, the earlier you can update your lower bound and prune branches. Thus you need to change the way you calculate right.V (and left.V) to take the greedy solution based on the partial solution in that branch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T17:31:38.353", "Id": "77880", "Score": "0", "body": "Are you saying that rather than testing if `bound >= best.V`, we should test if `bound >= best.V + solution to filling remaining weight with according to greedy algorithm`? \n\nShould we also create a node corresponding to the greedy solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T18:08:39.270", "Id": "77895", "Score": "1", "body": "I updated my answer." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T14:36:18.517", "Id": "44757", "ParentId": "44421", "Score": "13" } }, { "body": "<p>I would add this as a comment, but as I am new in here, I can't.\nMathematically speaking, this piece of code <code>if w &gt; self.capacity - (w + weight):</code> may not make sense, since you already know that <code>w + weight &lt;= self.capacity</code> is false. If my math is not failing me, the \"if\" statement is always true, since <code>self.capacity - (w + weight)</code> is smaller than zero, since <code>w + weight &gt; self.capacity</code>, and w > 0.</p>\n\n<p>Am I right?</p>\n\n<p>And yet it doesn't give me the optimal solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T18:38:50.920", "Id": "77899", "Score": "0", "body": "It's possible for the code to execute. Please review my logic here starting with, \"One optimization (or reduction on a node's upper bound) is to avoid taking items of high value density whose weight exceeds the leftover weight we're trying to fill.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T19:06:12.070", "Id": "77906", "Score": "0", "body": "I'm really sorry but it's not because you can't comment that you should post an answer that is just a comment. You have some options: transform your answer in a real complete answer, or wait to have enough reputation to post your comment. The first one, would be a good option since you're not that far from a good answer, and this would surely earn you reputation!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T19:13:58.430", "Id": "77908", "Score": "0", "body": "@gjdanis, It does execute. My point is: can I remove it? If yes, less computations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T19:14:19.577", "Id": "77909", "Score": "0", "body": "@Marc-Andre, suggestion accepted. But his question asks how to improve the algorithm. If we can take this piece of code off, it will improve the performance. If it is just a mistake, then it will help him improve the code. Anyway, an improvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T19:36:33.067", "Id": "77916", "Score": "0", "body": "+1 Renato is correct. The if-branch will always be taken and the method simplifies to a greedy algorithm. As I said in the second section of my answer. :) Essentially that piece of code simplifies to: `if (w <= capacity - weigh){...}else{if(2*w > capacity - weight){continue;}else{return}` as we entered the else then it is certain that `w > capacity - weight` and thus it follows that `2*w > capacity-weight` always." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T20:30:28.563", "Id": "77932", "Score": "0", "body": "@EmilyL. This isn't necessarily always the case, though. As you correctly prove, it can lead to incorrect pruning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T21:44:13.953", "Id": "77952", "Score": "0", "body": "@gjdanis, I think you're wrong. In what case would `if w > self.capacity - (w + weight):` evaluate to false if the previous `if w + weight <= self.capacity:` is not taken?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T22:38:10.677", "Id": "77969", "Score": "0", "body": "@EmilyL.: Yes, there's a bug. The code `self.capacity - (w + weight)` assumes you've added `w` to the bag. What we're trying to say is skip the current item if it is heavier than the bag's residual weight. This should be: `w > self.capacity - weight`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T22:49:42.520", "Id": "77970", "Score": "0", "body": "Yes and `if w + weight <= self.capacity` is false, then `w + weight > self.capacity` must be true. Thus the `if` statement will always be taken." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T18:35:10.490", "Id": "44778", "ParentId": "44421", "Score": "4" } }, { "body": "<h1>Readability leads to efficiency</h1>\n<p>My first recommendation is readability. More readable code makes it easier (for you or others) to understand the algorithm and thus easier to think of efficiency improvements. You are free to choose whatever line length suits you, but if you want other people to be able to read your code easily <a href=\"http://legacy.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">79 characters is a good guide</a>.</p>\n<blockquote>\n<p><strong>Note:</strong> code blocks on Stack Exchange will require horizontal scroll bars beyond 91 characters.\nSome people (including me...) may be less likely to review code that requires scrolling left and right, when there is other code available to review without the inconvenience.</p>\n</blockquote>\n<p>Blank lines can help readability by separating one block of code lines from another. However, using blank lines excessively means they lose their separating purpose and just stretch your code, actually reducing readability. How much is too much and how much is too little is a personal decision, but <a href=\"http://legacy.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">this guidance</a> may help.</p>\n<p>It's easier to understand a function if it fits on one page. If you have to scroll up and down to view a function then ask yourself if it could be broken down into smaller functions. In this particular case your <code>solve</code> method <strong>would</strong> fit on one page if it had fewer blank lines. You could remove some of the blank lines, or split the function into smaller ones. I recommend you do both.</p>\n<hr />\n<h1>Algorithm fine tuning?</h1>\n<p>Consider this method:</p>\n<pre><code> def _greedy_solution(self):\n\n weight = 0\n value = 0\n taken = []\n\n for (v, w), index in self.ordered:\n\n if w + weight &lt;= self.capacity:\n value += v\n weight += w\n taken.append(index)\n</code></pre>\n<blockquote>\n<pre><code> else:\n return TreeNode(index, value, weight, taken)\n</code></pre>\n</blockquote>\n<pre><code> return TreeNode(index, value, weight, taken)\n</code></pre>\n<p>The highlighted <code>else</code> block here causes the method to return at the first occurrence of an item that would exceed capacity. Is this what you require? I'm not familiar with the algorithm but I expected that the greedy algorithm would continue considering the less dense items to add any which do not exceed capacity. This means the remaining space will always be used for the most dense of the remaining items that fit. Since the items are sorted according to density (that is, value/weight) the first item that exceeds capacity is not necessarily the last item worth considering. There could still be an item with lower density but smaller weight which would fit.</p>\n<p>If I've understood correctly, removing the highlighted <code>else</code> block will give you a potentially higher value for your greedy solution, so you can start your <code>solve</code> method with a slightly higher lower bound (<code>best</code>). This should allow you to discard more of the potential branches later on, saving you unnecessary calculation.</p>\n<hr />\n<h1>A look at the <code>solve</code> method</h1>\n<p>Here is your <code>solve</code> method with some of the blank lines and spaces removed so we can see it all at once for discussion:</p>\n<pre><code> def solve(self):\n best = self._greedy_solution()\n root = TreeNode(0, 0, 0, [])\n stack = [root]\n\n while len(stack) &gt; 0:\n current = stack.pop()\n index = current.level\n if current.V &gt;= best.V:\n best = current\n\n if index &lt; len(self.values):\n if current.W + self.weights[index] &lt;= self.capacity:\n taken = list(current.taken)\n taken.append(index)\n right = TreeNode(index + 1, current.V + self.values[index],\n current.W + self.weights[index], taken)\n\n if right.V &gt; best.V:\n best = right\n\n bound = self._linear_relaxation(index, right.V, right.W)\n if bound &gt;= best.V:\n stack.append(right)\n\n left = TreeNode(index + 1, current.V, current.W, list(current.taken))\n bound = self._linear_relaxation(index, left.V, left.W)\n if bound &gt;= best.V:\n stack.append(left)\n return best \n</code></pre>\n<p>Consider this section:</p>\n<pre><code> if right.V &gt; best.V:\n best = right\n\n bound = self._linear_relaxation(index, right.V, right.W)\n if bound &gt;= best.V:\n stack.append(right)\n</code></pre>\n<p>If you have already assigned <code>best = right</code> then am I right in thinking that <code>bound &gt;= best.V</code> will always be <code>True</code>? If so you can avoid the call to <code>_linear_relaxation</code> each time right is the new best, like this:</p>\n<pre><code> if right.V &gt; best.V:\n best = right\n stack.append(right)\n else:\n bound = self._linear_relaxation(index, right.V, right.W)\n if bound &gt;= best.V:\n stack.append(right)\n</code></pre>\n<p>Before adding <code>left</code> or <code>right</code> to your tree, you check if <code>bound &gt;= best.V</code>. Since <code>bound</code> is an upper bound on the possible value obtainable through this branch, it is guaranteed that the branch will not find a better solution that the current <code>best</code> if <code>bound = best.V</code>. For those occasions when equality occurs, abandoning the branch will save you unnecessary work. So I would recommend replacing <code>bound &gt;= best.V</code> with <code>bound &gt; best.V</code>, before appending <code>right</code> and before appending <code>left</code>. There is no point in keeping a branch which can at best provide an equal value solution, since your program is not designed to return multiple solutions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:53:16.860", "Id": "78196", "Score": "0", "body": "Glad to help @gjdanis" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T20:55:05.437", "Id": "78197", "Score": "0", "body": "\"Since the items are sorted according to density (that is, value/weight) the first item that exceeds capacity is not necessarily the last item worth considering.\" Very, very good way to say it!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T19:25:36.807", "Id": "44899", "ParentId": "44421", "Score": "4" } } ]
{ "AcceptedAnswerId": "44757", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T07:19:06.043", "Id": "44421", "Score": "17", "Tags": [ "python", "optimization", "algorithm", "recursion" ], "Title": "Knapsack branch and bound: forward filter" }
44421
<blockquote> <p>Our version of getword does not properly handle underscores, string constants, comments, or preprocessor control lines. Write a better version.</p> </blockquote> <p>This is the exercise 6-1 and can be foud on K&amp;R 2 at page 150. <a href="http://net.pku.edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf" rel="nofollow">http://net.pku.edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf</a></p> <p>My solution: </p> <pre><code>static int isValidKeyWord(char c) { if(isalnum(c) || c == '_') { return 1; } return 0; } int getword(char *word, int lim) { int c; char *w = word; int ordinaryKeyWord = 0; int comment = 0; int stringConstant = 0; while(isspace((c = getch()))) ; if(c == '#' || c == '_' || isalpha(c)) { ordinaryKeyWord = 1; *w++ = c; } else if(c == '/') { *w++ = c; c = getch(); if(c == '*') { *w++ = c; comment = 1; } else { *w = '\0'; return *--w; } } else if(c == '\"') { *w++ = c; stringConstant = 1; } else { *w++ = c; *w = '\0'; return c; } for(; --lim; w++) { *w = getch(); if(ordinaryKeyWord &amp;&amp; (!isValidKeyWord(*w))) { ungetch(*w); break; } else if(stringConstant &amp;&amp; *w == '\"') { w++; break; } else if(comment &amp;&amp; *w == '*') { *++w = getch(); if(*w == '/') { w++; break; } else { ungetch(*w); w--; } } } *w = '\0'; return word[0]; } </code></pre> <p>There are 3 main cases:</p> <ul> <li>case 1: comments, if the first two characters are <code>/</code> and <code>*</code>. In this case the function should return when the corresponding <code>*</code> and <code>/</code> are met.</li> <li>case 2: string constants, if the first character is a <code>"</code>, then the function should return when the closing <code>"</code> is met.</li> <li>case 3: words that begin with <code>#</code>, <code>_</code> and letters. In this case, the program should return when a character different that <code>_</code> or an alphanumeric character is met.</li> </ul> <p>First, the program analyzes which case is. Based on that, "it knows" when to stop, then it returns the first character of that word.</p>
[]
[ { "body": "<p>I <strike>don't</strike> didn't immediately see a bug in it and you're doing a lot of things well; so some minor comments.</p>\n\n<hr>\n\n<pre><code>while(isspace((c = getch())))\n ;\n</code></pre>\n\n<p>This will often cause a compiler warning \"possible missing or empty statement\". If you use a compound statement instead that may suppress that warning:</p>\n\n<pre><code>while(isspace((c = getch()))) { }\n</code></pre>\n\n<hr>\n\n<pre><code>int ordinaryKeyWord = 0;\nint comment = 0;\nint stringConstant = 0;\n</code></pre>\n\n<p>These are mutually exclusive, so a 3-valued enum might be better.</p>\n\n<hr>\n\n<pre><code>for(; --lim; w++)\n</code></pre>\n\n<p>I don't think your <code>lim</code> testing is strict enough: for example if lim is 8 then <code>/*this*/</code> would overrun (write past the end of) the input buffer; even an ordinaryKeyWord will write its last <code>'\\0'</code> past the end of the buffer.</p>\n\n<hr>\n\n<pre><code>return *--w;\n</code></pre>\n\n<p>That's a bit tricky. It would be clearer to <code>return word[0];</code> everywhere consistently.</p>\n\n<hr>\n\n<pre><code> if(ordinaryKeyWord &amp;&amp; (!isValidKeyWord(*w))) {\n ungetch(*w);\n break;\n }\n</code></pre>\n\n<p>That's compact (few lines) but could be expanded to make the logic clearer for a tired reviewer:</p>\n\n<pre><code> if(ordinaryKeyWord) {\n if (isValidKeyWord(*w)) {\n continue;\n }\n ungetch(*w);\n break;\n }\n if (stringConstant) {\n ... break or continue ...\n</code></pre>\n\n<hr>\n\n<pre><code>else if(c == '/') {\n *w++ = c;\n c = getch();\n if(c == '*') {\n *w++ = c;\n comment = 1;\n }\n else {\n *w = '\\0';\n return *--w;\n }\n</code></pre>\n\n<p>You're missing ungetch in the else case.</p>\n\n<hr>\n\n<p>Is there any way to show end-of-input: pressing <code>&lt;Ctrl&gt;-D</code> for EOF for example? If so, how does getword signal that?</p>\n\n<hr>\n\n<p>I don't know an easy way to automate code which reads from the keyboard using getch and ungetch.</p>\n\n<p>That's a pity because I'd like to see the automated unit tests which define how well your code works.</p>\n\n<p>For example, <a href=\"https://codereview.stackexchange.com/q/43818/34757\">this question</a> includes its unit tests: 6 different tests of the function being coded. I was able to identify one or two bugs in the function, not by reading the function but by reviewing the set of unit tests, to find a condition (a set of input data) that wasn't being tested.</p>\n\n<p>My boss wasn't a programmer but used to user-acceptance-test the software before shipping it: he said, not 'you get what you expect' but \"You get what you INspect\".</p>\n\n<p>Especially when you're beginning you should learn to do unit testing, and <a href=\"http://www.t3y.com/tangledwebs/07/tw0706.html\" rel=\"nofollow noreferrer\">take pride in constructing a good/complete set of test cases</a>, which is able to detect bugs in the earlier versions of your software.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T11:01:49.963", "Id": "44431", "ParentId": "44424", "Score": "2" } } ]
{ "AcceptedAnswerId": "44431", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T08:31:10.590", "Id": "44424", "Score": "3", "Tags": [ "c", "beginner", "parsing", "pointers" ], "Title": "getword that properly handles undersores, string constants, comments, or preprocessor control lines" }
44424
<p>Based on feedback on an <a href="https://codereview.stackexchange.com/q/44128">earlier question</a>, I decided to implement the addition of two big ints by putting multiple digits in a node of a linked list. Can somebody take a look at my code and let me know if I am on the right track.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; typedef struct node{ int data; struct node* next; } LList; void printList(LList * list); LList* pushToResult(LList* resultList,int entry){ LList * temp = malloc(sizeof(LList)); temp -&gt; data = entry; temp -&gt; next = resultList; resultList = temp; return resultList; } char* substr(char const* input,size_t start,size_t len){ char *nstr = malloc(len+1); memcpy(nstr,input+start,len); nstr[len] = '\0'; return nstr; } LList* convertToList(char* line){ int i; int strSize = strlen(line); //Eight elements in every node int maxelem = 8; int currentPartition = 0; int currentIndex = 0; int totalPartitions = strSize/maxelem; LList* temp = NULL; for(i = 0;i &lt; strSize - 1;i = i+maxelem){ if(currentPartition &gt;= totalPartitions){ break; } char * currStr = substr(line,i,maxelem); int number = atoi(currStr); if(temp == NULL){ temp = malloc(sizeof(LList)); temp -&gt; data = number; temp -&gt; next = NULL; }else{ LList * current = malloc(sizeof(LList)); current -&gt; data = number; current -&gt; next = temp; temp = current; } currentIndex = i; currentPartition++; } currentIndex = currentIndex + maxelem; if((currentIndex &gt; 0) &amp;&amp; (currentIndex &lt; (strSize - 1))){ char * remainingStr = substr(line,currentIndex,strSize-1); int remainingNum = atoi(remainingStr); LList * current = malloc(sizeof(LList)); current -&gt; data = remainingNum; current -&gt; next = temp; temp = current; } return temp; } void printList(LList * list){ LList * counter = list; while( counter != NULL){ printf(" %d ",counter -&gt; data); counter = counter -&gt; next; } printf("\n\n"); } int main(){ //Read number 1 from the input file into a linked list //The unit's place is the head and the most significant number is the tail //Read number 2 from the input file into a linked list //The unit's place is the head and the most significant number is the tail //Create temporary List where the elements will be added //Create the carry variable that will consist of the element's carry over after addition int counter = 0; ssize_t read; size_t len = 0; char * line = NULL; int carry = 0; LList* num1 = NULL; LList* num2 = NULL; LList* result = NULL; FILE * input = fopen("input.txt","r"); if(input == NULL){ exit(EXIT_FAILURE); } while((read = getline(&amp;line,&amp;len,input)) != -1){ printf("Read the line %s",line); //If it's the first line if(counter == 0){ num1 = convertToList(line); printf("Printing the list containing the num1(it will be in reversed order)\n"); printList(num1); }else{ num2 = convertToList(line); printf("Printing the list containing the num2(it will be in reversed order)\n"); printList(num2); } counter++; } fclose(input); while((num1 != NULL) || (num2 != NULL)){ if(num1 != NULL){ carry = carry + (num1-&gt;data); num1 = num1 -&gt; next; } if(num2 != NULL){ carry = carry + (num2 -&gt; data); num2 = num2 -&gt; next; } //Get the carry and the left over int carryOver = carry / 100000000; int leftOver = carry % 100000000; //put the left over in the result linked list //printf("Pushing the result into the result list"); result = pushToResult(result,leftOver); carry = carryOver; } //Done with traversing the linked lists,if the carry is zero no need to push the value to the result //else push the value to the result if(carry != 0){ result = pushToResult(result,carry); } //Print the result here printf("Printing out the result of the addition\n"); printList(result); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T13:19:40.960", "Id": "77114", "Score": "0", "body": "@palacsint I don't think the compiler requires you to type-cast `void*` from malloc when it's C (not C++)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T13:31:53.783", "Id": "77115", "Score": "0", "body": "@ChrisW: Thanks, renaming from `.cpp` to `.c` makes compilable with `gcc`. Close vote retracted." } ]
[ { "body": "<p>Your calculator gives erroneous results due to incorrect partition alignment when converting the input into linked lists. For example:</p>\n\n<pre><code>$ cat input.txt\n122223\n45555555555555555556\n$ ./cr44425\nRead the line 122223\nPrinting the list containing the num1(it will be in reversed order)\n\n\nRead the line 45555555555555555556\nPrinting the list containing the num2(it will be in reversed order)\n 5556 55555555 45555555 \n\nPrinting out the result of the addition\n 45555555 55555555 5556\n</code></pre>\n\n<p>I expect the sum to be</p>\n\n<pre><code>45555555555555555556\n+ 122223\n====================\n45555555555555677779\n</code></pre>\n\n<p>(In my opinion, aggregating the digits to reduce the number of list nodes adds a lot of complication for questionable gains.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T04:30:18.893", "Id": "77204", "Score": "0", "body": "Thanks for your input. Would it be possible to consolidate all your answers so that I can accept it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T11:44:04.240", "Id": "44434", "ParentId": "44425", "Score": "2" } }, { "body": "<p>Aside from the glaring bug, the major theme I see is that you can strive to generalize your code.</p>\n\n<p>Examples:</p>\n\n<ol>\n<li><p>Instead of reading from <code>input.txt</code>, read from <code>stdin</code>. For less work, the user gets more flexibility.</p></li>\n<li><p>Why limit the program to adding two numbers, when you could add <em>n</em> numbers? It may be counterintuitive, but writing a program to add many lines of numbers would take <em>less</em> code, since you don't have to copy-and-paste the code to handle <code>num1</code> and <code>num2</code>. (Start with an empty list, which represents an accumulator with an initial 0 value.)</p></li>\n<li><p>In <code>ConvertToList()</code>, you don't need a special case for <code>if(temp == NULL){ … }</code> — the general case works just fine. Also, it's weird that your <code>temp</code> variable has a longer lifespan than <code>current</code>. Therefore, I would consider <code>temp</code> to be misnamed. I suggest <code>head</code> instead.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T11:58:29.433", "Id": "44436", "ParentId": "44425", "Score": "3" } }, { "body": "<p>By inspection, I see memory leaks everywhere. Every <code>malloc()</code> should have a corresponding <code>free()</code>, and there isn't a single call to <code>free()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T12:01:06.297", "Id": "44437", "ParentId": "44425", "Score": "6" } } ]
{ "AcceptedAnswerId": "44436", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T08:33:31.970", "Id": "44425", "Score": "5", "Tags": [ "c", "linked-list", "memory-management" ], "Title": "Adding two BigIntegers by putting mutiple digits in a linked list" }
44425
<p>I need to find linear conflicts of 8 puzzle state, state is represented by <code>int[9]</code>, goal state is {1,2,3,4,5,6,7,8,0}. A linear conflict would be if in a line two tiles that are supposed to be in that line are reversed.</p> <p>For example, in goal state, the first row is 1,2,3 if in the state the first row is 2,1,3 then that is one linear conflict made by tiles 2 and 1. </p> <p>My code works, but is way too long and awkward. Here it is:</p> <pre><code>public static int linearConflicts(int[] state) { ArrayList&lt;Integer&gt; row1 = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; row2 = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; row3 = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; column1 = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; column2 = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; column3 = new ArrayList&lt;Integer&gt;(); int[] columnMarkers = new int[] { 0, 3, 6, 1, 4, 7, 2, 5, 8 }; for (int i = 0; i &lt; 9; i++) { if (i &lt; 3) { row1.add(state[i]); column1.add(state[columnMarkers[i]]); } else if (i &lt; 6) { row2.add(state[i]); column2.add(state[columnMarkers[i]]); } else { row3.add(state[i]); column3.add(state[columnMarkers[i]]); } } return row1Conflicts(row1) + row2Conflicts(row2) + row3Conflicts(row3) + column1Conflicts(column1) + column2Conflicts(column2) + column3Conflicts(column3); } public static int row1Conflicts(ArrayList&lt;Integer&gt; rowState) { int conflicts = 0; if (rowState.contains(1)) { if ((rowState.contains(2)) &amp;&amp; rowState.indexOf(1) &gt; rowState.indexOf(2)) { conflicts++; } if ((rowState.contains(3)) &amp;&amp; rowState.indexOf(1) &gt; rowState.indexOf(3)) { conflicts++; } } if (rowState.contains(2) &amp;&amp; rowState.contains(3) &amp;&amp; rowState.indexOf(2) &gt; rowState.indexOf(3)) conflicts++; return conflicts; } public static int row2Conflicts(ArrayList&lt;Integer&gt; rowState) { int conflicts = 0; if (rowState.contains(4)) { if ((rowState.contains(5)) &amp;&amp; rowState.indexOf(4) &gt; rowState.indexOf(5)) { conflicts++; } if ((rowState.contains(6)) &amp;&amp; rowState.indexOf(4) &gt; rowState.indexOf(6)) { conflicts++; } } if (rowState.contains(5) &amp;&amp; rowState.contains(6) &amp;&amp; rowState.indexOf(5) &gt; rowState.indexOf(6)) conflicts++; return conflicts; } public static int row3Conflicts(ArrayList&lt;Integer&gt; rowState) { int conflicts = 0; if (rowState.contains(7) &amp;&amp; rowState.contains(8) &amp;&amp; rowState.indexOf(7) &gt; rowState.indexOf(8)) conflicts++; return conflicts; } public static int column1Conflicts(ArrayList&lt;Integer&gt; columnState) { int conflicts = 0; if (columnState.contains(1)) { if ((columnState.contains(4)) &amp;&amp; columnState.indexOf(1) &gt; columnState.indexOf(4)) { conflicts++; } if ((columnState.contains(7)) &amp;&amp; columnState.indexOf(1) &gt; columnState.indexOf(7)) { conflicts++; } } if (columnState.contains(4) &amp;&amp; columnState.contains(7) &amp;&amp; columnState.indexOf(4) &gt; columnState.indexOf(7)) conflicts++; return conflicts; } public static int column2Conflicts(ArrayList&lt;Integer&gt; columnState) { int conflicts = 0; if (columnState.contains(2)) { if ((columnState.contains(5)) &amp;&amp; columnState.indexOf(2) &gt; columnState.indexOf(5)) { conflicts++; } if ((columnState.contains(8)) &amp;&amp; columnState.indexOf(2) &gt; columnState.indexOf(8)) { conflicts++; } } if (columnState.contains(5) &amp;&amp; columnState.contains(8) &amp;&amp; columnState.indexOf(5) &gt; columnState.indexOf(8)) conflicts++; return conflicts; } public static int column3Conflicts(ArrayList&lt;Integer&gt; columnState) { int conflicts = 0; if (columnState.contains(3) &amp;&amp; columnState.contains(6) &amp;&amp; columnState.indexOf(3) &gt; columnState.indexOf(6)) conflicts++; return conflicts; } </code></pre> <p>Does anyone know how to do it shorter and less clumsy? If I keep doing methods like this, my code will be very hard to read.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T10:02:53.940", "Id": "77094", "Score": "1", "body": "There are numbers from 1 to 8 in 3x3 grid, the leftover tile is empty one and you can exchange it with one of it's neighbors every turn. Like this http://en.wikipedia.org/wiki/Fifteen_puzzle, but just a smaller variation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T10:12:35.070", "Id": "77098", "Score": "0", "body": "Do you need to count the number of inversions in each row and each column, or do you just want to test whether the whole puzzle is solvable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T10:16:06.630", "Id": "77099", "Score": "0", "body": "No I'm already doing that seperatedly, by this point any state that this function is used on is definetly solvable. What I need is a heuristic function, I have Manhattan distance, but that is not good enough so I want to add linear conflicts as explained here: http://heuristicswiki.wikispaces.com/Linear+Conflict" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T10:49:37.440", "Id": "77100", "Score": "0", "body": "I think what you are trying to count is called an inversion, i.e. a pair (i,j) i<j, so that a[i] > a[j]. I'd advise reading about Merge Sort, and thinking about how it can be modified to count inversions in O(N log N)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T11:03:29.827", "Id": "77103", "Score": "0", "body": "I'm not really trying to count inversions at least not for the whole thing, as I'm only interested in pieces that are in the row they are supposed to be in, but inversed. For example state {6,2,4,1,5,3,7,8,0} has a lot of inversions but not a single linear conflict." } ]
[ { "body": "<p>I would have some tweaks how you could improve your code quality. Reading it from the top I would start adding a comment for your method linearConflict and mention that the array as the argument contains two dimensional matrix mapped into a 1D array. It is a short comment and then immediately you get the idea why the next variables are called columns and rows.</p>\n\n<p>Another thing is I would avoid using <code>i &lt; 9</code> in for <code>(i = 0; i &lt; 9; i++)</code>. I know it is supposed to be <code>9</code> but in case it is not then you will get <code>ArrayOutOfBound</code>. I would say better would be to use <code>i &lt; state.lentgh</code> or <code>i &lt; CONSTANT</code>. The <code>CONSTANT</code> would be defined as <code>static final</code> in the class, but then I would suggest checking the length of the state array so that you know it will not be shorter - just more defensive style of programming.</p>\n\n<p>The methods <code>row1conflict</code>, <code>row2conflict</code>,.... look exactly the same just the numbers inside the method are different. I would suggest have those numbers as the arguments and then you can have only one method. I would also make the numbers as constants in the class because the particular numbers does not change and then you can pass the constants in the method. This prevents you from running into a situation when you find out that you make a mistake in one method and since all the method are \"the same\" you have to correct it in multiple places.</p>\n\n<p>So the signature could look:</p>\n\n<pre><code>public static int arrayConflicts(List&lt;Integer&gt; array, int number1, int number2,....)\n//And then call it like this\narrayConflict(column1, NUMBER_1, NUMBER_2, NUMBER_3....)\n</code></pre>\n\n<p>I named the arguments <code>number1</code> and <code>number2</code> just for illustration but if you can come up with more descriptive name that would be better.</p>\n\n<p>Another point as a type of variables use <code>List</code> instead of <code>ArrayList</code>. It gives you the freedom to change later on <code>ArrayList</code> for something else without refactoring all the types of the variables.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T11:32:19.657", "Id": "44432", "ParentId": "44427", "Score": "5" } }, { "body": "<p>The key is to generalize like mad!</p>\n\n<ul>\n<li>Force your code to deal with any square puzzle.</li>\n<li>Strive to reuse the same code for rows and columns.</li>\n</ul>\n\n<p>Additional tips:</p>\n\n<ul>\n<li>Make it object-oriented to reduce parameter-passing clutter.</li>\n<li>Use 0-based indexing for row and column numbers.</li>\n<li>Avoid <code>ArrayList</code> — your lists aren't going to grow. Arrays have tidier syntax and better performance.</li>\n</ul>\n\n\n\n<pre><code>// Use Arrays.binarySearch() like ArrayList.indexOf()\nimport static java.util.Arrays.binarySearch;\n\npublic class Puzzle {\n public static enum Axis { ROW, COL };\n\n private int[] state;\n private int side;\n\n public Puzzle(int[] state) {\n this.state = state;\n this.side = (int)Math.sqrt(state.length);\n if (side * side != state.length) {\n throw new IllegalArgumentException(\"Puzzle must be square\");\n }\n }\n\n /**\n * Returns the squares of the puzzle for a specified row or column.\n *\n * @param rc row or col number (0-based)\n */\n private int[] tuple(Axis dir, int rc) {\n int[] result = new int[this.side];\n switch (dir) {\n case ROW:\n System.arraycopy(this.state, rc * this.side, result, 0, this.side);\n break;\n case COL:\n for (int i = 0, j = rc; i &lt; this.side; i++, j += this.side) {\n result[i] = this.state[j];\n }\n break;\n }\n return result;\n }\n\n /**\n * Returns the squares of the puzzle of this size as if it were in\n * its solved state for a specified row or column.\n *\n * @param rc row or col number (0-based)\n */\n private int[] idealTuple(Axis dir, int rc) {\n int[] result = new int[this.side];\n switch (dir) {\n case ROW:\n for (int i = 0, j = rc * this.side + 1; i &lt; this.side; i++, j++) {\n result[i] = (j &lt; this.state.length) ? j : 0;\n }\n break;\n case COL:\n for (int i = 0, j = this.side + rc + 1; i &lt; this.side; i++, j += this.side) {\n result[i] = (j &lt; this.state.length) ? j : 0;\n }\n break;\n }\n return result;\n }\n\n /**\n * Count inversions (linear conflicts) for a row or column.\n */\n public int inversions(Axis dir, int rc) {\n int[] have = this.tuple(dir, rc);\n int[] want = this.idealTuple(dir, rc);\n int inversions = 0;\n\n // For each pair of squares, if both numbers are supposed to be in this\n // tuple, and neither is 0 (blank)...\n for (int i = 1, iPos; i &lt; this.side; i++) {\n if (have[i] != 0 &amp;&amp; 0 &lt;= (iPos = binarySearch(want, have[i]))) {\n for (int j = 0, jPos; j &lt; i; j++) {\n if (have[j] != 0 &amp;&amp; 0 &lt;= (jPos = binarySearch(want, have[j]))) {\n // ... and are inverted, count it as a conflict.\n if ((have[i] &lt; have[j]) != (i &lt; j)) {\n inversions++;\n }\n }\n }\n }\n }\n return inversions;\n }\n\n public static void main(String[] args) {\n Puzzle p = new Puzzle(new int[] {\n 3, 2, 1,\n 4, 7, 5,\n 8, 6, 0\n });\n System.out.printf(\"Row %d inversions = %d\\n\", 0, p.inversions(Axis.ROW, 0));\n System.out.printf(\"Row %d inversions = %d\\n\", 1, p.inversions(Axis.ROW, 1));\n System.out.printf(\"Row %d inversions = %d\\n\", 2, p.inversions(Axis.ROW, 2));\n System.out.printf(\"Col %d inversions = %d\\n\", 0, p.inversions(Axis.COL, 0));\n System.out.printf(\"Col %d inversions = %d\\n\", 1, p.inversions(Axis.COL, 1));\n System.out.printf(\"Col %d inversions = %d\\n\", 2, p.inversions(Axis.COL, 2));\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T11:33:20.690", "Id": "44433", "ParentId": "44427", "Score": "5" } } ]
{ "AcceptedAnswerId": "44433", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T09:49:59.860", "Id": "44427", "Score": "7", "Tags": [ "java", "algorithm", "mathematics", "matrix" ], "Title": "Counting linear conflicts of the state of 8 puzzle for heuristic" }
44427
<p>The purpose of this class is to read an IIS log (or multiple ones). One thing to note is that the columns can differ based on settings in IIS.</p> <p>A couple of concerns that I have:</p> <ol> <li>Is The ILogReader Interface neccessary?</li> <li>Is the IFileReader the right way to allow me to stub out the <code>File.ReadAllLines</code> method?</li> <li>Any other refactoring / clean code suggestions</li> <li>How are my tests?</li> <li>Is the static variable a nice and clean way to setup test data?</li> </ol> <p></p> <pre><code>public class LogReader : ILogReader { private IFileReader _fileReader; private List&lt;string[]&gt; _lines = new List&lt;string[]&gt;(); private string[] _infoLines = new[] { "#Version:", "#Date:", "#Software:", "#Fields:" }; public LogReader(IFileReader fileReader) { _fileReader = fileReader; } public List&lt;LogEntry&gt; LogEntries { get { return _lines .Where(line =&gt; IsLogEntry(line)) .Select(logEntryLine =&gt; new LogEntry(logEntryLine, Header)) .ToList(); } } private bool IsLogEntry(string[] line) { return !_infoLines.Contains(line.First()); } public void AddFileToEntries(string fileName) { var newLines = _fileReader.ReadAllLines(fileName) .Select(line =&gt; line.Split(' ')) .ToList(); _lines.AddRange(newLines); } public List&lt;string&gt; Header { get { return _lines .FirstOrDefault(l =&gt; l.First() .Contains("#Fields")) .Skip(1) .Select(field =&gt; field.Replace("-","")) .ToList(); } } } </code></pre> <p>Here are my tests:</p> <pre><code>[TestClass] public class LogReaderTests { private ILogReader _logReader; Moq.Mock&lt;IFileReader&gt; _fileReaderMock; const string _logFileWith404String = "LogFileWith404"; const string _logFileWith200String = "LogFileWith200"; [TestInitialize] public void Init() { _fileReaderMock = new Moq.Mock&lt;IFileReader&gt;(); _fileReaderMock.Setup(fileReader =&gt; fileReader.ReadAllLines(_logFileWith404String)).Returns(TestData.LogFileWith404); _fileReaderMock.Setup(fileReader =&gt; fileReader.ReadAllLines(_logFileWith200String)).Returns(TestData.LogFileWith200); _logReader = new LogReader(_fileReaderMock.Object); _logReader.AddFileToEntries(_logFileWith404String); } [TestMethod] public void OpenLogAndReadLines() { Assert.IsTrue(_logReader.LogEntries.Count &gt; 0); } [TestMethod] public void OpenLogAndReadHeaderEnsureThatFirstNonHeaderValueIsDate() { Assert.AreEqual(_logReader.Header.First(),"date"); } [TestMethod] public void TestFirstValueCanConvertToDate() { var logEntries = _logReader.LogEntries; dynamic value = logEntries.First(); var convertedDate = Convert.ToDateTime(value.date); } [TestMethod] public void PrintAllLines() { var headerLine = String.Join("," , _logReader.Header); System.Diagnostics.Debug.WriteLine(headerLine); foreach (var item in _logReader.LogEntries) { System.Diagnostics.Debug.WriteLine(String.Join(",", item)); } } [TestMethod] public void GetAllLinesWithNotFoundErrors() { var notFoundLines = from logEntries in _logReader.LogEntries where ((dynamic)logEntries).scstatus == "404" select logEntries; foreach (dynamic item in notFoundLines) { Assert.AreEqual("404", item.scstatus); } } [TestMethod] public void ReadMultipleFilesIntoLogParser() { int realLineCount = TestData.LogFileWith404 .Count(entry =&gt; FileDoesNotContainHeaderLine(entry)); realLineCount += TestData.LogFileWith200 .Count(entry =&gt; FileDoesNotContainHeaderLine(entry)); _logReader.AddFileToEntries(_logFileWith200String); Assert.IsTrue(_logReader.LogEntries.Count() == realLineCount); } private bool FileDoesNotContainHeaderLine(string c) { return !new[] { "#Version:", "#Date:", "#Software:", "#Fields:" } .Contains(c.Split(' ')[0]); } } </code></pre>
[]
[ { "body": "<p>Let's take a look.</p>\n\n<blockquote>\n <p>Is The ILogReader Interface neccessary?</p>\n</blockquote>\n\n<p>It is not, as long as you reasonably expect that it will stay with just this one log reader. I think it is not out of the question that you might adapt your application to also account for different types of logs so I would leave it in there for future purposes.</p>\n\n<p>It also indicates more that you are talking about <em>a</em> logreader instead of <em>the</em> logreader, which you'll need when adding more logs.</p>\n\n<blockquote>\n <p>Is the IFileReader the right way to allow me to stub out the File.ReadAllLines method?</p>\n</blockquote>\n\n<p>Yes, definitely. External dependencies should be stubbed out into their own layer so you have no interference with the actual system and thus stick to unit tests and not integration tests (they should live together, not replace eachother).</p>\n\n<p>As a sidenote here: are you using an actual sample logfile or are you hardcoding the strings? I feel like you could benefit from adding an additional layer for mocking data in your unit tests. Read more <a href=\"https://stackoverflow.com/questions/22409912/unit-testing-valid-inputs-to-a-method/22410273#22410273\">here</a> on that subject.</p>\n\n<blockquote>\n <p>Any other refactoring / clean code suggestions</p>\n</blockquote>\n\n<p>Honestly.. No. Your code is very clean and slim and it looks like you have little room for improvement, you're fine on that aspect.</p>\n\n<blockquote>\n <p>How are my tests?</p>\n</blockquote>\n\n<p>I prefer explicit <code>private</code> mentioning for variables. It leaves no room for confusion and it keeps your types aligned with eachother.</p>\n\n<pre><code>private ILogReader _logReader;\nprivate Moq.Mock _fileReaderMock;\nprivate const string _logFileWith404String = \"LogFileWith404\";\nprivate const string _logFileWith200String = \"LogFileWith200\";\n</code></pre>\n\n<p>When it comes to unit testing method naming I very much appreciate the approach as described in <a href=\"http://rads.stackoverflow.com/amzn/click/1617290890\" rel=\"nofollow noreferrer\">The art of Unit Testing, 2nd Edition by Roy Osherove</a> which comes down to </p>\n\n<pre><code>[UnitOfWorkName]_[ScenarioUnderTest]_[ExpectedBehaviour]\n</code></pre>\n\n<p>For example for your method named <em>OpenLogAndReadHeaderEnsureThatFirstNonHeaderValueIsDate</em> this could become</p>\n\n<pre><code>ReadingLogHeader_FirstNonHeaderValue_IsDate\n</code></pre>\n\n<p>Now you have clearly separated your method name's intentions and it's more easily to see where the problem is located when tests fail.</p>\n\n<p>There are two methods (<code>TestFirstValueCanConvertToDate</code> and <code>PrintAllLines</code>) that don't test anything thus they shouldn't be marked with the <code>TestMethodAttribute</code>. Likewise they should be <code>private</code> if they're just helper methods (although I don't see the purpose of <code>TestFirstValueCanConvertToDate</code>).</p>\n\n<blockquote>\n <p>Is the static variable a nice and clean way to setup test data?</p>\n</blockquote>\n\n<p>I assume you are referring to the <code>const</code> variables considering I don't see any <code>static</code> behaviour aside from that.</p>\n\n<p>No, I don't think they're necessary. It won't have any impact on your performance and you shouldn't have another class that tests the same class so it shouldn't be used for that purpose either.</p>\n\n<p>That being said: it doesn't negatively impact you either so it is yours to choose if you keep them or not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:30:09.577", "Id": "77121", "Score": "0", "body": "Thanks, helps allot. In terms of the static variable part, the TestData.LogFileWith200 actually is just a string[] inside a class taken from a log file (to be clean). This is so that I don't go and read the file (as you mentioned to avoid integration testing). My idea was that this is mocked out? Thanks for the very thoughtful review!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:31:06.877", "Id": "77122", "Score": "0", "body": "O yes, the constants are there to make it a bit more reusable as well as to promote reuse although I can see how this might be a bit of an overkill" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:37:09.267", "Id": "77123", "Score": "0", "body": "The reuse isn't relevant here since you will never create multiple instances of your test class so it doesn't do anything. But yes, you basically incorporated a datasource layer for your tests which is what I would do as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:42:06.170", "Id": "77125", "Score": "0", "body": "I actually did read the art of unit testing, very good book. I find it a bit laborious to write my methods like that and am experimenting with different options. I do actually reuse one of the strings in ReadMultipleFilesIntoLogParser (yes, I know most people say you should only consider reuse after using it 3 times) and so to keep a standard I renamed both. Thinking about it now though I see your point that it's been refactored out to soon. Thanks again" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T11:54:32.667", "Id": "44435", "ParentId": "44429", "Score": "3" } }, { "body": "<blockquote>\n <p>Is the IFileReader the right way to allow me to stub out the File.ReadAllLines method?</p>\n</blockquote>\n\n<p>I'm not sure. In which component is <code>IFileReader</code> defined?</p>\n\n<p>An alternative would be to use a delegate: <code>Func&lt;string, string[]&gt;</code>.</p>\n\n<p>I'm unsure of this answer because I don't know/understand Moq, but IMO using a delegate instead of an interface would let you pass <code>File.ReadAllLines</code> directly as the delegate parameter ...</p>\n\n<pre><code>LogReader reader = new LogReader(System.IO.File.ReadAllLines);\n</code></pre>\n\n<p>... instead of defining and instantiating a class which implements the <code>IFileReader</code> interface and uses <code>File.ReadAllLines</code> in its implementation ...</p>\n\n<pre><code>interface IFileReader\n{\n string[] ReadAllLines(string filename);\n}\n\nclass FileReader : IFileReader\n{\n public string[] ReadAllLines(string filename)\n {\n return System.IO.File.ReadAllLines(filename);\n }\n}\n\nLogReader reader = new LogReader(new FileReader());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T12:41:20.713", "Id": "44438", "ParentId": "44429", "Score": "3" } } ]
{ "AcceptedAnswerId": "44435", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T10:19:11.737", "Id": "44429", "Score": "3", "Tags": [ "c#", "unit-testing", "tdd" ], "Title": "Read Lines From IIS Log" }
44429
<p>Is there any way of counting how many shifts would it take to count shifts while doing insertion sort? This is a Hackerrank problem. Here's my solution, but it takes more than 16 seconds.</p> <pre><code>counts = [] for _ in range(int(input())): size = int(input()) ar = list(map(int, input().split())) count = 0 for i in range(1, len(ar)): j = i while j &gt;= 1 and ar[j] &lt; ar[j-1]: ar[j], ar[j-1] = ar[j-1], ar[j] j -= 1 count+=1 counts.append(count) for c in counts: print(c) </code></pre> <blockquote> <p>Insertion Sort is a simple sorting technique which was covered in previous challenges. Sometimes, arrays may be too large for us to wait around for insertion sort to finish. Is there some other way we can calculate the number of times Insertion Sort shifts each elements when sorting an array?</p> <p>If ki is the number of elements over which ith element of the array has to shift then total number of shift will be k1 + k2 + … + kN.</p> <p>Input: The first line contains the number of test cases T. T test cases follow. The first line for each case contains N, the number of elements to be sorted. The next line contains N integers a[1],a[2]…,a[N].</p> <p>Output: Output T lines, containing the required answer for each test case.</p> </blockquote> <p>That's the problem. Is there any way I could optimize my solution?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-03T01:29:02.037", "Id": "125394", "Score": "0", "body": "My code did 0.04s: https://github.com/LeandroTk/Algorithm_DataStructure/blob/master/insertion_sort.py I think your code takes more than 16 seconds, because of the 3 nested loops.. (n³)." } ]
[ { "body": "<p>Insertion sort is an O(<em>n</em><sup>2</sup>) algorithm. There's only so much you can do to optimize it.</p>\n\n<p>This is a bit of trick question. It doesn't actually ask you to sort the arrays in question; it just asks you to count the number of shifts involved. So, for each element to be \"inserted\", just count the number of preceding elements that have a larger value.</p>\n\n<p>Stylistically, your program should be modularized. Each of the <em>T</em> test cases is independent, so isolate each test case in a function. You probably don't have to buffer the results, either — just print the result from each test case as soon as you have the answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T13:05:18.303", "Id": "77113", "Score": "0", "body": "you mean to remove those swaps?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T20:39:43.957", "Id": "77167", "Score": "0", "body": "Yes, that's right. [Hint](http://stackoverflow.com/a/2643910/1157100)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T12:54:53.640", "Id": "44440", "ParentId": "44430", "Score": "3" } } ]
{ "AcceptedAnswerId": "44440", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T10:51:09.877", "Id": "44430", "Score": "3", "Tags": [ "python", "optimization", "sorting", "python-3.x", "insertion-sort" ], "Title": "Time optimization of counting shifts in insertion sort" }
44430
<p>I consider these two options exactly the same. I prefer the first one but I'm not sure if it's better than the second option in terms of cyclomatic complexity or readability.</p> <p>Assuming that this is not pure Ruby and I can call to the <a href="http://apidock.com/rails/Object/try" rel="nofollow"><code>try</code> method</a>.</p> <pre><code>existing_transaction = database.find_transaction_by_id(transaction.id) database.create_transaction(transaction) unless existing_transaction database.update_transaction(transaction) unless existing_transaction.try(:processed) </code></pre> <p></p> <pre><code>existing_transaction = database.find_transaction_by_id(transaction.id) if existing_transaction unless existing_transaction.processed database.update_transaction(transaction) end else database.create_transaction(transaction) end </code></pre>
[]
[ { "body": "<p>It's obviously subjective, but IMHO inline conditionals make code harder to understand, indentation is very important. So I'd definitely take the second approach, but writing it differently to use only one indentation level:</p>\n\n<pre><code>existing_transaction = database.find_transaction_by_id(transaction.id)\nif !existing_transaction\n database.create_transaction(transaction)\nelsif !existing_transaction.processed\n database.update_transaction(transaction)\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T13:47:07.247", "Id": "44443", "ParentId": "44441", "Score": "4" } }, { "body": "<p>I would actually take a mixed approach:</p>\n\n<pre><code>if existing_transaction\n database.update_transaction(transaction) unless existing_transaction.processed\nelse\n database.create_transaction(transaction)\nend\n</code></pre>\n\n<p>This way the code is more readable than the first option, but more succinct than the second option.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T19:57:39.827", "Id": "77161", "Score": "0", "body": "This is exactly my solution wrote with `unless` inlined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T20:18:52.143", "Id": "77162", "Score": "0", "body": "Yes, it is - it just reads better IMHO" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:46:45.290", "Id": "44456", "ParentId": "44441", "Score": "1" } } ]
{ "AcceptedAnswerId": "44443", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T13:25:51.250", "Id": "44441", "Score": "3", "Tags": [ "ruby", "comparative-review", "cyclomatic-complexity" ], "Title": "Readability and cyclomatic complexity of database transaction code" }
44441
<p><a href="http://easymock.org/" rel="nofollow">Easymock</a> is an open source mocking framework for Java. It is used for creating mock objects and stubs for unit tests.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:27:34.787", "Id": "44446", "Score": "0", "Tags": null, "Title": null }
44446
Easymock is a mocking framework for Java.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:27:34.787", "Id": "44447", "Score": "0", "Tags": null, "Title": null }
44447
<p><a href="http://stackoverflow.com/tags/jsf/info">JSF tag wiki on Stack Overflow</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:30:31.127", "Id": "44448", "Score": "0", "Tags": null, "Title": null }
44448
JavaServer Faces (JSF) is a model-view-presenter framework typically used to create web applications. Using the standard components and render kit, stateful HTML views can be defined using JSP or Facelets tags and wired to model data and application logic.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:30:31.127", "Id": "44449", "Score": "0", "Tags": null, "Title": null }
44449
<p><a href="http://stackoverflow.com/tags/jsf-2/info">JSF 2 tag wiki on Stack Overflow</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:31:44.647", "Id": "44450", "Score": "0", "Tags": null, "Title": null }
44450
JavaServer Faces (JSF) is a model-view-presenter framework typically used to create web applications. Version 2.x is a major step ahead compared to JSF 1.x, significantly expanding the standard set of components and component libraries.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:31:44.647", "Id": "44451", "Score": "0", "Tags": null, "Title": null }
44451
<p>I have used Intel VTune in order to find the hotspots in my code. I wrote comments next to the worst lines.</p> <p>Can you please review my code? General review or performance issues is more than welcome.</p> <pre><code>void ALGO::computeSADs(int (&amp;nbr_SAD_RES)[ALGO_NBR_SZ][ALGO_NBR_SZ], int (&amp;SAD)[ALGO_NUM_CANDIDATE]) { // Computes SAD values between P and each candidate in the neighborhood. // // Type | Name | Size | Precision | // ------+-------------+---------------------------+----------------| // Input | Nbr_SAD_RES | ALGO_NBR_SZ x ALGO_NBR_SZ | ALGO_SIM_RES | // Output| SAD | 1 x ALGO_NUM_CANDIDATE | ALGO_SAD_RES | // int candLocX[ALGO_NUM_CANDIDATE]; int candLocY[ALGO_NUM_CANDIDATE]; // init inner candidate position vectors candLocX[0 ] = ALGO_CAND00_LOC_X; candLocY[0 ] = ALGO_CAND00_LOC_Y; candLocX[1 ] = ALGO_CAND01_LOC_X; candLocY[1 ] = ALGO_CAND01_LOC_Y; candLocX[2 ] = ALGO_CAND02_LOC_X; candLocY[2 ] = ALGO_CAND02_LOC_Y; candLocX[3 ] = ALGO_CAND03_LOC_X; candLocY[3 ] = ALGO_CAND03_LOC_Y; candLocX[4 ] = ALGO_CAND04_LOC_X; candLocY[4 ] = ALGO_CAND04_LOC_Y; candLocX[5 ] = ALGO_CAND05_LOC_X; candLocY[5 ] = ALGO_CAND05_LOC_Y; candLocX[6 ] = ALGO_CAND06_LOC_X; candLocY[6 ] = ALGO_CAND06_LOC_Y; candLocX[7 ] = ALGO_CAND07_LOC_X; candLocY[7 ] = ALGO_CAND07_LOC_Y; if (m_CandConstellation==0) { candLocX[8 ] = ALGO_CAND08_0_LOC_X; candLocY[8 ] = ALGO_CAND08_0_LOC_Y; candLocX[9 ] = ALGO_CAND09_0_LOC_X; candLocY[9 ] = ALGO_CAND09_0_LOC_Y; candLocX[10] = ALGO_CAND10_0_LOC_X; candLocY[10] = ALGO_CAND10_0_LOC_Y; candLocX[11] = ALGO_CAND11_0_LOC_X; candLocY[11] = ALGO_CAND11_0_LOC_Y; candLocX[12] = ALGO_CAND12_0_LOC_X; candLocY[12] = ALGO_CAND12_0_LOC_Y; candLocX[13] = ALGO_CAND13_0_LOC_X; candLocY[13] = ALGO_CAND13_0_LOC_Y; candLocX[14] = ALGO_CAND14_0_LOC_X; candLocY[14] = ALGO_CAND14_0_LOC_Y; candLocX[15] = ALGO_CAND15_0_LOC_X; candLocY[15] = ALGO_CAND15_0_LOC_Y; } else if (m_CandConstellation==1) { candLocX[8 ] = ALGO_CAND08_1_LOC_X; candLocY[8 ] = ALGO_CAND08_1_LOC_Y; candLocX[9 ] = ALGO_CAND09_1_LOC_X; candLocY[9 ] = ALGO_CAND09_1_LOC_Y; candLocX[10] = ALGO_CAND10_1_LOC_X; candLocY[10] = ALGO_CAND10_1_LOC_Y; candLocX[11] = ALGO_CAND11_1_LOC_X; candLocY[11] = ALGO_CAND11_1_LOC_Y; candLocX[12] = ALGO_CAND12_1_LOC_X; candLocY[12] = ALGO_CAND12_1_LOC_Y; candLocX[13] = ALGO_CAND13_1_LOC_X; candLocY[13] = ALGO_CAND13_1_LOC_Y; candLocX[14] = ALGO_CAND14_1_LOC_X; candLocY[14] = ALGO_CAND14_1_LOC_Y; candLocX[15] = ALGO_CAND15_1_LOC_X; candLocY[15] = ALGO_CAND15_1_LOC_Y; } else if (m_CandConstellation==2) { candLocX[8 ] = ALGO_CAND08_2_LOC_X; candLocY[8 ] = ALGO_CAND08_2_LOC_Y; candLocX[9 ] = ALGO_CAND09_2_LOC_X; candLocY[9 ] = ALGO_CAND09_2_LOC_Y; candLocX[10] = ALGO_CAND10_2_LOC_X; candLocY[10] = ALGO_CAND10_2_LOC_Y; candLocX[11] = ALGO_CAND11_2_LOC_X; candLocY[11] = ALGO_CAND11_2_LOC_Y; candLocX[12] = ALGO_CAND12_2_LOC_X; candLocY[12] = ALGO_CAND12_2_LOC_Y; candLocX[13] = ALGO_CAND13_2_LOC_X; candLocY[13] = ALGO_CAND13_2_LOC_Y; candLocX[14] = ALGO_CAND14_2_LOC_X; candLocY[14] = ALGO_CAND14_2_LOC_Y; candLocX[15] = ALGO_CAND15_2_LOC_X; candLocY[15] = ALGO_CAND15_2_LOC_Y; } else { ErrMsg("ALGO:\\Internal error!! Unsupported Constellation!"); } // Compute SADs for inner candidates int fast_SAD_index_i = 0; bool exit_loop_sad_max = false; int candLocY_index_i ; int candLocX_index_i ; int * nbr_SAD_RES_index_ALGO_PATCH_LOC_Y_plus_k_offset_ALGO_PATCH_LOC_X; int * nbr_SAD_RES_candLocY_index_iplus_k_offset_candLocX_index_i; int patch_pixel_value ; int cand_pixel_value ; int i,j,k; int temp1 = ((1&lt;&lt;(ALGO_SAD_RES-1)) - 1)); for (i = 0; i &lt; ALGO_NUM_CANDIDATE; ++i) { fast_SAD_index_i = 0; exit_loop_sad_max = false; //SAD[i] = 0; if (m_CandEnable[i]) { candLocY_index_i = candLocY[i]; candLocX_index_i = candLocX[i]; for (k = 0; !exit_loop_sad_max &amp;&amp; ( k &lt; ALGO_PATCH_SZ); ++k) { nbr_SAD_RES_index_ALGO_PATCH_LOC_Y_plus_k_offset_ALGO_PATCH_LOC_X = nbr_SAD_RES[ALGO_PATCH_LOC_Y+k ]+ALGO_PATCH_LOC_X; nbr_SAD_RES_candLocY_index_iplus_k_offset_candLocX_index_i = nbr_SAD_RES[candLocY_index_i+k]+candLocX_index_i; patch_pixel_value =*nbr_SAD_RES_index_ALGO_PATCH_LOC_Y_plus_k_offset_ALGO_PATCH_LOC_X; cand_pixel_value = *nbr_SAD_RES_candLocY_index_iplus_k_offset_candLocX_index_i; for (j=0; !exit_loop_sad_max &amp;&amp; (j&lt;ALGO_PATCH_SZ); ++j) { if(patch_pixel_value&lt;cand_pixel_value) { fast_SAD_index_i -= patch_pixel_value-cand_pixel_value; } else { fast_SAD_index_i += patch_pixel_value-cand_pixel_value; } if (fast_SAD_index_i &gt;= temp1) { fast_SAD_index_i = temp1; exit_loop_sad_max = true; } else { patch_pixel_value =*(++nbr_SAD_RES_index_ALGO_PATCH_LOC_Y_plus_k_offset_ALGO_PATCH_LOC_X); // worst line cand_pixel_value = *(++nbr_SAD_RES_candLocY_index_iplus_k_offset_candLocX_index_i); } } } } SAD[i] = fast_SAD_index_i; }// End for i } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:11:17.077", "Id": "77126", "Score": "0", "body": "Did the change to `int temp1 ...` make a difference?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:11:56.887", "Id": "77127", "Score": "0", "body": "yes i'm not computing it over and over again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:12:33.097", "Id": "77128", "Score": "0", "body": "Isn't `ALGO_SAD_RES` a constant? Where is it defined?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:13:12.217", "Id": "77129", "Score": "0", "body": "still i have some hard performance issues. in this line patch_pixel_value =*(++nbr_SAD_RES_index_BNLM_PATCH_LOC_Y_plus_k_offset_BNLM_PATCH_LOC_X); i'm spending a lot of time i don't know why" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:14:17.387", "Id": "77130", "Score": "0", "body": "Meh, you have edited your question and moved the 'worst-lines'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:14:28.573", "Id": "77131", "Score": "0", "body": "it is a const but i'm not doing it over and over again. assume my function is being called millions of times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:16:02.167", "Id": "77133", "Score": "0", "body": "yes i know i'm using vtune and now i changed the worst line. to where the hotspots are." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T16:17:28.767", "Id": "77135", "Score": "0", "body": "these are still very bad lines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T15:50:59.877", "Id": "77360", "Score": "0", "body": "Haha, I found a way to bypass all the initialization boilerplate, but it's plain horrible. Do you like code-generating macros?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:06:12.817", "Id": "77389", "Score": "0", "body": "No. This code needs to be maintained bye someone else one day." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T15:45:25.900", "Id": "44452", "Score": "3", "Tags": [ "c++", "optimization", "algorithm", "performance" ], "Title": "Compute SAD values" }
44452
<p>I have written a C# file reader that reads a file converts the bytes of the file to hex and writes it out to another file. It works fine but it takes 7.2GB of memory when converting a 300MB file.</p> <p>What can I do to this code to make it take less memory?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hex__Reader { class Program { static void Main(string[] args) { OpenFile(); } private static void OpenFile() { uint j = 0; byte[] bytes = System.IO.File.ReadAllBytes(filename); char[] hex = BitConverter.ToString(bytes).Replace("-", " ").ToCharArray(); //char[] hexchar = hex.ToCharArray(); System.IO.StreamWriter writer = new System.IO.StreamWriter(filename,false); Console.WriteLine("Writing Bytes"); for (uint i = 0; i &lt; hex.Length; i++) { if (j == 50) { writer.WriteLine(); writer.WriteLine(); j = 0; } else { writer.Write(hex[i]); j++; } } } } } </code></pre>
[]
[ { "body": "<p>Your problem is that you load the whole file into memory, convert each byte to three characters (that's the file size times 6), going through <code>Replace</code> and <code>ToCharArray</code>.</p>\n\n<p>To avoid holding all in memory, you should <em>stream</em> the data, converting and writing <em>each chunk</em>. This way, you'll only hold a fraction of the file at each time:</p>\n\n<pre><code>using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filename,false)) {\n using (FileStream fs = File.OpenRead(filename)) \n {\n byte[] b = new byte[50];\n\n while (fs.Read(b,0,b.Length) &gt; 0) \n {\n writer.WriteLine(BitConverter.ToString(bytes).Replace(\"-\", \" \"));\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>If (even when the buffer size is more optimal at 1024) you still have memory issues, it might be because of <code>BitConverter.ToString(bytes).Replace(\"-\", \" \")</code>... you could use some other methods to make to conversion, as suggested <a href=\"http://social.msdn.microsoft.com/Forums/vstudio/en-US/3928b8cb-3703-4672-8ccd-33718148d1e3/byte-array-to-hex-string?forum=csharpgeneral\">here</a>, for example:</p>\n\n<pre><code>int itemsInLineCounter = 0;\nusing (System.IO.StreamWriter writer = new System.IO.StreamWriter(filename,false)) {\n using (FileStream fs = File.OpenRead(filename)) {\n byte[] b = new byte[1024];\n int read;\n\n while ((read = fs.Read(b,0,b.Length)) &gt; 0) {\n for (int i = 0; i &lt; read; i++) {\n writer.Write(bytes[i].ToString(\"X2\"));\n if (itemsInLineCounter &gt; NUM_OF_ITEMS_IN_LINE) {\n writer.WriteLine();\n itemsInLineCounter = 0;\n } else {\n writer.Write(' ');\n itemsInLineCounter++;\n }\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T19:28:42.260", "Id": "77158", "Score": "0", "body": "it uses more memory now and it also takes longer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T19:32:36.993", "Id": "77160", "Score": "0", "body": "hmm... the buffer size is not optimal... try using buffer size 1024..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T20:38:36.790", "Id": "77166", "Score": "0", "body": "added some other options" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T20:42:06.250", "Id": "77169", "Score": "0", "body": "Another option, which should create fewer temporary/short strings, would be to expand line-sized chunks of text from `bytes` into a StringBuilder." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:23:30.613", "Id": "77225", "Score": "1", "body": "Down To 320MB Now" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T18:43:32.883", "Id": "44459", "ParentId": "44457", "Score": "9" } }, { "body": "<p>If you're interested in further optimization, this should maintain a minimal memory footprint and be about 25% faster:</p>\n\n<pre><code> private static void OpenFile()\n {\n string[] digits = new string[] { \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\" };\n using(System.IO.BinaryReader br = new System.IO.BinaryReader\n (new System.IO.FileStream\n (\n \"ByteFile.dat\", \n System.IO.FileMode.Open, \n System.IO.FileAccess.Read, \n System.IO.FileShare.None, \n 1024)\n )\n )\n {\n using(System.IO.StreamWriter sw = new System.IO.StreamWriter(\"HexFile.txt\"))\n {\n byte[] inbuff = new byte[0];\n int b = 0;\n while((inbuff = br.ReadBytes(50)).Length &gt; 0)\n {\n for(b = 0; b &lt; inbuff.Length - 1; b++)\n {\n sw.Write(digits[(inbuff[b] / 16) % 16] + digits[inbuff[b] % 16] + \" \");\n }\n sw.WriteLine(digits[(inbuff[b] / 16) % 16] + digits[inbuff[b] % 16]);\n\n }\n }\n }\n }\n</code></pre>\n\n<p>You'll notice that using a string array as a look up table for the hex digits eliminates any tostring conversions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:54:44.323", "Id": "44598", "ParentId": "44457", "Score": "4" } } ]
{ "AcceptedAnswerId": "44459", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T18:14:44.567", "Id": "44457", "Score": "7", "Tags": [ "c#", "optimization", "memory-management", "converting" ], "Title": "Hex file converter" }
44457
<p>Sometimes I run across the problem of having two member function overloads that only differ in the constness of <code>this</code> (and the return type, but that is less important):</p> <pre><code>int&amp; operator[](int); const int&amp; operator[](int)const; </code></pre> <p>Most of the time these are one-liners, but even then, I hate the code duplication. That's why I like to use (if possible) the <code>const</code> version to implement the non <code>const</code> version via <code>const_cast</code>:</p> <pre><code>const int&amp; MyClass::operator[](int index)const { return const_cast&lt;int&amp;&gt;(const_cast&lt;MyClass&amp;&gt;(*this)[index]); } </code></pre> <p>The first <code>const_cast</code> is required (at least I think so), but I wonder if the second one can be circumvented and if so, if the code is more readable then.</p> <p>How do you solve this problem?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T19:30:25.007", "Id": "77159", "Score": "1", "body": "There are several good answers on StackOverflow: see [How do I remove code duplication between similar const and non-const member functions?](http://stackoverflow.com/q/123758/49942)" } ]
[ { "body": "<p>As ChrisW commented, this has been covered in depth <a href=\"https://stackoverflow.com/q/123758/49942\">at Stack Overflow</a>. You're very close, but you should actually have the non-const version cast away the const-ness of the const version rather than how you're doing it. </p>\n\n<p>If you're calling a non-const method, you are operating on a non-const object. This means that the const cast is technically valid since you are assured that the underlying object is non-const anyway.</p>\n\n<hr>\n\n<p>Note that there are other options that are potentially cleaner from a \"I should always avoid const_cast!\" point of view. Personally, I think this is one of the legitimate uses of <code>const_cast</code>, and it is the approach I use. If you'd like to see more information on the other options, see <a href=\"https://stackoverflow.com/q/123758/49942\">the Stack Overflow post</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T20:55:11.247", "Id": "77172", "Score": "0", "body": "Hm I just reproduced the code from the top of my head and did not notice I had done it the other way around. Of course you are right. The non const code could do manipulations that we don't want the const code to suffer from." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T20:53:48.543", "Id": "44468", "ParentId": "44460", "Score": "5" } }, { "body": "<p>One (C++11) solution is to \"hide\" the ugly second <code>const_cast</code> with a macro (<em>shudder</em>):</p>\n\n<pre><code>#include &lt;type_traits&gt; \n#define CONST_THIS const_cast&lt; \\\n std::add_pointer&lt; \\\n std::add_const&lt; \\\n std::remove_pointer&lt; \\\n decltype(this)&gt;::type&gt;::type&gt;::type&gt;(this)\n</code></pre>\n\n<p>And use it like this:</p>\n\n<pre><code>int&amp; operator[](int index) {\n return const_cast&lt;int&amp;&gt;((*CONST_THIS)[index]);\n}\n</code></pre>\n\n<p>The code in the macro uses type traits to add constness to the this pointer. To do so it must at first strip the pointer (to apply the <code>const</code> to the pointed to type) and then make it a pointer again to use the macro as if it where the <code>this</code> pointer in a <code>const</code> member function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T09:42:45.217", "Id": "77328", "Score": "4", "body": "Does any of the downvoters mind to give an explanation? I dislike macros but I find the code more readable that way and it certainly improves over the \"useless\" repetition of the type of this to use the `const_cast`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T21:07:07.207", "Id": "44469", "ParentId": "44460", "Score": "1" } }, { "body": "<p>First you have it the wrong way around.</p>\n\n<p>You should not use the mutating version to supply data to the non-mutating function:</p>\n\n<pre><code>const int&amp; MyClass::operator[](int index)const {\n return const_cast&lt;int&amp;&gt;(const_cast&lt;MyClass&amp;&gt;(*this)[index]);\n}\n</code></pre>\n\n<p>What happens if <code>operator[]</code> is modified and does mutate slightly the internal state? By casting away the constness you have opened up your class to undefined behavior. You should <strong>NEVER</strong> cast away constness. If you must you can use const_cast to add constness, but removing it is so dangerous that this should be looked at as breaking code.</p>\n\n<p>If you had written it the other way around:</p>\n\n<pre><code>int&amp; MyClass::operator[](int index) {\n return const_cast&lt;int&amp;&gt;(const_cast&lt;MyClass const&amp;&gt;(*this)[index]);\n}\n</code></pre>\n\n<p>This is better. Because if you change the <code>operator[]</code> so that it actually mutates the class it will generate a compiler error and thus prevent you from accidentally getting undefined behavior. </p>\n\n<p>But personally I prefer to add another helper method and thus remove all athe casting:</p>\n\n<pre><code>private:\n// NOTE: This is not a perfect solution for all situations.\n// But it works for 99% of situations and keeps the code clean\n// For the remaining situations switch back to use const cast\n// **BUT** always add never remove constness from an object.\n// Never make public as it is const and gives away an internal reference.\n// Only use via the public API\nint&amp; get(int index) const\n{\n return stuff[index];\n}\n\npublic:\n// Keep the API simple/clean and DRY\n// move all the work to private methods.\nint&amp; operator[](int index) { return get(index);}\nint const&amp; operator[](int index) const { return get(index);}\n</code></pre>\n\n<h3>Answer to comment below:</h3>\n\n<p>I would not use it for const/non-const iterators</p>\n\n<pre><code>const_iterator begin() const {return const_iterator(&lt;X&gt;);}\niterator begin() {return iterator(&lt;X&gt;);}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:46:03.040", "Id": "77178", "Score": "1", "body": "Would you show how that works if get is supposed to return a const or non-const iterator type, instead of a const or non-reference? Perhaps get return a non-const iterator instance, and you define the const iterator type so that it can be explicitly or implicitly created from a non-const iterator instance?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T01:02:09.580", "Id": "77193", "Score": "0", "body": "@ChrisW: Hope the edit helps." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T09:39:44.297", "Id": "77327", "Score": "0", "body": "It seems you have misplaced the `(` in your comment answer. @ChrisW: As the code in question is usually about own code, you can write your own `const_cast` that converts the iterators. If you are dealing with (automatically) const standard contains in C++11 you can use the `erase` function to convert const iterators to mutable iterators in O(1)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T16:33:11.537", "Id": "176097", "Score": "1", "body": "Your `get()` function fails to compile since it is declared `const` (thus `*this` is const) and tries to return a non-const reference to a class data member. The approach seemed good at first, but I think you can't avoid a `const_cast` somewhere if you want to share the code that actually accesses the data member. Perhaps using a template could help you elimnate the duplication and avoid a `const_cast`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:03:40.700", "Id": "44472", "ParentId": "44460", "Score": "16" } } ]
{ "AcceptedAnswerId": "44472", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T18:54:08.900", "Id": "44460", "Score": "19", "Tags": [ "c++", "casting" ], "Title": "Avoiding code duplication and retaining const correctness" }
44460
<p>I am trying to create an AngularJS directive that will give information to the user about the text they are inputting such as the number of characters they must or may enter and so on and so forth.</p> <p>To cut a long story short, I would be very grateful if someone could help me <strong>improve the javascript code for my directives</strong>. As of now the only thing the directives do is <strong>provide the user with the number of characters</strong> in the textarea.</p> <p>Code is hosted on Github and located in <a href="https://github.com/balteo/angularjs-directives/tree/21c8ea4a22e161e53079f9a946b633b8b44cdd7c/app" rel="nofollow">this repository</a>.</p> <p>Here are my <strong>directives</strong>:</p> <pre><code>'use strict'; angular.module('myApp.directives', []) .directive('enhanced', function () { return { restrict: 'A', controller: 'enhancedCtrl', scope: {}, transclude: true, template: '&lt;div ng-transclude&gt;&lt;/div&gt;' }; }) .controller('enhancedCtrl', ['$scope', function ($scope) { var info = function () { var size = 0; return { getSize: function () { return size; }, setSize: function (newSize) { size = newSize; } }; }(); var callback; this.registerSizeChangedCallback = function (callback) { this.callback = callback; }; this.notifyObserver = function () { this.callback(); }; this.setSize = function (size) { info.setSize(size); this.notifyObserver(); }; this.getSize = function () { return info.getSize(); }; }]) .directive('enhancedTextarea', function () { return { restrict: 'A', require: '^enhanced', scope: true, replace: true, template: '&lt;textarea&gt;&lt;/textarea&gt;', link: function ($scope, $element, $attrs, enhancedCtrl) { $scope.$watch($attrs.ngModel, function (newVal) { enhancedCtrl.setSize(newVal.length); }); } }; }) .directive('notice', function () { return { restrict: 'A', require: '^enhanced', replace: true, scope: {}, template: '&lt;div&gt;{{size}} characters&lt;/div&gt;', link: function ($scope, $element, $attrs, enhancedCtrl) { enhancedCtrl.registerSizeChangedCallback(function () { $scope.size = enhancedCtrl.getSize(); }); } }; }); </code></pre> <p>And my <strong>html</strong>:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en" ng-app="myApp"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;My AngularJS App&lt;/title&gt; &lt;link rel="stylesheet" href="css/app.css"/&gt; &lt;/head&gt; &lt;body&gt; &lt;div ng-controller="myCtrl"&gt; &lt;div enhanced&gt; &lt;div enhanced-textarea ng-model="text"&gt;&lt;/div&gt; &lt;h3&gt;{{text}}&lt;/h3&gt; &lt;div notice&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="lib/angular/angular.js"&gt;&lt;/script&gt; &lt;script src="js/directives.js"&gt;&lt;/script&gt; &lt;script src="js/controllers.js"&gt;&lt;/script&gt; &lt;script src="js/app.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Can someone please provide feedback about both:</p> <ul> <li><strong>My usage of the AngularJS framework</strong></li> <li><strong>My usage of Javascript</strong></li> </ul> <p><strong>edit</strong>: I have greatly changed the api of my directive since my original post. Please have a look at the following <a href="https://github.com/balteo/angularjs-directives/tree/3624e0743d83d749c7629e448eba5ceeffd1c44d" rel="nofollow">commit</a>. I am looking for people willing to help me on this "lone-directive" open-source projet... Everyone welcome!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T20:11:27.397", "Id": "77929", "Score": "0", "body": "It looks like a duplicate of one of your own questions. http://codereview.stackexchange.com/questions/42543/simplifying-an-angularjs-directive-that-counts-the-number-of-characters-entered If you have new info to add to the question you could simply edit it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T07:49:06.153", "Id": "83501", "Score": "0", "body": "Does your code here reflect the last change?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T20:51:41.893", "Id": "44467", "Score": "2", "Tags": [ "javascript", "angular.js" ], "Title": "Building a set of AngularJS directives to provide the user information about their input" }
44467
<p>This is my first Haskell application, so any non-name-calling tips will be taken extremely well! It is just a beta reducer:</p> <pre><code>data Term = Var Int | Lam Term | App Term Term | Num Int | Add Term Term deriving (Show) subs :: Int -&gt; Term -&gt; Term -&gt; Term subs depth value (Lam body) = Lam (subs (depth + 1) value body) subs depth value (App abstraction body) = App (subs depth value abstraction) (subs depth value body) subs depth value (Var bind) | bind == depth = inc depth value | otherwise = Var (bind + depth) inc :: Int -&gt; Term -&gt; Term inc depth (Var a) = Var (a + depth) inc depth (App a b) = App (inc depth a) (inc depth b) inc depth (Lam a) = Lam (inc depth a) red :: Term -&gt; Term red (Var a) = Var a red (Lam a) = Lam (red a) red (App (Lam body) value) = red (subs 0 value body) red (App a b) = (App (red a) (red b)) val = red (App (Lam (Lam (Lam (App (Var 2) (Var 1))))) (Lam (Var 77))) main = print val </code></pre> <p>I want to know what I could improve on the style or how I could make the code cleaner. I have mostly problems with indentation, I never know where I can (and should) make a newline without confusing the parser.</p> <p>Comment: making this was ridiculously easier than I thought. The type system actually helped me a lot.</p>
[]
[ { "body": "<p>This looks reasonable and idiomatic to me.</p>\n\n<p>I don't recognise the reduction strategy, though. Specifically, the line</p>\n\n<pre><code>red (App a b) = App (red a) (red b)\n</code></pre>\n\n<p>looks like you're not reducing to a normal form, and you might be reducing, say, one redex in the function and one in the argument. This may be intentional on your part, but if it isn't, maybe take a look <a href=\"http://en.wikipedia.org/w/index.php?title=Lambda_calculus&amp;section=32#Reduction_strategies\" rel=\"nofollow\">here</a> for a brief overview of reduction strategies, or <a href=\"http://www.itu.dk/~sestoft/papers/sestoft-lamreduce.pdf\" rel=\"nofollow\">here</a> for more detail. </p>\n\n<p>I haven't looked at de Bruijn indices in a while, so I wouldn't be able to promise that your implementation is correct. Nothing untoward comes to mind, though. </p>\n\n<p>About the style–and this is really nitpicking–in the <code>subs</code> definition you might use simply <code>a</code> instead of the cumbersome <code>abstraction</code>. And I'd have indented the <code>|</code> one more space. (See? Nitpicking.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:59:42.643", "Id": "77182", "Score": "0", "body": "Oh, of course. It does reach normal form if I apply `red` to `App (red a) (red b)` and to `(subs 0 val body)`, right? Great advices, though, thanks. Replaced the names. Why the extra space there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T23:05:59.433", "Id": "77184", "Score": "2", "body": "Well, what about `App (Var 0) (Var 0)`? This is a normal form, but I don't think your program terminates on it. Try take a look at p. 425 in the second link. (It's an excerpt, it's not actually 425 pages.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T23:27:54.520", "Id": "77188", "Score": "0", "body": "I guess I got it now... is it correct? I'm still reducing the body inside a lambda abstraction, though, the author doesn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T07:47:56.037", "Id": "77216", "Score": "0", "body": "I can't find the difference between this and the original?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:53:57.027", "Id": "44478", "ParentId": "44470", "Score": "3" } }, { "body": "<p>There is a problem with your <code>inc</code> function: it should only modify the variables which are free in the term you are traversing. Here you are going to have a bad time if you are pushing a closed term under a lambda. Let's see an example of such a situation. We start by introducing normalization as the reflexive, transitive closure of red:</p>\n\n<pre><code>closure :: Eq a =&gt; (a -&gt; a) -&gt; a -&gt; a\nclosure f a =\n let fa = f a\n in if fa == a then fa\n else closure f fa\n\nnorm :: Term -&gt; Term\nnorm = closure red\n</code></pre>\n\n<p>Now, let's call <code>tid</code> the identity in your language (i.e. <code>Lam (Var 0)</code>). The term <code>App (Lam tid) tid</code> should reduce to <code>tid</code> but when running</p>\n\n<pre><code>main = print . norm $ App (Lam tid) tid\n</code></pre>\n\n<p>we get: <code>Lam (Var 1)</code></p>\n\n<p>The traditional solution to checking whether a variable is bound or free in this kind of context is to introduce an extra parameter <code>protected</code> which counts the number of <code>Lam</code> abstraction we go under.</p>\n\n<pre><code>inc :: Int -&gt; Term -&gt; Term\ninc depth term = go 0 depth term\n where\n go :: Int -&gt; Int -&gt; Term -&gt; Term\n go protected depth (Var a)\n | a &lt; protected = Var a\n | otherwise = Var (a + depth)\n go protected depth (App a b) = App (go protected depth a) (go protected depth b)\n go protected depth (Lam a) = Lam (go (protected + 1) depth a)\n</code></pre>\n\n<p>Now, we are one step closer to a correct solution. There is still a bit of weakening in the <code>Var</code> case of the <code>subs</code> function. Once this is fixed too (same pattern: add an extra parameter to remember which variables are protected), you'll get a correct implementation of the normalizer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T17:15:59.610", "Id": "44518", "ParentId": "44470", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T21:27:07.110", "Id": "44470", "Score": "6", "Tags": [ "beginner", "haskell", "lambda" ], "Title": "Beta Reducer in Haskell" }
44470
<p>I'm looking for code review, optimizations, best practices.</p> <pre><code>/** * Huffman encoding obeys the huffman algorithm. * It compresses the input sentence and serializes the "huffman code" * and the "tree" used to generate the huffman code * Both the serialized files are intended to be sent to client. * */ public final class Huffman { private Huffman() {}; private static class HuffmanNode { char ch; int frequency; HuffmanNode left; HuffmanNode right; HuffmanNode(char ch, int frequency, HuffmanNode left, HuffmanNode right) { this.ch = ch; this.frequency = frequency; this.left = left; this.right = right; } } private static class HuffManComparator implements Comparator&lt;HuffmanNode&gt; { @Override public int compare(HuffmanNode node1, HuffmanNode node2) { return node1.frequency - node2.frequency; } } /** * Compresses the string using huffman algorithm. * The huffman tree and the huffman code are serialized to disk * * @param sentence The sentence to be serialized * @throws FileNotFoundException If file is not found * @throws IOException If IO exception occurs. */ public static void compress(String sentence) throws FileNotFoundException, IOException { if (sentence == null) { throw new NullPointerException("Input sentence cannot be null."); } if (sentence.length() == 0) { throw new IllegalArgumentException("The string should atleast have 1 character."); } final Map&lt;Character, Integer&gt; charFreq = getCharFrequency(sentence); final HuffmanNode root = buildTree(charFreq); final Map&lt;Character, String&gt; charCode = generateCodes(charFreq.keySet(), root); final String encodedMessage = encodeMessage(charCode, sentence); serializeTree(root); serializeMessage(encodedMessage); } private static Map&lt;Character, Integer&gt; getCharFrequency(String sentence) { final Map&lt;Character, Integer&gt; map = new HashMap&lt;Character, Integer&gt;(); for (int i = 0; i &lt; sentence.length(); i++) { char ch = sentence.charAt(i); if (!map.containsKey(ch)) { map.put(ch, 1); } else { int val = map.get(ch); map.put(ch, ++val); } } return map; } /** * Map&lt;Character, Integer&gt; map * Some implementation of that treeSet is passed as parameter. * @param map */ private static HuffmanNode buildTree(Map&lt;Character, Integer&gt; map) { final Queue&lt;HuffmanNode&gt; nodeQueue = createNodeQueue(map); while (nodeQueue.size() &gt; 1) { final HuffmanNode node1 = nodeQueue.remove(); final HuffmanNode node2 = nodeQueue.remove(); HuffmanNode node = new HuffmanNode('\0', node1.frequency + node2.frequency, node1, node2); nodeQueue.add(node); } // remove it to prevent object leak. return nodeQueue.remove(); } private static Queue&lt;HuffmanNode&gt; createNodeQueue(Map&lt;Character, Integer&gt; map) { final Queue&lt;HuffmanNode&gt; pq = new PriorityQueue&lt;HuffmanNode&gt;(11, new HuffManComparator()); for (Entry&lt;Character, Integer&gt; entry : map.entrySet()) { pq.add(new HuffmanNode(entry.getKey(), entry.getValue(), null, null)); } return pq; } private static Map&lt;Character, String&gt; generateCodes(Set&lt;Character&gt; chars, HuffmanNode node) { final Map&lt;Character, String&gt; map = new HashMap&lt;Character, String&gt;(); doGenerateCode(node, map, ""); return map; } private static void doGenerateCode(HuffmanNode node, Map&lt;Character, String&gt; map, String s) { if (node.left == null &amp;&amp; node.right == null) { map.put(node.ch, s); return; } doGenerateCode(node.left, map, s + '0'); doGenerateCode(node.right, map, s + '1' ); } private static String encodeMessage(Map&lt;Character, String&gt; charCode, String sentence) { final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i &lt; sentence.length(); i++) { stringBuilder.append(charCode.get(sentence.charAt(i))); } return stringBuilder.toString(); } private static void serializeTree(HuffmanNode node) throws FileNotFoundException, IOException { final BitSet bitSet = new BitSet(); try (ObjectOutputStream oosTree = new ObjectOutputStream(new FileOutputStream("/Users/ap/Desktop/tree"))) { try (ObjectOutputStream oosChar = new ObjectOutputStream(new FileOutputStream("/Users/ap/Desktop/char"))) { IntObject o = new IntObject(); preOrder(node, oosChar, bitSet, o); bitSet.set(o.bitPosition, true); // padded to mark end of bit set relevant for deserialization. oosTree.writeObject(bitSet); } } } private static class IntObject { int bitPosition; } /* * Algo: * 1. Access the node * 2. Register the value in bit set. * * * here true and false dont correspond to left branch and right branch. * there, * - true means "a branch originates from leaf" * - false mens "a branch originates from non-left". * * Also since branches originate from some node, the root node must be provided as source * or starting point of initial branches. * * Diagram and how an bit set would look as a result. * (source node) * / \ * true true * / \ * (leaf node) (leaf node) * | | * false false * | | * * So now a bit set looks like [false, true, false, true] * */ private static void preOrder(HuffmanNode node, ObjectOutputStream oosChar, BitSet bitSet, IntObject intObject) throws IOException { if (node.left == null &amp;&amp; node.right == null) { bitSet.set(intObject.bitPosition++, false); // register branch in bitset oosChar.writeChar(node.ch); return; // DONT take the branch. } bitSet.set(intObject.bitPosition++, true); // register branch in bitset preOrder(node.left, oosChar, bitSet, intObject); // take the branch. bitSet.set(intObject.bitPosition++, true); // register branch in bitset preOrder(node.right, oosChar, bitSet, intObject); // take the branch. } private static void serializeMessage(String message) throws IOException { final BitSet bitSet = getBitSet(message); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/ap/Desktop/encodedMessage"))){ oos.writeObject(bitSet); } } private static BitSet getBitSet(String message) { final BitSet bitSet = new BitSet(); int i = 0; for (i = 0; i &lt; message.length(); i++) { if (message.charAt(i) == '0') { bitSet.set(i, false); } else { bitSet.set(i, true); } } bitSet.set(i, true); // dummy bit set to know the length return bitSet; } /** * Retrieves back the original string. * * * @return The original uncompressed string * @throws FileNotFoundException If the file is not found * @throws ClassNotFoundException If class is not found * @throws IOException If IOException occurs */ public static String expand() throws FileNotFoundException, ClassNotFoundException, IOException { final HuffmanNode root = deserializeTree(); return decodeMessage(root); } private static HuffmanNode deserializeTree() throws FileNotFoundException, IOException, ClassNotFoundException { try (ObjectInputStream oisBranch = new ObjectInputStream(new FileInputStream("/Users/ap/Desktop/tree"))) { try (ObjectInputStream oisChar = new ObjectInputStream(new FileInputStream("/Users/ap/Desktop/char"))) { final BitSet bitSet = (BitSet) oisBranch.readObject(); return preOrder(bitSet, oisChar, new IntObject()); } } } /* * Construct a tree from: * input [false, true, false, true, (dummy true to mark the end of bit set)] * The input is constructed from preorder traversal * * Algo: * 1 Create the node. * 2. Read what is registered in bitset, and decide if created node is supposed to be a leaf or non-leaf * */ private static HuffmanNode preOrder(BitSet bitSet, ObjectInputStream oisChar, IntObject o) throws IOException { // created the node before reading whats registered. final HuffmanNode node = new HuffmanNode('\0', 0, null, null); // reading whats registered and determining if created node is the leaf or non-leaf. if (!bitSet.get(o.bitPosition)) { o.bitPosition++; // feed the next position to the next stack frame by doing computation before preOrder is called. node.ch = oisChar.readChar(); return node; } o.bitPosition = o.bitPosition + 1; // feed the next position to the next stack frame by doing computation before preOrder is called. node.left = preOrder(bitSet, oisChar, o); o.bitPosition = o.bitPosition + 1; // feed the next position to the next stack frame by doing computation before preOrder is called. node.right = preOrder(bitSet, oisChar, o); return node; } private static String decodeMessage(HuffmanNode node) throws FileNotFoundException, IOException, ClassNotFoundException { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/ameya.patil/Desktop/encodedMessage"))) { final BitSet bitSet = (BitSet) ois.readObject(); final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i &lt; (bitSet.length() - 1);) { HuffmanNode temp = node; // since huffman code generates full binary tree, temp.right is certainly null if temp.left is null. while (temp.left != null) { if (!bitSet.get(i)) { temp = temp.left; } else { temp = temp.right; } i = i + 1; } stringBuilder.append(temp.ch); } return stringBuilder.toString(); } } public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { // even number of characters Huffman.compress("some"); Assert.assertEquals("some", Huffman.expand()); // odd number of characters Huffman.compress("someday"); Assert.assertEquals("someday", Huffman.expand()); // repeating even number of characters + space + non-ascii Huffman.compress("some some#"); Assert.assertEquals("some some#", Huffman.expand()); // odd number of characters + space + non-ascii Huffman.compress("someday someday&amp;"); Assert.assertEquals("someday someday&amp;", Huffman.expand()); } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Currently both <code>compress()</code> and <code>expand()</code> are static methods in the class which limits its usability. Only one thread can compress/expand only one string. It could have a better API which stores the encoded in memory and allows creating multiple encoded data at the same time.</p></li>\n<li><p>The code contains a lot of hard-coded paths, like <code>/Users/ap/Desktop/tree</code>. The tests fail with <code>FileNotFoundException</code> because on my system the class could not create these files/directories due to file system permission settings. If they are temporary files they should be created in the <a href=\"https://stackoverflow.com/q/2429612/843804\"><code>java.io.tmpdir</code> directory</a>. If not, they should be set by the clients of the class.</p></li>\n<li><p>It's great that you have self-checking test! They are usually in a <code>Test</code> file (<code>HuffmanTest</code>, in this case) run by JUnit. They are also in a separated source folder which enables to not package <code>junit.jar</code> (and other test dependencies) with production code.</p>\n\n<pre><code>import static org.junit.Assert.assertEquals;\n\nimport org.junit.Test;\n\npublic class HuffmanTest {\n\n @Test\n public void testHuffman() throws Exception {\n Huffman.compress(\"some\");\n assertEquals(\"some\", Huffman.expand());\n }\n\n @Test\n public void testOddNumberOfCharacters() throws Exception {\n // odd number of characters\n Huffman.compress(\"someday\");\n assertEquals(\"someday\", Huffman.expand());\n }\n\n @Test\n public void testRepeatingEvenNumberOfCharactersAndSpaceAndNonAsciiCharacters() throws Exception {\n Huffman.compress(\"some some#\");\n assertEquals(\"some some#\", Huffman.expand());\n\n }\n\n @Test\n public void testOddNumberOfCharactersAndSpaceAndNonAscii() throws Exception {\n Huffman.compress(\"someday someday&amp;\");\n assertEquals(\"someday someday&amp;\", Huffman.expand());\n }\n}\n</code></pre>\n\n<p>A few other modifications:</p>\n\n<ul>\n<li>static import of <code>assertEquals</code> for less clutter,</li>\n<li>separate test methods for <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow noreferrer\">defect localization</a> (in the original code if the first assert throws an exception you won't know that the others are failed or not),</li>\n<li>comments turned to test method names (see <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Don’t Use a Comment When You Can Use a Function or a Variable</em>, p67),</li>\n<li>changed the three exceptions in the signature to only <code>throws Exception</code>. JUnit will catch all exceptions (as well as JRE, you can do the same with the <code>main</code> method).</li>\n</ul></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T23:37:08.193", "Id": "44479", "ParentId": "44473", "Score": "5" } }, { "body": "<p><strong>Great Start</strong></p>\n\n<ul>\n<li>Clear code</li>\n<li>Short methods</li>\n<li>JavaDoc</li>\n<li>Tests (though they need reorganizing as palacsint noted)</li>\n</ul>\n\n<p><strong>Encapsulate</strong></p>\n\n<p>Separate and encapsulate some of the logic into custom classes rather than passing around collections directly. Doing so improves testability and reusability. One prime example is the character frequency map which could easily be reused in many other programs.</p>\n\n<p>Here's a simple implementation that provides only what's necessary for this program, but it could certainly benefit from methods such as <code>size()</code>, <code>getCount(Character c)</code>, etc. I also haven't bothered wrapping the exposed map/set in unmodifiable collections which would be advisable (though see below for another option).</p>\n\n<pre><code>/**\n * Keeps a running count of how many times each unique character is seen.\n */\npublic class CharacterCounter\n{\n private final HashMap&lt;Character, Integer&gt; counts = new HashMap&lt;&gt;();\n\n /**\n * Increments the count of the given character,\n * setting it to one on first appearance.\n *\n * @param c the character to count\n */\n public void increment(Character c) {\n Integer freq = counts.get(c);\n if (freq == null) {\n counts.put(c, 1);\n } else {\n counts.put(c, freq + 1);\n }\n }\n\n /**\n * Increments the count of each character in the given text.\n *\n * @param text contains the characters to count\n */\n public void increment(String text) {\n for (char c : text) {\n increment(c);\n }\n }\n\n /**\n * Returns the set of characters seen.\n *\n * @return set containing each character seen while counting\n */\n public Set&lt;Character&gt; getCharacters() {\n return counts.keySet();\n }\n\n /**\n * Returns the set of characters seen along with their counts.\n *\n * @return set containing each character seen while counting and its count\n */\n public Set&lt;Map.Entry&lt;Character, Integer&gt;&gt; getCharacterCounts() {\n return counts.entrySet();\n }\n}\n</code></pre>\n\n<p>To avoid exposing the underlying map you could go further by using a closure (Java 8) or anonymous visitor class:</p>\n\n<pre><code>public class CharacterCounter\n{\n ...\n public interface Visitor {\n void visit(Character c, Integer count);\n }\n\n /**\n * Passes each character and its count to the given visitor.\n *\n * @param visitor receives characters and counts in an undefined order\n */\n public void apply(Visitor visitor) {\n for (Map.Entry&lt;Character, Integer&gt; entry : counts.entrySet()) {\n visitor.visit(entry.getKey(), entry.getValue());\n }\n }\n}\n\nprivate static Queue&lt;HuffmanNode&gt; createNodeQueue(CharacterCounter counter) {\n final Queue&lt;HuffmanNode&gt; pq = new PriorityQueue&lt;&gt;(11, new HuffManComparator());\n counter.apply(new CharacterCounter.Visitor() {\n public void visit(Character c, Integer count) {\n pq.add(new HuffmanNode(c, count, null, null));\n }\n });\n return pq;\n}\n</code></pre>\n\n<p>I would perform the same encapsulation with <code>HuffmanTree</code> building and managing the nodes from the <code>CharacterCounter</code>.</p>\n\n<p><strong>Miscellaneous</strong></p>\n\n<ul>\n<li><p>Provide a two-argument constructor for <code>HuffmanNode</code> that defaults the other parameters to <code>null</code>.</p></li>\n<li><p>Implement <code>Comparable&lt;HuffmanNode&gt;</code> directly for natural ordering instead of supplying a separate <code>Comparator</code> to the priority queue.</p></li>\n<li><p>Be careful not to include too much code detail in the comments. As the code changes, the comments become incorrect. Case in point:</p>\n\n<pre><code>/** \n * Map&lt;Character, Integer&gt; map\n * Some implementation of that treeSet is passed as parameter.\n * @param map\n */\nprivate static HuffmanNode buildTree(Map&lt;Character, Integer&gt; map) {\n</code></pre>\n\n<p>The first line is unnecessary since it's in the method signature, and the second line mentions the parameter should be a <code>TreeSet</code> which is not correct.</p></li>\n<li><p>Thanks to the garbage collector this is totally unnecessary:</p>\n\n<pre><code>// remove it to prevent object leak.\nreturn nodeQueue.remove();\n</code></pre>\n\n<p>Since <code>nodeQueue</code> is local and never exposed externally, it will be collected along with its reference to the root node.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T00:58:43.850", "Id": "44483", "ParentId": "44473", "Score": "8" } }, { "body": "<h2>Reading the code you assume that:</h2>\n\n<ol>\n<li>Data is always serialised to the same location on disk.</li>\n<li>Data is always decoded from the same location on disk.</li>\n<li>Your source alphabet can only consist of UTF-16 codepoints.</li>\n</ol>\n\n<p>Number 1 and 2 are bad in my humble opinion. You might want to do something else with the compressed data at some point, like encode it in base64 and transmit to a webpage in text mode. Number 3 is so-so depending on how you use the Huffman coder.</p>\n\n<h2>I disagree with the accepted answer that the code is clear.</h2>\n\n<p>There is a limit when small functions become too many and I believe you have crossed that line. It is difficult to follow the algorithm in order to verify correct implementation (I understand Huffman it's just difficult to follow with jumping across all functions).</p>\n\n<h2>Test that your compressed data is smaller than the source data</h2>\n\n<p>Your tests should really be unit tests as palacsint says in their answer. \nAlso the probably most important test that you should do is to see that the compressed data is smaller than the original data. </p>\n\n<p>Specifically, any correctly implemented Huffman coder should perform very closely to <strong><a href=\"http://en.wikipedia.org/wiki/Shannon%27s_source_coding_theorem\" rel=\"nofollow\" title=\"Shannon&#39;s Source Coding Theorem\">Shannon's Source Coding Theorem</a></strong>. For sufficiently many samples you should be within 1% of the limit in that link.</p>\n\n<h2>Other comments</h2>\n\n<p>You are generating your prefix codes as strings and by doing string addition. I find this kind of code difficult to follow as you are covering up the fact that you are doing bit arithmetic. </p>\n\n<p>I would use a natural ordering for the nodes instead of implementing a comparator class.</p>\n\n<p>I do not see any mention of a stop symbol which prevents accidental decoding of junk when your output bitstream is not an even multiple of 8 bits.</p>\n\n<p>And this: </p>\n\n<pre><code> try (ObjectOutputStream oosTree = new ObjectOutputStream(new FileOutputStream(\"/Users/ap/Desktop/tree\"))) {\n try (ObjectOutputStream oosChar = new ObjectOutputStream(new FileOutputStream(\"/Users/ap/Desktop/char\"))) {\n</code></pre>\n\n<p>I would do it like this to avoid the nesting:</p>\n\n<pre><code> try (ObjectOutputStream oosTree = \n new ObjectOutputStream(new FileOutputStream(\"/Users/ap/Desktop/tree\"));\n ObjectOutputStream oosChar = \n new ObjectOutputStream(new FileOutputStream(\"/Users/ap/Desktop/char\"))) {\n</code></pre>\n\n<p>The <code>IntObject</code> class seems like a work around for a problem with passing integers as arguments, I would structure my code so that this is not needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T15:59:05.967", "Id": "77250", "Score": "0", "body": "Inspired by the post, I updated the Huffman code linked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-11T13:06:42.737", "Id": "169682", "Score": "0", "body": "Your links are not working." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T14:14:35.280", "Id": "44508", "ParentId": "44473", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:07:16.230", "Id": "44473", "Score": "12", "Tags": [ "java", "algorithm", "compression" ], "Title": "Huffman code implementation" }
44473
<p>I spent the past hour trying to optimize a block of code I wrote that renders a simple coloured line directly to a backbuffer.</p> <p>I've compared it with one of the <code>DrawLine</code> method implementations of the WriteableBitmapEx project, and found that my algorithm isn't quite as fast (unless I use <code>Parallel</code>).</p> <pre><code>public static unsafe void DrawLineVector(this IntPtr target, Line2D line, int colour, int width, int height) { var buf = (int*) target; var start = line.Start; var lineVector = line.Stop - start; var steps = (int)lineVector.Magnitude(); var uX = lineVector.X / steps; var uY = lineVector.Y / steps; var col = colour; Parallel.For(0, steps, i =&gt; //for (var i = 0; i != steps; ++i) { var x = start.X + uX * i; var y = start.Y + uY * i; if (x &gt; -1 &amp;&amp; y &gt; -1 &amp;&amp; x &lt; width &amp;&amp; y &lt; height) buf[(int)y * width + (int)x] = col; //x += uX; //y += uY; } ); } </code></pre> <p>Note, the <code>Line2D</code> object is basically just a container for two <code>VectorD</code> objects (which are my own implementation of vectors).</p> <p>Running this as it is currently, will get me, on my machine, roughly 300MPixels per second, while the "default" <code>DrawLine</code> method from <code>WriteableBitmapEx</code> gets me around 170MPixels per second. If I use the 'serial' version of this (i.e. not use <code>Parallel</code>), I get around 100MPixels per second.</p> <p>Is there any way I can optimize this further?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-17T01:39:58.493", "Id": "417075", "Score": "0", "body": "You should probably check out the bresenham line drawing algorithm, it’s a classic in computer graphics and unless you want to do anti aliasing I think it’s still the go to for line rasterization https://en.m.wikipedia.org/wiki/Bresenham's_line_algorithm" } ]
[ { "body": "<p>I'm curious about why the code starts with <code>if (x &gt; -1</code></p>\n\n<p>Doesn't that mean you need to scan values of i which end up doing nothing?</p>\n\n<p>Perhaps you could skip those stages; something like:</p>\n\n<pre><code>var initial_i = 0;\nif (start.X &lt; 0)\n // need a bigger i to make it visible\n initial_i = -start.X / uX;\n</code></pre>\n\n<p>The above needs to be changed in uX can be negative, and beware floating point and divide by zero.</p>\n\n<p>Do something similar (i.e. increase <code>initial_i</code>) to ensure that <code>y</code> is visible.</p>\n\n<p>Then do something similar to ensure that i is not too large.</p>\n\n<p>Then you ought to be able to have code like,</p>\n\n<pre><code>Parallel.For(initial_i, ending_i, i =&gt;\n//for (var i = 0; i != steps; ++i)\n{\n var x = start.X + uX * i;\n var y = start.Y + uY * i;\n // if (x &gt; -1 &amp;&amp; y &gt; -1 &amp;&amp; x &lt; width &amp;&amp; y &lt; height)\n buf[(int)y * width + (int)x] = col;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:53:45.143", "Id": "77179", "Score": "0", "body": "The problem with that would be to take in to account all the four 'sides' of the backbuffer, meaning I'd have to check both negative x, negative y, and positive x and positive y. Since a line can be both from -x to +x, and from +x to -x (And the same for y). But thanks for the suggestion!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:58:46.587", "Id": "77181", "Score": "0", "body": "A 'branch' i.e. a conditional jump is slow because of [CPU branch prediction](http://en.wikipedia.org/wiki/Branch_predictor), so I was hoping that removing all those `if` expressions would make it faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T23:04:36.237", "Id": "77183", "Score": "0", "body": "Yeah, I figured - I'll try tinkering with it a bit, see if I can't get that \"iffy\" branch out of the loop. Would require more complexity before the loop though, I think... Unless I can figure out a way to do the 'offsetting' correctly, with a bit of maths. The other thing I'd have to take in to consideration in that case, would be lines that don't ever intersect with the backbuffer at all. I'd initially done some nasty intersection checking in a method that uses this one, but decided not to do that here, yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T23:13:22.710", "Id": "77185", "Score": "0", "body": "Minor update: I've tried just removing the branch from the loop, and the improvement is marginal at best. It would of course be great to not step through the points outside the backbuffer, but the branch itself doesn't appear to be very expensive." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T22:40:31.753", "Id": "44476", "ParentId": "44474", "Score": "1" } }, { "body": "<p>Because you're comparing your performance with that of the WriteableBitmapEx project, you might like to compare your algorithm with theirs, which is here on github: <a href=\"http://writeablebitmapex.codeplex.com/SourceControl/latest#trunk/Source/WriteableBitmapEx/WriteableBitmapShapeExtensions.cs\" rel=\"noreferrer\">WriteableBitmapShapeExtensions.cs</a></p>\n\n<p>You say your performance isn't much slower than theirs (100 versus 170 MPixels/second).</p>\n\n<p>A difference between yours and there's might be that yours is using <code>float</code> or <code>double</code> arithmetic, whereas theirs is using <code>int</code> arithmetic.</p>\n\n<p>Their code is much longer (more lines of code) than yours, but their inner loop is something like this:</p>\n\n<pre><code> for (int x = x1; x &lt;= x2; ++x)\n {\n pixels[index] = color;\n ys += incy;\n y = ys &gt;&gt; PRECISION_SHIFT;\n if (y != previousY)\n {\n previousY = y;\n index += k;\n }\n else\n {\n ++index;\n }\n }\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>Only <code>int</code> (not <code>double</code>)</li>\n<li>Few branches</li>\n<li>Every write is to a significant pixels (in your algorithm if you write a line at 45 degrees then you do 1.414 writes per pixels).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T09:40:36.243", "Id": "77220", "Score": "0", "body": "Yeah, I did think about that. I'm not sure if there's any 'smart' way of avoiding the overdraw of my algorithm, at least not right now. - Thanks again for your time, and your analysis :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T10:50:24.190", "Id": "77222", "Score": "1", "body": "Instead of `var steps = (int)lineVector.Magnitude();` would it work to do `var steps = (int)Math.Max(lineVector.X,lineVector.Y;`? That would be fewer steps (if it's a slanted line) but still every pixel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:15:02.023", "Id": "77224", "Score": "0", "body": "The line wouldn't be long enough if it is angled. If we assume we have a line from `0,0 to 5,5` then the actual length would need to be about 7.07 pixels to cover the distance (Hypothenuse), while the \"Max\" approach would only draw 5 pixels." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:26:13.193", "Id": "77226", "Score": "0", "body": "@MelanieSchmidt But IMO you should only want to draw 5 pixels, i.e. `[0,0]`, `[1,1]`, etc., through `[5,5]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:40:36.063", "Id": "77227", "Score": "0", "body": "Right, didn't realize that. One modification though. `(int)Math.Max(Math.Abs(lineVector.X), Math.Abs(lineVector.Y))` - Since x and y can be negative." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:41:41.510", "Id": "77228", "Score": "0", "body": "@MelanieSchmidt Either uX or uY should be an integer of value `1` (or perhaps `-1`) and the other should be smaller (less than 1)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T01:56:34.367", "Id": "44486", "ParentId": "44474", "Score": "5" } } ]
{ "AcceptedAnswerId": "44486", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-15T22:17:54.293", "Id": "44474", "Score": "7", "Tags": [ "c#", "performance" ], "Title": "Line rendering optimization" }
44474
<p>Given an array start from the first element and reach the last by jumping. The jump length can be at most the value at the current position in the array. Optimum result is when u reach the goal in minimum number of jumps. </p> <p>For example: </p> <blockquote> <p>Given array A = {2,3,1,1,4} <br/> possible ways to reach the end (index list) <br/> i) 0,2,3,4 (jump 2 to index 2, then jump 1 to index 3 then 1 to index 4) <br/> ii) 0,1,4 (jump 1 to index 1, then jump 3 to index 4) </p> </blockquote> <p>Since second solution has only 2 jumps it is the optimum result.</p> <p>A lot of input has been derived from previous review <a href="https://codereview.stackexchange.com/questions/38142/jump-game-in-java">here</a>.</p> <pre><code>public final class JumpGame { private JumpGame() {} /** * Returns the shortest jump path from the source to destination * * @param jump The jump array * @return Returns one of the shortest paths to the destination. */ public static List&lt;Integer&gt; getShortestJumps(int[] jump) { final List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(); list.add(0); for (int i = 0; i &lt; jump.length - 1; ) { int iSteps = Math.min(jump.length - 1, i + jump[i]); // iSteps is all the consecutive steps reachable by jumping from i. int maxStep = Integer.MIN_VALUE; // max step is one of the step in iSteps, which has the max potential to take us forward. /* trying each step of iSteps */ for (int j = i + 1; j &lt;= iSteps; j++) { /* being greedy and picking up the best step */ if (maxStep &lt; jump[j]) { maxStep = j; } } list.add(maxStep); i = maxStep; // jump to the maxStep. } return list; } public static void main(String[] args) { int[] a1 = {2,3,1,1,4}; List&lt;Integer&gt; expected = new ArrayList&lt;Integer&gt;(); expected.add(0); expected.add(1); expected.add(4); Assert.assertEquals(expected, getShortestJumps (a1)); int[] a2 = {3, 1, 10, 1, 4}; expected = new ArrayList&lt;Integer&gt;(); expected.add(0); expected.add(2); expected.add(4); Assert.assertEquals(expected, getShortestJumps (a2)); } } </code></pre>
[]
[ { "body": "<h2>Code-Style</h2>\n<p>For the most part, this is good:</p>\n<ul>\n<li>return types are good.</li>\n<li>Collections are well typed</li>\n<li>method names are good</li>\n<li>apart from <code>list</code>, <code>a1</code>, and <code>a2</code>, variable names are good</li>\n</ul>\n<p>The <code>list</code> is a bad name for a List. The fact that it is a list is obvious... but, what is the list...? I prefer <code>result</code> to <code>list</code>.</p>\n<p><code>a1</code> and <code>a2</code> are not bad, but they are not good either. They are just 'OK'.</p>\n<h2>Algorithm</h2>\n<p>I have worked the code through, and figure there is a plane-jane <em>O(n)</em> solution to the problem. Your algorithm is something larger than <em>O(n)</em>, It is closer to <em>O(n * m)</em> where <code>m</code> is the longest jump.</p>\n<p>The alternate algorithm I cam up with sets up a 'range' for the next jump.... It seaches all the values from the current cursor to the current range, and it looks for the jump within that range that would extend the range the furthest.</p>\n<p>The method looks like:</p>\n<pre><code>public static List&lt;Integer&gt; getShortestJumps(int[] jump) {\n final List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();\n if (jump.length == 0) {\n return list;\n }\n int cursor = 0;\n int best = 0;\n int range = 0;\n int remaining = 1;\n while (cursor + 1 &lt; jump.length) {\n if (cursor + jump[cursor] &gt; range) {\n // jumping from here would extend us further than other alternatives so far\n range = cursor + jump[cursor];\n best = cursor;\n if (range &gt;= (jump.length - 1)) {\n // in fact, this jump would take us to the last member, we have a solution\n list.add(best);\n break;\n }\n }\n if (--remaining == 0) {\n // got to the end of our previous jump, move ahead by our best.\n list.add(best);\n remaining = range - cursor;\n }\n \n cursor++;\n }\n // always add the last member of the array\n list.add(jump.length - 1);\n return list;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T03:58:51.973", "Id": "44491", "ParentId": "44482", "Score": "7" } }, { "body": "<p>Your unit tests could be less verbose, using <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)\" rel=\"nofollow\"><code>java.util.Arrays.asList(...)</code></a>.</p>\n\n<pre><code>int[] a1 = {2,3,1,1,4};\nAssert.assertEquals(Arrays.asList(0, 1, 4), getShortestJumps(a1));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:44:54.157", "Id": "44504", "ParentId": "44482", "Score": "3" } } ]
{ "AcceptedAnswerId": "44491", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T00:52:29.883", "Id": "44482", "Score": "7", "Tags": [ "java", "algorithm" ], "Title": "Jump game to find minimum hops from source to destination" }
44482
<p>I'm primarily looking for ways to increase the performance of my code. </p> <p>It is used to transform mesh data from <a href="http://www.blender.org/documentation/blender_python_api_2_69_10/bpy.types.Mesh.html">blender</a> into a format I can use and then save it to a file. </p> <p>First it collects the colors of each vertex with an index to reference them, then for each of the vertices it writes its coordinates followed by its average color. The last part decides if each polygon is a triangle or a rectangle and writes the indices of each of its vertices, while converting rectangles to 2 triangles.</p> <pre><code>import bpy mesh = "mesh" filepath = "filepath" out = open(filepath, 'w') m = bpy.data.meshes[mesh] colData = m.vertex_colors["Col"].data colors = [] index = [] for pol in m.polygons: count = 0 for li in pol.loop_indices: for rgb in colData[li].color: colors += [rgb] index += [pol.vertices[count]] count += 1 for ver in m.vertices: indices = [i for i, x in enumerate(index) if x == ver.index] for f in ver.co: out.write(str(f)+' ') for f in range(3): c = 0 for i in indices: c += colors[i*3+f] c = c/len(indices) out.write(str(c)+' ') out.write('\n') out.write('\n') for pol in m.polygons: if len(pol.vertices)==3: for i in pol.vertices: out.write(str(i)+' ') else: for i in pol.vertices[:3]: out.write(str(i)+' ') for i in pol.vertices[2:]: out.write(str(i)+' ') out.write(str(pol.vertices[0])+' ') out.write('\n') out.write('\n') out.close() </code></pre>
[]
[ { "body": "<p>You could try to replace some loops with string formatting, for example change this</p>\n\n<pre><code>for i in pol.vertices[:3]:\n out.write(str(i)+' ')\nfor i in pol.vertices[2:]:\n out.write(str(i)+' ')\nout.write(str(pol.vertices[0])+' ') \n</code></pre>\n\n<p>to this</p>\n\n<pre><code>out.write('{0} {1} {2} {2} {3} {0} '.format(*pol.vertices))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T14:59:18.087", "Id": "44510", "ParentId": "44484", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T01:10:17.637", "Id": "44484", "Score": "5", "Tags": [ "python", "performance" ], "Title": "Formatting and writing data" }
44484
<p>This question is a follow up to these questions:</p> <ol> <li><p><a href="https://codereview.stackexchange.com/q/36482/18427">RPSLS Game in C#</a></p></li> <li><p><a href="https://codereview.stackexchange.com/q/43965/18427">Ensuring user input is an integer in a range</a></p></li> <li><p><a href="https://codereview.stackexchange.com/q/44034/18427">RPSLS is less messy now, but is it clean?</a></p></li> </ol> <p>Right now I have a couple of ideas in the think tank about how I want to code what I like to call "killMessage" the whole process seems a little intimidating at the moment, in other words I haven't decided exactly how it is going to work out yet.</p> <p>There is plenty of code that I borrowed/altered/stole from other answers, but I think we all assumed that was going to happen a little bit, and I think that I understand most of what I included, so I still learned something from it and didn't just copy pasta in the code.</p> <p>I really like the idea of a Gesture class so that I can actually give the Gesture abilities.</p> <pre><code>/// &lt;summary&gt; /// Thanks to /// https://codereview.stackexchange.com/users/38054/benvlodgi /// https://codereview.stackexchange.com/users/4318/eric-lippert /// https://codereview.stackexchange.com/users/23788/mats-mug /// https://codereview.stackexchange.com/users/30346/chriswue /// &lt;/summary&gt; namespace RPSLSGame { class MainClass { public static void Main (string[] args) { /* Here are your rules: "Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors, scissors decapitate lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock. And as it always has, rock crushes scissors." -- Dr. Sheldon Cooper */ int win = 0; int lose = 0; int tie = 0; IList&lt;Gesture&gt; gameGestures = GetGestures(); do{ Console.WriteLine("Please choose your Gesture "); PrintMenu(gameGestures); var playerGesture = gameGestures[PromptForNumber("Please choose your gesture",1,gameGestures.Count)-1]; var computerPlay = GetRandomOption(gameGestures); Console.WriteLine ("Computer: " + computerPlay); Console.WriteLine ("your Gesture: " + playerGesture); if (playerGesture.Equals(computerPlay)){ tie++; }else if(playerGesture.Defeats(computerPlay)){ win++; }else{ lose++; } Console.WriteLine ("Your Score is (W:L:T:) : {0}:{1}:{2}", win, lose, tie); if (Choice("Would you like to reset your score?")) { win = 0; lose=0; tie=0; } }while (Choice("Would you like to play again? Y/N")); Console.WriteLine("Goodbye"); Console.ReadLine (); } public static void DecideWinner () { //TODO: Create Method for Deciding the Winner. //I still need to move the decision logic here. //but it won't be as big as I thought it was going to be } static int PromptForNumber (string prompt, int lower, int upper) { int? pick = null; while (pick == null) { Console.WriteLine(prompt); pick = Console.ReadLine().BoundedParse (lower, upper); } return pick.Value; } public static void PrintMenu (List&lt;string&gt; List) { for (int i=0; i&lt;List.Count; i++) { Console.WriteLine ((i+1) + ": " + List[i]); } } public static void PrintMenu (IList&lt;Gesture&gt; GestureList) { for (int i=0; i &lt; GestureList.Count; i++) { Console.WriteLine ((i + 1) + ": " + GestureList [i]); } } public static string GetRandomOption (List&lt;string&gt; options) { Random rand = new Random(); return options[rand.Next(0,options.Count)]; } public static Gesture GetRandomOption (IList&lt;Gesture&gt; options) { Random rand = new Random(); return options[rand.Next (0,options.Count)]; } public static Boolean Choice (string prompt) { while(true) { Console.WriteLine (prompt); switch (Console.ReadKey (true).Key) { case ConsoleKey.Y: { Console.Write ("Y\n"); return true; } case ConsoleKey.N: { Console.Write ("N\n"); return false; } } } } /// &lt;summary&gt; /// This is some code that I borrowed from /// https://codereview.stackexchange.com/users/14749/peter-kiss /// from an answer that he gave to one of my Questions, the answer has since been deleted. /// &lt;/summary&gt; static IList&lt;Gesture&gt; GetGestures() { var spock = new Gesture("Spock"); var lizard = new Gesture("Lizard"); var paper = new Gesture("Paper"); var rock = new Gesture("Rock"); var scissors = new Gesture("Scissors"); spock.AddDefeats(new[] { scissors, rock }); lizard.AddDefeats(new[] { paper, spock }); paper.AddDefeats(new[] { rock, spock }); rock.AddDefeats(new[] { lizard, scissors }); scissors.AddDefeats(new[] { paper, lizard }); var gestures = new List&lt;Gesture&gt; {rock, paper, scissors, lizard, spock}; gestures.ForEach(x =&gt; x.Seal()); return gestures; } } public class Gesture { public override string ToString() { return Name; } private HashSet&lt;Gesture&gt; _defeats = new HashSet&lt;Gesture&gt;(); private bool _isSealed; public string Name { get; private set; } public Gesture(string name) { if (name == null) throw new ArgumentNullException("name"); Name = name; } public void Seal() { _isSealed = true; } public void AddDefeats(IEnumerable&lt;Gesture&gt; defeats) { if (_isSealed) { throw new Exception("Gesture is sealed"); } foreach (var gesture in defeats) { _defeats.Add(gesture); } } //public void AddKillMessage(Tuple&lt;Gesture,Gesture,string&gt; public void AddKillMessage (Dictionary&lt;Dictionary&lt;Gesture,Gesture&gt;,string&gt; killMessage) { if (_isSealed) { throw new Exception ("Gesture is Sealed"); } } protected bool Equals(Gesture other) { return string.Equals(Name, other.Name); } 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((Gesture) obj); } public override int GetHashCode() { return Name.GetHashCode(); } public bool Defeats(Gesture gesture) { return _defeats.Any(x =&gt; x.Equals(gesture)); } } } static class Extensions { public static int? BoundedParse (this string str, int lower, int upper) { int result; bool success; success = int.TryParse (str, out result); if (!(lower &lt;= result &amp;&amp; result &lt;= upper) || (!success) || (str == null)){ return null; } return result; } } </code></pre> <p>I hope that repeat reviewers find that I have taken their advice to heart and hopefully I haven't slaughtered their code while making it my own.</p> <p>There are several overloaded methods in the code that I left there from previous iterations.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T21:17:19.127", "Id": "77287", "Score": "0", "body": "I did fail to mention that I gave in to peer pressure and used a do while loop for my main loop. Any feed back on that is also welcome, please also let me know what you think I am doing right as well." } ]
[ { "body": "<p>I'm going to leave a broader review to other answers, and only focus on a single line of code:</p>\n\n<blockquote>\n<pre><code>throw new Exception(\"Gesture is sealed\");\n</code></pre>\n</blockquote>\n\n<p>Don't do that.</p>\n\n<p>There are really two alternatives to throwing exceptions.</p>\n\n<p>One is to throw an existing exception, <strong>derived</strong> from <code>System.Exception</code>. This is trickier than it sounds, because you need to pick your exception carefully - you want to throw a <em>meaningful</em> exception.</p>\n\n<p>In this case an <code>InvalidOperationException</code> seems in line with the <a href=\"http://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\"><em>Principle of Least Astonishment</em></a>:</p>\n\n<blockquote>\n <h1>InvalidOperationException Class</h1>\n \n <p>The exception that is thrown when a method call is invalid for the object's current state.\n <sub><a href=\"http://msdn.microsoft.com/en-us/library/system.invalidoperationexception(v=vs.110).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.invalidoperationexception(v=vs.110).aspx</a></sub></p>\n</blockquote>\n\n<p>There are a few exception subclasses like this one (and <code>ArgumentException</code> and its derivatives), that are very often the most meaningful and <em>written-for-that-purpose</em> exception to use.</p>\n\n<hr>\n\n<p>Another way would be to define your own. That's easier that it sounds, you just derive a new class from <code>System.Exception</code>:</p>\n\n<pre><code>public class GestureSealedException : Exception\n{\n public GestureSealedException()\n : base(\"Gesture is sealed.\") { }\n}\n</code></pre>\n\n<p>And now you can <code>throw</code> and <code>catch</code> a <code>GestureSealedException</code>.</p>\n\n<hr>\n\n<h3>That said...</h3>\n\n<blockquote>\n <p><em>Don't throw <code>System.Exception</code>.</em></p>\n</blockquote>\n\n<p>In my quick research for why that class wasn't <code>abstract</code> in the first place if it wasn't intended to be instanciated and thrown, I found an interesting <a href=\"https://softwareengineering.stackexchange.com/questions/119668/abstract-exception-super-type\">discussion on Programmers.SE</a>. Emphasis mine: </p>\n\n<blockquote>\n <p><em>when coding <strong>small demo apps</strong> or <strong>proof-of-concepts</strong>, I don't want to start designing 10 different exception sub-classes, or <strong>spending time</strong> trying to decide which is the \"best\" exception class for the situation. I'd rather just throw Exception and pass a string that explains the details. When it's <strong>throw-away code</strong>, I don't care about these things [...]</em></p>\n \n <p><sub><a href=\"https://softwareengineering.stackexchange.com/a/119683/68834\">https://softwareengineering.stackexchange.com/a/119683/68834</a></sub></p>\n</blockquote>\n\n<p>The flipside of this out-of-context quote, is that when <em>it is</em> quality code, you <em>do</em> care about these things.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T04:58:21.843", "Id": "77205", "Score": "0", "body": "I like this answer, 1. I was using someone else's code there and should have changed that exception. 2. I have created exceptions before, but I need the practice. 3. not sure why I would use an exception there. I need to look into it more this coming week probably before(or while) I work on the KillMessages" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:26:05.907", "Id": "78171", "Score": "1", "body": "@Malachi FYI, I've moved this answer [here](http://codereview.stackexchange.com/a/44880/23788) as a canonical answer to *\"Throwing System.Exception\"*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T18:44:17.663", "Id": "78174", "Score": "0", "body": "sounds good to me." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T03:38:09.883", "Id": "44490", "ParentId": "44487", "Score": "11" } }, { "body": "<ol>\n<li><p>In the scope of this program, there is no benefit to using a <code>Gesture</code> <code>class</code> vs using an <code>enum</code> with some extension methods. I will draw upon my latest version of an <a href=\"https://codereview.stackexchange.com/questions/44577/rpslsmb-oop-version-2\">OOP RPSLS</a> for some examples.</p>\n\n<p>Using a <code>Gesture</code> <code>enum</code> </p>\n\n<pre><code>enum Gesture\n{\n Rock,\n Paper,\n Scissors,\n Lizard,\n Spock\n}\n</code></pre>\n\n<p>You can easily add an extension method to give you the <code>Defeats</code> method you implemented in your <code>Gesture</code> <code>class</code>. Below I assume you have a Dictionary of Rules like in <a href=\"https://codereview.stackexchange.com/questions/44577/rpslsmb-oop-version-2\">my version</a>.</p>\n\n<pre><code>public static class Extensions\n{\n public static bool Defeates(this Gesture me, Gesture gesture)\n {\n return Game.Rules[me].Item1.ContainsKey(gesture);\n }\n}\n</code></pre></li>\n<li><p>I see that you have a few duplicated functions which do the exact same thing, only.. with a different data type. This is a bit of a red flag. Instead in this case you should just make one method. The one that takes a list of strings. Then make a function to convert an IList to a List ... this is super simple</p>\n\n<pre><code> myGestureList.select(g=&gt;g.ToString()).ToList();\n</code></pre>\n\n<p>Or, better yet... make a method that uses Generic T, then you can use PrintMenu GetRandomOption with any data type. </p>\n\n<pre><code>public static T GetRandomOption&lt;T&gt;(List&lt;T&gt; options)\n{\n return options[new Random().Next(0, options.Count)];\n}\n</code></pre>\n\n<p>Now whenever you call this method the type <code>T</code> will be inferred from the type of <code>List</code> you pass in and will result with that type of <code>object</code> being returned. I also in-lined the declaration of your <code>Random</code> <code>object</code> with the call of its <code>Next</code> method.</p>\n\n<p>Using this same technique, your PrintMenu Function will look like this (I think you should call this <code>PrintOptions</code>).</p>\n\n<pre><code>public static void PrintMenu&lt;T&gt;(List&lt;T&gt; List)\n{\n for (int i = 0; i &lt; List.Count; i++)\n {\n Console.WriteLine((i + 1) + \": \" + List[i]);\n }\n}\n</code></pre>\n\n<p>Here is re-worked version of this code, which makes it easy to offset the base number if desired.</p>\n\n<pre><code>public static void PrintMenu&lt;T&gt;(List&lt;T&gt; values, int baseIndex = 0)\n{\n values.ForEach(value =&gt; Console.WriteLine(\"{0}: {1}\", baseIndex++, value));\n}\n</code></pre></li>\n<li><p>Your win/lose/tie variables should be plural.</p>\n\n<pre><code>int wins = 0;\nint loses = 0;\nint ties = 0;\n</code></pre></li>\n<li><p>In your Choice Function you should take off the brackets from your case statements.</p>\n\n<pre><code>switch (Console.ReadKey(true).Key)\n{\n case ConsoleKey.Y:\n Console.Write(\"Y\\n\");\n return true;\n case ConsoleKey.N:\n Console.Write(\"N\\n\");\n return false;\n}\n</code></pre></li>\n<li><p>In C# the convention is different than Java where you are encouraged to add your brackets at the end of a statement.. ie. </p>\n\n<pre><code>if(Boolean value){\n statement;\n}\n</code></pre>\n\n<p>Your if-else chain should not use that convention. And really you could just not have the brackets at all considering they are 1 liners. I wouldn't even be opposed to 1-lining each of these statements. This point is a little more opinion based, but that is the C# convention. If you just press <kbd>Ctrl</kbd><kbd>E</kbd><kbd>D</kbd> in Visual Studio, you will find that your code will be reformatted to expand those brackets (only works if your code has no errors).</p>\n\n<pre><code>if (playerGesture.Equals(computerPlay))\n tie++;\nelse if(playerGesture.Defeats(computerPlay))\n win++;\nelse\n lose++;\n</code></pre></li>\n<li><p>You should use OO for players instead of for Gestures, you can see my <a href=\"https://codereview.stackexchange.com/a/44175/38054\">old review</a> for more info on that. Or look at my more recent <a href=\"https://codereview.stackexchange.com/questions/44577/rpslsmb-oop-version-2\">CR post</a>.</p></li>\n<li><p>Anything else I would have pointed out, has already been said by <a href=\"https://codereview.stackexchange.com/users/23788/mats-mug\">@Mat's Mug</a></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:25:23.127", "Id": "77369", "Score": "0", "body": "I completely disagree with #4 and #5. you should use brackets where you can. this keeps your code neat and tidy. as far as stating it's C# convention, which convention are you referring to?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:26:29.750", "Id": "77370", "Score": "0", "body": "encapsulation begs to differ with you on creating Gesture Objects rather than creating Gesture Variables. Gestures have Properties associated with them, they should be objects and not variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:37:11.067", "Id": "77374", "Score": "1", "body": "@Malachi #4 is correct, you should use the curly braces to define a *scope* - the `case` blocks of a `switch` statement **do not** define a scope, by wrapping `case` blocks in curly braces you are introducing a scope there, which means each `case` can then define its own local variables, which smells. As for #5, it's also correct, you should spare \"egyptian braces\" for Java... but using them won't cause any harm (other than a future maintainer would probably *CSharpify* them - I know I would!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:41:44.497", "Id": "77377", "Score": "0", "body": "@Mat'sMug ok I understand that. but I still think that using the brackets on if statements and for loops is necessary, for loops for the reason you mention of scope, and if statements because it defines the ending of the code block, which also has scope, if you have more than one line isn't it mandatory to use brackets?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:44:47.200", "Id": "77379", "Score": "1", "body": "@Malachi indeed, `if (true) DoSomething();` is legal (same for a 1-liner loop), but for maintainability and readability purposes, it's recommended to **always** correctly scope these code blocks, i.e. *use them curly braces* and go `if (true) { DoSomething(); }`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:11:40.103", "Id": "77390", "Score": "0", "body": "@Malachi \"as far as stating it's C# convention, which convention are you referring to?\" Visual studio IDE editor won't line your braces under the case: it will put the brace 4 spaces to the right of the case, and the code another 4 spaces to the right of that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:14:19.450", "Id": "77391", "Score": "1", "body": "@Malachi in a case statement you should use use the `break` keyword to end your code for that specific case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:24:30.950", "Id": "77394", "Score": "0", "body": "@Malachi Also... Gestures don't have properties associated with them, which is the reason why an enum works" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:26:44.850", "Id": "77396", "Score": "0", "body": "they have a property that says what Gestures they beat and what Gestures they lose to. they also have specific kill messages that are not shared. these things are properties specific to Gesture Objects" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:28:08.467", "Id": "77397", "Score": "0", "body": "this \"Gesture\" kills this \"Gesture\" Vs. Rock smashes scissors \"Gesture\" Times" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:31:48.717", "Id": "77399", "Score": "1", "body": "@Malachi maintain a list of rules, it is sooo much simpler than making a gigantic clunky Gesture class. Then just use an extension method as I did above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:44:13.077", "Id": "77403", "Score": "0", "body": "@BenVlodgi, you speak of C# convention and then you go against OOP Principles because it is \"clunky\"? Gesture is a class. a Rock is an object. a lizard is an object. a pair of scissors is an object. these are objects and not variables you can create an enumeration of these objects I suppose, but they are still objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T18:56:41.333", "Id": "77407", "Score": "0", "body": "@Malachi I'm not going against OOP principles by using an enum, even so, using OO is not a C# standard. It is a good practice. In your case, you're not even using OO properly, those objects are just encasing strings and maintaining a list of strings that they interact with. you shouldn't be using strings, you should be using enums... even if you were using Gesture objects, there should still be a gesture enums determining what kind of Gesture object that is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T19:02:05.457", "Id": "77408", "Score": "0", "body": "@Malachi Gestures aren't necessarily a class (with associated behaviour). Instead they can be modelled as a mere value (i.e. as an enum), with \"Rules\" as a class (where 'rules' define the gesture-gesture interactions)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T19:02:25.657", "Id": "77409", "Score": "1", "body": "FWIW an enum is also an `object` :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T19:18:46.843", "Id": "77415", "Score": "0", "body": "@Mat'sMug indeed.. I was just making a distinction between Malachi's Gesture class and my Gesture enum :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T19:23:15.133", "Id": "77416", "Score": "1", "body": "I guess I don't fully understand Enums, maybe that should be my next study subject" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T13:22:20.493", "Id": "78071", "Score": "0", "body": "although you have really good information here, this is more about how my structure doesn't look like your structure, and not so much if my structure is good....I don't know if that makes complete sense, but I like @Mat'sMug Answer a little bit better for this question, I still value your answer though. I will be looking into Enums when I get back to this project. Thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T13:43:09.610", "Id": "78080", "Score": "1", "body": "@Malachi its not that your strucutre is different than mine which is the problem. I think that you made design poor design choices. I happen to be pointing out what I believe the right choice to be, and that it is something that I have already implemented. Where proper use of a language is great when programming, but the design of your application is the most important part. If your programs structure is poorly designed it will become cumbersome, it will affect you at every stage of development, and be difficult to change once you decide to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:55:09.123", "Id": "78113", "Score": "1", "body": "@BenVlodgi, I see your point." } ], "meta_data": { "CommentCount": "20", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T16:58:37.457", "Id": "44593", "ParentId": "44487", "Score": "5" } }, { "body": "<p>I find it a nuisance to define so many methods merely in order to override Equals.</p>\n\n<p>Therefore I sometimes define and invoke a method named <code>Matches</code> instead.</p>\n\n<p>Given that you only have one instance of each gesture, do you even need to define it? The default implementation of object.Equals is to call object.ReferenceEquals.</p>\n\n<hr>\n\n<p>Your <code>Seal</code> functionality is ugly, for several reasons. Two alternatives:</p>\n\n<ul>\n<li><p>Define AddDefeats as private; create a static constructor of the Gesture class, and construct the list of Gesture instance in the static constructor (which can invoke the private method)</p>\n\n<pre><code>class Gesture\n{\n internal static IList&lt;Gesture&gt; AllGestures;\n\n static Gesture\n {\n var spock = new Gesture(\"Spock\");\n var lizard = new Gesture(\"Lizard\");\n var paper = new Gesture(\"Paper\");\n var rock = new Gesture(\"Rock\");\n var scissors = new Gesture(\"Scissors\");\n\n spock.AddDefeats(new[] { scissors, rock });\n lizard.AddDefeats(new[] { paper, spock });\n paper.AddDefeats(new[] { rock, spock });\n rock.AddDefeats(new[] { lizard, scissors });\n scissors.AddDefeats(new[] { paper, lizard });\n\n AllGestures = new List&lt;Gesture&gt; {rock, paper, scissors, lizard, spock};\n }\n</code></pre></li>\n<li><p>Remove the AddDefeats method, and pass the array of defeats as a parameter to the Gesture constructor (so that a Gesture instance is fully-constructed immediately)</p>\n\n<pre><code>// defeats expressed using strings (gesture names) instead of Gesture instances\n// because we need to refer to gestures which haven't been constructed yet\npublic Gesture(string name, IEnumerable&lt;string&gt; defeats)\n{\n if (name == null) throw new ArgumentNullException(\"name\");\n Name = name;\n\n foreach (var gesture in defeats)\n {\n _defeats.Add(gesture);\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:34:10.883", "Id": "77373", "Score": "0", "body": "would you still feel this way if I made it possible for an admin user to create new Gestures from the console interface of the application? I mean for the Static Gesture Constructor? little confused about the static constructor part as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:58:25.463", "Id": "77387", "Score": "0", "body": "I edited the answer to show an example of a static constructor." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T17:30:21.487", "Id": "44594", "ParentId": "44487", "Score": "2" } } ]
{ "AcceptedAnswerId": "44490", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T02:05:37.853", "Id": "44487", "Score": "7", "Tags": [ "c#", "game", "community-challenge", "rock-paper-scissors" ], "Title": "RPSLS game revisited. Is my design better than previous attempts?" }
44487
<p>I have this conditional statement with use of regex:</p> <pre><code>do_stuff if (@string.match(/&lt;(?:ingr?)&gt;/i) &amp;&amp; @string.match(/&lt;(?:prod:alchemy?)&gt;/i)) || @string.match(/&lt;(?:key?)&gt;/i) </code></pre> <p>It's a 1-line conditional statement, but due to it's length, it taking 3 lines instead. I'm wondering if there's a way to trim this down, so that I can fit it into 1 line. Preferably to be something like</p> <pre><code>do_stuff if (regex here) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T05:57:19.557", "Id": "77208", "Score": "1", "body": "I am not clear why you need the non-capture groups and why they need to be non-greedy (the `?` at the end of each). If, for example, you are just trying to see if the string '<ingr>' is present, you could use just `@string.include?('<ingr>')`. Could you please elaborate? It would be helpful if you could edit to include some example strings and expected results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T08:19:56.593", "Id": "77217", "Score": "1", "body": "The question marks here aren't lazy quantifiers. They simply make the preceding letter optional. (I'm not sure if that was that the author intended, but that's what it does.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T00:55:21.970", "Id": "77308", "Score": "0", "body": "Thanks, @200_success. I see a `?` implies lazy (aka \"non-greedy\", \"reluctant\") only when if follows one of the qualifiers `*` , `+` , `?` , or `{}`. My regex skills need work." } ]
[ { "body": "<p>You <em>could</em> combine all the tests into one regular expression, but I don't recommend it. The following is equivalent to what you wrote:</p>\n\n<pre><code>do_stuff if @string =~ /(?'i'&lt;ingr?&gt;).*(?'a'&lt;prod:alchemy?&gt;)|\\g&lt;a&gt;.*\\g&lt;i&gt;|&lt;key?&gt;/i\n</code></pre>\n\n<hr>\n\n<p>Your regular expressions are a bit odd, so I suspect that what you wrote is not what you meant to write.</p>\n\n<p>The non-capturing grouping parentheses <code>(?:…)</code> don't seem to serve any purpose, so you can get rid of them.</p>\n\n<p>The other question marks make the preceding letter optional. For example, <code>/&lt;key?&gt;/i</code> matches <code>&lt;key&gt;</code> or <code>&lt;Key&gt;</code> or <code>&lt;ke&gt;</code> but not <code>&lt;ken&gt;</code>.</p>\n\n<p>The tricky obstacle to merging the regular expressions is that the <code>&lt;ingr?&gt;</code> and <code>&lt;prod:alchemy?&gt;</code> tests both have to pass, and they can occur in either order. Therefore, you have to allow <code>&lt;ingr?&gt;.*&lt;prod:alchemy?&gt;</code> as well as <code>&lt;prod:alchemy?&gt;.*&lt;ingr?&gt;</code> That's possible with</p>\n\n<pre><code>&lt;ingr?&gt;.*&lt;prod:alchemy?&gt;|&lt;prod:alchemy?&gt;.*&lt;ingr?&gt;\n</code></pre>\n\n<p>Of course, repeating yourself is bad for verbosity and maintainability. You can lessen the pain slightly by using <a href=\"http://www.ruby-doc.org/core-2.1.0/Regexp.html#class-Regexp-label-Subexpression+Calls\" rel=\"nofollow\">named groups and subexpression calls</a>.</p>\n\n<p>After having done all that, though, the one long regex is more difficult to understand than your original code. Therefore, I recommend leaving it alone.</p>\n\n<p>If you're dissatisfied with the original code, though, there may be other improvements that you could make, but you haven't provided any context for your question so I can't make alternative suggestions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T19:35:28.747", "Id": "77266", "Score": "0", "body": "Ah, thank you. Your feedback is more than helpful. Especially that sub-expression call. I saw what you did there with \\g<a>.*\\g<i>. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T08:46:14.473", "Id": "44495", "ParentId": "44492", "Score": "3" } } ]
{ "AcceptedAnswerId": "44495", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T04:08:35.877", "Id": "44492", "Score": "1", "Tags": [ "ruby", "regex" ], "Title": "1-line conditional statement needs to be trimmed down" }
44492
<p>My main concern is code style. Could you review this?</p> <pre><code>#pragma once #include &lt;time.h&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;iterator&gt; #include &lt;algorithm&gt; #include &lt;functional&gt; #include &lt;math.h&gt; #include &lt;exception&gt; #include "InfInt.h" #include "Array2d.h" template &lt;typename ContainerT&gt; ContainerT splitString(const std::string &amp; source) { ContainerT cont; std::stringstream ss(source); typedef typename ContainerT::value_type ElementT; std::copy(std::istream_iterator&lt;ElementT&gt;(ss), std::istream_iterator&lt;ElementT&gt;(), std::back_inserter(cont)); return cont; } template &lt;typename T&gt; std::string joinString(const T &amp; v, const std::string &amp; delim = " ") { std::ostringstream s; bool empty = true; for (const auto &amp; i : v) { if (empty) empty = false; else s &lt;&lt; delim; s &lt;&lt; i; } return s.str(); } class CodeJam { public: std::stringstream input; std::stringstream output; int curCase; int solveJam(const std::string &amp; data) { int res = 0; std::cout &lt;&lt; "Solving jam:" &lt;&lt; std::endl &lt;&lt; std::endl; try { input.clear(); output.clear(); auto inputFile = "Data\\" + data + ".in"; std::ifstream finput(inputFile); if (!finput.is_open()) throw std::runtime_error("Can not open input file " + inputFile); auto outputFile = "Data\\" + data + ".out"; std::ofstream foutput(outputFile); if (!foutput.is_open()) throw std::runtime_error("Can not open output file " + outputFile); input &lt;&lt; finput.rdbuf(); input.seekg(0); auto elapsedTime = clock(); res = solveAll(); elapsedTime = clock() - elapsedTime; foutput &lt;&lt; output.rdbuf(); finput.close(); foutput.close(); std::cout &lt;&lt; std::endl; std::cout &lt;&lt; "Success! Finished " &lt;&lt; res &lt;&lt; " tests in " &lt;&lt; elapsedTime &lt;&lt; " ms" &lt;&lt; std::endl; } catch (const std::exception &amp; e) { std::cout &lt;&lt; "Error: " &lt;&lt; e.what() &lt;&lt; std::endl; } std::cout &lt;&lt; std::endl; system("pause"); return res; } protected: virtual int solveAll() { int testCases; readln(testCases); for (curCase = 1; curCase &lt;= testCases; ++curCase) { solve(curCase); std::cout &lt;&lt; "Test " &lt;&lt; curCase &lt;&lt; " of " &lt;&lt; testCases &lt;&lt; std::endl; }; return testCases; } virtual void solve(int task) = 0; public: std::string readLine() { std::string line; std::getline(input, line); return line; } template&lt;typename T&gt; T readLine() { std::string line; std::getline(input, line); T list = splitString&lt;T&gt;(line); return list; } std::vector&lt;int&gt; readInts() { return readLine&lt;std::vector&lt;int&gt;&gt;(); } std::vector&lt;std::string&gt; readStrings() { return readLine&lt;std::vector&lt;std::string&gt;&gt;(); } std::vector&lt;double&gt; readDoubles() { return readLine&lt;std::vector&lt;double&gt;&gt;(); } void readln() { readLine(); } template &lt;typename T&gt; void readln(T &amp; t) { input &gt;&gt; t; input.ignore(); } template &lt;typename First, typename... Rest&gt; void readln(First &amp; first, Rest &amp;... rest) { input &gt;&gt; first; readln(rest...); } template &lt;typename T&gt; void writeResult(T value) { output &lt;&lt; "Case #" &lt;&lt; curCase &lt;&lt; ": " &lt;&lt; value &lt;&lt; std::endl; }; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T09:09:45.103", "Id": "77219", "Score": "0", "body": "You probably want a virtual destructor there (http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:00:53.423", "Id": "77223", "Score": "0", "body": "Keep all your public and private methods together. Right now you have two blocks of public methods. This is confusing. Also generally speaking, public member variables are frowned upon." } ]
[ { "body": "<pre><code>#pragma once\n</code></pre>\n\n<p>This really only makes sense in a header, but the rest of your code doesn't really look like a header (but maybe it's intended to be one anyway--not really sure). If it is a header, I'd recommend adding normal <code>#ifndef</code>/<code>#define</code>/<code>#endif</code> style header guards as well, since some compilers don't support this <code>#pragma</code>.</p>\n\n<pre><code>template &lt;typename ContainerT&gt;\nContainerT splitString(const std::string &amp; source) {\n ContainerT cont;\n std::stringstream ss(source);\n typedef typename ContainerT::value_type ElementT;\n std::copy(std::istream_iterator&lt;ElementT&gt;(ss), std::istream_iterator&lt;ElementT&gt;(), std::back_inserter(cont));\n return cont;\n}\n</code></pre>\n\n<p>I think I'd use something a bit simpler, such as:</p>\n\n<pre><code>template &lt;typename ContainerT&gt;\nContainerT splitString(const std::string &amp; source) {\n std::stringstream ss(source);\n ContainerT cont{std::istream_iterator(ss), std::istream_iterator()};\n return cont;\n}\n</code></pre>\n\n<p>If you're stuck with C++03 instead of 11, you'll need to use:</p>\n\n<pre><code> ContainerT cont((std::istream_iterator(ss)), std::istream_iterator());\n</code></pre>\n\n<p>...instead (note the double parens around the first param, to avoid the <a href=\"https://stackoverflow.com/q/10039657/179910\">Most Vexing Parse</a>).</p>\n\n<p>As @Mat already alluded to in a comment, the fact that this contains a pure virtual function indicates that it's intended to be used as a base class for derivation. If so, you almost certainly want to make the destructor virtual as well--this is needed if the user might ever create a pointer to the base class, and destroy an instance via that pointer to the base.</p>\n\n<p>To be honest, this scenario strikes me as somewhat unlikely though. Such a virtual function is generally useful when you have something like a heterogeneous container that might contain pointers to objects of any of a number of derived classes, so the correct function to call must be determined individually for each item.</p>\n\n<p>In this case, it appears more likely (at least to me) that the intent is to have only <em>one</em> derived class per program, so what we really have is \"static polymorphism\" -- i.e., in a given program, there will be only one derived class, so one program will really only have one implementation of <code>solve</code>.</p>\n\n<p>If that's correct, it would probably be better to model that a bit more directly, such as by passing the <code>solve</code> as a template parameter instead:</p>\n\n<pre><code>template &lt;class solve&gt;\nclass CodeJam {\n// ...\n void solveAll() { \n // ...\n for (curCase = 1; curCase &lt;= testCases; ++curCase) {\n // Note that the syntax is only minimally affected:\n solve()(curCase);\n std::cout &lt;&lt; \"Test \" &lt;&lt; curCase &lt;&lt; \" of \" &lt;&lt; testCases &lt;&lt; std::endl;\n }\n }\n};\n</code></pre>\n\n<p>This seems to improve flexibility at least somewhat, because the user is no longer required to write a class that's derived from <code>CodeJam</code>.</p>\n\n<p>At the same time, I feel obliged to point out what seems to me an even greater problem (and one that's not so easily fixed either, I'm afraid). This comes down to the simple fact that your code simply doesn't seem to provide all that much functionality. I can hardly imagine how anybody could hope to save even 10 whole minutes by using your code rather than starting from nothing at all--and in some cases, I can see where this code might easily be no more than a break-even proposition.</p>\n\n<p>In short, you're placing constraints on how code is written, but providing rather minimal functionality in return. I question whether it provides enough return on investment to justify itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T06:43:26.930", "Id": "45807", "ParentId": "44494", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T05:58:21.370", "Id": "44494", "Score": "3", "Tags": [ "c++", "beginner", "c++11", "contest-problem" ], "Title": "Simple framework for Google Code Jam problems" }
44494
<p>I have a WCF service which should authenticate user against any bruteforce attack. Below is the code to avoid any bruteforce attack. I have used <code>MemoryCache</code> to keep track of invalid attempts by a user.</p> <p>Could you please review the code and let me know if there are any issues?</p> <p>Following defined in config file:</p> <pre><code>&lt;InvalidLoginAttemptsThreshold value = "5"/&gt; &lt;InvalidLoginLockoutInMinutes value = "20"/&gt; </code></pre> <p>Code to add invalid login to cache and lock the account if invalid logins reaches threshold set in config.</p> <pre><code>private readonly CacheItemPolicy cacheInvalidLoginPolicy = new CacheItemPolicy(); private readonly ObjectCache cacheInvalidLogins = MemoryCache.Default; //Cache to hold Invalid Login Attempts: {UserId, obj UserLogin} public class UserLogin { public string UserName { get; set; } public List&lt;DateTime&gt; InvalidLoginTimestamp { get; set; } public bool IsLocked { get; set; } } private bool AuthenticateUser(string userName, string password) { bool validCredentials = false; string userNameUpperCase = userName.ToUpper(); //MemoryCache treats 'a' and 'A' as different names if (cacheInvalidLogins.Contains(userNameUpperCase) &amp;&amp; ((UserLogin)cacheInvalidLogins[userNameUpperCase]).IsLocked) { log.ErrorFormat("UserId: {0} tried to access locked account at {1}", userName, DateTime.Now); throw new FaultException("Your account is locked out. Please try after some time.", new FaultCode("AccountLocked")); } try { validCredentials = securityService.Authenticate(userName, password); if (!validCredentials) { AddInvalidLoginToCache(userNameUpperCase); } else if (validCredentials &amp;&amp; cacheInvalidLogins.Contains(userNameUpperCase)) { //For valid credentials - remove from cache cacheInvalidLogins.Remove(userNameUpperCase); } } catch (Exception exception) { log.Error(exception); } return validCredentials; } private void AddInvalidLoginToCache(string userName) { if (cacheInvalidLogins.Contains(userName)) { string clientId = userName.Split('\\')[0]; //Increment InvalidLoginCount for this user UserLogin invalidLogin = (UserLogin)cacheInvalidLogins[userName]; invalidLogin.InvalidLoginTimestamp.Add(DateTime.Now); cacheInvalidLogins[userName] = invalidLogin; //todo: update cache policy here //Lock user account if InvalidLoginCount reach threshold set in config if (invalidLogin.InvalidLoginTimestamp.Count == invalidLoginThresholdFromConfig)) { invalidLogin.IsLocked = true; cacheInvalidLogins.Set(userName.ToUpper(), invalidLogin, LockOutCachePolicyFromConfig()); log.ErrorFormat("Invalid Login attempted by UserId: {0} at these timestamps: {1}", userName, String.Join(",", invalidLogin.InvalidLoginTimestamp)); log.ErrorFormat("Account is locked out for UserId: {0}", userName); throw new FaultException("Your account is locked out. Please try after some time.", new FaultCode("AccountLocked")); } } else { //todo: check if extra config setting is required for this cache policy cacheInvalidLoginPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5); cacheInvalidLogins.Add(userName.ToUpper(), new UserLogin {UserName = userName, InvalidLoginTimestamp = new List&lt;DateTime&gt; {DateTime.Now}}, cacheInvalidLoginPolicy); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T17:41:12.143", "Id": "77257", "Score": "0", "body": "What type/class is `securityService`?" } ]
[ { "body": "<ol>\n<li><p>If I'm right it's not thread-safe. I suppose two browsers with the same username could login at the same time which means that the <code>AuthenticateUser</code> method runs parallel on two threads.</p>\n\n<p>Suppose the following:</p>\n\n<ul>\n<li>the user already has an invalid login attempt,</li>\n<li>two new threads enter <code>AddInvalidLoginToCache</code> the same time,</li>\n<li><code>invalidLoginThresholdFromConfig = 2</code>. </li>\n</ul>\n\n<p>A possible execution order is the following: </p>\n\n<pre><code>// InvalidLoginTimestamp.Count = 1, we already have an invalid login attempt\nthread1: enters AddInvalidLoginToCache\nthread2: enters AddInvalidLoginToCache\nthread1: runs invalidLogin.InvalidLoginTimestamp.Add(DateTime.Now); // InvalidLoginTimestamp.Count = 2\nthread2: runs invalidLogin.InvalidLoginTimestamp.Add(DateTime.Now); // InvalidLoginTimestamp.Count = 3\nthread1: runs if (invalidLogin.InvalidLoginTimestamp.Count == 2)) // false \nthread2: runs if (invalidLogin.InvalidLoginTimestamp.Count == 2)) // false\n</code></pre>\n\n<p>The result is that a lucky attacker will never be locked out.</p>\n\n<p>The second problem is visibility. Since <code>InvalidLoginTimestamp</code> and <code>invalidLogin</code> are shared between threads you need some synchronization to ensure other threads will see modifications (not just stale data or invalid state).</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/1668719/843804\">C# multi-threading: Acquire read lock necessary?</a></li>\n<li><a href=\"https://stackoverflow.com/a/186550/843804\">How to synchronize the access to a List used in ASP.NET?</a></li>\n</ul></li>\n<li><blockquote>\n<pre><code>private readonly ObjectCache cacheInvalidLogins = MemoryCache.Default; //Cache to hold Invalid Login Attempts: {UserId, obj UserLogin}\n</code></pre>\n</blockquote>\n\n<p>I'd put the comment before the line to avoid horizontal scrolling:</p>\n\n<pre><code>//Cache to hold Invalid Login Attempts: {UserId, obj UserLogin}\nprivate readonly ObjectCache cacheInvalidLogins = MemoryCache.Default; \n</code></pre>\n\n<p>Furthermore, I'd rename it to <code>invalidLoginAttemptsCache</code>. The <code>cacheInvalidLogins</code> name looks like a method name since it starts with a verb (<code>cache...</code>).</p></li>\n<li><blockquote>\n<pre><code>bool validCredentials = false;\n... // other statements\ntry\n{\n validCredentials = securityService.Authenticate(userName, password);\n</code></pre>\n</blockquote>\n\n<p>The boolean could be declared right before the first use with a smaller scope:</p>\n\n<pre><code>... // other statements\nbool validCredentials = false;\ntry\n{\n validCredentials = securityService.Authenticate(userName, password);\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/q/6133586/843804\">Should I declare variables as close as possible to the scope where they will be used?</a></p></li>\n<li><blockquote>\n<pre><code>private void AddInvalidLoginToCache(string userName)\n{\n ...\n cacheInvalidLogins.Set(userName.ToUpper(), invalidLogin, LockOutCachePolicyFromConfig());\n</code></pre>\n</blockquote>\n\n<p>The code calls this method with the uppercased username. I'd rename the parameter to <code>upperCasedUserName</code> and remove the <code>.ToUpper()</code> call.</p></li>\n<li><p>This variable is never user, I guess you could remove it:</p>\n\n<blockquote>\n<pre><code>string clientId = userName.Split('\\\\')[0];\n</code></pre>\n</blockquote></li>\n<li><p><a href=\"https://english.stackexchange.com/q/43436/13023\"><em>Username</em> seems to be one word</a>, I'd not capitalize the <code>n</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:28:28.950", "Id": "44502", "ParentId": "44496", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T09:06:26.727", "Id": "44496", "Score": "3", "Tags": [ "c#", "security", "authentication" ], "Title": "MemoryCache - Login Security" }
44496
<p>I read about W3C Web Components spec and JavaScript's libraries like polymer.js and others, so I tried to find something similar in PHP, but with no luck.</p> <p>So I wrote a tiny class to work with custom tags in PHP and I'd like to know what do you think about it. Is the idea somehow reasonable?</p> <p><a href="https://github.com/SimoneS93/PHPWebComp" rel="nofollow">Here is the Github repo</a>.</p> <pre><code>public static function loadString($string, array $context = array()) { $context = new Context($context); //eval the first time $string = self::evall($string, $context); //eval 'til there are custom tags while ($matches = self::matchWebComp($string)) { $context = new Context($matches); $context-&gt;setArray(Context::fromAttributesString($context-&gt;attributesList)-&gt;toArray()); $webComp = self::getWebCompDefinition($context-&gt;tag); $webComp = self::evall($webComp, $context); $string = str_replace($context-&gt;match, $webComp, $string); } return $string; } public static function evall($string, Context $context = NULL) { ob_start(); eval('; ?&gt;' . $string); return ob_get_clean(); } public static function matchWebComp($string) { //match &lt;a-tag [attributes]&gt;[inner html]&lt;/a-tag&gt; if (preg_match('/&lt;(?P&lt;tag&gt;\w+-[\w\-]+)( *.*)&gt;([\s\S]*)&lt;\/(?P=tag)&gt;/U', $string, $matches)) { return array( 'match' =&gt; $matches[0], 'tag' =&gt; $matches[1], 'attributesList' =&gt; $matches[2], 'innerHtml' =&gt; $matches[3] ); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T20:09:34.997", "Id": "77927", "Score": "0", "body": "I'm not sure if there is much point to this library - the 'magic' of Web Components is partly that elements have methods, and that the inside code of an element can be hidden.Replacing a custom element with its Shadow DOM representation before render kinda defeats the point with my understanding anyway!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T09:57:58.657", "Id": "44497", "Score": "1", "Tags": [ "php", "html", "template" ], "Title": "PHP Web Components" }
44497
<p>I have a program that accesses a certain I/O controller using memory-mapped I/O. I currently store the base address of this controller in a <code>const</code> variable.</p> <p>This leads to a code structure something like this:</p> <p><strong>gpio.h:</strong></p> <pre><code>int gpioFunc (unsigned int pin, unsigned int func); int setGpio (unsigned int pin, unsigned int val); </code></pre> <p><strong>gpio.c:</strong></p> <pre><code>#include "gpio.h" unsigned volatile int* const gpioAddr = (unsigned int*) 0x20200000; int gpioFunc (unsigned int pin, unsigned int func) { //code that uses the variable } int setGpio (unsigned int pin, unsigned int val) { //code that uses the variable } </code></pre> <p><strong>main.c:</strong></p> <pre><code>#include "gpio.h" void main () { gpioFunc (16,1); setGpio(16,0); hlt(); } </code></pre> <p>I have always been uncertain of the best practices in C as to where to put constants. Does this way make sense, or would it be better practice to put it somewhere else? If so, where?</p>
[]
[ { "body": "<p>You should make a small driver layer, so that the main doesn't know about the low level details of what is going on - and here in that .c file that you have implemented the driver in, the constants goes as well. </p>\n\n<p>Then you call your driver and all is good :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T12:18:36.363", "Id": "77231", "Score": "0", "body": "I think this may what I have currently... how would this be different from my current implementation? Thank you for your help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T12:20:45.090", "Id": "77232", "Score": "0", "body": "No, this is not a driver. This is calling the bare metal layer from your main. You want to make a small driver layer, so that you get calls like \"<driver_name>_get<data_pin_name>\" and \"<driver_name>_init\". This also allows you to easily change the setup in the future, when you need to." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T12:13:59.237", "Id": "44506", "ParentId": "44503", "Score": "2" } }, { "body": "<p>I recommend you to declare <code>gpioAddr</code> variable as static. That way the program can only access it from <code>gpio.c</code> and nowhere else (unless you somehow pass the address of the variable to somewhere, which is a poor design, IMO). Making it static also helps the compiler to optimize the variable and just generates code for reading from/writing to the particular memory address.</p>\n\n<p>Also, <code>0x20200000</code> is a magic number, you should consider to define it somewhere appropriate.</p>\n\n<p>Lastly, casting as <code>(unsigned volatile int*)</code> may be better for readability, although it makes no difference.</p>\n\n<p><strong>Edit:</strong> The appropriate place for defining constants depend on the context. If these definitions are needed somewhere else, you <em>must</em> put them in header file. Defining them in source file is more appropriate otherwise, as unnecessary information would be hidden. Unfortunately, <code>#define</code> preprocessor directives in C are in the global namespace, so appropriate prefixes should be added to the name regardless of the definition place.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T19:06:25.520", "Id": "77411", "Score": "0", "body": "I am aware that I should consider to define it somewhere appropriate. The question was where would be considered appropriate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T19:07:43.417", "Id": "77412", "Score": "0", "body": "It is the source file if it does not needed to know from somewhere else, i.e. including a header file, header file if otherwise. I think source file is more appropriate in this occasion." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T19:04:47.980", "Id": "44601", "ParentId": "44503", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T11:38:33.130", "Id": "44503", "Score": "4", "Tags": [ "c", "io", "constants" ], "Title": "Accessing a certain I/O controller using memory-mapped I/O" }
44503