body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have been implementing a delegate class with C++11 that supports class member functions. I am interested in knowing if there are any potential problems with this implementation. My main concern is the private <code>Key</code> struct of the <code>Delegate</code> class. Can I always rely on the key being correct in all situations? Meaning, can I always identify certain function of certain object with it?</p> <p>In there I am storing 3 things:</p> <ol> <li>hash of the member function pointer </li> <li>pointer to the object </li> <li><code>std::function</code> wrapping the actual function</li> </ol> <p>The hash is calculated from the function pointer with the <code>getHash()</code> function. I've originally used only that as key, but I run into a problem with inherited classes. I've gotten the same hash for the inherited function with 2 different classes inheriting from same base class. For that reason, I've also stored the pointer to the actual object, using these 2 as key I am able to identify certain entry in the list of stored keys. I'd be really interested to know any potential issues with this implementation. This compiles with VS2013, and I am hoping it will also work with Clang, but I haven't tried it out yet.</p> <pre><code>template &lt;typename...Params&gt; class Delegate { private: typedef std::function &lt; void(Params...)&gt; FunctionType; struct Key { size_t m_funcHash; void* m_object; FunctionType m_func; Key(void* object, size_t funcHash, FunctionType func) : m_object(object), m_funcHash(funcHash), m_func(func) {} bool operator==(const Key&amp; other) const { return other.m_object == m_object &amp;&amp; other.m_funcHash == m_funcHash; } }; std::vector &lt;Key&gt; m_functions; public: template &lt;typename Class&gt; void connect(Class&amp; obj, void (Class::*func) (Params...) ) { std::function &lt; void (Class, Params...) &gt; f = func; FunctionType fun = [&amp;obj, f](Params... params) { f(obj, params...); }; size_t hash = getHash(func); m_functions.push_back(Key( &amp;obj, hash, fun)); } template &lt;typename Class&gt; size_t getHash(void (Class::*func) (Params...)) { const char *ptrptr = static_cast&lt;const char*&gt;(static_cast&lt;const void*&gt;(&amp;func)); int size = sizeof (func); std::string str_rep(ptrptr, size); std::hash&lt;std::string&gt; strHasher; return strHasher(str_rep); } template &lt;typename Class&gt; void disconnect( Class&amp; obj, void (Class::*func) (Params...) ) { size_t hash = getHash(func); for (unsigned int i = 0; i &lt; m_functions.size(); ++i) { auto key = m_functions[i]; if (key.m_funcHash == hash &amp;&amp; key.m_object == &amp;obj) { m_functions.erase(m_functions.begin() + i); --i; } } } template &lt;typename ... Args&gt; void operator() (Args...args) { for (auto&amp; key : m_functions) { key.m_func (args...); } } }; class BaseClass { public: virtual void print(const std::string&amp; str) = 0; }; class A : public BaseClass { public: void print(const std::string&amp; str) { std::cout &lt;&lt; " Class A : Print [" &lt;&lt; str &lt;&lt; "]\n"; } }; class B : public BaseClass { public: void print(const std::string&amp; str) { std::cout &lt;&lt; " Class B : Print [" &lt;&lt; str &lt;&lt; "]\n"; } }; int _tmain(int argc, _TCHAR* argv[]) { A a; B b; Delegate &lt;const std::string&amp;&gt; delegate; delegate.connect(a, &amp;A::print); delegate.connect(b, &amp;B::print); delegate("hello"); delegate("world"); delegate.disconnect(a, &amp;A::print); delegate("bye world"); delegate.disconnect(b, &amp;B::print); delegate("nobody there."); // should not print anything std::cin.ignore(); return 0; } </code></pre>
[]
[ { "body": "<h2>Fatal bugs:</h2>\n\n<p>A <strong>big</strong> issue is the fact that you take a copy of the object in the function in this line:</p>\n\n<pre><code> std::function &lt; void (Class, Params...) &gt; f = func;\n</code></pre>\n\n<p>This needs to be <code>Class&amp;</code> at the very least. Otherwise, invocations of handlers would operate on <em>copies</em> of the intended objects. See demonstration here: <strong><a href=\"http://coliru.stacked-crooked.com/a/f59868574e018fa7\" rel=\"nofollow\">Live On Coliru</a></strong> with debug information showing copies are being made.</p>\n\n<h2>Conceptual issues:</h2>\n\n<ul>\n<li><p>you are using a hash for equality. This is a conceptual flaw: hashes can have collisions. Hashes are used to organize large domains into a smaller set of buckets. </p>\n\n<blockquote>\n <p><em>this could really be considered a fatal bug, as <code>disconnect</code> might disconnect unrelated handlers here</em></p>\n</blockquote></li>\n<li><p>you're wrapping your member-function pointers in a std::function. <strong>Twice</strong>. This is gonna be very bad for anything performance-sensitive</p></li>\n<li><p>you are abusing <code>std::function</code> for generic calleables. Instead, use perfect storage on user-supplied calleables (why bother whether it's <code>std::mem_fun_ref_t</code>, a <em>bind-expression</em>, a lambda or indeed a function pointer?). This way</p>\n\n<ul>\n<li>you don't incur the overhead of type erasure and virtual dispatch that comes with std::function, unless your situation requires it</li>\n<li>you don't have to bother with the annoying details that you have to, now\n<ul>\n<li>you don't need to treat member functions differently to begin with (<code>std::bind</code> to the rescue)</li>\n<li>you don't need to rely on implementation defined implementation of <em>pointer-to-member-function</em></li>\n</ul></li>\n</ul></li>\n<li><p>you're using implementation defined behaviour to get a hash of a <em>pointer-to-member-function</em> (see previous bullet)</p></li>\n<li><p>your less-than generic solution works for <em>pointer-to-member-function</em> only. This you already knew. But, you may not have realized, it <em>doesn't</em> work for <code>const</code> or <code>volatile</code> qualified member functions.</p></li>\n<li><p>your <code>Delegate</code> class tries to \"guess\" identity of registered handlers. In fact, the registering party should be responsible for tracking exactly which registration it manages. A cookie-based design would be most suitable here, and certainly takes all the implementation defined behaviour out of the equation (as well as immediately making it clear what happens when the same handler gets registered multiple times). See the <strong><a href=\"http://coliru.stacked-crooked.com/a/df7afbead3712e0b\" rel=\"nofollow\">\"more drastic rewrite\" below.</a></strong></p></li>\n</ul>\n\n<h2>Style, Efficiency</h2>\n\n<ul>\n<li><p>Your <code>Key</code> class isn't the Key. It's the collection Entry (Key + Function).</p></li>\n<li><p>Your <code>Key</code> defines <code>operator==</code>. An object that's <em>equatable</em> necessitates linear search to do a lookup. Instead, define a <em>weak total ordering</em> (using <code>operator&lt;</code>) so you can use tree-like data-structures. See below for a sample that uses <code>std::tie()</code> to quickly implement both <em>relational operators</em> (<a href=\"http://coliru.stacked-crooked.com/a/55858bdee7561e79\" rel=\"nofollow\">the first version</a>).</p></li>\n<li><p>Also, need to use <code>Key::operator==</code> instead of just comparing <code>m_object</code> and <code>m_funcHash</code> again (encapsulation)</p></li>\n<li><p>Your Key stores the object, but the object is also part of <code>FunctionType</code> implicitely, because you capture it by reference. You should probably remove the redundancy.</p></li>\n<li><p>Your disconnect lookup is ... not very effective: </p>\n\n<ul>\n<li>linear search? really?</li>\n<li><p>no early out? (it's unclear how you really want repeatedly registered callbacks to be handled, but I'd say </p>\n\n<pre><code> del.connect(some_handler);\n del.connect(some_handler);\n del.disconnect(some_handler); // disconnect 1 of the two\n del.disconnect(some_handler); // disconnect the other\n</code></pre>\n\n<p>would be the principle of least surprise)</p></li>\n<li><p>your <code>i--</code> invokes unsigned integer wraparound. Now, this is not undefined behaviour, but it's bad style IMO. You could use</p>\n\n<pre><code>for(unsigned int i = 0; i &lt; m_functions.size(); ) {\n auto key = m_functions[i];\n if(key.m_funcHash == hash &amp;&amp; key.m_object == &amp;obj) {\n m_functions.erase(m_functions.begin() + i);\n } else\n {\n ++i;\n }\n}\n</code></pre>\n\n<p>instead.</p></li>\n<li><p>the loop <em>crucially</em> depends on <code>m_functions.size()</code> being evaluated each iteration. This is inefficient and error-prone</p></li>\n</ul>\n\n<blockquote>\n <p><strong>Guideline:</strong> <em>Whenever you see a loop that became... non-trivial and obscure like this, it's a sure sign you need to use an (existing) algorithm</em></p>\n</blockquote></li>\n</ul>\n\n<p>Fixing just these elements: just use a better datastructure, like</p>\n\n<pre><code>struct Key {\n void* m_object;\n size_t m_funcHash;\n // no ctor: let just just be an aggregate\n\n bool operator==(const Key&amp; other) const { return key() == other.key(); }\n bool operator&lt; (const Key&amp; other) const { return key() &lt; other.key(); }\n private:\n // trick to make it trivial to consistently implement relational operators:\n std::key&lt;void* const&amp;, size_t const&amp;&gt; key() const { return std::tie(m_object, m_funcHash); }\n};\n\nstd::multimap&lt;Key, FunctionType&gt; m_functions;\n</code></pre>\n\n<p>The whole <code>disconnect</code> function becomes trivial:</p>\n\n<pre><code>template &lt;typename Class&gt;\nvoid disconnect(Class&amp; obj, void (Class::*func)(Params...)) {\n m_functions.erase(Key { &amp;obj, getHash(func) });\n}\n</code></pre>\n\n<h1>Fixed version(s)</h1>\n\n<p>Here's a version that uses the <code>multimap</code> approach (fixing <em>just</em> the style/efficiency issues) <strong><a href=\"http://coliru.stacked-crooked.com/a/55858bdee7561e79\" rel=\"nofollow\">Live On Coliru</a></strong></p>\n\n<hr>\n\n<h3><strong>A more drastic rewrite</strong></h3>\n\n<p>would look like this: <strong><a href=\"http://coliru.stacked-crooked.com/a/df7afbead3712e0b\" rel=\"nofollow\">Live On Coliru</a></strong></p>\n\n<p>This version alters the design so most (if not all) the problems are sidestepped. It uses boost's <code>stable_vector</code> to do a cookie-based design. This moves the burden to track handler identities on the registering parties (where it <em>belongs</em> after all).</p>\n\n<pre><code>#include &lt;functional&gt;\n#include &lt;iostream&gt;\n#include &lt;boost/container/stable_vector.hpp&gt;\n\ntemplate &lt;typename... Params&gt;\nclass Delegate {\nprivate:\n typedef std::function&lt;void(Params...)&gt; Handler;\n typedef boost::container::stable_vector&lt;Handler&gt; Vector;\n Vector m_handlers;\npublic:\n typedef typename Vector::const_iterator cookie;\n\n cookie connect(Handler&amp;&amp; func) {\n m_handlers.push_back(std::move(func));\n return m_handlers.begin() + m_handlers.size() - 1;\n }\n\n template &lt;typename... BindArgs, typename Sfinae = typename std::enable_if&lt;(sizeof...(BindArgs)&gt;1), void&gt;::type&gt;\n cookie connect(BindArgs&amp;&amp;... args) {\n return connect(Handler(std::bind(std::forward&lt;BindArgs&gt;(args)...)));\n }\n\n void disconnect(cookie which) {\n m_handlers.erase(which);\n }\n\n template &lt;typename ... Args&gt; void operator()(Args...args) {\n for(auto const&amp; handler : m_handlers) \n handler(args...);\n }\n};\n\n//////////////////////////////////\n// demonstration\n#define CV volatile const\nstruct BaseClass {\n virtual void print(const std::string&amp; str) CV = 0;\n};\n\nstruct A : BaseClass {\n A() {}\n void print(const std::string&amp; str) CV { std::cout &lt;&lt; \" Class A : Print [\" &lt;&lt; str &lt;&lt; \"]\\n\"; }\n};\n\nstruct B : BaseClass {\n B() {}\n void print(const std::string&amp; str) CV { std::cout &lt;&lt; \" Class B : Print [\" &lt;&lt; str &lt;&lt; \"]\\n\"; }\n};\n\nusing namespace std::placeholders;\n\nint main() {\n Delegate &lt;const std::string&amp;&gt; delegate;\n A CV a;\n B CV b;\n auto acookie = delegate.connect(&amp;A::print, std::ref(a), _1);\n auto bcookie = delegate.connect(&amp;B::print, std::ref(b), _1);\n\n delegate(\"hello\");\n delegate(\"world\");\n\n delegate.disconnect(acookie);\n delegate(\"bye world\");\n\n delegate.disconnect(bcookie);\n delegate(\"nobody there.\"); // should not print anything\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T03:04:20.223", "Id": "59718", "Score": "0", "body": "Oh, and consider exception safety of the handlers. And error handling in case of invalid cookies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T10:07:24.860", "Id": "59724", "Score": "0", "body": "Hey, thanks for a great answer! Really good points on how to improve. The linear search at disconnect was planned actually, as function could have been registered more than once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T12:25:11.160", "Id": "59729", "Score": "0", "body": "Yeah, linear lookup is probably fine for usual numbers of registered handlers. Disconnecting the same more than once is handled (much cleaner) using the `multimap` approach: http://coliru.stacked-crooked.com/a/658e6d086eb2f859. Bear in mind you still need to prevent the problem of abusing the hash for identity" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T15:18:08.197", "Id": "59740", "Score": "0", "body": "@KJS If you insist on a cookie-less/token-less design you can never support lambdas or bind expressions, I think. In that case you still need to do work to allow for const-volatile cases (use sfinae to avoid overload swamp): **[cv_qualified_fix.cpp](http://coliru.stacked-crooked.com/a/0545a9669396bbdb)**. And as that Coliru shows, you will still want to check _properly_ for different ptmf with the same hash. You might add a typeindex to disambiguate: **[disambiguating_fix.cpp](http://coliru.stacked-crooked.com/a/9907526bdbcad642)**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T15:54:48.130", "Id": "59744", "Score": "0", "body": "I'm willing to try solutions that can be implemented with standard library (i'm not currently using boost at all). About the hashing, I was thinking about just checking if this object already has a function registered with that hash, and assert if so. Overall this review contains a lot of new information for me, I'll need to dig in to the details and learn them :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T16:29:13.067", "Id": "59749", "Score": "0", "body": "The thing is, your hash comparison _doesn't_ tell you that. It tells you a handler with the same _hash_ has been registered for the same object. It can still be (legally) the same hash for different `func` -- see e.g. [here](http://stackoverflow.com/q/7968674/85371). This is the nature of hashing: it loses information _by design_" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T16:41:01.780", "Id": "59752", "Score": "0", "body": "Also, I suggest the [disambiguating_fix.cpp](http://coliru.stacked-crooked.com/a/9907526bdbcad642) as it is standard-library only and handles CV-qualified member functions. And here's a standard-library only version of the cookie-based approach [map_cookies.cpp](http://coliru.stacked-crooked.com/a/50a2b91ec72eeb2b)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T06:03:40.257", "Id": "59818", "Score": "0", "body": "disambiguating_fix.cpp is what I was going after, problem with cookie-based approach is that you need to store the cookies somewhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T13:47:23.740", "Id": "60329", "Score": "0", "body": "I am surprised at your implementation of `operator()`, is it intentional not to use universal references and perfect forwarding for the arguments ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T03:46:31.330", "Id": "507542", "Score": "0", "body": "@MatthieuM. very late response: yes, because otherwise we might move multiple times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T09:45:52.120", "Id": "507569", "Score": "0", "body": "@sehe: _Bit_ late, but right on point." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T01:45:10.497", "Id": "36441", "ParentId": "36251", "Score": "3" } } ]
{ "AcceptedAnswerId": "36441", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T21:16:50.540", "Id": "36251", "Score": "3", "Tags": [ "c++", "c++11", "delegates", "pointers" ], "Title": "C++ delegate implementation with member functions" }
36251
<p>Euler problems (projecteuler.net) often invites to quick and dirty solutions. </p> <p>While hurrying through <a href="http://projecteuler.net/problem=32" rel="nofollow">Problem 32</a> I found myself in want of the std:: toolkit. Not sure what it is though.</p> <p>The problem description is included in the first comment.</p> <p>I would really appreciate any suggestions as for the usage of the tools provided by standard c++ (11 if need be, lambdas might make it more succinct/elegant). </p> <pre><code>/* * File: main.cpp * Author: cpt_giraffe * * * We shall say that an n-digit number is pandigital if it makes use of all the * digits 1 to n exactly once; for example, * the 5-digit number, 15234, is 1 through 5 pandigital. * The product 7254 is unusual, as the identity, 39 × 186 = 7254, * containing multiplicand, multiplier, and product is 1 through 9 pandigital. * Find the sum of all products whose multiplicand/multiplier/product * identity can be written as a 1 through 9 pandigital. * HINT: Some products can be obtained in more than one way * so be sure to only include it once in your sum. * Created on November 27, 2013, 9:41 PM */ #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;set&gt; #include &lt;algorithm&gt; #include &lt;numeric&gt; #include &lt;sstream&gt; using namespace std; // store the products, a set is ideal because of the HINT: set&lt;unsigned&gt; products; /** * Insert to products if string arguments is a proper product */ void insert_if_product(string factor1, string factor2, string product) { stringstream values(factor1 + " " + factor2 + " " + product); // is this a valid product. (Most cases says no) unsigned f1, f2, p; values &gt;&gt; f1 &gt;&gt; f2 &gt;&gt; p; if (f1 * f2 == p) { products.insert(p); } } /** * magnitudes needs to add up: I'm checking * 9 digits total * m1 * m3 = m5 * m1 * m4 = m4 * m2 * m3 = m4 * Is this all? * * @param check this permutation */ void check_products(string perm) { // all permutations are coming from perm, so no need to perm stuff here. string factor1 = perm.substr(0, 1); string factor2 = perm.substr(1, 3); string product = perm.substr(4, 5); insert_if_product(factor1, factor2, product); factor1 = perm.substr(0, 1); factor2 = perm.substr(1, 4); product = perm.substr(5, 4); insert_if_product(factor1, factor2, product); factor1 = perm.substr(0, 2); factor2 = perm.substr(2, 3); product = perm.substr(5, 4); insert_if_product(factor1, factor2, product); } int main(int argc, char** argv) { string s = "123456789"; do { check_products(s); } while (next_permutation(s.begin(), s.end())); // Test case if (products.find(7254) != products.end()) { cout &lt;&lt; "found 7254" &lt;&lt; endl; } else { cout &lt;&lt; "did not find 7254" &lt;&lt; endl; } unsigned sum = 0; sum = accumulate(products.begin(), products.end(), 0); cout &lt;&lt; "Sum:" &lt;&lt; sum &lt;&lt; endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T12:09:44.667", "Id": "59442", "Score": "0", "body": "I think, you should add a reference to the original task in your comment. I think it's at least as important as the date and stating that you were the author." } ]
[ { "body": "<ol>\n<li><p>Your conversions are... pretty WTF :)</p>\n\n<pre><code>void insert_if_product(string const&amp; factor1, string const&amp; factor2, string const&amp; product) {\n auto p = std::stoul(product);\n if (std::stoul(factor1, nullptr, 10) * std::stoul(factor2, nullptr, 10) == p) {\n products.insert(p);\n }\n}\n</code></pre>\n\n<p>I mean why use an intermediate stream? Why, if you're using a stream, build it using string <em>concatenation</em>? Also, why pass in copies of read-only strings?!</p></li>\n<li><p>avoid unnecesary allocations:</p>\n\n<pre><code>string factor1 = perm.substr(0, 1);\nstring factor2 = perm.substr(1, 3);\nstring product = perm.substr(4, 5);\n</code></pre>\n\n<p>is gonna do a lot of allocations. Probably more than you'd think. At least, reuse <code>factor1</code>,<code>factor2</code> and <code>product</code> capacities? (My sample below makes them static)</p>\n\n<blockquote>\n <h3><em><strong>Edit</strong> Squeezing a few more drops out:</em></h3>\n</blockquote></li>\n<li><p>avoiding strings in more places avoids the temps from <code>perm.substr()</code>. Now I just directly assign by indices:</p>\n\n<pre><code> factor1.assign(perm.begin()+0, perm.begin()+1);\n factor2.assign(perm.begin()+1, perm.begin()+4);\n product.assign(perm.begin()+4, perm.begin()+9);\n</code></pre></li>\n<li><p>using <code>unordered_set</code> seems to shave off milliseconds on average :)</p></li>\n</ol>\n\n<p>Quick performance comparison (g++ -std=c++11 -march=native -O3`) shows the time taken goes down from ~1.036s to ~0.116s.</p>\n\n<p>So, roughly <strong>8.9x speed</strong> effectively.</p>\n\n<p>Full code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;unordered_set&gt;\n#include &lt;algorithm&gt;\n#include &lt;numeric&gt;\n#include &lt;sstream&gt;\n\n// store the products, a set is ideal because of the HINT:\nstd::unordered_set&lt;unsigned&gt; products;\n\n/**\n * Insert to products if string arguments is a proper product\n */\nvoid insert_if_product(std::string const&amp; factor1, std::string const&amp; factor2, std::string const&amp; product) {\n auto p = std::stoul(product);\n if (std::stoul(factor1, nullptr, 10) * std::stoul(factor2, nullptr, 10) == p) {\n products.insert(p);\n }\n}\n\n/**\n * magnitudes needs to add up: I'm checking \n * 9 digits total\n * m1 * m3 = m5\n * m1 * m4 = m4\n * m2 * m3 = m4\n * Is this all?\n * \n * @param check this permutation\n */\n\nvoid check_products(std::string const&amp; perm)\n{\n static std::string factor1, factor2, product;\n // all permutations are coming from perm, so no need to perm stuff here.\n factor1.assign(perm.begin()+0, perm.begin()+1);\n factor2.assign(perm.begin()+1, perm.begin()+4);\n product.assign(perm.begin()+4, perm.begin()+9);\n\n insert_if_product(factor1, factor2, product);\n\n// factor1.assign(perm.begin()+0, perm.begin()+1);\n factor2.assign(perm.begin()+1, perm.begin()+5);\n product.assign(perm.begin()+5, perm.begin()+9);\n\n insert_if_product(factor1, factor2, product);\n\n factor1.assign(perm.begin()+0, perm.begin()+2);\n factor2.assign(perm.begin()+2, perm.begin()+5);\n// product.assign(perm.begin()+5, perm.begin()+9);\n\n insert_if_product(factor1, factor2, product);\n}\n\nint main() {\n std::string s = \"123456789\";\n\n do {\n check_products(s);\n } while(std::next_permutation(std::begin(s), std::end(s)));\n\n std::cout &lt;&lt; \"Sum:\" &lt;&lt; std::accumulate(products.begin(), products.end(), 0u) &lt;&lt; \"\\n\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T00:46:57.273", "Id": "59378", "Score": "1", "body": "**updated** now 8x faster, `check_products` back as a free function (better IMO). Also, note subtle things like `0u` in the `accumulate` call!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T21:48:24.937", "Id": "59512", "Score": "0", "body": "And thank you for your time and insights sehe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T23:22:53.987", "Id": "59710", "Score": "1", "body": "Oh hey, shaved off another 15% after _actually looking at the indices :)_. Now ~8.9x faster :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T00:08:11.217", "Id": "36258", "ParentId": "36252", "Score": "7" } } ]
{ "AcceptedAnswerId": "36258", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T21:38:28.440", "Id": "36252", "Score": "1", "Tags": [ "c++", "c++11", "project-euler" ], "Title": "Euler problem c++ / std::library usage" }
36252
<p>I have a Combobox and I want to edit a boolean value.</p> <pre><code> &lt;dxe:ComboBoxEdit ItemsSource="{Binding EnumItemsSource}" DisplayMember="Name" ValueMember="Id" IsTextEditable="False" EditValue="{Binding TargetValue, UpdateSourceTrigger=PropertyChanged}"/&gt; </code></pre> <p>My ViewModel:</p> <pre><code> /// &lt;summary&gt; /// Contains the ItemsSource for Enums /// &lt;/summary&gt; public List&lt;EnumItemObject&gt; EnumItemsSource { get { return _enumItemsSource; } set { _enumItemsSource = value; OnPropertyChanged(); } } public class EnumItemObject { public int Id {get;set;} public string Name {get;set;} } </code></pre> <p>And I prepare the data for the Combobox ItemsSource that:</p> <pre><code> /// &lt;summary&gt; /// Sets the value to the properties for the BitTemplate view. (similar with EnumTemplate) /// &lt;/summary&gt; /// &lt;param name="propertyInfo"&gt;a boolean property&lt;/param&gt; private void PrepareDataForBitTemplate(PropertyInfo propertyInfo) { TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem); EnumItemsSource = new List&lt;EnumItemObject&gt;(); EnumItemsSource.Add(new EnumItemObject() { Id = 0, Name = "Nein" }); EnumItemsSource.Add(new EnumItemObject() { Id = 1, Name = "Ja" }); } </code></pre> <p>Is it the approach correct? Is there any easier solution?</p> <p><strong>UPDATE:</strong> Extract from my ViewModel code (you remember EnumItemsSource is ItemsSource for Combobox and TargetValue the Combobox selected item):</p> <pre><code> private void LookUpViewData() { var propertyInfo = _firstSelectedItem.GetType().GetProperty(TargetFieldDescription.fdBigViewColumnName); if ((propertyInfo != null) &amp;&amp; (propertyInfo.GetValue(_firstSelectedItem) != null)) { if ((int) FieldDataType.ENum == TargetFieldDescription.fdDataType) PrepareDataForEnumTemplate(propertyInfo); if ((int) FieldDataType.Bit == TargetFieldDescription.fdDataType) PrepareDataForBitTemplate(propertyInfo); // like EnumTemplate else if ((int) FieldDataType.Time == TargetFieldDescription.fdDataType) PrepareDataForTimeTemplate(propertyInfo); else PrepareDataForDefaultTemplate(propertyInfo); } else TargetValue = String.Empty; } private void PrepareDataForEnumTemplate(PropertyInfo propertyInfo) { TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem); if (_targetFieldDescription.fdEnumSource != null) { switch (_targetFieldDescription.fdEnumSource) { case "Station": EnumItemsSource = ConvertListToEnumItemObjectList(_targetFieldDescription.fdEnumSource); break; default: EnumItemsSource = EnumUtil.ConvertEnumToEnumItemObjectList(_targetFieldDescription.fdEnumSource); break; } } } private void PrepareDataForBitTemplate(PropertyInfo propertyInfo) { var value = propertyInfo.GetValue(_firstSelectedItem); bool bValue; if (value == null) TargetValue = 0; else if (bool.TryParse(value.ToString(), out bValue)) TargetValue = (bValue) ? 1 : 0; else TargetValue = 0; //TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem); var bitItems = new List&lt;EnumItemObject&gt;(); bitItems.Add(new EnumItemObject { Id = 0, Name = "Nein" }); bitItems.Add(new EnumItemObject { Id = 1, Name = "Ja" }); EnumItemsSource = bitItems; } </code></pre> <p>So I want to load three possible kind of data in my Combobox. Enums, List of Objects (with name and id) and booleans (Yes/No List).</p>
[]
[ { "body": "<p>It's not clear <em>where</em> this <code>PrepareDataForBitTemplate(PropertyInfo)</code> method is located. Is it code-behind? Whatever it is, if the goal is to bind a <em>ComboBox</em> with some enum values, I would much rather keep it standard - meaning the <code>DataContext</code> of the <em>ComboBox</em> is the <em>ViewModel</em> of the containing <code>Window</code> or <code>UserControl</code>:</p>\n\n\n\n<pre><code>public IEnumerable&lt;SomeEnumType&gt; ViewModelEnumValues\n{\n get { return Enum.GetValues(typeof(SomeEnumType)).Cast&lt;SomeEnumType&gt;(); }\n}\n\nprivate SomeEnumType _selectedEnumValue;\npublic SomeEnumType SelectedEnumValue\n{\n get { return _selectedEnumValue; }\n set { _selectedEnumValue = value; NotifyPropertyChanged(() =&gt; SelectedEnumValue); }\n}\n</code></pre>\n\n<p>Before I move on to the corresponding XAML markup, a few observations:</p>\n\n<ul>\n<li>The <em>ViewModel</em> implementation derives from some <code>ViewModelBase</code> abstract class which implements <code>INotifyPropertyChanged</code> and allows its derivatives to specify a property name in a strongly-typed way. I see your setter calls some <code>OnPropertyChanged()</code> method, but not how that method is able to notify the <em>View</em> that a <em>specific property</em> was changed.</li>\n<li>The name <code>Enum</code> refers to a <em>specific language construct</em>. Calling something \"Enum\" when that something <strong>is not an enum</strong> is rather confusing.</li>\n<li>I don't see why you're not using an actual <code>enum</code> when the values you're trying to load are basically \"Yes\" and \"No\".</li>\n<li><code>EnumItemObject</code> is an awful name, for several reasons:\n<ol>\n<li>It's not an <em>object</em>, it's a <em>class</em> - an <em>object</em> is an <em>instance</em> of a <em>class</em>.</li>\n<li>It's not an <em>enum item</em>, it's essentially a <em>ViewModel</em> that exposes two properties - an <code>int</code> and a <code>string</code>.</li>\n<li>It's not immediately apparent how this class relates to any type of enum.</li>\n</ol></li>\n</ul>\n\n<p>Now, given that your <em>ViewModel</em> exposes the above <code>SelectedEnumValue</code> and <code>ViewModelEnumValues</code> properties (both bad/stub names), with a ValueConverter the XAML for the ComboBox would be as simple as this:</p>\n\n\n\n<pre><code>&lt;ComboBox ItemSource=\"{Binding ViewModelEnumValues}\"\n SelectedItem=\"{Binding SelectedEnumValue, Mode=TwoWay}\"&gt;\n &lt;ComboBox.ItemTemplate&gt;\n &lt;DataTemplate&gt;\n &lt;Border Style=\"{StaticResource ListItemBorder}\"&gt; &lt;!-- just some border --&gt;\n &lt;StackPanel&gt;\n &lt;Image Source=\"{Binding Value, Converter={StaticResource EnumValueIconConverter}}\" /&gt;\n &lt;Label Content=\"{Binding Value, Converter={StaticResource EnumValueNameConverter}}\" /&gt;\n &lt;/StackPanel&gt;\n &lt;/Border&gt;\n &lt;/DataTemplate&gt;\n &lt;/ComboBox.ItemTemplate&gt;\n&lt;/ComboBox&gt;\n</code></pre>\n\n<p>And the converters would look like this:</p>\n\n<pre><code>using resx = Project.Properties.Resources; \n\npublic class EnumValueToStringConverter : ConverterBase\n{\n public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n SomeEnumType result;\n return Enum.TryParse(value.ToString(), out result)\n ? resx.ResourceManager.GetString(promoType + \"Caption\")\n : string.Empty;\n }\n}\n\npublic class EnumValueToIconConverter : ConverterBase\n{\n public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n var result = string.Empty;\n var typedValue = value As SomeEnumType;\n if (typedValue != null)\n {\n switch(typedValue)\n {\n case SomeEnumType.EnumValue1:\n result = \"images/image-for-value1.png\";\n break;\n case SomeEnumType.EnumValue2:\n result = \"images/image-for-value2.png\";\n break;\n }\n }\n\n return new BitmapImage(new Uri(\"/project.namespace;component/\" + result, UriKind.Relative));\n }\n}\n</code></pre>\n\n<p>Of course this is overkill if all you want is the enum <em>names</em> in your dropdown list - but I tend to define a <code>DataTemplate</code> for just about everything (and I think I have a tendency to abuse converters, too).</p>\n\n<p>If all you need is to display an enum value directly in the UI, then this will suffice:</p>\n\n\n\n<pre><code>public IEnumerable&lt;string&gt; ViewModelEnumNames\n{\n get { return Enum.GetNames(typeof(SomeEnumType)).ToList(); }\n}\n\nprivate string _selectedEnumName;\npublic string SelectedEnumName\n{\n get { return _selectedEnumName; }\n set { _selectedEnumName = value; NotifyPropertyChanged(() =&gt; SelectedEnumName); }\n}\n</code></pre>\n\n\n\n<pre><code>&lt;ComboBox ItemSource=\"{Binding ViewModelEnumNames}\"\n SelectedItem=\"{Binding SelectedEnumName, Mode=TwoWay}\"&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T09:18:20.010", "Id": "59420", "Score": "0", "body": "Hello retailcoder, thanks for your support. Your opinion is very interesting, thanks. \n\nPrepareDataForBitTemplate is a function located in my ViewModel. But one question. I do an update in my post. I want to be able to load in this Combobox not only enums. Also list of Stations, list of countries, list of enumvalues, list with Yes/No.\nHow can I design the property public IEnumerable<SomeEnumType> ViewModelEnumValues to achieve this? Your solution is based only for enums, but my combobox should load list of objects and be able to update also boolean values. Pls take a look at my update above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T11:44:08.680", "Id": "59437", "Score": "0", "body": "See the 2nd example; all the combobox needs is any `IEnumerable`, *how* the displayable data ends up there is irrelevant to the *view* (could be your *model*'s concern) - for full-fledged objects all you need is a data template. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T02:42:04.037", "Id": "36263", "ParentId": "36255", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T23:03:34.190", "Id": "36255", "Score": "3", "Tags": [ "c#", "wpf", "xaml" ], "Title": "WPF Load boolean values in combobox" }
36255
<p>I have to do a task hard for me and maybe you can help me. I've tried to design a window dialog to update data from a database view. This database view contains integer, DateTime, string, Time, Boolean properties. </p> <p>First of all, I load the database view data into a <code>GridControl</code>. The <code>GridControl</code> is <code>readonly</code> not editable. I configure the columns of my <code>GridControl</code> dynamically and this configuration is located in a database table called <code>FieldDescription</code>. </p> <p>When the end-user doubleclicks on a cell, this window dialog pops up. This dialog shows a <code>Combobox</code> when the type of the column is <code>enum</code> or bit (<code>boolean</code>) and otherwise a <code>TextEdit</code> as default content.Notice for example that I know that a <code>GridColumn</code> represents an <code>enum</code> type because of the <code>FieldDescription</code>. Because the type of this database view property bound to this <code>GridColumn</code> is an integer (specifically the value)</p> <p>The code of this window dialog is (I use DevExpress controls):</p> <pre class="lang-xaml prettyprint-override"><code> &lt;!-- DataTemplates --&gt; &lt;DataTemplate x:Key="DefaultTemplate"&gt; &lt;dxe:TextEdit Name="TxtNewValue" Grid.Column="0" Margin="0" HorizontalAlignment="Stretch" Text="{Binding TargetValue, UpdateSourceTrigger=PropertyChanged}" Mask="{Binding TargetFieldDescription.fdValidateExp}" Loaded="FocusTextEditOnLoad"/&gt; &lt;DataTemplate.Triggers&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.Date}"&gt; &lt;Setter TargetName="TxtNewValue" Property="MaskType" Value="DateTime" /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.DatTime}"&gt; &lt;Setter TargetName="TxtNewValue" Property="MaskType" Value="DateTime" /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.Time}"&gt; &lt;Setter TargetName="TxtNewValue" Property="MaskType" Value="RegEx" /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.Num}"&gt; &lt;Setter TargetName="TxtNewValue" Property="MaskType" Value="RegEx" /&gt; &lt;/DataTrigger&gt; &lt;/DataTemplate.Triggers&gt; &lt;/DataTemplate&gt; &lt;DataTemplate x:Key="ComboboxTemplate"&gt; &lt;dxe:ComboBoxEdit ItemsSource="{Binding EnumItemsSource}" DisplayMember="Name" ValueMember="Id" IsTextEditable="False" EditValue="{Binding TargetValue, UpdateSourceTrigger=PropertyChanged}"/&gt; &lt;/DataTemplate&gt; &lt;!-- Select a Datatemplate depending on the type of the Enum FieldDataType--&gt; &lt;DataTemplate DataType="{x:Type massedit:SimpleFieldVM}"&gt; &lt;ContentControl Content="{Binding .}"&gt; &lt;ContentControl.Style&gt; &lt;Style TargetType="{x:Type ContentControl}"&gt; &lt;Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" /&gt; &lt;Style.Triggers&gt; &lt;!-- Without selector, only with DataTriggers select my ContentControl --&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.ENum}"&gt; &lt;Setter Property="ContentTemplate" Value="{StaticResource ComboboxTemplate}" /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.Bit}"&gt; &lt;Setter Property="ContentTemplate" Value="{StaticResource ComboboxTemplate}" /&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ContentControl.Style&gt; &lt;/ContentControl&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;!-- Layout --&gt; &lt;Grid x:Name="LayoutRoot" VerticalAlignment="Center"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="20"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;ContentControl Name="MainLayout" Content="{Binding}" /&gt; &lt;/Grid&gt; </code></pre> <p>I have only one <code>ViewModel</code> to provide the values to this Dialog Window. My <code>ViewModel</code> has an <code>enum FieldDataType</code> property called <code>TargetFieldType</code>. It contains the type of the doubleclicked <code>GridColumn</code>. This value is an <code>enum</code> (<code>FieldDataType.DatTime</code>, <code>FieldDataType.Time</code>, <code>FieldDataType.Date</code>, <code>FieldDataType.Bit</code>, <code>FieldDataType.Num</code>, <code>FieldDataType.Enum</code>, <code>FieldDataType.String</code>).</p> <p>The <code>ItemsSource</code> of the <code>ComboBox</code> is bound with the <code>ViewModel</code> property:</p> <pre class="lang-xaml prettyprint-override"><code>public List&lt;EnumItemObject&gt; EnumItemsSource </code></pre> <p>Depending on the type of the column I prepare the data and I convert an <code>enum</code> of my model, in <code>List&lt;EnumItemObject&gt;</code>, a<code>boolean</code> property also in <code>List&lt;EnumItemObject&gt;</code>(Yes, No). But my <code>ViewModel</code> has to prepare the data depending on the <code>FieldDataType</code>. Maybe I can do more things in the XAML code to save a lot of code to prepare the provided data to my view, or separating my current <code>ViewModel</code> into multiple <code>ViewModel</code>s, to do this clearly.</p> <p>It is difficult to explain the whole task but maybe you can help and tell me if my approach is correct or too difficult. I hope you understand what I mean.</p> <p>XAML code:</p> <p></p> <pre class="lang-xaml prettyprint-override"><code>&lt;!-- DataContext definition --&gt; &lt;Window.DataContext&gt; &lt;massedit:SimpleFieldVM/&gt; &lt;/Window.DataContext&gt; &lt;!-- Behaviors --&gt; &lt;i:Interaction.Behaviors&gt; &lt;behavior:WindowBehavior x:Name="WindowBehavior" OnOk="{Binding DoOnOk}" OnCancel="{Binding DoOnCancel}"/&gt; &lt;/i:Interaction.Behaviors&gt; &lt;!-- Resources --&gt; &lt;Window.Resources&gt; &lt;!-- DataTemplates --&gt; &lt;DataTemplate x:Key="DefaultTemplate"&gt; &lt;dxe:TextEdit Name="TxtNewValue" Grid.Column="0" Margin="0" HorizontalAlignment="Stretch" Text="{Binding TargetValue, UpdateSourceTrigger=PropertyChanged}" Mask="{Binding TargetFieldDescription.fdValidateExp}" Loaded="FocusTextEditOnLoad"/&gt; &lt;DataTemplate.Triggers&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.Date}"&gt; &lt;Setter TargetName="TxtNewValue" Property="MaskType" Value="DateTime" /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.DatTime}"&gt; &lt;Setter TargetName="TxtNewValue" Property="MaskType" Value="DateTime" /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.Time}"&gt; &lt;Setter TargetName="TxtNewValue" Property="MaskType" Value="RegEx" /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.Num}"&gt; &lt;Setter TargetName="TxtNewValue" Property="MaskType" Value="RegEx" /&gt; &lt;/DataTrigger&gt; &lt;/DataTemplate.Triggers&gt; &lt;/DataTemplate&gt; &lt;DataTemplate x:Key="ComboboxTemplate"&gt; &lt;dxe:ComboBoxEdit ItemsSource="{Binding EnumItemsSource}" DisplayMember="Name" ValueMember="Id" IsTextEditable="False" EditValue="{Binding TargetValue, UpdateSourceTrigger=PropertyChanged}"/&gt; &lt;/DataTemplate&gt; &lt;!-- Select a Datatemplate depending on the type of the Enum FieldDataType--&gt; &lt;DataTemplate DataType="{x:Type massedit:SimpleFieldVM}"&gt; &lt;ContentControl Content="{Binding .}"&gt; &lt;ContentControl.Style&gt; &lt;Style TargetType="{x:Type ContentControl}"&gt; &lt;Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" /&gt; &lt;Style.Triggers&gt; &lt;!-- Without selector, only with DataTriggers select my ContentControl --&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.ENum}"&gt; &lt;Setter Property="ContentTemplate" Value="{StaticResource ComboboxTemplate}" /&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding TargetFieldType}" Value="{x:Static eva:FieldDataType.Bit}"&gt; &lt;Setter Property="ContentTemplate" Value="{StaticResource ComboboxTemplate}" /&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ContentControl.Style&gt; &lt;/ContentControl&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;!-- Layout --&gt; &lt;Grid x:Name="LayoutRoot" VerticalAlignment="Center"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="20"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;ContentControl Name="MainLayout" Content="{Binding}" /&gt; &lt;dx:UniformStackPanel Grid.Column="1" Orientation="Vertical" ChildSpacing="0"&gt; &lt;Button Command="{Binding ElementName=WindowBehavior, Path=OnCancelCommand}" Width="18" Height="18" Padding="-1" Background="Transparent" BorderBrush="Transparent"&gt; &lt;Button.Content&gt; &lt;Image Source="../images/cancel-16x16.png"/&gt; &lt;/Button.Content&gt; &lt;/Button&gt; &lt;Button Command="{Binding ElementName=WindowBehavior, Path=OnOkCommand}" Width="18" Height="18" Padding="-1" Background="Transparent" BorderBrush="Transparent"&gt; &lt;Button.Content&gt; &lt;Image Source="../images/ok-16x16.png"/&gt; &lt;/Button.Content&gt; &lt;/Button&gt; &lt;/dx:UniformStackPanel&gt; &lt;/Grid&gt; </code></pre> <p></p> <p><code>ViewModel</code> code:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using DevExpress.Data.Filtering; using DevExpress.Xpo; using DevExpress.Xpo.DB; using EVA.Types; using Model.Eva; using Model.Eva.EvaDataModelCode; using Utilities.Eva; namespace EVAGui.MassEdit { /// &lt;summary&gt; /// ViewModel for view SimpleFieldDialog. Provides values that need the view. (From this view can be edited simple types /// (uses defaulttemplate and Enumtemplate) ) /// &lt;/summary&gt; public class SimpleFieldVM : NotificationObject { #region properties private Action _doOnOk; private Action _doOnCancel; private object _targetValue; private List&lt;EnumItemObject&gt; _enumItemsSource; private IList&lt;DbvBigView&gt; _selectedItems; private DbvBigView _firstSelectedItem; private DbFieldDescription _targetFieldDescription; /// &lt;summary&gt; /// Action is executed when button ok is clicked /// &lt;/summary&gt; public Action DoOnOk { get { return _doOnOk; } set { _doOnOk = value; OnPropertyChanged(); } } /// &lt;summary&gt; /// Action is executed when button cancel is clicked /// &lt;/summary&gt; public Action DoOnCancel { get { return _doOnCancel; } set { _doOnCancel = value; OnPropertyChanged(); } } /// &lt;summary&gt; /// Contains the new value to be saved in database /// &lt;/summary&gt; public object TargetValue { get { return _targetValue; } set { _targetValue = value; OnPropertyChanged(); } } /// &lt;summary&gt; /// Contains the enum value of the kind of type of the field that should be edited /// &lt;/summary&gt; public FieldDataType TargetFieldType { get; set; } /// &lt;summary&gt; /// Contains the ItemsSource for Enums /// &lt;/summary&gt; public List&lt;EnumItemObject&gt; EnumItemsSource { get { return _enumItemsSource; } set { _enumItemsSource = value; OnPropertyChanged(); } } /// &lt;summary&gt; /// Contains the field description of the property of BigView that is being edited /// &lt;/summary&gt; public DbFieldDescription TargetFieldDescription { get { return _targetFieldDescription; } set { _targetFieldDescription = value; if (_targetFieldDescription != null) TargetFieldType = (FieldDataType)_targetFieldDescription.fdDataType; else TargetFieldType = FieldDataType.None; } } /// &lt;summary&gt; /// Selected elements in the MassEditGrid /// &lt;/summary&gt; public IList&lt;DbvBigView&gt; SelectedItems { get { return _selectedItems; } set { _selectedItems = value; if (_selectedItems.Any()) FirstSelectedItem = _selectedItems.ToList()[0]; } } /// &lt;summary&gt; /// Contains the first selected element. In this view is displayed the data of the first element and /// will be applied to all selected items /// &lt;/summary&gt; protected DbvBigView FirstSelectedItem { get { return _firstSelectedItem; } set { _firstSelectedItem = value; if (_firstSelectedItem != null &amp;&amp; TargetFieldDescription != null) LookUpViewData(); } } #endregion #region constructor /// &lt;summary&gt; /// constructor of this ViewModel. Defines the delegate for Ok Action (save changes) /// Ok Action will save the changes in Database /// &lt;/summary&gt; public SimpleFieldVM() { DoOnOk = () =&gt; DbvBigViewUtils.SaveSimpleData(SelectedItems, TargetFieldDescription, TargetValue); //DoOnOk = () =&gt; PersistentDataManager.SaveData(); } #endregion /// &lt;summary&gt; /// Initializes the ViewModel with the FieldDescription of the field that will be updated and the selected BidView elements in MassEditView /// before this dialog pops up /// &lt;/summary&gt; /// &lt;param name="items"&gt;Selected BigView elements in MassEditView&lt;/param&gt; /// &lt;param name="fieldDescription"&gt;FieldDescription of the current field&lt;/param&gt; public void InitializeModelView(IList&lt;DbvBigView&gt; items, DbFieldDescription fieldDescription) { TargetFieldDescription = fieldDescription; SelectedItems = items; } /// &lt;summary&gt; /// Loads the data to be displayed in the view /// &lt;/summary&gt; private void LookUpViewData() { var propertyInfo = _firstSelectedItem.GetType().GetProperty(TargetFieldDescription.fdBigViewColumnName); if ((propertyInfo != null) &amp;&amp; (propertyInfo.GetValue(_firstSelectedItem) != null)) { if ((int) FieldDataType.ENum == TargetFieldDescription.fdDataType) PrepareDataForEnumTemplate(propertyInfo); if ((int) FieldDataType.Bit == TargetFieldDescription.fdDataType) PrepareDataForBitTemplate(propertyInfo); // like EnumTemplate else if ((int) FieldDataType.Time == TargetFieldDescription.fdDataType) PrepareDataForTimeTemplate(propertyInfo); else PrepareDataForDefaultTemplate(propertyInfo); } else TargetValue = String.Empty; } /// &lt;summary&gt; /// Sets the value to the properties for the DefaultTemplate view /// &lt;/summary&gt; /// &lt;param name="propertyInfo"&gt;&lt;/param&gt; private void PrepareDataForTimeTemplate(PropertyInfo propertyInfo) { var value = propertyInfo.GetValue(_firstSelectedItem); var converter = new ConvertTimeDisplay(); TargetValue = converter.Convert(value, null, null, null); } /// &lt;summary&gt; /// Sets the value to the properties for the BitTemplate view. (similar with EnumTemplate) /// &lt;/summary&gt; /// &lt;param name="propertyInfo"&gt;a boolean property&lt;/param&gt; private void PrepareDataForBitTemplate(PropertyInfo propertyInfo) { TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem); EnumItemsSource = new List&lt;EnumItemObject&gt;(); EnumItemsSource.Add(new EnumItemObject() { Id = 0, Name = "Nein" }); EnumItemsSource.Add(new EnumItemObject() { Id = 1, Name = "Ja" }); } /// &lt;summary&gt; /// Sets the value to the properties for the DefaultTemplate view /// &lt;/summary&gt; /// &lt;param name="propertyInfo"&gt;&lt;/param&gt; private void PrepareDataForDefaultTemplate(PropertyInfo propertyInfo) { TargetValue = propertyInfo.GetValue(_firstSelectedItem).ToString(); } /// &lt;summary&gt; /// Sets the value to the properties for the EnumTemplate view /// &lt;/summary&gt; /// &lt;param name="propertyInfo"&gt;&lt;/param&gt; private void PrepareDataForEnumTemplate(PropertyInfo propertyInfo) { TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem); if (_targetFieldDescription.fdEnumSource != null) { switch (_targetFieldDescription.fdEnumSource) { case "Station": EnumItemsSource = ConvertListToEnumItemObjectList(_targetFieldDescription.fdEnumSource); break; default: EnumItemsSource = EnumUtil.ConvertEnumToEnumItemObjectList(_targetFieldDescription.fdEnumSource); break; } } } /// &lt;summary&gt; /// Returns a list of EnumItemObjects from a collection /// &lt;/summary&gt; /// &lt;param name="fdEnumSource"&gt;Type of objects to be converted in EnumItemObjects&lt;/param&gt; /// &lt;returns&gt;The list of EnumItemObjects&lt;/returns&gt; private List&lt;EnumItemObject&gt; ConvertListToEnumItemObjectList(string fdEnumSource) { switch (fdEnumSource) { case "Station": return new XPCollection&lt;DbStation&gt;(EvaApplication.App.MainUnitOfWork, CriteriaOperator.Parse("1=1"), new[] { new SortProperty("stExternalID", SortingDirection.Ascending) }). Select(s=&gt; new EnumItemObject(){Id=s.stID, Name = s.stGVLsysName}). ToList(); default: return null; } } } } </code></pre>
[]
[ { "body": "<p>I think Controls related code should be in XAML. Ideally in MVVM pattern we provide property values in our viewmodel. But how those property will be displayed is define by XAML. You have told that you are using DevExpress Controls. I have not explored DevExpress Controls, but I bet Gridview available from DevExpress should have different options that you should be able to configure in XAML file.</p>\n\n<p>I will tell you about Telerik Grid(hope it helps). In Telerik Grid we can set how the look and file of Grid columns should be in read only mode and how it should be in editable mode. On similar line you can give a try to solve your business problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T16:31:31.380", "Id": "59479", "Score": "1", "body": "could you provide some examples?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T14:46:43.390", "Id": "36292", "ParentId": "36256", "Score": "0" } }, { "body": "<h2>ViewModel</h2>\n<p>IMHO <code>#region</code> should be banned; if you <em>need</em> to split your class in regions, it's probably doing too many things. If you <em>need</em> to split a method in regions, it's <em>definitely</em> doing too many things.</p>\n<p>Maybe it's just me, but I like seeing the class' constructor as the first thing in the class - with the only possible exception of some <code>private readonly</code> fields, constructor-injected.</p>\n<p>Your <code>#region properties</code> includes private fields. I would simply put the backing field close to the property it's backing:</p>\n<pre><code>private object _targetValue;\n\n/// &lt;summary&gt;\n/// Contains the new value to be saved in database\n/// &lt;/summary&gt;\npublic object TargetValue\n{\n get { return _targetValue; }\n set\n {\n _targetValue = value;\n OnPropertyChanged();\n }\n}\n</code></pre>\n<p>I've never used <code>NotificationObject</code>, but from what I've just read on MSDN it's implementing <code>INotifyPropertyChanged</code>, and by <em>not specifying</em> which property has changed I believe you are invalidating your entire <em>ViewModel</em>, which I find is inefficient - the end result might be the same, but depending on how complex your <em>View</em> is this could mean <em>lots</em> of redundant/useless updates. If <code>TargetValue</code> was modified, notify a change on the <code>TargetValue</code> property.</p>\n<p>I think your <code>Action</code> delegates shouldn't start with &quot;do&quot; - they're <em>actions</em>, of course they <em>do</em> something! Given you called them <code>DoOnOk</code> and <code>DoOnCancel</code>, I'd rename them <code>OnOkAction</code> and <code>OnCancelAction</code>.</p>\n<p>Your <code>DbvBigViewUtils</code> has a bad smell. It's a <code>static</code> <em>ambient context</em> dependency that's <em>tightly coupled</em> with your <em>ViewModel</em>, which means if you were to try and write unit tests for your class, you would have no way of mocking that dependency and fully controlling your class' behavior.</p>\n<hr />\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T05:51:14.710", "Id": "36397", "ParentId": "36256", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T23:08:41.050", "Id": "36256", "Score": "6", "Tags": [ "c#", "wpf", "mvvm", "xaml" ], "Title": "WPF Window with different DataTemplates" }
36256
<p>Below is my java code with some complexity,</p> <pre><code>String input; double a; if (null != input &amp;&amp; !input.isEmpty()) { a = Double.parseDouble(input); } else { a = defaultValue; } </code></pre> <p>With Guava, we can compress the code from 5 lines into a 'single' line,</p> <pre><code>a = Double.parseDouble( Objects.firstNonNull(Strings.emptyToNull(input), defaultValue) ); </code></pre> <p>The complexity is reduced but readability is getting worst. Any comment on improving readability at the same time reducing complexity?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T09:52:10.247", "Id": "59424", "Score": "0", "body": "What do you want to happen, if the input is not a valid `double`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T02:07:58.820", "Id": "59801", "Score": "0", "body": "Thanks for pointing out, but I am afraid it is not within the scope of this question." } ]
[ { "body": "<p>This is a 'specialized' task, converting an input string to a double value. Whenever I have micro-tasks like this I try to refactor them in to a method which does things <strong>properly</strong>.</p>\n\n<p>As far as I am concerned, neither of the above two systems are valid. You should be validating the input value to make sure that, even if it <strong>is</strong> populated with a value, that the value is meaningful, and the parse succeeds.</p>\n\n<p>So, I would have a function:</p>\n\n<pre><code>private static final double inputToDouble(String input, double defaultval) {\n if (input == null || input.isEmpty()) {\n // clear out the obviusly invalid values\n return defaultval;\n }\n try {\n return Double.parseDouble(input.trim());\n } catch (NumberFormatException nfe) {\n // silently ignore invalid data, and return the default value\n return defaultval;\n }\n}\n</code></pre>\n\n<p>Sure, the above may be a bit more complicated, but, using it is a charm....</p>\n\n<pre><code>a = inputToDouble(input, defaultValue);\n</code></pre>\n\n<p>Sometimes applications do this sort of thing a lot, and in those cases I centralize these micro-tasks to static classes like:</p>\n\n<pre><code>public final class InputUtils {\n private InputUtils() {\n // nothing\n }\n\n public static final double inputToDouble(......) {....};\n\n .....\n\n}\n</code></pre>\n\n<p>And then you can reference these micro-tasks from many places, perhaps even doing a static import on the class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T02:29:46.100", "Id": "36262", "ParentId": "36261", "Score": "4" } } ]
{ "AcceptedAnswerId": "36262", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T02:20:17.207", "Id": "36261", "Score": "4", "Tags": [ "java", "complexity" ], "Title": "Using Guava to reduce code complexity (and possibiliy to improve readability) of null check and assign default value" }
36261
<p>A little while ago I was fiddling with <a href="/questions/tagged/dependency-injection" class="post-tag" title="show questions tagged &#39;dependency-injection&#39;" rel="tag">dependency-injection</a> and came up with this small WPF application that I can launch with command-line arguments.</p> <p>Not only this was my first experiment with DI, it was also my first experiment with parsing command-line arguments. The result works nicely, but looking at the code today I see a number of things I would have done differently.</p> <p><strong>What would <em>you</em> have done differently?</strong></p> <p>Looking mainly for feedback on readability and maintainability.</p> <hr> <p>I have an interface/class that exposes getters for all <em>possible</em> command-line arguments; the implementation's constructor uses Ninject's <code>InjectAttribute</code> to specify the required <code>ICommandLineArg</code> implementation to receive:</p> <pre><code>public class AutoBuildCommandLineHelper : IAutoBuildCommandLineArgs { public ICommandLineArg QuietInterfaceArgument { get; private set; } public ICommandLineArg BuildServerArgument { get; private set; } public ICommandLineArg CompletionMessageArgument { get; private set; } public ICommandLineArg LoggingDisabledArgument { get; private set; } public ICommandLineArg FailureNotificationOnlyArgument { get; private set; } public AutoBuildCommandLineHelper([QuietInterfaceArg] ICommandLineArg quietInterfaceArg, [BuildServerArg] ICommandLineArg buildServerArg, [NoLogArg] ICommandLineArg noLogArg, [MessageArg] ICommandLineArg msgArg, [FailureNotifyArg] ICommandLineArg failArg) { QuietInterfaceArgument = quietInterfaceArg; BuildServerArgument = buildServerArg; LoggingDisabledArgument = noLogArg; CompletionMessageArgument = msgArg; FailureNotificationOnlyArgument = failArg; } } </code></pre> <hr> <p>Here are a couple <code>ICommandLineArg</code> implementations:</p> <pre><code>public class QuietInterfaceArgument : CommandLineArgumentBase { public QuietInterfaceArgument(string[] args) : base(args, "q", "quiet") { } } public class NoLoggingArgument : CommandLineArgumentBase { public NoLoggingArgument(string[] args) : base(args, "n", "nolog") { } } </code></pre> <p>As you see there's really nothing going on here - this is the base class:</p> <pre><code>public abstract class CommandLineArgumentBase : ICommandLineArg { private readonly string[] _args; private const char ParamSpecifier = ':'; private readonly char[] _switches = { '-', '/' }; public string Name { get; private set; } public string Alias { get; private set; } public bool MustHaveParameter { get; private set; } protected CommandLineArgumentBase(string[] args, string name, string alias) : this(args, name, alias, false) { } protected CommandLineArgumentBase(string[] args, string name, string alias, bool mustHaveParam) { _args = args; Name = name; Alias = alias; MustHaveParameter = mustHaveParam; } public virtual string ParameterValue() { if (!IsSpecified()) throw new InvalidOperationException(); var arg = GetArgument(); var values = arg.Split(ParamSpecifier); if (MustHaveParameter &amp;&amp; values.Length == 1) throw new InvalidOperationException(); return values[1].TrimStart('"').TrimEnd('"'); } private string GetArgument() { if (!IsSpecified()) throw new InvalidOperationException(); return _args.Single(arg =&gt; new[] {Name, Alias}.Contains(TrimArgument(arg).Split(ParamSpecifier)[0])); } private string TrimArgument(string arg) { return arg.TrimStart(_switches).TrimEnd(_switches); } public bool IsSpecified() { return _args.Select(arg =&gt; arg.Split(ParamSpecifier)[0]) .Select(TrimArgument) .Contains(Name) || _args.Any(arg =&gt; TrimArgument(arg).StartsWith(Name)); } } </code></pre> <hr> <p>This "thing" is used in <code>Program.cs</code> / <code>Main()</code>, like this:</p> <pre><code> if (argsHelper.LoggingDisabledArgument.IsSpecified()) logProvider.DisableLogging(); if (argsHelper.QuietInterfaceArgument.IsSpecified() || argsHelper.BuildServerArgument.IsSpecified()) { // running with -quiet or -build command-line switches: just execute and exit. autoBuildApp.Execute(); } else { // run with UI: var app = new App(autoBuildApp); app.Run(); } </code></pre> <p>I like that arguments are strongly-typed and all I need to do to check if they're specified, is to call <code>.IsSpecified()</code> - the flipside is that to achieve this I'm passing the <code>args</code> string everywhere, so it gets "parsed" <em>every time</em>.</p> <p><strong>Thoughts?</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T06:37:22.727", "Id": "59394", "Score": "0", "body": "Forgive me if this is a dumb question but should the `[QuietInterfaceArg]` part of `[QuietInterfaceArg] ICommandLineArg quietInterfaceArg` instead be `[QuietInterfaceArgument]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T12:44:33.123", "Id": "59446", "Score": "1", "body": "@JamesKhoury That still wouldn't work, attributes have to derive from `Attribute`. Which means that there has to be a type that the OP forgot to include, probably called `QuietInterfaceArgAttribute`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T13:39:05.923", "Id": "59451", "Score": "0", "body": "Indeed, I didn't bother including the Ninject `InjectAttribute`-derived classes. Should I add them in?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T23:04:04.110", "Id": "59518", "Score": "0", "body": "@retailcoder only for those like me who are not versed in ninject-ness" } ]
[ { "body": "<p><strong>Style</strong></p>\n\n<ol>\n<li>I don't like the name <code>AutoBuildCommandLineHelper</code> for a class which implements an interface like <code>IAutoBuildCommandLineArgs</code>. I would have named it <code>AutoBuildCommandLineArgs</code></li>\n<li>You have made <code>ParamSpecifier</code> a named constant but not the quotes you strip of the parameter value.</li>\n</ol>\n\n<p><strong>Possible Bugs</strong></p>\n\n<ol>\n<li>If I read <code>IsSpecified()</code> correctly then it accepts arguments starting with <code>Name</code>. Given that <code>Name</code> seems to be the one letter abbreviation this means if I specify an invalid argument which happens to start with a letter of a valid argument then <code>IsSpecified()</code> will return true.</li>\n<li>If you call <code>ParameterValue()</code> on an argument which does not have (i.e. doesn't require) a parameter it will throw an <code>IndexOutOfRangeException</code> as <code>values</code> will only have 1 entry</li>\n</ol>\n\n<p><strong>Design</strong></p>\n\n<p>When you want to add a new command line option you have to do 5 or 6 things:</p>\n\n<ol>\n<li>Add a new class representing the new option</li>\n<li>Register that class with the IoC container (this could possibly happen automagically depending on the container used)</li>\n<li>Add a new property to <code>IAutoBuildCommandLineArgs</code></li>\n<li>Add a new property to <code>AutoBuildCommandLineHelper</code></li>\n<li>Add a new property to <code>AutoBuildCommandLineHelper</code> constructor</li>\n<li>Add a new assignment in <code>AutoBuildCommandLineHelper</code> constructor to copy parameter into property</li>\n</ol>\n\n<p>Seems a bit involved. I hacked together an alternative version which should fit DI just nicely:</p>\n\n<pre><code>public enum Option\n{\n NoLog,\n Quiet,\n Server,\n LogLevel,\n Help,\n}\n\npublic interface ICommandLineOptions\n{\n bool Has(Option option);\n string ValueOf(Option option);\n}\n\npublic class CommandLineOptions : ICommandLineOptions\n{\n private class CommandLineOption\n {\n public CommandLineOption(Option type, string shortKey, string longKey, string description, bool requiresParam)\n {\n Type = type;\n Short = shortKey;\n Long = longKey;\n Description = description;\n RequiresParam = requiresParam; \n }\n\n public readonly Option Type;\n public readonly string Short;\n public readonly string Long;\n public readonly string Description;\n public readonly bool RequiresParam;\n }\n\n private static readonly List&lt;CommandLineOption&gt; _AllOptions = \n new List&lt;CommandLineOption&gt;\n {\n new CommandLineOption(Option.NoLog, \"n\", \"nolog\", \"Don't log\", false),\n new CommandLineOption(Option.Quiet, \"q\", \"quiet\", \"Run quietly\", false),\n new CommandLineOption(Option.Server, \"s\", \"server\", \"Run in server mode\", false),\n new CommandLineOption(Option.LogLevel, \"ll\", \"loglevel\", \"Set log level\", true),\n new CommandLineOption(Option.Help, \"?\", \"help\", \"Print help\", false),\n };\n\n private static const char _ParamSpecifier = ':';\n private static readonly char[] _Switches = { '-', '/' };\n private static readonly char[] _Quotes = { '\"', '\\'' };\n\n private Dictionary&lt;Option, string&gt; _AvailableOptions = new Dictionary&lt;Option, string&gt;();\n\n public CommandLineOptions(string[] args)\n {\n foreach (var arg in args.Select(a =&gt; a.Trim(_Switches)))\n {\n var parts = arg.Split(new char[] {_ParamSpecifier }, 2, StringSplitOptions.RemoveEmptyEntries);\n\n var option = _AllOptions.FirstOrDefault(o =&gt; o.Short == parts.First().ToLower() || o.Long == parts.First().ToLower());\n if (option == null)\n throw new ArgumentException(string.Format(\"Unknown command line option {0}\", arg));\n if (option.RequiresParam &amp;&amp; parts.Length == 1)\n throw new ArgumentException(string.Format(\"Command line option {0} is missing required parameter\", arg));\n _AvailableOptions[option.Type] = option.RequiresParam ? parts.Last().Trim(_Quotes) : \"\";\n }\n }\n\n public bool Has(Option option)\n {\n return _AvailableOptions.ContainsKey(option);\n }\n\n public string ValueOf(Option option)\n {\n string value;\n if (!_AvailableOptions.TryGetValue(option, out value))\n throw new ArgumentException(string.Format(\"Option {0} not present\", option));\n return value;\n }\n}\n</code></pre>\n\n<p>When you want to add a new option you have to do 2 things:</p>\n\n<ol>\n<li>Add a new entry to the <code>enum</code></li>\n<li>Add a new entry to the <code>_AllOptions</code> dictionary</li>\n</ol>\n\n<p>From a DI perspective anything which needs access to the options just depends on <code>ICommandLineOptions</code>. </p>\n\n<p>If you wanted to get real fancy you could make <code>CommandLineOption</code> public, add an interface <code>ICommandLineOption</code> for it and make <code>CommandLineOptions</code> take a dependency on a collection of <code>ICommandLineOption</code>s. Then you could register all the options you want to support in the container rather than hard coding them in <code>CommandLineOptions</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T09:44:37.130", "Id": "36279", "ParentId": "36264", "Score": "5" } }, { "body": "<h2>Default command line switches</h2>\n<p>It is recommended that tools specify the following standard switches. You should always define these. Also, on error, output the error and the help text.</p>\n<pre><code>- help (--help -h -?)\n- about (--version -!)\n</code></pre>\n<hr />\n<h2>Maintainability</h2>\n<p>The fact your arguments include the keywords used for parsing is a breach of <strong>Single Responsibility</strong>. I would extract all lexing in a seperate class behind some interface. This way, you can make different lexers for Posix, DOS, Windows, Google style.</p>\n<hr />\n<h2>Readability</h2>\n<p>Get rid of the postfix <code>-Argument</code> in your property names. It's redundant and verbose.</p>\n<hr />\n<h2>Command line parsing</h2>\n<p>Command line parsing is an art. A good command line parser is able to parse both readable and administrative command lines, different styles, grammars, literals, escape sequences.</p>\n<p>There are different formatting styles.</p>\n<p><a href=\"https://developers.google.com/style/code-syntax\" rel=\"nofollow noreferrer\">Google dev style</a></p>\n<pre><code>tool --get-logs --in c:\\data\\in\\ -quiet\n</code></pre>\n<p><a href=\"https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html\" rel=\"nofollow noreferrer\">POSIX short style</a></p>\n<pre><code>tool-gq-ic:\\data\\in\\\n</code></pre>\n<p><a href=\"https://www.computerhope.com/issues/chusedos.htm\" rel=\"nofollow noreferrer\">Windows/DOS style</a></p>\n<pre><code>tool /gq /i c:\\data\\in\\\n</code></pre>\n<hr />\n<h2>Design Restrictions</h2>\n<p>I don't know your intend, but if you want to comply to at least the aforementioned command line styles, you have restricted yourself.</p>\n<p>You have hardcoded your delimiters. This means you are only compliant to your own standards, not universal ones. For instance, other <code>ParamSpecifier</code> that could have been allowed are <code>'='</code>, <code>','</code> and even a <em>blank space</em> in the right context. Other <code>_switches</code> include the Posix long-option <code>'--'</code>.</p>\n<blockquote>\n<pre><code> private const char ParamSpecifier = ':';\n private readonly char[] _switches = { '-', '/' };\n</code></pre>\n</blockquote>\n<p>Command switches could have <code>0..*</code> arguments. However, you limit this to <code>0..1</code>.</p>\n<blockquote>\n<p><code>public bool MustHaveParameter { get; private set; }</code></p>\n</blockquote>\n<p>You perform a naive switch-value split. This does not take into account escaped delimiters or file paths.</p>\n<blockquote>\n<p><code>var values = arg.Split(ParamSpecifier);</code></p>\n</blockquote>\n<pre><code>- -a:literal\\:value\n- -a:literal&quot;:&quot;value\n- -a:c:\\temp\\\n</code></pre>\n<p>Quoted literals should not be restricted to the start and end of a string, but could also be inline.</p>\n<blockquote>\n<p><code>return values[1].TrimStart('&quot;').TrimEnd('&quot;');</code></p>\n</blockquote>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T19:26:48.147", "Id": "429270", "Score": "1", "body": "Blast from the past! Nice review. I've since made it a habit to download a nuget package for handling command-line args whenever I need them =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T19:28:01.437", "Id": "429271", "Score": "0", "body": "@MathieuGuindon Good thinking not to reinvent the wheel for command line parsing. It could get you sucked into the rabbit hole :-p" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T19:08:52.670", "Id": "221877", "ParentId": "36264", "Score": "3" } } ]
{ "AcceptedAnswerId": "36279", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T04:23:20.213", "Id": "36264", "Score": "6", "Tags": [ "c#", "strings", "parsing" ], "Title": "First attempt at dealing with command-line args" }
36264
<p>I'm visualizing my stored data in an histogram similar to this one:</p> <p><img src="https://i.stack.imgur.com/Wu3ih.gif" alt="enter image description here"></p> <p>However, I'm sure that my code smells a lot! So I'd like to have your opinion on how to make it better. </p> <pre><code>$listings = array( array('Price' =&gt; 10), array('Price' =&gt; 10), array('Price' =&gt; 11) ); // so on and so forth, this data is pulled from the database. // flattening the array so I remove the "Price" key // the array takes the form of array(10,10,11,...) foreach($listings as $listing) { $flattenedListings[] = $listing['Price']; } $widths = range(0, 100, 10); // creates array of the form: array(0, 10, 20, 30, 40, ...) $bins = array(); $isLast = count($widths); foreach($widths as $key =&gt; $value) { if($key &lt; $isLast - 1) { $bins[] = array('min' =&gt; $value, 'max' =&gt; $widths[$key+1]); } } // creates array of the form: // $bins = array( // array('min'=&gt;0, 'max' =&gt; 10), // array('min'=&gt;10,'max' =&gt; 20), // array('min'=&gt;30, 'max'=&gt;40) // ); $histogram = array(); foreach($bins as $bin) { $histogram[$bin['min']."-".$bin['max']] = array_filter($flattenedListings, function($element) use ($bin) { if( ($element &gt; $bin['min']) &amp;&amp; ($element &lt;= $bin['max']) ) { return true; } return false; }); } // Last one is a bit complicated, but basically what it does is that it creates an array of ranges as keys, so it generates this: // array('0-10' =&gt; array(1, 2, 3, 4, 5, 6), // '10-20' =&gt; array(11, 19, 12), // '20-30' =&gt; array(), // ); // Or in other words: foreach range in the histogram, php creates an array containing values within the allowed limits. foreach($histogram as $key =&gt; $val) { $flotHistogram[$key] = (is_array($val)) ? ( (count($val)) ? count($val) : 0 ) : 0; } // And finally it just counts them, and returns a new array. </code></pre> <p>As you can see in my code, I'm making an excessive use of <code>foreach</code> loops to basically do a "simple task."</p> <p>Basically what I have is a list of items along with their prices, and I want to count how many items belong to each range. My ranges are 10 numbers apart: (0 - 10, 10 - 20, 20 - 30, etc...)</p> <p>Ideally the output should tell me how many items there are in a given category, like 3 items in the range of <code>$10 - $20</code>, 2 items in the range of <code>$20 - $30</code> and 1 item in the range of <code>$30 - $40</code>, etc... In the following format:</p> <pre><code>array('0-10' =&gt; 0, '10-20' =&gt; 3, '20-30' =&gt; 2, '30-40' =&gt; 1); </code></pre> <p>Given the following input:</p> <pre><code>array( array('Price' =&gt; 11), array('Price' =&gt; 12), array('Price' =&gt; 20), array('Price' =&gt; 25), array('Price' =&gt; 20.1), array('Price' =&gt; 33.5) ); </code></pre> <p>Additional info:</p> <p>I'm pulling my prices from a MySQL database using PDO option <code>PDO::FETCH_ASSOC</code>. How could the flattening of the array be skipped (instead of fetching an array of arrays, just fetch the numbers in a 1 dimensional array)?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-10T02:23:50.303", "Id": "99771", "Score": "0", "body": "Have you seen [`count_array_values`](http://www.php.net/manual/en/function.array-count-values.php)?" } ]
[ { "body": "<p>Your code isn't exactly terrible, but this is code-review, and <a href=\"https://codereview.meta.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag\">good code review has to be harsh</a>, so please keep in mind that I mean this in the nicest of ways.<br/>\nThat said, there are some issues I'd like to address:</p>\n\n<p><em>Redundancies - DNRY:</em><br/>\nThat old dead horse: Do Not Repeat Yourself. You have a lot of redundant code. Of course, you can get into code-golfing, and try to write everything as a one-liner. That will result in unmaintainable code, and that's not what we want, but in your case, there is room for some minor improvements that won't harm readability one bit, quite the contrary.</p>\n\n<p>You say you're getting the data (prices, I take it) from a PDO resultset, why, then, don't you fill the <code>$flattenedListings</code> array like so:</p>\n\n<pre><code>$flattenedListings = array();\nwhile($row = $pdoResOrStmt-&gt;fetch(PDO::FETCH_ASSOC))\n{\n $flattenedListings[] = $row['Price'];\n}\n</code></pre>\n\n<p>That's going to reduce the resources your script requires a tad, and fetches the data while at the same time constructing the flattened array.<br/>\nNext, the <code>$isLast = count($widths);</code> variable can be ditched all together, either by a simple foreach, very close to to the loop you currently have:</p>\n\n<pre><code>$widths = range(0, 100, 10);\n$bins = array();\nforeach($widths as $key =&gt; $val)\n{\n if (!isset($widths[$key +1])) break;//break on the last key\n $bins[] = array(\n 'min' =&gt; $val,\n 'max' =&gt; $widths[$key + 1]\n );\n}\n</code></pre>\n\n<p>But, and this might be personal, I dislike this <code>if() break;</code> thing in a loop. Personally, I'd probably write something like:</p>\n\n<pre><code>for($i=0, $j=count($widths) -1; $i&lt;$j;++$i)\n{//count -1 = last key, but $i &lt;$j =&gt; next to last key\n $bins[] = array(\n 'min' =&gt; $widths[$i],\n 'max' =&gt; $widths[$i+1],//can get last key\n );\n}\n</code></pre>\n\n<p>Next, the <code>$histogram</code>. You're using a closure function + <code>array_filter</code> to group your values according to the price range. In itself, it's quite easy to read, and not that inefficient. But I find that closures in PHP (which are <em>objects</em>, instances of <code>Closure</code>) are 9/10 overkill. They're also not a <em>\"natural\"</em> feature of the language. PHP isn't a functional language, like Lisp, Scheme or JavaScript are. I've compared them to drag queens: A man <em>can</em> wear a dress, stockings, a wig and put on make-up as much as he wants, it still doesn't change the fact that he's a man.<br/>\nOften, what you end up with is a grotesque, bemusing performance that leaves some feeling ill at ease.</p>\n\n<p>There is a far easier way of determining the range for each price:</p>\n\n<pre><code>$histogram = array();\nforeach($flattenedListings as $price)\n{//assuming nothing costs 0\n $key = floor(($price -1)/10);\n $range = $bins[$key];\n $key = $range['min'] .'-'. $range['max'];\n if (!isset($histogram[$key])) $histogram[$key] = array();\n $histogram[$key][] = $price;\n}\n</code></pre>\n\n<p>If some price <em>can</em> be zero, then just replace:</p>\n\n<pre><code>$key = floor(($price -1)/10);\n</code></pre>\n\n<p>with </p>\n\n<pre><code>$key = $price ? floor(($price -1)/10) : 0;\n</code></pre>\n\n<p>And you're good to go.</p>\n\n<p><em>Simplify:</em><br/>\nNow we've got that sorted out, it's time to simplify things a bit. As you can see by the way I've filled <code>$histogram</code>, I don't actually <em>need</em> the min and max values from the <code>$bins</code> array, so instead of filling that array with <code>array('min'=&gt; $x, 'max'=&gt; $x+1)</code>, I could easily have written:</p>\n\n<pre><code>$widths = range(0, 100, 10);\n$bins = array();\nforeach($widths as $key =&gt; $val)\n{\n if (!isset($widths[$key + 1])) break;\n $bins[] = $val.'-'. ($widths[$key + 1]);\n}\n</code></pre>\n\n<p>This also makes filling the <code>$flotHistogram</code> array a lot easier:</p>\n\n<pre><code>$flotHistogram = array_fill_keys($bins, 0);//set all keys to 0\n</code></pre>\n\n<p>Then, when filling the <code>$histogram</code>:</p>\n\n<pre><code>$histogram = array();\nforeach($flattenedListings as $price)\n{\n $key = $bins[floor(($price -1)/10)];\n if (!isset($histogram[$key])) $histogram[$key] = array();\n $flotHistogram[$key]++;//add 1 count\n $histogram[$key][] = $price;\n}\n</code></pre>\n\n<p>This leaves us with the following code:</p>\n\n<pre><code>//get prices\n$flattenedListings = array();\nwhile($row = $pdoResOrStmt-&gt;fetch(PDO::FETCH_ASSOC))\n{\n $flattenedListings[] = $row['Price'];\n}\n//construct range-keys array\n$widths = range(0, 100, 10);\n$bins = array();\nforeach($widths as $key =&gt; $val)\n{\n if (!isset($widths[$key + 1])) break;\n $bins[] = $val.'-'. ($widths[$key + 1]);\n}\n//construct flotHistogram count array\n$flotHistogram = array_fill_keys($bins, 0);\n//construct array of prices for each key\n$histogram = array();\nforeach($flattenedListings as $price)\n{\n $key = $bins[floor(($price -1)/10)];\n if (!isset($histogram[$key])) $histogram[$key] = array();\n $flotHistogram[$key]++;\n $histogram[$key][] = $price;\n}\n</code></pre>\n\n<hr>\n\n<p><em>A bridge too far(?)</em><br/>\nI may be taking things a bit too far, but that <code>$flattenedListings</code> array seems a bit redundant, now. However I don't know what else you need the db results for, but all in all, you may want to consider doing something like</p>\n\n<pre><code>$widths = range(0, 100, 10);\n$bins = array();\nforeach($widths as $key =&gt; $val)\n{\n if (!isset($widths[$key + 1])) break;\n $bins[] = $val.'-'. ($widths[$key + 1]);\n}\n\n$flotHistogram = array_fill_keys($bins, 0);\n\n$histogram = array();\n//query data:\nwhile($row = $pdoVar-&gt;fetch(PDO::FETCH_ASSOC))\n{\n $key = $bins[floor(($row['Price'] -1)/10)];\n if (!isset($histogram[$key])) $histogram[$key] = array();\n $flotHistogram[$key]++;\n $histogram[$key][] = $row['Price'];\n}\n</code></pre>\n\n<p>Which reduces your code even more. Of course, if you find this too hard to read (imagine, a couple of months from now, will you still be able to make sense of this code), then don't use it, add more comments and don't feel shy to be a bit more verbose or repetitive. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T17:12:47.777", "Id": "59483", "Score": "2", "body": "This is excellent! By no mean I would take this the wrong way, and the refactored code 100% understandable. Thanks a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T07:49:24.463", "Id": "36274", "ParentId": "36266", "Score": "6" } } ]
{ "AcceptedAnswerId": "36274", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T05:06:42.143", "Id": "36266", "Score": "4", "Tags": [ "php", "array", "php5", "pdo", "statistics" ], "Title": "Building a histogram array in PHP" }
36266
<p>I need to merge some large csv files but I feel that the way I am doing it is not optmized. It gets a number of csvfiles and creates one</p> <pre><code>public static void MergeFiles(IEnumerable&lt;string&gt; csvFileNames, string outputPath) { var sb = new StringBuilder(); bool hasHeader = false; foreach (string csvFileName in csvFileNames) { TextReader tr = new StreamReader(csvFileName); string headers = tr.ReadLine(); if (!hasHeader) { sb.AppendLine(headers); hasHeader = true; } sb.AppendLine(tr.ReadToEnd()); } File.WriteAllText(outputPath, sb.ToString()); } </code></pre> <p>Any suggestion or code snippets?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T13:38:53.670", "Id": "59450", "Score": "0", "body": "In which way you think it's not optimized?" } ]
[ { "body": "<ol>\n<li><p><code>StreamReader</code> is <code>IDisposable</code> and therefor the use of it should be wrapped in a <code>using</code> block like this:</p>\n\n<pre><code>using (TextReader tr = new StreamReader(csvFileName))\n{\n ...\n}\n</code></pre></li>\n<li><p>You are reading all files into memory and then writing it out. While this probably has a fairly good performance as it's first performing a bunch of (probably) sequential reads of all the files and then one big block write you could consider writing it out as you read it:</p>\n\n<pre><code>using (var writer = new StreamWriter(outputPath))\n{\n foreach (var csvFileName in csvFileNames)\n {\n using (var reader = new StreamReader(csvFileName))\n {\n string headers = tr.ReadLine();\n\n if (!hasHeader)\n {\n writer.WriteLine(headers);\n hasHeader = true;\n }\n\n writer.Write(reader.ReadToEnd());\n }\n }\n}\n</code></pre>\n\n<p>If the files are very big you even might want to consider reading the input line by line and writing it to the output line by line. This will be less performant but also use much less memory. In the end it's a trade off between speed and memory consumption (as it often is in software development). </p>\n\n<p>The other advantage with the write as you go method is that you open the output file first - so if there is a problem with writing to the target you will know before you do any work at all.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T08:05:16.093", "Id": "59404", "Score": "0", "body": "Wouldn't it be faster to first read everything to the memory and then start with the I/O operations? - or did I misunderstand you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T08:19:48.050", "Id": "59407", "Score": "0", "body": "@Max: Yes, I thought that's what I said: `You are reading all files into memory and then writing it out. While this probably has a fairly good performance as it's first performing a bunch of (probably) sequential reads of all the files and then one big block write`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T08:20:57.180", "Id": "59409", "Score": "0", "body": "o, my bad then :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T06:05:13.090", "Id": "59543", "Score": "0", "body": "@ChrisWue Thank you very much for your time and input I will do that" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T07:59:56.497", "Id": "36276", "ParentId": "36273", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T07:41:10.367", "Id": "36273", "Score": "5", "Tags": [ "c#", "csv", "file" ], "Title": "Improve my copying of a CSV file" }
36273
<p>This is roughly what my data file looks like:</p> <pre><code># Monid U B V R I u g r i J Jerr H Herr K Kerr IRAC1 I1err IRAC2 I2err IRAC3 I3err IRAC4 I4err MIPS24 M24err SpT HaEW mem comp Mon-000001 99.999 99.999 21.427 99.999 18.844 99.999 99.999 99.999 99.999 16.144 99.999 15.809 0.137 16.249 99.999 15.274 0.033 15.286 0.038 99.999 99.999 99.999 99.999 99.999 99.999 null 55.000 1 N Mon-000002 99.999 99.999 20.905 19.410 17.517 99.999 99.999 99.999 99.999 15.601 0.080 15.312 0.100 14.810 0.110 14.467 0.013 14.328 0.019 14.276 0.103 99.999 0.048 99.999 99.999 null -99.999 2 N </code></pre> <p>...and it's a total of 31mb in size. Here's my python script that pulls the Mon-###### IDs (found at the beginning of each of the lines).</p> <pre><code>import re def pullIDs(file_input): '''Pulls Mon-IDs from input file.''' arrayID = [] with open(file_input,'rU') as user_file: for line in user_file: arrayID.append(re.findall('Mon\-\d{6}',line)) return arrayID print pullIDs(raw_input("Enter your first file: ")) </code></pre> <p>The script works but for this particular file it ran for well into 5 minutes and I eventually just killed the process due to impatience. Is this just something I'll have to deal with in python? i.e. Should this be written with a compiled language considering the size of my data file?</p> <p>Further info: This script is being run within Emacs. This, by the checked answer, explains why it was running so slow.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T12:24:51.317", "Id": "59444", "Score": "1", "body": "I can't reproduce your problem. When I tried it, your program reads the ids from a 31 MiB file in less than a second. So I think there must be something you're not telling us." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T17:34:24.090", "Id": "59484", "Score": "0", "body": "The only thing that might be of interest is that I'm running it through Emacs on a macbook pro." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T17:52:06.793", "Id": "59491", "Score": "0", "body": "Me too, so that can't be it. Can you post a self-contained test case? For example, you could write some code that generates 31 MiB of test data, and then we could check our timing against yours on the same data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T01:59:01.503", "Id": "59531", "Score": "0", "body": "Hmmmm. I'd like to do that, but I wouldn't even know where to start with it. That's a little bit advanced for my level. I'd like to learn though if you wouldn't mine explaining how to go about doing that..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T02:18:01.810", "Id": "59532", "Score": "0", "body": "@GarethRees A second thing I just discovered...if I run the script in my terminal it finishes in about 2 seconds. It also completes within Eclipse Kepler within about 3 to 4 seconds. Hmmmm, Emacs?" } ]
[ { "body": "<p>If you know that <code>Mon-######</code> IDS will always be in the first part of each line there is no need to <code>.findall(..)</code>, just extract the first 10 characters from the line (granted the <code>Mon-######</code> is never more than 10 characters</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T08:10:46.947", "Id": "59405", "Score": "0", "body": "If it isn't though would this be the only way? I only ask because I plan on using this on multiple files, some of which may not have the IDs in the first part of the line. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T08:20:05.567", "Id": "59408", "Score": "0", "body": "Another thing could be to change .findall(..) to only finding the first instance (if there are some kind of .find() or .findfirst()). The difference would be that instead of traversing the entire line it only traverses it until it's found, a small improvement but I guess it adds up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T14:26:41.033", "Id": "59456", "Score": "0", "body": "@Max: Did you try any of these suggestions? How much improvement to the runtime did they make?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T14:29:07.770", "Id": "59457", "Score": "0", "body": "No I didn't try it, and I don't expect it to be any major improvements, but when you're after performance boosts I guess it all adds up." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T08:02:48.883", "Id": "36277", "ParentId": "36275", "Score": "3" } }, { "body": "<p>You said in comments that you don't know how to create a self-contained test case. But that's really easy! All that's needed is a function like this:</p>\n\n<pre><code>def test_case(filename, n):\n \"\"\"Write n lines of test data to filename.\"\"\"\n with open(filename, 'w') as f:\n for i in range(n):\n f.write('Mon-{0:06d} {1}\\n'.format(i + 1, ' 99.999' * 20))\n</code></pre>\n\n<p>You can use this to make a test case of about the right size:</p>\n\n<pre><code>&gt;&gt;&gt; test_case('cr36275.data', 200000)\n&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.stat('cr36275.data').st_size\n34400000\n</code></pre>\n\n<p>That's about 34 MiB so close enough. Now we can see how fast your code really is, using the <a href=\"http://docs.python.org/3/library/timeit.html\" rel=\"nofollow\"><code>timeit</code></a> module:</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit(lambda:pullIDs('cr36275.data'), number=1)\n1.3354740142822266\n</code></pre>\n\n<p>Just over a second. There's nothing wrong with your code or the speed of Python.</p>\n\n<p>So why does it take you many minutes? Well, you say that you're running it inside Emacs. That means that when you run</p>\n\n<pre><code>&gt;&gt;&gt; pullIDs('cr36275.data')\n</code></pre>\n\n<p>Python prints out a list of 200,000 ids, and Emacs reads this line of output into the <code>*Python*</code> buffer and <em>applies syntax highlighting rules to it as it goes</em>. Emacs' syntax highlighting code is designed to work on lines of source code (at most a few hundred characters but mostly 80 characters or less), not on lines of output that are millions of characters long. This is what is taking all the time.</p>\n\n<p>So don't do that. Read the list of ids into a variable and if you need to look at it, use slicing to look at bits of it:</p>\n\n<pre><code>&gt;&gt;&gt; ids = pullIDs('cr36275.data')\n&gt;&gt;&gt; ids[:10]\n[['Mon-000001'], ['Mon-000002'], ['Mon-000003'], ['Mon-000004'], ['Mon-000005'],\n ['Mon-000006'], ['Mon-000007'], ['Mon-000008'], ['Mon-000009'], ['Mon-000010']]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:21:27.523", "Id": "59612", "Score": "0", "body": "Wow. Thank you so much for this. It isn't crucial that I print these IDs to my screen but I wanted to see if my script was working correctly and this crazy slow down kind of confused me. But, you've cleared all of that up. Thanks for the test-case pointers and the insight into Emacs." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T12:08:31.833", "Id": "36348", "ParentId": "36275", "Score": "4" } } ]
{ "AcceptedAnswerId": "36348", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T07:51:31.623", "Id": "36275", "Score": "4", "Tags": [ "python", "optimization", "array" ], "Title": "Why is this program for extracting IDs from a file so slow?" }
36275
<p>I'm new to jQuery, and am using it to dynamically construct chunks of a page.</p> <p>The created HTML is what I want, but I'm not sure if the way I'm generating it is sensible or idiomatic.</p> <pre><code>function setupIndex() { $(document.body).append($("&lt;img/&gt;", {src : 'logo.png'})); var div = $("&lt;div/&gt;", {"class" : "content"}).appendTo(document.body); div.append("&lt;h2/&gt;", { text :'My Panels'}); div.append($("&lt;table/&gt;", {id : 'maintable'})); } function addPanel(name, desc) { if (!$("#maintable")) setupIndex(); var row = $("&lt;tr/&gt;",{"class":"panels"}).appendTo("#maintable"); var div = $("&lt;td/&gt;").appendTo(row); div.append($("&lt;h3/&gt;").append($("&lt;a/&gt;", { text : name, href : name + "/index.html"}))); div.append(document.createTextNode(desc)); div = $("&lt;td/&gt;").appendTo(row); var anc = div.append($("&lt;a/&gt;", {href: name + "/index.html"})); anc.append($("&lt;img/&gt;", { css : {width : "200px", height : "auto"}, src : name + "/thumbnail.png"})); } </code></pre>
[]
[ { "body": "<p>I know that the following might seem crazy at first but humour me for a minute. The main improvement is so that variables are not reused (which confuses their meaning) and the subtle <code>.appendTo(\"#maintable\")</code> is at the end (which means the document is altered once).</p>\n\n<p>There is not functional need to store the objects into variables as they aren't re-used. I often try to write in this pattern as it looks more like the way you'd write html. </p>\n\n<pre><code>if (!$(\"#maintable\"))\n setupIndex();\n\n$(\"&lt;tr/&gt;\", {\"class\":\"panels\"})\n .append(\n $(\"&lt;td/&gt;\")\n .text(desc)\n .prepend(\n $(\"&lt;h3/&gt;\")\n .append($(\"&lt;a/&gt;\", { text : name, href : name + \"/index.html\"})))\n )\n )\n .append(\n $(\"&lt;td/&gt;\")\n .append($(\"&lt;a/&gt;\", {href: name + \"/index.html\"}))\n .append($(\"&lt;img/&gt;\", { css : {width : \"200px\", height : \"auto\"}, src : name + \"/thumbnail.png\"}))\n )\n .appendTo(\"#maintable\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T02:52:26.130", "Id": "60121", "Score": "0", "body": "I've just found a StackOverflow question similar: http://stackoverflow.com/questions/9760328/clearest-way-to-build-html-elements-in-jquery" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T13:23:46.987", "Id": "60154", "Score": "1", "body": "Your first conditional won't work as expected: `$()` _always_ returns a jQuery object (i.e. something truth'y) regardless of whether it finds an element, so `setupIndex()` will never be called. You'll want to check `if($('#maintable').length === 0)` (or, shorter, `if(!$('#maintable').length)`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:07:09.087", "Id": "60230", "Score": "0", "body": "@Flambino. Yup, you're right. I hadn't spotted that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T21:10:02.000", "Id": "60232", "Score": "0", "body": "@JamesKhoury - Thanks. What about `$(\"<td/>\")` vs. `$(\"<td>\")` ? Either seems to work..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T00:48:38.863", "Id": "60268", "Score": "0", "body": "@Flambino I think that alone is worth an answer. I'd encourage you to create one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T00:49:42.930", "Id": "60269", "Score": "1", "body": "@Roddy I am not sure jQuery sees any difference between `$(\"<td/>\")` and `$(\"<td>\")`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T02:50:48.890", "Id": "36617", "ParentId": "36287", "Score": "5" } } ]
{ "AcceptedAnswerId": "36617", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T13:41:48.160", "Id": "36287", "Score": "2", "Tags": [ "javascript", "jquery", "beginner" ], "Title": "jQuery to construct elements" }
36287
<p>I have done the following code for testing a web-service.</p> <p>Is my style correct for using OOP in JavaScript?</p> <pre><code>&lt;script&gt; function Ajax() { var Base = { createAjaxInstance: function() { var ajax = null; try { ajax = new ActiveXObject( "Msxml2.XMLHTTP" ); } catch ( exception ) { try { console.log( "Can't create `Msxml2.XMLHTTP` object for " + navigator.userAgent + "." ); ajax = new ActiveXObject( "Microsoft.XMLHTTP" ); } catch ( exception ) { console.log( "Can't create `Microsoft.XMLHTTP` object for " + navigator.userAgent + "." ); ajax = false; } } if ( !ajax &amp;&amp; typeof XMLHttpRequest != "undefined" ) ajax = new XMLHttpRequest(); else console.error( "Failed to create any `XmlHttp` instance!" ); return ajax; }, getAjaxInstance: function() { var ajax = this.createAjaxInstance(); return ajax; } }; var instance = Base.getAjaxInstance(); return instance; } function UI() { var Base = { Controllers: { addContainer: function( element, id, inputHtml ) { var container = document.createElement( element ); container.id = id; container.innerHTML = inputHtml; document.body.appendChild( container ); }, addControl: function( element, id, type, value, eventName, eventBehaviour ) { var control = document.createElement( element ); control.id = id; control.type = type; control.value = value; control.addEventListener( eventName, eventBehaviour ); document.body.appendChild( control ); }, setupPage: function() { Base.Controllers.addContainer( "div", "divInfo", "Here will be the result data." ); Base.Controllers.addControl( "input", "inputLatitude", "text", "Latitude", "click", function() { this.value = ''; } ); Base.Controllers.addControl( "input", "inputLongitude", "text", "Longitude", "click", function() { this.value = ''; } ); Base.Controllers.addControl( "input", "inputZoom", "text", "Zoom", "click", function() { this.value = ''; } ); Base.Controllers.addControl( "input", "buttonAjaxTest", "button", "click me", "click", function() { var httpMethods = new Enums( "http" ); var container = document.getElementById( "divInfo" ); var request = new Ajax(); request.onreadystatechange = function() { if ( request.readyState == 4 ) { container.innerHTML = request.statusText; if ( request.status == 200 ) container.innerHTML = request.responseText; } }; var latitude = document.getElementById( "inputLatitude" ).value; var longitude = document.getElementById( "inputLongitude" ).value; var zoom = document.getElementById( "inputZoom" ).value; var endpoint = "/mapimage/generate/bing/static/" + latitude + "/" + longitude + "/" + zoom; console.log( endpoint ); request.open( httpMethods.Get, endpoint, true ); request.send( null ); container.innerHTML = "&lt;img src='/img/loader.gif'&gt; Awaiting for the server response..."; } ); } } }; var instance = Base; return instance; } function Enums( inputType ) { function getEnumCollection( type ) { switch ( type ) { case "http": return HttpMethods; default: return null; } } var HttpMethods = { Post: "POST", Get: "GET" }; var instance = getEnumCollection( inputType ); return instance; } function Engine() { var ui = new UI(); var Base = { setFunctionMain: function( objectFunction ) { window.onload = objectFunction; } }; Base.setFunctionMain( ui.Controllers.setupPage ); } var engine = new Engine(); &lt;/script&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T15:17:35.243", "Id": "59462", "Score": "0", "body": "https://gist.github.com/Zirak/3373067" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T15:26:15.020", "Id": "59466", "Score": "0", "body": "@Florian: care to provide some background?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T15:27:11.373", "Id": "59467", "Score": "1", "body": "Not a JS expert so I'll only comment: Why use the Base object? That's an object that relates to the HTML DOM. You don't seem to be using any of those features in your code snippet, so why not attach the various functions directly on to the prototype of each of your object functions? Also, why does every object function also automatically create one instance of itself? Shouldn't those be created separately, and/or only if needed? This is a great question BTW, can't wait to read the answers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T16:26:03.960", "Id": "59477", "Score": "0", "body": "@ShivanDragon **Why use the Base object?** answer: for structuring and some hiding options (encapsulation). **... relates to the HTML DOM.** - where does it relate to `DOM`? It's just an object, where some functions work with DOM and that's all. **so why not attach the various functions directly on to the prototype of each of your object functions?**, answer: because you such a suggested protoype will be public and isn't encapsulated. Also The need in `Base` is for a clean well-structered code with the good use of it and it wouldn't look like a garbage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T16:29:46.913", "Id": "59478", "Score": "0", "body": "@ShivanDragon **Also, why does every object function also automatically create one instance of itself?** answer: for the getting a copy of instance when just creating it, less code and more elegant (as for my opinion). **Shouldn't those be created separately, and/or only if needed?** - As for me - now, because it wouldn't be look like a well structured class. PS: I'n not an expert in JS too, my first language , which I have to use professionaly is C#, so I came from C# and trying to implement the thins I've looked in C#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T06:52:58.493", "Id": "59821", "Score": "0", "body": "Answer to your question is _no_, that's what @FlorianMargaine meant with his link: OO is often ridiculously over-engineering the simple things (Java's _Hello world_, for example). Apart from that, your _\"constructors\"_ are just glorified factories of object literals that'll be constructed over and over, including its functions..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T07:02:23.447", "Id": "59824", "Score": "0", "body": "@EliasVanOotegem Where is it constructing over and over exactly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T07:05:06.810", "Id": "59826", "Score": "0", "body": "@GeloVolro: Every time you're calling `Ajax`, for example, a new object literal is constructed and assigned to `var Base` (local variable), then you're simply calling `getAjaxInstance`, and return that. Once you've done that, `Base` is no longer referenced, and is flagged for GC. The next time you call the `Ajax` constructor (which isn't a constructor, really), the process starts all over. The `Base` object is constructed, its functions (which are objects, too, in JS) are constructed, and you construct an XHR object, return that and GC the lot again..." } ]
[ { "body": "<p>When talking about OOP, there are <a href=\"http://en.wikipedia.org/wiki/Object-oriented_programming#Fundamental_features_and_concepts\" rel=\"nofollow\">several concepts</a> which are common to OOP languages, like encapsulation, dynamic dispatch, polymorphism, and abstraction. Of all these, I can only see that you are trying to implement <a href=\"http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29\" rel=\"nofollow\">encapsulation</a> (in the sense of information hiding), although you could still do it slightly simpler in my honest opinion.</p>\n\n<p>Generally, if your functions are not <strong>members</strong> of the parent function object, but merely contained inside <strong>variables</strong>, they are private to the outside world, so that alone is enough to achieve hiding. Using an additional object (<code>Base</code>, as you call it) achieves nothing in this direction and only adds noise (again in my honest opinion). No outside object will ever be able to access it anyway.</p>\n\n<p>If you are trying to mimic OOP style programming in JavaScript, think how you would implement a polymorphism (i.e. create a derived class which has access to base class' methods) using your current convention.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T16:33:49.607", "Id": "59480", "Score": "0", "body": "Thanks for the great answer. I must make a remark , because you wiil understand why did I make such code. I came from C# lang and JS I'm only learning. Trully... I don't event imagine how to create a normal polymorphism, which will be similar to C# with `virtual/override` keywords, as for the inheritance, I can imagine that it could be done just with the object copying in JS." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T15:38:46.660", "Id": "36297", "ParentId": "36296", "Score": "2" } } ]
{ "AcceptedAnswerId": "36297", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T15:14:49.510", "Id": "36296", "Score": "2", "Tags": [ "javascript", "object-oriented", "prototypal-class-design", "closure" ], "Title": "Is my JavaScript OOP style correct?" }
36296
<p>Got this design for getting rid of checking network availability and informing user of errors. Is it good at all? Please, help.</p> <p>Overall point is to fire server call as short as possible:</p> <pre><code>new DefaultServerCallTask&lt;LoginResponse&gt;(){ @Override protected void onSuccess(LoginResponse response){ //go to nextActivity} } @Override void callServer() throws ConnectionException, InternalServerException, JSONException { return ServerApi.login(/*enclosed params from outer variables */); } }.execute(); </code></pre> <p><code>AsyncResult</code> is a wrapper class, it's main purpose to be returned from <code>AsyncTask.doInBackground</code>.</p> <p><code>CheckableResult</code> is an inteface for POJOs, returned from server.</p> <pre><code>class AsyncResult&lt;T&gt;{ T mResponse; boolean mOk; String mErrorMessage; T getResponse(){ return mResponse; } boolean isOk(){ return mOk; } String getErrorMessage(){ return mErrorMessage; } public AsyncResult (T response){ mErrorMessage = ""; mOk = true; mResponse = response; } public AsyncResult (String errorMessage){ mErrorMessage = errorMessage; mOk = false; } } </code></pre> <p><code>AbstractServerCallTask</code> handles connection and server-side exceptions^</p> <pre><code>abstract class AbstractServerCallTask&lt;Result extends CheckableResponse&gt; extends AsyncTask&lt;Void, Void, AsyncResult&lt;Result&gt;&gt;{ @Override protected AsyncResult&lt;Result&gt; doInBackground(Void... arg0) { if (!AppUtils.isNetworkAvailable()) return new AsyncResult("No network available. Please, check your connection"); try { return new AsyncResult&lt;Result&gt;(callServerMethod()); } catch (ConnectionException e) { return new AsyncResult&lt;Result&gt;("Can't connect to server, chek your network state"); } catch (InternalServerException e) { return new AsyncResult&lt;Result&gt;("Server-side fault. Please, try again later"); } catch (JSONException e) { return new AsyncResult&lt;Result&gt;("Wrong data format. Please try again later"); } } abstract Result callServerMethod() throws ConnectionException, InternalServerException, JSONException ; @Override protected void onPostExecute(AsyncResult&lt;Result&gt; asyncResult){ if (asyncResult.isOk()){ Result r = asyncResult.getResponse(); if (r.isOk()) onSuccess(r); else onRequestFailed(r); // we got to server, but somehing is wrong } else onError(asyncResult.getErrorMessage()); } protected abstract void onError(String errorMessage); protected abstract void onRequestFailed(Result r) ; protected abstract void onSuccess(Result r); } </code></pre> <p><code>DefaultServerCallTask</code> leaves onSuccess for derived innerclasses to override:</p> <pre><code>abstract class DefaultServerCallTask&lt;Result extends CheckableResponse&gt; extends AbstractServerCallTask&lt;Result&gt;{ @Override protected void onError(String errorMessage) { AppUtils.showToast(errorMessage); } @Override protected void onRequestFailed(Result r) { AppUtils.showToast(r.getErrorMessage()); // show server-side generated message } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T15:57:19.233", "Id": "59473", "Score": "0", "body": "What if someone wants to get a `String` response from the server, can he create an `AsyncResult<String>`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T18:32:35.963", "Id": "59497", "Score": "0", "body": "It is not meant to be used that way. You'll have to make a wrapper for String, implementing CheckableResult (isOk, getError etc, very AsyncResult alike)." } ]
[ { "body": "<p>There are many things that you do well here. Overall the code is fine.</p>\n<p>I have some points that you should seriously consider and some things that you should think about. In the end, this is your code and I don't know everything that you know about it's purpose, usage and further plans.</p>\n<h3>Seriously consider</h3>\n<ul>\n<li><p>Android provides a lovely way to handle <a href=\"http://developer.android.com/guide/topics/resources/string-resource.html\" rel=\"noreferrer\">String Resources</a>. I suggest you make use of that. Not only is it very handy to keep all your strings stored in <code>.xml</code>-files but it is also impossible to internationalize your messages if you hardcode string values within your code.</p>\n</li>\n<li><p>As <code>AsyncResult</code> seems to be a good, flexible, generic (generic as in both Java-generics and English generic) utility class, it wouldn't hurt to put getters as <code>public</code> and the fields as <code>private final</code></p>\n</li>\n</ul>\n<h3>Think about</h3>\n<ul>\n<li><p>What if the server provides both an error message and more detailed information as a response? I suggest that you create a constructor for your <code>AsyncResult</code> which accepts both <code>T response</code> and <code>String errorMessage</code>. You can then use <a href=\"https://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java\">constructor chaining</a> in your class. Constructor chaining is a good way to reduce code duplication in constructors.</p>\n</li>\n<li><p>I find the naming of <code>DefaultServerCallTask</code> to be a bit misleading, the usage of the word <code>Default</code> together with the keyword <code>abstract</code> on the same class doesn't make sense to me. If it really is <code>Default</code>, then why is it <code>abstract</code>? (Although I understand your reasons for having it this way, I question the naming of the class).</p>\n</li>\n<li><p>Your <code>AbstractServerCallTask</code> extends <code>AsyncTask&lt;Void, Void, AsyncResult&lt;Result&gt;&gt;</code>. It is functional and I understand that you can specify data to be sent to the server by calling a constructor and storing it in a field, or creating an inner anonymous class which you actually do when you call <code>new DefaultServerCallTask&lt;LoginResponse&gt;(){ ... }.execute();</code>.</p>\n<p>I think that you should consider allowing change of the first <code>Void</code> generics, which is the <code>Param</code> class. If you would allow changing that, then you can pass arguments to your <code>execute</code> method, which can be passed on to <code>callServerMethod</code> instead of having to get variables from outside into your <code>new DefaultServerCallTask&lt;LoginResponse&gt;(){...</code></p>\n</li>\n<li><p>It is OK to have a <code>AsyncResult&lt;T&gt;</code> class, but will you have any use for the generics in that class outside your server calls? Your server calls only makes use of <code>AsyncResult&lt;Result&gt;</code>. As hinted by rolfl in his comment, a user currently can't use a <code>AsyncResult&lt;String&gt;</code> along with your classes for server calls.</p>\n</li>\n</ul>\n<p>I want to leave you with something positive though: Overall, your code is fine. So for your question &quot;Is it good at all?&quot; I have to say &quot;yes&quot;.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T18:23:04.087", "Id": "59495", "Score": "1", "body": "Simon, thank you very much for your detailed answer, i really appreciate it. Actually asyncresult isn't meant to be used outside of abstractservercalltask, it is needed for moving exceptions handling to main thread only. It is my inconvenience that have left it outside abstractservercalltask. About resource strings - i haven.t posted this part for the sake of simplicity, and I absolutely will incorporate in in final code. I should refine code now and think of other points you've made." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-25T02:03:02.597", "Id": "236545", "Score": "0", "body": "Awesome explaination. It will help all new devs to understand the design pattern and generics. Kudos @Simon for detailing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T16:45:18.230", "Id": "36302", "ParentId": "36298", "Score": "5" } } ]
{ "AcceptedAnswerId": "36302", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T15:46:20.873", "Id": "36298", "Score": "3", "Tags": [ "java", "android", "asynchronous" ], "Title": "AsyncTask for handling server api calls" }
36298
<p>I'm trying to find all the 3, 4, 5, and 6 letter words given 6 letters. I am finding them by comparing every combination of the 6 letters to an <code>ArrayList</code> of words called <code>sortedDictionary</code>. I have worked on the code a good bit to get it to this point.</p> <p>I tested how many six letter words are checked and got 720 which is good because 6*5*4*3*2*1=720 which means I am not checking any words twice. I can't make it faster by getting rid of duplicate checks because I have already gotten rid of them all. </p> <p>Can I still make this faster?</p> <p>Note that <code>sortedDictionary</code> only contains about 27 hundred words. </p> <pre><code>for(int l1 = 0; l1 &lt; 6; l1++){ for(int l2 = 0; l2 &lt; 6; l2++){ if(l2 != l1) for(int l3 = 0; l3 &lt; 6; l3++){ if(l3 != l1 &amp;&amp; l3 != l2){ if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3])) anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]); for(int l4 = 0; l4 &lt; 6; l4++){ if(l4 != l1 &amp;&amp; l4 != l2 &amp;&amp; l4 != l3){ if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4])) anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]); for(int l5 = 0; l5 &lt; 6; l5++){ if(l5 != l1 &amp;&amp; l5 != l2 &amp;&amp; l5 != l3 &amp;&amp; l5 != l4){ if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5])) anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]); for(int l6 = 0; l6 &lt; 6; l6++){ if(l6 != l1 &amp;&amp; l6 != l2 &amp;&amp; l6 != l3 &amp;&amp; l6 != l4 &amp;&amp; l6 != l5) if(sortedDictionary.contains(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]+anagramCharacters[l6])) anagram_words.add(""+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]+anagramCharacters[l4]+anagramCharacters[l5]+anagramCharacters[l6]); } } } } } } } } } </code></pre> <p>My solution, still probably not the best written code but it reduce the loading time from about 1-2 seconds to nearly instant (no noticeable wait time; didn't actually test how long it was).</p> <pre><code>for(int i = 0; i &lt; sortedDictionary.size(); i++){ for(int index = 0; index &lt; anagram.length(); index++) anagramCharacters[index] = anagram.charAt(index); forloop: for(int i2 = 0; i2 &lt; sortedDictionary.get(i).length(); i2++){ for(int i3 = 0; i3 &lt; anagramCharacters.length; i3++){ if(sortedDictionary.get(i).charAt(i2) == anagramCharacters[i3]){ anagramCharacters[i3] = 0; break; } else if(i3 == anagramCharacters.length-1) break forloop; } if(i2 == sortedDictionary.get(i).length()-1) anagram_words.add(sortedDictionary.get(i)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T17:48:08.603", "Id": "59490", "Score": "1", "body": "Just to be sure: you can't use the same letter twice in a word? Unless some of the 6 letters are themselves duplicates?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T01:33:31.823", "Id": "59526", "Score": "2", "body": "The only \"it\" you need to speed up is how long it takes to understand the code. Seriously, splitting this into subroutines will hep you speed the code up by helping you understand what the code actually does." } ]
[ { "body": "<p>if the number of words in the dictionary is small then you might be better off turning the code around and going over the words in the dictionary and checking if the words there have the 6 letters</p>\n\n<p>disregarding that you recreate the string several times it would be more efficient to keep the prefix in a char array</p>\n\n<pre><code>char[] prefix= new char[6];\nfor(int l1 = 0; l1 &lt; 6; l1++){\n prefix[0]=anagramCharacters[l1];\n for(int l2 = 0; l2 &lt; 6; l2++)\n if(l2 != l1){\n prefix[1]=anagramCharacters[l2];\n</code></pre>\n\n<p>then you can create the string with new String(prefix,0,3) (replace the 3 with the length)</p>\n\n<p><s>otherwise recursion to the rescue:</p>\n\n<pre><code>List&lt;String&gt; createAnagrams(char[] chars, SortedSet&lt;String&gt; sortedDictionary){\n List&lt;String result = new ArrayList&lt;String&gt;();\n fillListWithAnagrams(result, sortedDictionary, chars, 0);\n return result;\n}\n\nvoid fillListWithAnagrams(List&lt;String&gt; result, SortedSet&lt;String&gt; sortedDictionary, char[] chars, int charIndex){\n if(charIndex&gt;=3){\n String resultString = new String(chars,0,charIndex);\n if(sortedDictionary.contains(resultString);\n list.add(resultString);\n }\n\n if(charIndex&gt;=chars.length)\n return;//end of the line\n\n for(int i = charIndex;i&lt;chars.length;i++){\n char t = chars[i];\n chars[i] = chars[charIndex];\n chars[charIndex] = t;\n\n fillListWithAnagrams(list, sortedDictionary, chars, charIndex+1);\n\n // revert the char array for the next step\n //t=chars[charIndex];\n chars[charIndex] = chars[i];\n chars[i] = t;\n }\n\n}\n</code></pre>\n\n<p></s></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T17:00:05.000", "Id": "36303", "ParentId": "36300", "Score": "13" } }, { "body": "<p>This problem begs for recursion....</p>\n\n<pre><code>private static final void checkWord(char[] chars, char[]current, int len, List&lt;String&gt; results) {\n if (len == chars.length) {\n final String result = new String(current);\n if (sortedDictionary.contains(result)) {\n results.add(result);\n }\n } else {\n // get the next combination for what is left in the chars\n for int (i = xx; i &lt; yy; i++) {\n current[len] = .... // next char to try\n checkWord(chars, current, len+1 results);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<h1>EDIT</h1>\n\n<p>This is a 'nice' problem, it ties in all the favourite educational problems, factorial, combinations, and permutations...</p>\n\n<p>Here is working code that runs through the process.... I have commented it where I think necessary. I am doing this so that I have a record on here of what things are, and can refer back to it later, if needed.:</p>\n\n<pre><code>import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Set;\nimport java.util.TreeSet;\n\n\npublic class Words {\n\n /**\n * Calculate all possible ways to permute data sets of up to 'max' values...\n * &lt;p&gt;\n * The result is a multi-dimensional array, with result[2] being the ways to\n * permute 2-sized data sets ([1,2],[2,1]), and result[3] the way to permute 3-sized sets:\n * ([1,2,3],[1,3,2],[2,3,1],[2,1,3],[3,1,2],[3,2,1]),\n * etc.\n * \n * @param max the largest set to calculate permutations for.\n * @return the possible ways to permute sets of values up to max values in size\n */\n private static final int[][][] permutations(int max) {\n int[][][] ret = new int[max + 1][][];\n ret[0] = new int[0][];\n ret[1] = new int[1][1];\n for (int i = 2; i &lt;= max; i++) {\n ret[i] = new int[factorial(i)][];\n int[] remaining = new int[i];\n for (int j = 0; j &lt; i; j++) {\n remaining[j] = j;\n }\n permutationGen(i, ret[i], 0, new int[0], remaining);\n }\n return ret;\n }\n\n /**\n * calculate the factorial of a number.\n * The factorial is the number of permutations available for a given set of values.\n * @param n the number to calculate\n * @return the factorial (n!)\n */\n private static int factorial(int n) {\n int ret = n;\n while (--n &gt; 1) {\n ret *= n;\n }\n return ret;\n }\n\n /**\n * Recursive function to calculate the permutations of a dataset of a specified size.\n * @param size The number of elements to calculate the permutations for\n * @param store The place to store the permutations\n * @param nextstore the next location to save values in the store\n * @param used the positions that have been used in already in building the current permutations\n * @param remaining the remaining positions that need to be used.\n * @return the index of the next permutation to save\n */\n private static int permutationGen(final int size, final int[][] store, int nextstore, final int[] used, final int[] remaining) {\n\n if (used.length == size) {\n store[nextstore] = used;\n return nextstore + 1;\n }\n int [] nremain = Arrays.copyOfRange(remaining, 1, remaining.length);\n for (int r = 0; r &lt; remaining.length; r++) {\n int [] nused = Arrays.copyOf(used, used.length + 1);\n if (r &gt; 0) {\n nremain[r - 1] = remaining[r - 1];\n }\n nused[used.length] = remaining[r];\n nextstore = permutationGen(size, store, nextstore, nused, nremain);\n\n }\n return nextstore; \n }\n\n /**\n * Recursive combination function. It determines all possible combinations for a set of data, and for\n * each combination it also then runs through all permutations.\n * With the permutations it checks to see whether the word created by that combination/permutation is\n * a real word, and if it is, it adds it to the anagrams solution set.\n * @param words the valid words\n * @param chars the actual characters we can use to anagram\n * @param charpos the position in the chars that we are currently processing\n * @param current the letters we currently have in our combination already.\n * @param currentlen the number of letters in current that are valid.\n * @param permutes the possible permutations for different-sized datasets.\n * @param anagrams where to store the valid words when we find them.\n */\n private static void checkCombinations(final String[] words, final char[] chars, final int charpos,\n final char[] current, final int currentlen, final int[][][] permutes, final Collection&lt;String&gt; anagrams) {\n\n if (currentlen &gt;= current.length) {\n return;\n }\n\n for (int i = charpos; i &lt; chars.length; i++) {\n current[currentlen] = chars[i];\n\n // This is th recursive function to calculate combinations.\n checkCombinations(words, chars, i + 1, current, currentlen + 1, permutes, anagrams);\n\n // for each combination, run through all the permutations.\n char[] strchr = new char[currentlen + 1];\n for (int[] perm : permutes[currentlen + 1]) {\n for (int j = 0; j &lt;= currentlen; j++) {\n strchr[j] = current[perm[j]];\n }\n String word = new String(strchr);\n if (Arrays.binarySearch(words, word) &gt;= 0) {\n anagrams.add(word);\n }\n }\n\n }\n\n }\n\n public static void main(String[] args) throws IOException {\n System.out.println(\"Reading Linux words file (typically /usr/share/dict/linux.words)\");\n String words[] = Files.readAllLines(Paths.get(\"linux.words\"), StandardCharsets.UTF_8).toArray(new String[0]);\n System.out.println(\"Convert all to lowercase\");\n for (int i = 0; i &lt; words.length; i++) {\n words[i] = words[i].toLowerCase();\n }\n System.out.println(\"Sort all words (\" + words.length + \")\");\n Arrays.sort(words);\n char[] chars = \"abcdef\".toLowerCase().toCharArray();\n\n Set&lt;String&gt; anagrams = new TreeSet&lt;&gt;();\n\n System.out.println(\"building permutations for \" + chars.length + \" sizes\");\n int[][][] permutations = permutations(chars.length);\n\n System.out.println(\"calculating combinations and permutations of '\" + new String(chars) + \"'.\");\n long time = System.nanoTime();\n checkCombinations(words, chars, 0, new char[chars.length], 0, permutations, anagrams);\n System.out.printf(\"Found %d words.... in %.3fms\\n\", anagrams.size(), (System.nanoTime() - time) / 1000000.0);\n for (String s : anagrams) {\n System.out.println(s);\n }\n\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T17:01:02.837", "Id": "36304", "ParentId": "36300", "Score": "14" } }, { "body": "<p>Before I get started I have to say: <strong>Thank you</strong> for coming here. <strong>Mess of Java For Loops</strong> is almost an understatement. Now, let's get working, shall we?</p>\n\n<p>In the below answer I assume that <code>sortedDictionary</code> and <code>anagram_words</code> is both of type <code>List&lt;String&gt;</code>. I also assume that <code>anagramCharacters</code> is of type <code>char[]</code>.</p>\n\n<h3>Code duplication</h3>\n\n<p>Start by identifying which parts of the code looks similar, and create some methods to reduce <strong>code duplication</strong></p>\n\n<p>Code like this is repeated several times:</p>\n\n<pre><code>if(sortedDictionary.contains(\"\"+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]))\n anagram_words.add(\"\"+anagramCharacters[l1]+anagramCharacters[l2]+anagramCharacters[l3]);\n</code></pre>\n\n<p>This can be extracted to a method: <code>addWord()</code> (Note that the below method is not optimized for what it is doing, it is mainly so that you are able to understand what it does better).</p>\n\n<pre><code>private void addWord(char... chars) {\n String string = \"\";\n for (char ch : chars) string += ch; // Create a strings of the chars\n if (sortedDictionary.contains(string))\n anagram_words.add(string);\n}\n</code></pre>\n\n<p>So instead of repeatedly writing</p>\n\n<pre><code>if (sortedDictionary.contains(....)) anagram_words.add(...)\n</code></pre>\n\n<p>we simply call a method:</p>\n\n<pre><code>addWord(anagramCharacters[l1], anagramCharacters[l2], anagramCharacters[l3]);\n</code></pre>\n\n<h3>Variables with index</h3>\n\n<p>Whenever you find yourself using variable names that contains numbered values, such as <code>l1</code>, <code>l2</code>, <code>l3</code>, <code>l4</code>, STOP and think \"Would an array be useful here?\". Creating an <code>int[] letters</code> is far more flexible than using the multiple variables <code>l1</code>, <code>l2</code>, <code>l3</code></p>\n\n<p>If all the <code>l</code>-variables are instead inside the <code>letters</code> array, some things can be simplified further at the moment: </p>\n\n<ul>\n<li><p>This:</p>\n\n<pre><code>if(l4 != l1 &amp;&amp; l4 != l2 &amp;&amp; l4 != l3)\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>if(letters[3] != letters[0] &amp;&amp; letters[3] != letters[1] &amp;&amp; letters[3] != letters[2])\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>if(letters[3] != letters[0] &amp;&amp; letters[3] != letters[1] &amp;&amp; letters[3] != letters[2])\n</code></pre>\n\n<p>can become a method</p>\n\n<pre><code>private boolean lastLetterDifferent(int index) {\n for (int i = 0; i &lt; index; i++) {\n if (letters[i] == letters[index]) return false;\n }\n return true;\n}\n</code></pre></li>\n<li><p>The previous call we made to <code>addWord</code> only needs to contain the number of indexes to check instead of each and every char.</p>\n\n<pre><code>private void addWord(int numberOfChars) {\n String string = \"\";\n for (int i = 0; i &lt; numberOfChars; i++) string += anagramCharacters[letters[i]]; // Create a strings of the chars\n if (sortedDictionary.contains(string))\n anagram_words.add(string);\n}\n</code></pre></li>\n</ul>\n\n<h3>So now that's done, what remains now?</h3>\n\n<p>After doing the above refactoring, here is what's left:</p>\n\n<pre><code>for(letters[0] = 0; letters[0] &lt; 6; letters[0]++){\n for(letters[1] = 0; letters[1] &lt; 6; letters[1]++) {\n if(lastLetterDifferent(1)) {\n for(letters[2] = 0; letters[2] &lt; 6; letters[2]++) {\n if(letters[2] != letters[0] &amp;&amp; letters[2] != letters[1]) {\n addWord(3);\n for(letters[3] = 0; letters[3] &lt; 6; letters[3]++) {\n if (lastLetterDifferent(3)) {\n addWord(4);\n for(letters[4] = 0; letters[4] &lt; 6; letters[4]++){\n if (lastLetterDifferent(4)) {\n addWord(5);\n for(letters[5] = 0; letters[5] &lt; 6; letters[5]++){\n if (lastLetterDifferent(5)) {\n addWord(6);\n }\n } \n }\n } \n }\n }\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>That looks a lot cleaner, but how flexible is this? What if we want to use an 8-letter word, or a 12-letter word? <strong>NO, you should NOT continue this pattern and add more for-loops!</strong> So what other alternative is there? <a href=\"https://codereview.stackexchange.com/questions/36074/guess-a-random-number-between-a-selected-interval/36076#36076\">Recursive methods</a>, my friend!</p>\n\n<p>To do this, we need a couple of helper methods. You mentioned the number 720. It just so happens that 720 equals 6 <a href=\"http://en.wikipedia.org/wiki/Factorial\" rel=\"nofollow noreferrer\">factorial</a>. So let's create a factorial method.</p>\n\n<pre><code>public static int fact(int x) {\n if (x &lt; 0) throw new IllegalArgumentException(\"x cannot be negative: \" + x);\n if (x &lt;= 1) return 1;\n return x * fact(x - 1);\n}\n</code></pre>\n\n<p>This is a recursive because it calls itself on some occasions. More precisely, when <code>x &gt;= 2</code>. Recursive methods are fun, so let's create another one!</p>\n\n<pre><code>public static &lt;E&gt; List&lt;E&gt; permutationI(List&lt;E&gt; values, int iteration) {\n if (values.size() == 0)\n return new ArrayList&lt;E&gt;();\n List&lt;E&gt; list = new ArrayList&lt;E&gt;(values.size());\n int divisor = fact(values.size() - 1);\n int pos = iteration / divisor; // Pick an index depending on the iteration value\n list.add(values.remove((int)pos)); // Remove from one list and add to another\n list.addAll(permutationI(values, iteration % divisor)); // Call method recursively to get all the elements\n return list;\n}\n</code></pre>\n\n<p>Every time this method is called, it picks an index in the <code>values</code> list depending on the value of <code>iteration</code>. Then it gets the element for that index from the <code>values</code> list, removes that element from the <code>values</code> list and adds it to the list called <code>list</code> (which will be the methods result. Then this method calls itself to add all the remaining elements for the current iteration.</p>\n\n<p><strong>Putting it together:</strong></p>\n\n<p>We will need one more utility method to convert from a List of characters to a String (again, this method is not fully optimized. There are plenty of faster ways to do this).</p>\n\n<pre><code>public String charListToString(List&lt;Character&gt; list) {\n String result = \"\";\n for (Character ch : list) {\n result += ch;\n }\n return result;\n}\n</code></pre>\n\n<p>And now, the final touch to use all this recursive-ness:</p>\n\n<pre><code>List&lt;Character&gt; indexes = new ArrayList&lt;Character&gt;();\nfor (char ch : anagramCharacters)\n indexes.add(ch); // Build a list of the characters in our original word\nint totalPermutations = fact(indexes.size());\nfor (int i = 0; i &lt; totalPermutations; i++) {\n // Since permutationI modifies the list we send, we copy the list\n List&lt;Character&gt; newList = permutationI(new ArrayList&lt;Character&gt;(indexes), i);\n addWord(charListToString(newList)); // Call our method to add the word to the result list\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T18:32:52.747", "Id": "59499", "Score": "3", "body": "Thanks for the detailed response, I will read this all over when I get the chance as my coding style does need improving. I found a solution to my problem by someone else suggestion, but this is definitely the most informative post. +1 and the internet needs more people like you :) thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T01:39:47.523", "Id": "59528", "Score": "1", "body": "Instead of using a loop to add characters to a string, you really ought to be using the `new String(char [])` constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T01:50:42.480", "Id": "59529", "Score": "0", "body": "OK, just edited to use the `String` constructor where possibe, and `StringBuilder` otherwise; also added the `null` check to the method to convert the char list to a string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:39:34.243", "Id": "59610", "Score": "0", "body": "What @AJMansfield said. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String(char[]). Other than that the answer is great." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T21:26:08.813", "Id": "60103", "Score": "0", "body": "@AseemBansal I am aware that such things can be improved here. I didn't want to improve too much, only focus on the most important things. I thought that using `String` and iteratively adding to it is more comprehensive for the OP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T22:30:10.830", "Id": "60424", "Score": "0", "body": "I +1'ed the recursive answer, but this one deserves some kind of recognition for good attention to detail and informational style" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-24T06:02:32.110", "Id": "152732", "Score": "0", "body": "This answer is why I love this site." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T18:15:52.360", "Id": "36308", "ParentId": "36300", "Score": "36" } }, { "body": "<p>The nested for-loops are not your only problem. Even if you could restructure the code to avoid nesting, you would still be left with a scalability problem from the combinatoric explosion. In other words, the fact that you may need to check 6! = 720 dictionary entries for each six-letter word is the fundamental issue. You need a new algorithm: one that checks validity without generating all the possibilities.</p>\n\n<p>I propose that you sort the list of six valid letters. Then check whether the sorted letters of each candidate word are a subsequence of your sorted valid letters. (Subsequence is like substring, but with possible gaps.)</p>\n\n<pre><code>public static List&lt;String&gt; findWords(char[] letters, List&lt;String&gt; sortedDictionary) {\n letters = Arrays.copyOf(letters, letters.length);\n Arrays.sort(letters);\n char[] buf = new char[letters.length];\n\n List&lt;String&gt; anagramWords = new ArrayList&lt;String&gt;();\n for (String word : sortedDictionary) {\n int len = word.length();\n if (len &lt; 3 || len &gt; letters.length) {\n continue;\n }\n word.getChars(0, len, buf, 0);\n Arrays.sort(buf, 0, len);\n if (isSubsequence(buf, len, letters)) {\n anagramWords.add(word);\n }\n }\n return anagramWords;\n}\n\nprivate static boolean isSubsequence(char[] needle, int needleLen, char[] haystack) {\n for (int n = 0, h = 0; n &lt; needleLen &amp;&amp; h &lt; haystack.length; n++, h++) {\n while (needle[n] &gt; haystack[h]) {\n h++;\n if (h &gt;= haystack.length) {\n return false;\n }\n }\n if (needle[n] &lt; haystack[h]) {\n return false;\n }\n assert needle[n] == haystack[h];\n }\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T00:21:59.477", "Id": "36318", "ParentId": "36300", "Score": "7" } }, { "body": "<p>Once you realised that you were permuting the characters you should have stopped there and worked out how to do that in a general way.</p>\n\n<p>Here is a base class for permutations iteration:</p>\n\n<pre><code>public abstract class PermutationsIterator implements Iterator&lt;List&lt;Integer&gt;&gt; {\n // Length of the lists required.\n protected final int length;\n // The working list.\n protected final List&lt;Integer&gt; indexes;\n // The next to deliver.\n private List&lt;Integer&gt; next = null;\n\n public PermutationsIterator(int length) {\n this.length = length;\n indexes = new ArrayList&lt;&gt;(length);\n for (int i = 0; i &lt; length; i++) {\n indexes.add(i);\n }\n // Deliver the base one first.\n this.next = Collections.unmodifiableList(indexes);\n }\n\n // Return true if a next was available.\n protected abstract boolean getNext();\n\n @Override\n public boolean hasNext() {\n if (next == null) {\n // Is there one?\n if ( getNext() ) {\n // That's next!\n next = Collections.unmodifiableList(indexes);\n }\n }\n return next != null;\n }\n\n @Override\n public List&lt;Integer&gt; next() {\n List&lt;Integer&gt; n = hasNext() ? next : null;\n next = null;\n return n;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Cannot remove from permutations\");\n }\n\n}\n</code></pre>\n\n<p>From there you can implement a simple lexicographic iterator like this:</p>\n\n<pre><code>public class LexicographicPermutationsIterator extends PermutationsIterator implements Iterator&lt;List&lt;Integer&gt;&gt; {\n\n public LexicographicPermutationsIterator(int length) {\n super(length);\n }\n\n @Override\n protected boolean getNext() {\n boolean got = false;\n // Find the largest index k such that a[k] &lt; a[k + 1]. If no such index exists, the permutation is the last permutation.\n int k = -1;\n for (int i = 0; i &lt; length - 1; i++) {\n if (indexes.get(i) &lt; indexes.get(i + 1)) {\n k = i;\n }\n }\n if (k &gt;= 0) {\n int ak = indexes.get(k);\n // Find the largest index l such that a[k] &lt; a[l].\n int l = k + 1;\n for (int i = 0; i &lt; length; i++) {\n if (ak &lt; indexes.get(i)) {\n l = i;\n }\n }\n // Swap the value of a[k] with that of a[l].\n Collections.swap(indexes, k, l);\n // Reverse the sequence from a[k + 1] up to and including the final element a[n].\n Collections.reverse(indexes.subList(k + 1, indexes.size()));\n // We got one.\n got = true;\n }\n return got;\n }\n\n}\n</code></pre>\n\n<p>and you can then work out your anagrams with something as simple as:</p>\n\n<pre><code>public static void main(String args[]) {\n String testWord = \"ABCDEF\";\n Iterator&lt;List&lt;Integer&gt;&gt; it = new LexicographicPermutationsIterator(testWord.length());\n StringBuilder s = new StringBuilder(testWord.length());\n while ( it.hasNext() ) {\n List&lt;Integer&gt; p = it.next();\n s.setLength(0);\n for ( Integer i : p ) {\n s.append(testWord.charAt(i));\n }\n System.out.println(s);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T10:28:23.230", "Id": "36344", "ParentId": "36300", "Score": "6" } }, { "body": "<p>As the order doesn't matter, you can look at all the sorted words instead. You can also prebuild an index and make sure the code is warmer. Looking at a dictionary of 22K words, it takes an average of 9 micro-seconds on my laptop</p>\n\n<p>This is faster because there is only 42 combinations of sorted letters which have a length of 3 to 6 and each lookup is O(1) so it doesn't need to scan all the words.</p>\n\n<p>BTW If you want to improve the performance of some code you really have to time it because often you might change something assuming it will be faster and it is not. If you don't measure performance, you are guessing.</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.*;\n\npublic class WordsSearchMain {\n public static void main(String... ignored) throws IOException {\n Dictionary dict = new Dictionary(\"/usr/share/dict/words\", 3, 6);\n final String alphabet = \"abcdefghifjklmnopqrstuvwxyz\";\n String[] words = new String[22];\n for (int i = 0; i &lt; words.length; i++)\n words[i] = alphabet.substring(i, i + 6);\n\n // warmup the code\n for (int i = 0; i &lt; 12000; i += words.length)\n for (String word : words)\n dict.allWordsFor(word);\n // time to do 20 searches\n Map&lt;String, Set&lt;String&gt;&gt; searches = new LinkedHashMap&lt;&gt;();\n long start = System.nanoTime();\n for (String word : words)\n searches.put(word, dict.allWordsFor(word));\n long time = System.nanoTime() - start;\n\n System.out.printf(\"Took an average of %.1f micro-seconds, searching %,d words%n\",\n time / words.length / 1e3, dict.count);\n for (Map.Entry&lt;String, Set&lt;String&gt;&gt; entry : searches.entrySet()) {\n System.out.println(entry);\n }\n }\n\n}\n\nclass Dictionary {\n private final int min;\n Map&lt;String, List&lt;String&gt;&gt; wordForLetters = new HashMap&lt;&gt;();\n int count = 0;\n\n public Dictionary(String filename, int min, int max) throws IOException {\n this.min = min;\n try (BufferedReader br = new BufferedReader(new FileReader(filename))) {\n for (String line; (line = br.readLine()) != null; ) {\n if (line.length() &gt;= min &amp;&amp; line.length() &lt;= max) {\n char[] chars = line.toLowerCase().toCharArray();\n Arrays.sort(chars);\n String sorted = new String(chars);\n List&lt;String&gt; words = wordForLetters.get(sorted);\n if (words == null)\n wordForLetters.put(sorted, words = new ArrayList&lt;&gt;());\n words.add(line);\n count++;\n }\n }\n }\n }\n\n public Set&lt;String&gt; allWordsFor(String s) {\n Set&lt;String&gt; allWords = new TreeSet&lt;&gt;();\n String lower = s.toLowerCase();\n for (int i = (1 &lt;&lt; min) - 1; i &lt; (1 &lt;&lt; s.length()); i++) {\n int bitCount = Integer.bitCount(i);\n if (bitCount &lt; min) continue;\n StringBuilder sb = new StringBuilder(bitCount);\n for (int j = 0; j &lt; s.length(); j++)\n if (((i &gt;&gt; j) &amp; 1) != 0)\n sb.append(lower.charAt(j));\n final List&lt;String&gt; words = wordForLetters.get(sb.toString());\n if (words != null)\n allWords.addAll(words);\n }\n return allWords;\n }\n}\n</code></pre>\n\n<p>Prints</p>\n\n<pre><code>Took an average of 9.1 micro-seconds, searching 22,299 words\nabcdef=[Abe, Dec, Feb, Fed, abed, ace, aced, bad, bade, bead, bed, cab, cad, dab, deaf, deb, decaf, face, faced, fad, fade, fed]\nbcdefg=[Dec, Feb, Fed, bed, beg, deb, fed]\ncdefgh=[Che, Dec, Fed, chef, fed]\ndefghi=[Fed, Gide, die, dig, fed, fie, fig, hid, hide, hie, hied]\nefghif=[fie, fig, hie]\nfghifj=[fig, jig]\nghifjk=[JFK, jig]\nhifjkl=[JFK, ilk]\nifjklm=[JFK, Jim, Kim, ilk, mil, milk]\nfjklmn=[JFK]\njklmno=[Jon, Lon, Mon, Monk, monk]\nklmnop=[Lon, Mon, Monk, Polk, lop, monk, mop, pol]\nlmnopq=[Lon, Mon, Qom, lop, mop, pol]\nmnopqr=[Mon, Qom, Ron, mop, morn, nor, norm, porn, pro, prom, romp]\nnopqrs=[Ron, Son, nor, porn, pro, pros, son, sop]\nopqrst=[Post, opt, opts, port, ports, post, pot, pots, pro, pros, rot, rots, sop, sort, sot, sport, spot, stop, strop, top, tops, tor, tors]\npqrstu=[Prut, Stu, pus, put, puts, rust, rut, ruts, spur, spurt, sup, ups]\nqrstuv=[Stu, rust, rut, ruts]\nrstuvw=[Stu, rust, rut, ruts]\nstuvwx=[Stu, tux]\ntuvwxy=[tux]\nuvwxyz=[]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T18:51:54.667", "Id": "36718", "ParentId": "36300", "Score": "3" } }, { "body": "<p>First, let's consider the numbers.</p>\n\n<p>You have 720 anagrams to check, and 2700 words. Instead of generating all anagrams and look them up, you can scan all words and see if they are \"included\" in the letters you have. You are trading one expensive lookup with 4 iterations in a loop. That might be faster.</p>\n\n<p>That is why I will comment your second code fragment. I think it was a good start.</p>\n\n<ol>\n<li>A loop over a collection can be written in a more compact style. Also. declaring a variable for the word avoids recomputing sortedDictionary.get(i) many times.</li>\n<li>Extracting chars from a String can be expressed with string.toCharArray().</li>\n<li>You can also test from outside the loop whether you completed the loop. The break out of a named loop isn't necessary.</li>\n<li>It is usually better to save to a local variable an expression like word.getCharAt(i) instead of recomputing it over and over. Not sure whether it is a big difference for getCharAt, though.</li>\n</ol>\n\n<p>So far we have</p>\n\n<pre><code> for(String word : sortedDictionary){\n char[] anagramCharacters = anagram.toCharArray();\n int i2, i3;\n for(i2 = 0; i2 &lt; word.length(); i2++){\n char wordChar = word.charAt(i2);\n for(i3 = 0; i3 &lt; anagramCharacters.length; i3++){\n if(wordChar == anagramCharacters[i3]){\n anagramCharacters[i3] = 0;\n break;\n }\n }\n // break out if wordChar did not match any anagramCharacters\n if(i3 == anagramCharacters.length)\n break;\n }\n // add the word if all letters were found in the anagram letters\n if(i2 == word.length())\n anagram_words.add(word);\n }\n</code></pre>\n\n<p>But I am still not happy with it. I prefer to control the program flow using boolean variables. They somehow explain the why of the execution flow.</p>\n\n<pre><code> for(String word : sortedDictionary){\n char[] anagramCharacters = anagram.toCharArray();\n boolean anagramOK = true;\n for(char wordChar : word.toCharArray()){\n boolean found = false;\n for(int i = 0; !found &amp;&amp; i &lt; anagramCharacters.length; i++){\n if(wordChar == anagramCharacters[i]){\n anagramCharacters[i] = 0;\n found = true;\n }\n }\n // if not found, the word is not compatible with the anagram letters\n if(!found){\n anagramOK = false;\n break;\n }\n }\n // add the word if all letters were found in the anagram letters\n if(anagramOK)\n anagram_words.add(word);\n }\n</code></pre>\n\n<p>PS: and yes, some people prefer brackets around every statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-30T00:38:58.503", "Id": "61524", "ParentId": "36300", "Score": "0" } } ]
{ "AcceptedAnswerId": "36303", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T16:38:07.880", "Id": "36300", "Score": "27", "Tags": [ "java", "array", "strings", "combinatorics" ], "Title": "Finding words of different lengths given six letters" }
36300
<p>With a first official commercial release in 1984, Progress 4GL was initially a procedural language and has since had object-oriented extensions added to the language starting with the OpenEdge 10.1 version. The language offers tight data binding to the Progress OpenEdge database and also runs on the OpenEdge AppServer.</p> <p>The Progress 4GL is now known as the <a href="http://en.wikipedia.org/wiki/OpenEdge_Advanced_Business_Language" rel="nofollow">OpenEdge ABL (Advanced Business Language)</a> and is produced by the OpenEdge division of Progress Software Corporation.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T00:02:47.790", "Id": "36316", "Score": "0", "Tags": null, "Title": null }
36316
The Progress 4GL is a multi-platform interpreted language typically used to build business applications and is now known as ABL.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T00:02:47.790", "Id": "36317", "Score": "0", "Tags": null, "Title": null }
36317
<p>From the <a href="https://github.com/baconjs/bacon.js#readme" rel="nofollow">GitHub README</a>:</p> <blockquote> <p>A small functional reactive programming lib for JavaScript.</p> <p>Turns your event spaghetti into clean and declarative feng shui bacon, by switching from imperative to functional. It's like replacing nested for-loops with functional programming concepts like <code>map</code> and <code>filter</code>. Stop working on individual events and work with event-streams instead. Transform your data with <code>map</code> and <code>filter</code>. Combine your data with <code>merge</code> and <code>combine</code>. Then switch to the heavier weapons and wield <code>flatMap</code> and <code>combineTemplate</code> like a boss. It's the <code>_</code> of Events. Too bad the symbol ~ is not allowed in Javascript. </p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T01:51:39.887", "Id": "36322", "Score": "0", "Tags": null, "Title": null }
36322
Functional reactive programming library for JavaScript.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T01:51:39.887", "Id": "36323", "Score": "0", "Tags": null, "Title": null }
36323
<p>'<a href="http://en.wikipedia.org/wiki/Secure_Sockets_Layer" rel="nofollow">Secure Sockets Layer</a>' was originally a comp.sources Usenet post in the 1980s, using a fairly primitive security protocol. Netscape Communication Corp pioneered the current SSL protocol, in SSL 2.0, the first version deployed, followed by SSL 3.0. At that point the <a href="http://www.ietf.org/" rel="nofollow">IETF</a> decided to standardize on this protocol, so <a href="http://tools.ietf.org/html/rfc2246" rel="nofollow">RFC 2246</a> defined the next version of this protocol. There was some uncertainty over the intellectual property rights to the SSL name so the IETF chose the name Transport Layer Security (TLS). Today the names SSL and TLS are essentially synonyms. However, if you refer to a specific version you should include the correct name, e.g SSL 3.0 or TLS 1.1. As a progression it goes SSL 2.0 &lt; SSL 3.0 &lt; TLS 1.0 &lt; TLS 1.1 &lt; ..., where "&lt;" means "precedes.</p> <p>Both SSL and TLS assume they are running above a connection-oriented protocol, i.e. TCP. A different but related protocol, <a href="http://tools.ietf.org/html/rfc4347" rel="nofollow">Datagram Transport Layer Security (DTLS)</a>, is defined over connectionless protocols such as UDP.</p> <p>SSL is a mature protocol, now more than 15 years old, with vast support on a multitude of clients, servers, platforms, and libraries. Perhaps the most well-known protocol that uses SSL is the <a href="http://tools.ietf.org/html/rfc2818" rel="nofollow">HTTPS</a> protocol, which is the HTTP protocol running over SSL.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T02:26:19.887", "Id": "36325", "Score": "0", "Tags": null, "Title": null }
36325
Secure Sockets Layer (SSL) is a cryptographic protocol that provides communications security over the Internet. The more modern version of this protocol is Transport Layer Security (TLS), specified by the IETF in RFC 2246.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T02:26:19.887", "Id": "36326", "Score": "0", "Tags": null, "Title": null }
36326
<p>Given some cubes, can cubes be arranged such that an input word can be formed from the top view of the cubes?</p> <p>For example: assume an imaginary cube with only 3 surfaces where <code>cube1: {a, b, c}</code> and <code>cube2 {m, n, o}</code>, then word <code>an</code> can be formed but word <code>ap</code> cannot be formed.</p> <p>Please look into the two following issues:</p> <ol> <li>A couple of questions nested inside the codes regarding premature optimization. </li> <li>Verifying complexity to be O(n!), where n is the number of alphabets in the word.</li> </ol> <p></p> <pre><code>public final class CubeFind { private CubeFind() {} public static boolean checkWord(char[][] cubeMatrix, String word) { /* * Premature optimization: read that they were bad practices. they look good in my code, should i keep them ? * * 1. If not checked now, then NPE would result after hashMap is computed. on line 46 * if (cubeMatrix == null) { throw new NullPointerException("The input cube matrix should not be null"); * * 2. if (word == null {throw new NullPointerException("The input word should not be null"); } * * 3. if (cubeMatrix.length != word.length()) return false; */ char[] chWords = word.toCharArray(); final Map&lt;Character, Integer&gt; charFreq = new HashMap&lt;Character, Integer&gt;(); for (char ch : chWords) { if (charFreq.containsKey(ch)) { charFreq.put(ch, charFreq.get(ch) + 1); } else { charFreq.put(ch, 1); } } return findWordExists(cubeMatrix, charFreq, 0); } private static boolean findWordExists (char[][] cubeMatrix, Map&lt;Character, Integer&gt; charFreq, int cubeNumber) { assert charFreq != null; if (cubeNumber == cubeMatrix.length) { for (Integer frequency : charFreq.values()) { if (frequency &gt; 0) return false; } return true; } for (int i = 0; i &lt; cubeMatrix[cubeNumber].length; i++) { if (charFreq.containsKey(cubeMatrix[cubeNumber][i])) { int frequency = charFreq.get(cubeMatrix[cubeNumber][i]); // this check is needed to get a false result when input chars are less than number of cubes // eg: 'hel' should return false. if (frequency &gt; 0) { charFreq.put(cubeMatrix[cubeNumber][i], frequency - 1); if (findWordExists(cubeMatrix, charFreq, cubeNumber + 1)) { return true; } charFreq.put(cubeMatrix[cubeNumber][i], frequency); } } } return false; } public static void main(String[] args) { char[][] m = {{'e', 'a', 'l'} , {'x', 'h' , 'y'}, {'p' , 'q', 'l'}, {'l', 'h', 'e'}}; System.out.println("Expected true, Actual: " + CubeFind.checkWord(m, "hell")); System.out.println("Expected true, Actual: " + CubeFind.checkWord(m, "help")); System.out.println("Expected false, Actual: " + CubeFind.checkWord(m, "hplp")); System.out.println("Expected false, Actual: " + CubeFind.checkWord(m, "hplp")); System.out.println("Expected false, Actual: " + CubeFind.checkWord(m, "helll")); System.out.println("Expected false, Actual: " + CubeFind.checkWord(m, "hel")); } } </code></pre>
[]
[ { "body": "<blockquote>\n<p>Verify complexity to be O(n!), where n is the number of alphabets in the word.</p>\n</blockquote>\n<p>Indeed.</p>\n<pre><code> private CubeFind() {}\n</code></pre>\n<p>You don't need this to get a default constructor.</p>\n<blockquote>\n<p>Premature optimization: read that they were bad practices. they look good in my code, should i keep them ?</p>\n<p>If not checked now, then NPE would result after hashMap is computed. on line 46</p>\n<ol>\n<li><p><code>if (cubeMatrix == null) { throw new NullPointerException(&quot;The input cube matrix should not be null&quot;)</code>;</p>\n</li>\n<li><p><code>if (word == null {throw new NullPointerException(&quot;The input word should not be null&quot;); }</code></p>\n</li>\n</ol>\n</blockquote>\n<p>Please don't do that! You're not gaining anything, the first reason being that it's going to fail very quickly if you really get <code>null</code> or <code>word</code>. The second reason is that there's no reason to get null here, why would that happen? You're simply calling this function from <code>main</code>, it cannot be null. When not for useless optimizations, this practice is called <a href=\"http://en.wikipedia.org/wiki/Defensive_programming\" rel=\"nofollow noreferrer\">defensive programming</a> and is only useful in a few specific scenarios.</p>\n<pre><code> if (cubeMatrix.length != word.length()) return false;\n</code></pre>\n<p>This one can also be seen as a way to eliminate cases you don't want to reason about later on. That is, you know after this line that you will have the correct number of cubes, and it simplifies the reasoning and the code. You should keep it.</p>\n<pre><code>if (cubeNumber == cubeMatrix.length) {\n</code></pre>\n<p>This one wasn't obvious at first, and could deserve a comment, eg. &quot;If we chose a letter for all cubes, check that no letter is left&quot;, maybe.</p>\n<pre><code>charFreq.put(cubeMatrix[cubeNumber][i], frequency - 1);\nif (findWordExists(cubeMatrix, charFreq, cubeNumber + 1)) {\n return true;\n}\ncharFreq.put(cubeMatrix[cubeNumber][i], frequency);\n</code></pre>\n<p>Nice trick. Another way to do it is to give a copy of cubeMatrix. You would then avoid the second <code>put</code>, but it could be very costly here due to the number of copies you would have to do: don't do it.</p>\n<p>I would define premature optimization as &quot;a change made for performance reasons that brings no benefit or degrades readability, and has not been proved to actually improve performance&quot;.</p>\n<p>Last, your tests are okay for this usage, but consider using an unit test library like JUnit to manage tests, this will help you later on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T12:41:41.227", "Id": "36350", "ParentId": "36328", "Score": "2" } } ]
{ "AcceptedAnswerId": "36350", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T03:15:24.333", "Id": "36328", "Score": "2", "Tags": [ "java", "recursion", "complexity", "matrix" ], "Title": "Given set of cubes can we get a given word?" }
36328
<p>This is a cocoa app that adds a right click menu option to change whether a file is executable. It works by executing the system command <code>chmod</code> on each of the files. But I want to know if there is a better way to change the permission of a file, such as a cocoa function that can change the permission of a file.</p> <p>What are some other ways that I can improve my code?</p> <pre><code>#import "AppDelegate.h" @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Insert code here to initialize your application [NSApp setServicesProvider:self]; NSUpdateDynamicServices(); } void runSystemCommand(NSString *cmd) { NSTask *task = [[NSTask alloc] init]; [task setLaunchPath:@"/bin/chmod"]; if ([[NSFileManager defaultManager] isExecutableFileAtPath:cmd]) { //NSLog(@"is executable \n"); [task setArguments:@[ @"-x", cmd]]; [task launch]; } else { //NSLog(@"is not executable \n"); [task setArguments:@[ @"+x", cmd]]; [task launch]; } } - (void)handleServices:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error { if([[pboard types] containsObject:NSFilenamesPboardType]){ NSArray* fileArray=[pboard propertyListForType:NSFilenamesPboardType]; int i; int count; count = [fileArray count]; for (i = 0; i &lt; count; i++){ //NSLog (@"%@", [fileArray objectAtIndex: i]); runSystemCommand([fileArray objectAtIndex: i]); } } } @end </code></pre> <p><a href="https://github.com/kylelk/Toggle-Executable" rel="nofollow">Here</a> is the repository for the complete project.</p>
[]
[ { "body": "<p>The relevant <code>NSFileManager</code> call, in Foundation, is <code>- setAttributes:ofItemAtPath:error:</code>, and it is the same in <a href=\"https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/setAttributes%3aofItemAtPath%3aerror%3a\" rel=\"nofollow\">iOS</a> as in <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/setAttributes%3aofItemAtPath%3aerror%3a\" rel=\"nofollow\">Mac OS X</a>. (It's funny that you already call <code>- isExecutableFileAtPath:</code> in the same <code>NSFileManager</code> class.) Even if you weren't familiar with Foundation, you would still be better off calling the POSIX function <a href=\"https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/chmod.2.html\" rel=\"nofollow\"><code>chmod(2)</code></a> rather than the <a href=\"https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/chmod.1.html\" rel=\"nofollow\"><code>chmod(1)</code></a> command.</p>\n\n<p>You've neglected to do any kind of error handling on the <code>/bin/chmod</code> task. The operation could easily fail if, for example, the user did not have permission to modify the file.</p>\n\n<p>It's misleading to name the parameter of <code>runSystemCommand()</code> <code>cmd</code>, as it really only contains the path to the file whose permissions are to be toggled.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T07:22:24.733", "Id": "36333", "ParentId": "36329", "Score": "3" } } ]
{ "AcceptedAnswerId": "36333", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T03:29:54.567", "Id": "36329", "Score": "4", "Tags": [ "beginner", "objective-c", "file-system", "osx" ], "Title": "Change whether file is executable" }
36329
<p>So, I have a basic 'contact us' form that i have built, and I do some jQuery checking first (that a phone number is only numbers, email address doesn't contain unneeded characters, etc), but I also wanted to do some sanitization before sending out the email.</p> <p>After reading many questions on SO (such a great service!) then doing some more reading on PHP.net and seeing some 'in use' code on W3Schools this is what I came up with. Is it secure? Is there more I should be doing? Is this overkill?</p> <p>It should be said that the user content lives on my server for a very short amount of time and then is sent off to email services (GMail and HostGator)</p> <pre><code>&lt;? $name = filter_var($_POST[name], FILTER_SANITIZE_STRING); $email = filter_var($_POST[email], FILTER_SANITIZE_EMAIL); $phone = filter_var($_POST[phone], FILTER_SANITIZE_NUMBER_INT); $usermessage = filter_var($_POST[message], FILTER_SANITIZE_STRING); $businessmessage = filter_var($_POST[businessmessage], FILTER_SANITIZE_STRING); $to = "spokedcouriers@gmail.com, tom@spokedcouriers.com"; $subject = "Incoming from SpokedCouriers."; $message = "&lt;b&gt;Submitted From: &lt;/b&gt;".$name."&lt;br&gt;". "&lt;b&gt;Email Address: &lt;/b&gt;".$email . "&lt;br&gt;" . "&lt;b&gt;Phone Number: &lt;/b&gt;".$phone . "&lt;br&gt;" . "&lt;b&gt;Message: &lt;/b&gt;".$usermessage . "&lt;br&gt;" . "&lt;b&gt;Possible Business Message From: &lt;/b&gt;".$businessmessage."&lt;br&gt;"; $headers = 'MIME-Version: 1.0' . "\r\n" .'Content-type: text/html; charset=iso-8859-1' . "\r\n" .'From: ' . $email . "\r\n" .'Reply-To: ' . $email . "\r\n"; //GO AWAY. mail($to, $subject, $message, $headers); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T10:17:16.640", "Id": "59555", "Score": "1", "body": "_\"PHP Notice: Use of undefined constant name - assumed 'name'\"_ and _\"PHP Notice: Use of undefined constant email - assumed 'email'_ and so on... edit your ini file, and set it to `E_STRICT | E_ALL` for debugging, and show the errors! The notices are there _to help you_, don't ignore them" } ]
[ { "body": "<p><strong>Is it secure?</strong></p>\n\n<p>Let me answer that question with a question, are you using the HTTPS protocol to send the form data from the user to the server? If not, anyone 'listening' on the connection could potentially read the mail-data that the user is sending to the server.</p>\n\n<p>As for the PHP script itself, well, you sure do sanitize it, but that's not a real issue with mail, the main problem with mail is having it exploited to the extent of someone spamming with it. So if the location of the PHP file containing the script is available to the world wide web, anyone can send mails with it, allowing <em>us</em> to exploit it.</p>\n\n<p>Try reading up on sessions, or maybe using a simple <code>.htaccess</code> file to avoid unwelcome users.</p>\n\n<p><code>GO AWAY.</code> What is that part in your code? Did you even notice that it's there?</p>\n\n<p>Also, this is how you fetch data from <code>$_POST</code>: <code>$_POST[\"key_here\"];</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T02:48:12.070", "Id": "59539", "Score": "0", "body": "I noticed the 'go away' blip right after I posted the question and commented it out in my code.\n\nHow would sessions help with this form? I do have a simple .htaccess blocking public view of my PHP files.\n\nI am not using HTTPS to send the data. I would have to do some reading up on using that over my current scheme. Any helpful links?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T02:51:18.107", "Id": "59540", "Score": "0", "body": "Sessions would be a go-to instead of .htaccess login, but seeing as you're using that, you wont need it. HTTPS is a whole different matter, but it's worthwhile reading up on if you're interested in having secure web applications. I'd suggest a google of: \"What is SSL?\" or \"What is HTTPS?\", gives some interesting results, just take into account that most of the answers are supplied by SSL cert. supplicants, so the answers may be biased." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T02:42:06.960", "Id": "36331", "ParentId": "36330", "Score": "1" } }, { "body": "<p>Ok, this may come across as blunt or harsh, but IMO, that's what CodeReview has to do, <a href=\"https://codereview.meta.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag\">as I explained earlier here</a>.<br/>\nSo please, keep that in mind while reading this post.</p>\n\n<p>Before I even start dealing with your code, I'd like to point out to you that you're using an unreliable, incomplete and misleading resource: w3schools. Sure, it may get some things right, but IMO, it's a misleading site. Many think the site is condoned, or even part of the W3C org. This is <em>not</em> the case, <a href=\"http://www.w3fools.com/\" rel=\"nofollow noreferrer\">Please check the criticisms</a>.<br/>\nYou are, of course, free to use w3schools, but be aware that it's not the best resource out there.</p>\n\n<p><strong><em>Is it secure?</em></strong><br/>\nNo. I'd like to be kind about this, but that wouldn't help you. No, your code is still vulnerable to things like mail injection. I could easily copy paste some mail headers into your form and have <em>your</em> server, seemingly, forward a message sent yesterday by your rich, recently so tragically deceased alienated uncle in Barbados who left you his entire fortune.<br/>\nI've included a link on mail injection in the bottom of this answer. This is an important issue that you need to address, still.</p>\n\n<p>Now, the code:</p>\n\n<p>I'll be going over your code block by block, sometimes even line-by-line:</p>\n\n<pre><code>&lt;?\n</code></pre>\n\n<p>Don't use the short tag! Never. Period. It's not a lot of effort to write <code>&lt;?php</code> instead, and it's far more reliable (<code>&lt;?php</code> won't be confused with the odd <code>&lt;? xml...</code>), and doesn't rely on the short-tags being enabled on your server.</p>\n\n<pre><code>$name = filter_var($_POST[name], FILTER_SANITIZE_STRING);\n$email = filter_var($_POST[email], FILTER_SANITIZE_EMAIL);\n$phone = filter_var($_POST[phone], FILTER_SANITIZE_NUMBER_INT);\n$usermessage = filter_var($_POST[message], FILTER_SANITIZE_STRING);\n$businessmessage = filter_var($_POST[businessmessage], FILTER_SANITIZE_STRING);\n</code></pre>\n\n<p>Ok, this block is essentially doing the same thing several times, and suffers from the same issue throughout.<br/>\nFirst off, when setting the error reporting level to the <em>Correct</em> debugging levels of <code>E_STRICT | E_ALL</code>, you'll see a ton of notices and warnings pop up:</p>\n\n<ul>\n<li>PHP Notice: Use of undefined constant name - assumed 'name'</li>\n</ul>\n\n<p>This means you forgot to quote the array keys, PHP will helpfully <em>assume</em> you meant 'name', but it will issue a notice. This makes your code look sloppy and amateurish. More over, it costs resources, slowing your code down.</p>\n\n<ul>\n<li>PHP Notice: Undefined index: name</li>\n</ul>\n\n<p>If your script is being executed and none, or not all of the post parameters have been sent, you're still accessing those keys in the <code>$_POST</code> super global. At no point are you checking if there has been a POST request.<br/>\nThis can produce the notice above, for each time you access the POST array. Add some basic checks:</p>\n\n<pre><code>&lt;?php//full tag\nif (!$_POST) exit();//no post request, no magic!\n$name = isset($_POST['name']) ? filter_var($_POST['name'], FILTER_SANITIZE_STRING) : null;\n</code></pre>\n\n<ul>\n<li>Don't \"over-filter\"!</li>\n</ul>\n\n<p>Where your usage of <code>filter_var($email, FILTER_VALIDATE_EMAIL)</code> is to be commended, your code:</p>\n\n<pre><code>$phone = filter_var($_POST[phone], FILTER_SANITIZE_NUMBER_INT);\n</code></pre>\n\n<p>is <em>not</em> the best of ideas. Now I don't know how you get the input from the user, but if I were to punch in <em>\"+10800123456\"</em>, I'd translate that <code>+</code> to double 0, to standardize the input.<br/>\nApart from that <code>FILTER_SANITIZE_NUMBER_INT</code> will clean up input like <em>\"123.313.456,1\"</em>, removing the comma and dots, but it will leave the dashes and plusses in <em>\"+123-313+456-1\"</em> untouched. If I were you, I'd simply do something like:</p>\n\n<pre><code>if ($phone{0} == '+')\n $phone = '00'.$phone;\npreg_replace('/[^0-9]+/','',$phone);\n</code></pre>\n\n<p>This expands a <em>leading</em> + to double zeroes and removes everything <em>Except</em> digits from the string. You can then easily check the length, to determine (roughly) the validity of the input. If it's 3 digits long, it probably isn't valid.</p>\n\n<ul>\n<li><code>mail</code> is good for testing, less so for production</li>\n</ul>\n\n<p>Sure <code>mail</code> is easy (once you get your server settings worked out), and does what it says on the tin: it sends an email.<br/>\nHowever, sometimes you might require an alt-body (text and HTML), sometimes you may want to add attachments. Writing those headers all the time is a bit of a faff, and <em>has been done before</em>. Good programmers are lazy: they won't bother writing code that exists, and is free to use. <a href=\"http://phpmailer.worxware.com/\" rel=\"nofollow noreferrer\">The <code>PHPMailer</code> class is in common usage</a> and is <em>very</em> easy to set up, and quite versatile. Though, <a href=\"http://www.codeproject.com/Articles/428076/PHP-Mail-Injection-Protection-and-E-Mail-Validatio#sanitisation_summary\" rel=\"nofollow noreferrer\">as you can see here, still somewhat open to mail injection</a>. </p>\n\n<p>In terms of security, <code>PEAR::Mail</code> is still the better option (though not in terms of clean code IMO). Read through the link, and learn about mail injection some more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:40:01.580", "Id": "60024", "Score": "0", "body": "`I could easily copy paste some mail headers into your form` - really? The only variable in the headers is `$email` which is `filter_var`ed as an email address - if you believe the code to be exploitable a specific example for the code posted would be appropriate. +1 anyway as the general advice is sound." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:02:23.163", "Id": "60028", "Score": "0", "body": "@AD7six: Try posting a raw email message in various online mail providers. Only a year ago, most of these services (yes, including microsoft's hotmail) failed to deal with that properly... It wasn't shown as simple copy-paste flat text, but it was actually rendered as a series of forwarded messages (I noticed this when I tried to help someone who was the victim of a scam. I needed the headers to track the origin of the messages)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:28:27.690", "Id": "60032", "Score": "0", "body": "That is a none-answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:03:42.147", "Id": "60038", "Score": "0", "body": "@AD7six: What I was hinting at is that `$usermessage` may contain html or mail headers, which may _\"confuse\"_ a mail client" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:07:24.120", "Id": "60039", "Score": "0", "body": "Maybe we aren't talking about the same thing then. email header injection is what the answer suggests is possible (\"No, your code is still vulnerable\") whereas the misrepresentation of text in a mail client is simply not the same sort of problem - it's not like you can exploit that to send mails as someone else." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T13:50:43.917", "Id": "36354", "ParentId": "36330", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T02:26:40.550", "Id": "36330", "Score": "2", "Tags": [ "php", "security" ], "Title": "Critique sanitized user email PHP Script" }
36330
<p>I've created a method which is useful for executing multiple queries, and it works perfectly. Is this a good way to handle this? </p> <pre><code>public function foo($rQuery) { try { $this-&gt;done-&gt;beginTransaction(); foreach($rQuery as $val) { $rSql = $this-&gt;done-&gt;prepare($val); $rSql-&gt;execute(); } $commitCode = $this-&gt;done-&gt;commit(); } catch (PDOException $ex) { $errorInfo = "Ooops: ".$ex-&gt;getMessage(); $roalBackCode = $this-&gt;done-&gt;rollBack(); } return array('errorInfo' =&gt; $errorInfo, 'commitCode' =&gt; $commitCode, 'roalBackCode' =&gt; $roalBackCode); } </code></pre>
[]
[ { "body": "<p>I think this is going to be a first, but <em>yes</em>. If I had to work on a project, and come across this code, I'd be happy. The only thing I'd change, perhaps, is the name of the PDO instance: <code>$this-&gt;done</code> doesn't say <em>I am a DB connection</em>, IMO. The catching of the exception is required here, but the fact that you're not re-throwing it, or throwing a new, more generic exception is debatable. I'll briefly explain why, but that's entirely up to you to decide</p>\n\n<p>Other than that, I'd say you're pretty much on the money.<br/>\nA couple of suggestions, though:</p>\n\n<p><em>Type-hinting</em><br/>\nYou're <em>assuming</em> the user of your code will be so kind as to pass an array of strings to your function. He/she would have to look at your method to determine what arguments you're expecting. An easier way of doing this would be:</p>\n\n<pre><code>public function foo(array $queries)\n{//this method clearly expects an array, pass something else, and it will crash\n}\n</code></pre>\n\n<p><em>Strings</em><br/>\nYou're also assuming the array argument will be an array of strings, whereas there is <em>no guarantee</em> that'll be the case. If I were you, I'd do some checking/filtering:</p>\n\n<pre><code>$queries = array_filter($queries, 'is_string');\n</code></pre>\n\n<p>That will filter out any non-string elements from the argument array.</p>\n\n<p><em>Notice: undefined variables</em><br/>\nThe array you're returning uses both the <code>$commitCode</code> and <code>$errorInfo</code> variables. Why? If the commitCode variable was set, then there will be no errorInfo. Include a return statement in the try block, or return <code>true</code>. If there was an error, <em>then</em> return the errorInfo.</p>\n\n<pre><code>return $this-&gt;db-&gt;commit();\n//in catch:\nreturn array('errorInfo' =&gt; $e-&gt;getMessage(), 'rollback' =&gt; $this-&gt;db-&gt;rollBack());\n</code></pre>\n\n<p>Or better still, <em>rethrow the exception</em> possibly contained within a more generic/custom exception object. The caller should be allowed to handle exceptions. <em>The caller should know what was passed to your method</em>, therefore any resulting exception is <em>his responsibility</em>:</p>\n\n<pre><code>catch (PDOException $e)\n{\n throw new RuntimeException(\n 'Not commited: '. $this-&gt;db-&gt;rollBack(),\n 0,\n $e\n );\n}\n</code></pre>\n\n<p><em>Prepared statements, no binds</em><Br/>\nOf course, this isn't your <em>actual</em> code, I take it, but you're creating prepared statements and then execute them with no (room for) binds.</p>\n\n<p>If the query strings come from a trusted source, there's no need to create an instance of <code>PDOStatement</code>, IMO:</p>\n\n<pre><code>foreach($queries as $query)\n{\n $this-&gt;db-&gt;exec($query);\n}\n</code></pre>\n\n<p>will do, and it'll increase performance, too</p>\n\n<p><em>Allow binds</em><br/>\nYou'll soon find this method lacking in usability, though. If I wanted to execute a number of <code>SELECT * FROM tbl WHERE ...</code> or <code>UPDATE</code> or <code>INSERT</code> or any query with parameters for that matter, I can't use your method.<br/>\nDon't worry, though, for that's an easy fix:</p>\n\n<pre><code>public function foo(array $queries)\n{\n try\n {\n foreach($queries as $query)\n {\n if (is_array($query))\n {\n $stmt = $this-&gt;db-&gt;prepare($query['prepare']);\n $stmt-&gt;execute($query['bind']);\n }\n else\n {\n if (is_string($query)) $this-&gt;db-&gt;exec($query);\n }\n }\n return $this-&gt;db-&gt;commit();\n }\n catch (PDOException $e)\n {\n return array(\n 'errorInfo' =&gt; $e-&gt;getMessage(),\n 'rollbackCode' =&gt; $this-&gt;db-&gt;rollBack()\n );\n }\n}\n</code></pre>\n\n<p>That way, I'm able to call this method like so:</p>\n\n<pre><code>$instance-&gt;foo(\n array(\n 'SELECT * FROM someTable',\n array(\n 'prepare' =&gt; 'SELECT * FROM anotherTable WHERE someField = :field',\n 'bind' =&gt; array(':field' =&gt; $val)\n )\n);\n</code></pre>\n\n<p>Of course, this implementation still depends on the user being kind enough to pass the correct arrays to your method. If I were you, I'd create an <em>\"Argument class\"</em>:</p>\n\n<pre><code>class QueryArgument\n{\n private $query = null;\n private $bind = null;\n public function __construct($query = null, array $bind = null)\n {\n if (is_array($query))\n {//allow user to pass array('prepare' =&gt; '', 'bind')\n $bind = isset($query['bind']) &amp;&amp; is_array($query['bind']) ? $query['bind'] : null;\n $query = isset($query['prepare']) ? $query['prepare'] : null;\n }\n $this-&gt;query = is_string($query) ? $query : null;\n $this-&gt;bind = null;\n }\n //this is just to make life easier\n public function getTransactionFormat()\n {\n if ($this-&gt;bind)\n {\n return array(\n 'prepare' =&gt; $this-&gt;query,\n 'bind' =&gt; $this-&gt;bind\n );\n }\n return $this-&gt;query;\n }\n //implement getters and setters\n public function setBind(array $bind)\n {\n $this-&gt;bind = $bind;\n return $this;\n }\n public function getBind()\n {\n return $this-&gt;bind;\n }\n}\n</code></pre>\n\n<p>Now you can use this like so:</p>\n\n<pre><code>public function foo(array $queryArgs)\n{\n $queries = array_filter($queryArgs, array($this, 'filterQueries'));\n try\n {\n foreach($queries as $query)\n {//same as before\n if (is_array($query)) {/* ... */}\n else {/* ... */}\n }\n }\n catch (PDOException $e) {}\n}\n//filter out only those elements that are instances of QueryArgument\n//convert them to array or string\nprivate function filterQueries($instance)\n{\n\n if ($instance instanceof QueryArgument) return $instance-&gt;getTransactionFormat();\n return false;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T07:55:01.223", "Id": "36337", "ParentId": "36332", "Score": "1" } } ]
{ "AcceptedAnswerId": "36337", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T05:40:18.197", "Id": "36332", "Score": "2", "Tags": [ "php", "object-oriented", "mysql" ], "Title": "Class method with begin transaction and return errors" }
36332
<p>This is a console application which takes as an argument either a .cs file or a directory. If it's a .cs file, it scans it; if it's a directory, it scans all .cs files within the directory.</p> <p>A simplified view of a method which chooses whether it's a file or a directory and reports errors is this one:</p> <pre><code>public static void ProcessPath(string path) { if (path.EndsWith(".cs")) { if (File.Exists(path)) { Program.ScanFile(path); } else { Console.WriteLine("The specified file doesn't exist."); Environment.Exit(1); } } else { if (Directory.Exists(path)) { Program.ScanDirectory(path); } else { if (File.Exists(path)) { Console.WriteLine("The path corresponds to a file, but only *.cs files are supported."); } else { Console.WriteLine("The specified directory doesn't exist."); } Environment.Exit(1); } } } </code></pre> <p>How can I rewrite the <code>if/else</code> logic in a more elegant way? Would it improve readability?</p>
[]
[ { "body": "<p>In my opinion, the easiest way would be to <em>embrace</em> exceptions. <code>DirectoryNotFoundException</code> and <code>FileNotFoundException</code> are there for a reason, and actually even calling <code>.Exists</code> might not save you from them - the file might be moved/removed between the <code>Exists</code> and the action you're taking next.</p>\n\n<p>You can do:</p>\n\n<pre><code>public static void ProcessPath(string path)\n{\n var extension = Path.GetExtension(path);\n\n if(string.IsNullOrEmpty(extension))\n {\n Program.ScanDirectory(path);\n }\n else\n {\n if(extension != \".cs\")\n throw new NotSupportedException(\"Only .cs files are supported\");\n\n Program.ScanFile(path);\n }\n}\n</code></pre>\n\n<p>And either catch those exceptions higher up and write them to console or (considering you're doing <code>Environment.Exit</code> in your example), just let them propagate and crash the application.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T09:27:29.543", "Id": "59552", "Score": "2", "body": "+1 for exceptions. The notion of being able to code defensively against file system objects is a fallacy. There are absolutely no guarantees with the file system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T10:28:01.870", "Id": "59557", "Score": "2", "body": "What if I want to scan the directory \".sharpDevelopProjects\" or \"backup 29.11.2013\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T12:46:07.897", "Id": "59563", "Score": "1", "body": "@abuzittingillifirca Then the `GetExtension` fails, but you have no real way of distinguishing those cases unless you try to [get the attributes](http://stackoverflow.com/a/1896995/1180426) from the filesystem." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T08:35:37.677", "Id": "36340", "ParentId": "36335", "Score": "13" } } ]
{ "AcceptedAnswerId": "36340", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T07:38:19.723", "Id": "36335", "Score": "6", "Tags": [ "c#" ], "Title": "Scanning a .cs file or a directory" }
36335
<p>I am working on coding up a set of models that are based on empirical models. These models tend to be quite complicated. In some cases, the logic used by the equations makes it impossible to compute the results using numpy fast arrays. As a result, I have decided to use list comprehension to do the math. However, this results in the functions being indent 3 levels. Is this bad? Is there a better way to organize this code? Any other comments on the style or organization would be most welcome.</p> <p>Currently, the code is organized with classes, which I think makes the most sense. Any opinions on this would be welcome too.</p> <p>Here are a few examples of the code:</p> <pre><code>import logging import math import numpy as np class Model(object): '''Abstract class for ground motion prediction models.''' INDICES_PSA = [] INDEX_PGA = None INDEX_PGV = None INDEX_PGD = None LIMITS = dict() def __init__(self, name, abbrev, **kwds): '''Compute the response predicted the model. No default implementation. Input names: mag: float moment magnitude of the event dist_closest: float closest distance to the rupture (km) v_s30: float time-averaged shear-wave velocity over the top 30 m of the site (m/s) ''' super(Model, self).__init__() self.name = name self.abbrev = abbrev self.parameters = kwds self._ln_resp = None self._ln_std = None self._check_inputs(**self.parameters) def interp_spec_accels(self, periods): return np.interp(periods, self.periods, self._ln_resp[self.INDICES_PSA]) @property def periods(self): return self.PERIODS[self.INDICES_PSA] @property def spec_accels(self): return self._resp(self.INDICES_PSA) @property def pga(self): '''Return the PGA [g]''' return self._resp(self.INDEX_PGA) @property def pgv(self): '''Return the PGV [cm/s]''' return self._resp(self.INDEX_PGV, FROM_GRAVITY) @property def pgd(self): '''Return the PGD [cm]''' return self._resp(self.INDEX_PGD, FROM_GRAVITY) def _resp(self, index, scale=1): if not index is None: return np.exp(self._ln_resp[index]) * scale def _check_inputs(self, **kwds): for key, (minimum, maximum) in self.LIMITS.items(): if not key in kwds: continue value = kwds[key] if not minimum is None and value &lt; minimum: logging.warning('{} ({:g}) is less than the recommended limit ({:g}).'.format( key, minimum, value)) elif not maximum is None and maximum &lt; value: logging.warning('{} ({:g}) is greater than the recommended limit ({:g}).'.format( key, maximum, value)) def load_data_file(name, skip_header=None): fname = os.path.join(os.path.dirname(__file__), 'data', name) return np.recfromcsv(fname, skip_header=skip_header).view(np.recarray) class ChiouYoungs2013(model.Model): '''Chiou and Youngs (2013) model.''' # Reference velocity (m/s) V_REF = 1130. # Load the coefficients for the model COEFF = model.load_data_file('chiou_youngs_2013.csv', 2) PERIODS = COEFF['period'] # Period independent coefficients COEFF_C_2 = 1.06 COEFF_C_4 = -2.1 COEFF_C_4a = -0.5 COEFF_C_RB = 50 COEFF_C_8 = 0.2153 COEFF_C_8a = 0.2695 INDICES_PSA = np.arange(23) LIMITS = dict( dist_closest=(0, 300), mag=(3.5, 8.5), v_s30=(180, 1500), z_tor=(0, 20), ) def __init__(self, **kwds): '''Compute the response predicted the Chiou and Youngs (2013) ground motion model. Input: depth_1_0_centered: float depth (m) to a shear-wave velocity of 1,000 m/sec centered to the California average depth_tor: float Depth to the top of the rupture (km) dist_jb: float Joyner-Boore distance to the rupture plane (km) dist_closest: float closest distance to the rupture (km) dist_x: float site coordinate (km) measured perpendicular to the fault strike from the fault line with the down-dip direction being positive (see Figure 3.12 in Chiou and Youngs (2008). dpp_centered: float direct point parameter for directivity effect (see Chiou and Spudich (2013)) centered on the earthquake-specific average DPP for California. A value of 0 provides the average directivity. dip_angle: float Fault dip angle (deg) flag_hw: int Hanging-wall flag. 1: R_x &gt;= 0 0: R_x &lt; 0 flag_nm: int Normal faulting flag. 1: -120° &lt;= rake angle &lt;= -60° (excludes normal-oblique) 0: otherwise flag_rv: int Reverse-faulting flag. 1: 30° &lt;= rake angle &lt;= 150° (combined reverse and reverse-oblique) 0: otherwise mag: float moment magnitude of the event v_s30: float time-averaged shear-wave velocity over the top 30 m of the site (m/s) ''' dist_jb = kwds['dist_jb'] dist_closest = kwds['dist_closest'] dist_x = kwds['dist_x'] dip_angle = kwds['dip_angle'] flag_hw = kwds['flag_hw'] flag_nm = kwds['flag_nm'] flag_rv = kwds['flag_rv'] mag = kwds['mag'] v_s30 = kwds['v_s30'] dpp_centered = kwds.get('dpp_centered', 0.) depth_tor = kwds.get('depth_tor', self.calc_depth_tor(mag, flag_rv)) depth_1_0_centered = kwds.get('depth_1_0_centered', self.calc_depth_1_0(v_s30, 'california')) def calc_ln_resp_ref(period, c_1, c_1a, c_1b, c_1c, c_1d, c_n, c_m, c_3, c_5, c_hm, c_6, c_7, c_7b, c_8b, c_9, c_9a, c_9b, c_11, c_11b, c_gamma1, c_gamma2, c_gamma3, phi_1, phi_2, phi_3, phi_4, phi_5, phi_6, tau_1, tau_2, sigma_1, sigma_2, sigma_3): cosh_mag = math.cosh(2 * max(mag - 4.5, 0)) return ( c_1 + (c_1a + c_1c / cosh_mag) * flag_rv + (c_1b + c_1d / cosh_mag) * flag_nm + (c_7 + c_7b / cosh_mag) * depth_tor + (c_11 + c_11b / cosh_mag) * math.cos(dip_angle) ** 2 + self.COEFF_C_2 * (mag - 6) + (self.COEFF_C_2 - c_3) / c_n * math.log(1 + math.exp(c_n * (c_m - mag))) + self.COEFF_C_4 * math.log(dist_closest + c_5 * math.cosh(c_6 * max(mag - c_hm, 0))) + (self.COEFF_C_4a - self.COEFF_C_4) * math.log(math.sqrt(dist_closest ** 2 + self.COEFF_C_RB ** 2)) + (c_gamma1 + c_gamma2 / math.cosh(max(mag - c_gamma3, 0))) * dist_closest + (self.COEFF_C_8 * max(1 - max(dist_closest - 40, 0) / 30, 0) * min(max(mag - 5.5, 0) / 0.8, 1) * math.exp(-self.COEFF_C_8a * (mag - c_8b) ** 2) * dpp_centered) + (c_9 * flag_hw * math.cos(dip_angle) * (c_9a + (1 - c_9a) * math.tanh(dist_x / c_9b)) * (1 - math.sqrt(dist_jb ** 2 + depth_tor ** 2) / (dist_closest + 1))) ) def calc_ln_resp(ln_resp_ref, period, c_1, c_1a, c_1b, c_1c, c_1d, c_n, c_m, c_3, c_5, c_hm, c_6, c_7, c_7b, c_8b, c_9, c_9a, c_9b, c_11, c_11b, c_gamma1, c_gamma2, c_gamma3, phi_1, phi_2, phi_3, phi_4, phi_5, phi_6, tau_1, tau_2, sigma_1, sigma_2, sigma_3): return (ln_resp_ref + phi_1 * min(math.log(v_s30 / 1130.), 0) + (phi_2 * (math.exp(phi_3 * (min(v_s30, 1130.) - 360.)) - math.exp(phi_3 * (1130. - 360.))) * math.log((math.exp(ln_resp_ref) + phi_4) / phi_4)) + phi_5 * (1 - math.exp(-depth_1_0_centered / phi_6))) def calc_ln_std(ln_resp_ref, period, c_1, c_1a, c_1b, c_1c, c_1d, c_n, c_m, c_3, c_5, c_hm, c_6, c_7, c_7b, c_8b, c_9, c_9a, c_9b, c_11, c_11b, c_gamma1, c_gamma2, c_gamma3, phi_1, phi_2, phi_3, phi_4, phi_5, phi_6, tau_1, tau_2, sigma_1, sigma_2, sigma_3): between = tau_1 + (tau_2 - tau_1) / 2.25 * (min(max(mag, 5.), 7.25) - 5.) nl_0 = (phi_2 * (math.exp(phi_3 * (min(v_s30, 1130.) - 360.)) - math.exp(phi_3 * (1130. - 360.))) * (ln_resp_ref / (ln_resp_ref + phi_4))) # FIXME logging.warning('CY do not specify what f_inf and f_meas should be in their equation') f_inf = 1 f_meas = 1 within_nl = (sigma_1 + (sigma_2 - sigma_1) / 2.25 * (min(max(mag, 5.), 7.25) - 5.) * math.sqrt( sigma_3 * f_inf + 0.7 * f_meas + (1 + nl_0) ** 2)) return math.sqrt((1 - nl_0) ** 2 * between ** 2 + within_nl ** 2) ln_resp_ref = [calc_ln_resp_ref(*c) for c in self.COEFF] self._ln_resp = np.array([calc_ln_resp(lrr, *c) for (lrr, c) in zip(ln_resp_ref, self.COEFF)]) self._ln_std = np.array([calc_ln_std(lrr, *c) for (lrr, c) in zip(ln_resp_ref, self.COEFF)]) def _check_inputs(self, **kwds): super(ChiouYoungs2013, self)._check_inputs(**kwds) assert flag_nm in [0, 1] assert flag_rv in [0, 1] if flag_nm or flag_rv: _min, _max = 3.5, 8.0 if not (_min &lt;= kwds['mag'] &lt;= _max): logging.warning( 'Magnitude ({}) exceeds recommened bounds ({} to {})'\ ' for a reverse or normal earthquake!'.format( kwds['mag'], _min, _max)) else: _min, _max = 3.5, 8.5 if not (_min &lt;= kwds['mag'] &lt;= _max): logging.warning( 'Magnitude ({}) exceeds recommened bounds ({} to {})'\ ' for a strike-slip earthquake!'.format( kwds['mag'], _min, _max)) def calc_depth_1_0(self, v_s30, region='california'): '''Calculate an estimate of the depth to 1 km/sec based on Vs30 and region. Input: v_s30: float time-averaged shear-wave velocity over the top 30 m of the site (m/s) region: str region for the V_s30-Z_1.0 correlation. Potential regions: california (default) japan Returns: depth_1_0_centered: float depth (m) to a shear-wave velocity of 1,000 m/sec. ''' assert region in ['california', 'japan'] if region == 'california': power = 4 bar = 571 foo = -7.15 / power elif region == 'japan': power = 2 bar = 412 foo = -5.23 / power return foo * math.log((v_s30 ** power + bar ** power) / ((1360. ** power + bar ** power))) def calc_depth_tor(self, mag, flag_rv): '''Calculate an estimate of the depth to top of rupture (km). Input: mag: float moment magnitude of the event flag_rv: int Reverse-faulting flag. 1: 30° &lt;= rake angle &lt;= 150° (combined reverse and reverse-oblique) 0: otherwise Returns: depth_tor: float Estimated depth to top of rupture (km) ''' if flag_rv: # Reverse and reverse-oblique faulting foo = 2.704 - 1.226 * max(mag - 5.849, 0) else: # Combined strike-slip and normal faulting foo = 2.673 - 1.136 * max(mag - 4.970, 0) return max(foo, 0) ** 2 class AtkinsonBoore2006(model.Model): '''Atkinson and Boore (2006) ground motion prediction model. Developed for the Eastern North America with a reference velocity of 760 or 2000 m/s.''' # Load the coefficients for the model COEFF = dict( bc=model.load_data_file('atkinson_boore_2006-bc.csv', 2), rock=model.load_data_file('atkinson_boore_2006-rock.csv', 2), ) PERIODS = COEFF['bc']['period'] COEFF_SITE = model.load_data_file('atkinson_boore_2006-site.csv', 2) COEFF_SF = model.load_data_file('atkinson_boore_2006-sf.csv', 2) INDEX_PGD = 0 INDEX_PGV = 1 INDEX_PGA = 2 INDICES_PSA = np.arange(3, 27) def __init__(self, **kwds): '''Compute the response predicted the Atkinson and Boore (2006) ground motion model. Input: mag: float moment magnitude of the event dist_closest: float closest distance to the rupture (km) v_s30: float time-averaged shear-wave velocity over the top 30 m of the site (m/s) ''' super(AtkinsonBoore2006, self).__init__( 'Atkinson and Boore (2006)', 'AB06', **kwds) mag = kwds['mag'] dist_closest = kwds['dist_closest'] v_s30 = kwds['v_s30'] def compute_log10_resp(period, c_1, c_2, c_3, c_4, c_5, c_6, c_7, c_8, c_9, c_10): R0 = 10.0 R1 = 70.0 R2 = 140.0 f0 = max(np.log10(R0 / dist_closest), 0) f1 = min(np.log10(dist_closest), np.log10(R1)) f2 = max(np.log10(dist_closest / R2), 0) log10_resp = (c_1 + c_2 * mag + c_3 * mag ** 2 + (c_4 + c_5 * mag) * f1 + (c_6 + c_7 * mag) * f2 + (c_8 + c_9 * mag) * f0 + c_10 * dist_closest) return log10_resp def compute_log10_site(pga_bc, period, b_lin, b_1, b_2): VS_1 = 180. VS_2 = 300. VS_REF = 760. if v_s30 &lt;= VS_1: b_nl = b_1 elif VS_1 &lt; v_s30 &lt;= VS_2: b_nl = ((b_1 - b_2) * np.log(v_s30 / VS_2) / np.log(VS_1 / VS_2)) elif VS_2 &lt; v_s30 &lt;= VS_REF: b_nl = (b_2 * np.log(v_s30 / VS_REF) / np.log(VS_2 / VS_REF)) else: # Vs30 &gt; VS_REF b_nl = 0 pga_bc = max(pga_bc, 60.) log10_site = np.log10(np.exp(b_lin * np.log(v_s30 / VS_REF) + b_nl * np.log(pga_bc / 100.))) return log10_site def compute_log10_stress_factor(stress_drop, period, delta, m1, mh): foo = delta + 0.05 bar = 0.05 + delta * max(mag - m1, 0) / (mh - m1) log10_stress_factor = min(2., stress_drop / 140.) * min(foo, bar) return log10_stress_factor COEFF = self.COEFF['bc'] if v_s30 else self.COEFF['rock'] # Compute the log10 PSA in units of cm/sec/sec log10_resp = np.array([compute_log10_resp(*c) for c in COEFF]) # Apply the stress correction factor as recommended by Atkinson and # Boore (2011) if mag &gt;= 5: stress_drop = 10. ** (3.45 - 0.2 * mag) log10_stress_factor = [compute_log10_stress_factor( stress_drop, *c) for c in self.COEFF_SF] log10_resp += np.interp(COEFF.period, self.COEFF_SF.period, log10_stress_factor) if v_s30: # Compute the site amplification pga_bc = (10 ** log10_resp[self.INDEX_PGA]) log10_site = [compute_log10_site(pga_bc, *c) for c in self.COEFF_SITE] # Amplification is specified at periods the differ from the ground # motion model so we have to interpolate to a common period # spacing before adding the influence of the site log10_site = np.interp(COEFF.period, self.COEFF_SITE.period, log10_site) log10_resp += log10_site # Convert from cm/sec/sec to gravity log10_resp += np.log10(model.TO_GRAVITY) # Convert to log-base 10 self._ln_resp = np.log(10 ** log10_resp) self._ln_std = 0.30 </code></pre>
[]
[ { "body": "<blockquote>\n <p>These models tend to be quite complicated.</p>\n</blockquote>\n\n<p>Maybe that's standard in your field, but they definitely <em>are</em> complicated, and converting those equations into code will never be pretty (I'm looking at you, <code>calc_ln_resp_ref</code>!).</p>\n\n<blockquote>\n <p>However, this results in the functions being indent 3 levels. Is this bad?</p>\n</blockquote>\n\n<p>No, it's not bad per se. You did an excellent job to keep the nesting under control with those helper functions, and the code is actually easy to read and follow.</p>\n\n<blockquote>\n <p>Is there a better way to organize this code? Any other comments on the style or organization would be most welcome.</p>\n</blockquote>\n\n<p>The code actually looks good. A few suggestions:</p>\n\n<ol>\n<li>Feel free to organize the different models into different files if your current file is going to continue growing.</li>\n<li>Add a docstring to the module (your existing docstrings in classes and methods are great).</li>\n<li>Get more confident and keep up the good job! ^_^</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T13:52:40.277", "Id": "59570", "Score": "0", "body": "Thanks for the feedback. I have one model per file because there will be probably 15+ models with more being added as they are published." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T12:03:45.523", "Id": "36347", "ParentId": "36336", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T07:52:35.773", "Id": "36336", "Score": "5", "Tags": [ "python", "numpy", "python-3.x" ], "Title": "Organization of complex empirical equations" }
36336
<p>I would like to ask those of you, who are a little bit more expirienced in development. I would like to ask about <code>toString()</code> method usage. In what situations do you use it?</p> <p>I've found some info about it, for example <a href="http://coffeewithcode.com/2011/11/tostring-method-of-object-class-in-java/">here</a>, but it's not what I'm looking for.</p> <p>Is there any convension which says when should I use it for my custom objects? In model layer or in view? Let me show a simple example...</p> <p>I've got a class called "<code>Component</code>". <code>Component</code> has some name, values etc... One of the fields can be a perfect information for the user about object's state. The rest is also important, but not nessesary to display on the screen (in a view layer). Moreover, this field is a <code>String</code> and should be translated depending on the language settings. It's also required to present this field as an <code>upperCase()</code>.</p> <p>So, the question is: Should I put all the logic connected with forming a "user-friendly" string (locals, upperCase...) in a <code>toString()</code> method? Or maybe I should create a <code>getUserFriendlyName()</code> method instead and use <code>toString()</code>, for instance, for debugging (so in model). So, should <code>toString()</code> method have any influence on what the end user can see on the screen?</p> <pre><code> @Override public String toString() { String toReturn; try { toReturn = language.getString("LOCAL_STRING_KEY_" + this.compInfo); } catch (MissingResourceException e) { logger.warning("No key found for " + compInfo); toReturn = this.compInfo; } return toReturn; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T10:17:44.580", "Id": "59556", "Score": "0", "body": "Post actual code, please. What is the content of 'compInfo'? I'm guessing it's some kind of naming scheme for services. JNDI resource name, etc?" } ]
[ { "body": "<p>You usually place it in your model, so when you invoke <code>.toString()</code> on an object you get a string representation of the object.</p>\n\n<p>How your string representation looks like can be up to you. Here is an example where I return a simple JSON-formatted string representation of my object Foo</p>\n\n<pre><code>public class Foo {\n\n private string name;\n private int id;\n\n public Foo(string name, int id) {\n this.name = name;\n this.id = id;\n }\n\n @override\n public string toString() {\n return \"{name: \" + this.name + \", id:\" + this.id + \"}\";\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T08:37:40.243", "Id": "36341", "ParentId": "36338", "Score": "3" } }, { "body": "<blockquote>\n <p>Is there any convension which says when should I use it for my custom objects? In model layer or in view?</p>\n</blockquote>\n\n<p>If your question is 'When should I override the default toString() method and use create my own?' then there is one set of answers. If your question is 'when should I call the <code>toString()</code> method (implicitly like <code>\"This is my object: \" + myobj</code> or explicitly)?' then there is a different set of answers.</p>\n\n<p>So, when should you override the <code>toString()</code>? From the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29\">Javadoc for Object</a>:</p>\n\n<blockquote>\n <p>In general, the toString method returns a string that \"textually represents\" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. </p>\n</blockquote>\n\n<p>I strongly agree with this statement. <em>Every</em> custom class you create should override the toString method, and should find a way to textually represent the class content in a meaningful (but not necessarily exhaustive) way. For example, a 'Point' class representing a co-ordinate <code>x</code> and <code>y</code> where x==3 and y==4 should return something like <code>Point(3,4)</code>. On the other hand, I believe that some classes are over-exhaustive with toString, like ArrayList does too much. I would prefer <code>ArrayList(size 10: [sample0 .... sample9])</code>. <strong>Edit:</strong> The Java tutorial for <code>Object</code> also <a href=\"http://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html\">says the same thing about toString()</a>:</p>\n\n<blockquote>\n <p>The Object's toString() method returns a String representation of the object, which is very useful for debugging</p>\n</blockquote>\n\n<p>The reasons for making every class have a toString is because of the times you should use the toString() method.... and, as far as I am concerned, there are only three places in general programming where using toString() is legitimate (and two 'special' cases):</p>\n\n<ol>\n<li>In exception handling: throw new IllegalStateException(\"Failed to process \" + value);</li>\n<li>for logging program progress using things like log4j.</li>\n<li>when the JavaDoc for the toString() Method for the class you are using defines a specific, and non-alterable format for the result. e.g. String.toString() or <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28%29\">Integer.toString()</a>. If the class you are using does not specify what the toString() returns, and does not guarantee that it won't change, then create your own way to present the data.</li>\n</ol>\n\n<p>There are two special cases for using <code>toString()</code>:</p>\n\n<ol>\n<li>I think, even though this is a special case, that this is the most important reason: when running your Java program through a debugger like the one built in to Eclipse. When you are stepping through your program the debugger will use the <code>toString()</code> method to show you the state of all your variables. This is where, in many cases, you will value the toString() more than anything else.</li>\n<li>when developing or debugging a program it is often convenient for you to add 'println' statements, and they can be things like: System.out.println(\"Processing customer \" + customer);`</li>\n</ol>\n\n<p>In summary, the toString() method should produce enough data to debug problems with the object content. It is used occasionally for a 'contractual' representation of a value (like <code>String.toString()</code>).</p>\n\n<p>But, in general, <strong>toString() Is a tool for the PROGRAMMER, not for the user</strong>. It is there to assist <strong>you</strong> when things go wrong, not when they go right.</p>\n\n<p>In my real Job I file bugs against code (and pursue the bugs relentlessly) which throws exceptions where the exception has an <code>Object.toString()</code> in the message. I also mentally +1 people who's programs produce good detail during exceptional conditions.</p>\n\n<p>Now, in your particular situation, I think that you should use the toString() method to represent the state of your Customer, and, because the display-conditions for your customer are different to the internal state (e.g. display needs to be UPPERCASE,) I think that you should have a different mechanism for displaying the Customer than the toString() method. </p>\n\n<p>In other words, the information you will need to debug a situation involving a Customer (something printed in a stack trace or debug session) is different than the information you want to display on the screen.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T13:04:16.220", "Id": "59565", "Score": "1", "body": "Thanks! \"But, in general, toString() Is a tool for the PROGRAMMER, not for the user\" - this is exactly what I wanted to know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-06T03:28:51.877", "Id": "286446", "Score": "0", "body": "Exceptions should only be seen by the programmer too, so I'm curious as to why you would think toString() should not be used from those." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-06T05:33:07.063", "Id": "286452", "Score": "0", "body": "@Trejkaz - It may not be as clear as it should be, but when I say _\"I file bugs against code ... which throws exceptions where the exception has an Object.toString() in the message\"_ I mean exceptions that have the raw output from `toString()` from the Object base class.... i.e. not an overridden `toString()`. e.g. It is a bug if an exception has things like `Illegal characters in: my.class.Name@106d69c` instead of `Illegal characters in: \"Joe Blogs!!\"`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-07T05:46:02.807", "Id": "286677", "Score": "0", "body": "Ah, that makes sense then. Those default toString() methods Java put in, I wonder why they thought that was better than, say, a dump of the fields and their values. :/" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T11:33:44.853", "Id": "36345", "ParentId": "36338", "Score": "11" } } ]
{ "AcceptedAnswerId": "36345", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T08:11:03.913", "Id": "36338", "Score": "11", "Tags": [ "java", "mvc" ], "Title": "toString() in a model or view layer?" }
36338
<p>I am hoping this is the right place. I was hoping to find someone to try and help me not only learn but have a look at what I have already done on Android.</p> <p><strong>DISCLAIMER: I am a long time (10+ years) script developer (PHP, Perl, Ruby) and am happy with OO but have not really had any experience with Java so this is a bit of an experiment so expect totally n00b questions.</strong></p> <p>I set myself a goal (it's always good to have one I find). I wanted to make an android version of the Nintendo Game &amp; Watch game Fire. I used the graphics from the inter webs and I'm well aware that should I release this on Google Play that Nintendo will send me a nice letter telling me to remove it so I am currently just looking to use this as a learning process.</p> <p>I have been reading an Android game developers book and implementing what I learn from that as well as surfing SO and the web in general for help.</p> <p>So if your willing have a look at what I have so far and if you can give me some feedback/pointers I will appreciate it. I intend to update the project as often as I can with new questions that come up that I cannot solve and even write how I solved them (if I do), maybe even go so far as to use an organisation tool like <a href="https://workflowy.com" rel="nofollow">Workflowy</a> to do this.</p> <p>I have pasted here the GameView file. Look in the update function where I am checking the collision of the jumper.</p> <pre><code>package com.example.gamewatch; /** * Only Currently tested on an emulator, emullating a 7" screen (Nexus 7) * 1280 x 628 */ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import android.os.AsyncTask; import android.content.Context; import android.graphics.*; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.util.Log; public class GameView extends SurfaceView implements SurfaceHolder.Callback { private GameLogic mGameLogic; private ArrayBlockingQueue&lt;InputObject&gt; inputObjectPool; private Map&lt;String, AnimatedSprite&gt; map = new HashMap&lt;String, AnimatedSprite&gt;(); private Integer score = 0; // Not being used at the moment but maybe in the future private class ScoringTask extends AsyncTask&lt;Canvas, Void, Boolean&gt; { protected Boolean doInBackground(Canvas... canvas) { Paint paint = new Paint(); paint.setColor(Color.RED); paint.setTextSize(30); //canvas.drawText("000", getWidth() - 100, 0, paint); //canvas.drawText("001", getWidth() - 100, 0, paint); return true; } } public GameView(Context context) { super(context); getHolder().addCallback(this); mGameLogic = new GameLogic(getHolder(), this); createInputObjectPool(); setFocusable(true); } private void createSprites() { map.put("firemen", new FiremenSprite( BitmapFactory.decodeResource(getResources(), R.drawable.firemen) )); map.put("jumper", new JumperSprite( BitmapFactory.decodeResource(getResources(), R.drawable.jumper) )); } private void createInputObjectPool() { inputObjectPool = new ArrayBlockingQueue&lt;InputObject&gt;(20); for (int i = 0; i &lt; 20; i++) { inputObjectPool.add(new InputObject(inputObjectPool)); } } @Override public boolean onTouchEvent(MotionEvent event) { try { int hist = event.getHistorySize(); if (hist &gt; 0) { for (int i = 0; i &lt; hist; i++) { InputObject input = inputObjectPool.take(); input.useEventHistory(event, i); mGameLogic.feedInput(input); } } InputObject input = inputObjectPool.take(); input.useEvent(event); mGameLogic.feedInput(input); } catch (InterruptedException e) { } try { Thread.sleep(16); } catch (InterruptedException e) { } return true; } public void processMotionEvent(InputObject input){ int half = (getWidth() / 2); int movement = 0; AnimatedSprite firemen = map.get("firemen"); if(input.x &lt; half) { // Left firemen.moveLeft(); } else { // Right firemen.moveRight(); } } public void processKeyEvent(InputObject input){ } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { createSprites(); mGameLogic.setGameState(mGameLogic.RUNNING); mGameLogic.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { } public void onDraw(Canvas canvas) { Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.background); int screenWidth = getWidth(); int screenHeight = getHeight(); float screenAspect = screenWidth / screenHeight; int addAmount = screenWidth - b.getWidth(); int half = screenWidth / 2; //Log.d("Screen", "Height: " + getHeight() + " Width: " + getWidth()); //b = b.createScaledBitmap(b, getWidth(), b.getHeight() + addAmount, false); Typeface tf = Typeface.create("Helvetica",Typeface.BOLD); Paint paint = new Paint(); paint.setTypeface(tf); paint.setColor(Color.RED); paint.setTextSize(30); canvas.drawBitmap(b, 0, 0, null); canvas.drawLine(half, 0, half, screenHeight, paint); canvas.drawText("LEFT", half - 100, screenHeight - 50, paint); canvas.drawText("RIGHT", half + 50, screenHeight - 50, paint); // Iterate through the sprite map that was created earlier and draw them to the screen for (Map.Entry&lt;String, AnimatedSprite&gt; entry : map.entrySet()) { ((AnimatedSprite) entry.getValue()).draw(canvas); } } public void update() { AnimatedSprite f = map.get("firemen"); AnimatedSprite j = map.get("jumper"); /** * Does the firemen still have more lives? */ if(f.getLives() &lt;= 0) { Log.d("LIVES", "GameOver"); mGameLogic.setGameState(mGameLogic.FINISHED); // What I would like to do here is finish the activity and hand back to the menu but I have no idea how } // Is the jumper at the bottom of his animations and collided with the Firemen if(j.isAtBottom() &amp;&amp; !f.collide(j)) { f.setLives(f.getLives()-1); Log.d("LIVES", "The jumper is at the bottom but has not collided with the fireman" + " this should loose a life"); // We also need to re-set the jumper here j.setCurrentFrame(0); } else if (j.isAtBottom() &amp;&amp; f.collide(j)) { // Here is where we should do something with the score perhaps } // Iterate through the sprite map that was created earlier and update them all according // to the timer and check for a collision for (Map.Entry&lt;String, AnimatedSprite&gt; entry : map.entrySet()) { AnimatedSprite s = ((AnimatedSprite) entry.getValue()); s.update(System.currentTimeMillis()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T12:53:00.810", "Id": "59564", "Score": "0", "body": "Code Review is the right place for reviewing code, we are not here to [solve problems](http://www.stackoverflow.com). Most of your question is about reviewing code though so it seems like you have come to the right place." } ]
[ { "body": "<p>Overall your code is good. If I only would say that though, you probably wouldn't learn much, and luckily for you I do have some points that you can improve:</p>\n\n<ul>\n<li><p>Within the (currently unused) <code>doInBackground</code> method in <code>ScoringTask</code>, you are creating a <code>Paint</code> object that you set color and text size on, but then you're not doing anything else with it which means that it will be garbage collected directly and what you just did was useless. I know it's currently unused, but still :)</p></li>\n<li><p>I don't see the meaning of this code:</p>\n\n<pre><code>try {\n Thread.sleep(16);\n} catch (InterruptedException e) {\n}\n</code></pre>\n\n<p>First of all, you should not run <code>Thread.sleep</code> on the UI-thread. Doing so will make your application not respond for the duration of <code>Thread.sleep</code>. Now, 16 ms is not a long time but it is still not good practice to make the UI-thread sleep. Right before this code snippet, you are also catching a <code>InterruptedException</code> - why? I really don't think that code should be able to throw such an exception. And if it does, try to avoid that (if you call <code>Thread.sleep</code> for example).</p></li>\n<li><p>The variables <code>mGameLogic.RUNNING</code> and <code>mGameLogic.FINISHED</code> should be set to <code>public static final</code> where they are declared. It sounds like these are constants (RUNNING = 1 and FINISHED = 2 or similar for example), constants should be <code>static final</code>. Then you should instead write <code>GameLogic.RUNNING</code> and <code>GameLogic.FINISHED</code>.</p></li>\n<li><p>When you iterate over the <code>Map</code>, you don't need to typecast <code>entry.getValue()</code> to <code>AnimatedSprite</code>. Since you are using generics correctly (<code>Map.Entry&lt;String, AnimatedSprite&gt;</code>), <code>entry.getValue()</code> returns an <code>AnimatedSprite</code> already. No need for typecasting.</p></li>\n<li><p>(Minor issue, not necessarily needed either) Instead of iterating on <code>map.entrySet()</code> which will give you both <em>key</em> and <em>value</em>, you can iterate on <code>map.values()</code> which only gives you the <em>value</em>. (You're currently not using the <em>key</em> when you are iterating on the entry set)</p></li>\n<li><p>In your <code>update</code> method, <code>f</code> and <code>j</code> are very short variable names, and therefore making their purpose unclear. <code>firemen</code> and <code>jumper</code> would be better names for those variables.</p></li>\n</ul>\n\n<p>To finish the activity from the view either call <code>getContext()</code>, typecast that to an <code>Activity</code> (assuming this won't throw a <code>ClassCastException</code>) and call <code>finish()</code> on that object, or use a <a href=\"https://stackoverflow.com/questions/3398363/how-to-define-callbacks-in-android\">callback</a>. (I would recommend using a callback, it is bad practice to let a view get it's activity. The view should be independent)</p>\n\n<p>Something to read up on when you have some more experience: Should the view really be responsible for creating the <code>GameLogic</code> object? There is a design pattern called <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC</a> which can be good to keep in mind (not necessarily following it to 100%) when dealing with both game logic and a view. <em>Don't fix what isn't broken</em> though, MVC can be heavy stuff. Learn that at your own risk.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T03:08:06.193", "Id": "59643", "Score": "0", "body": "I'll deal with your comments briefly. The Thread.sleep was a copy and paste from the 'Beginners Android Tablet Game programming' book I have been reading [Apress](http://www.apress.com/9781430238522) which states \"Finally, you cause the main thread to sleep for 16 milliseconds to make sure you don’t gather too much input at one time.”. The book may be old and out of date. I have used MVC extensively in PHP, but again I took the current approach from that book. Will look into the callback and continue to learn :) Thank you again" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T12:51:00.160", "Id": "36351", "ParentId": "36346", "Score": "4" } }, { "body": "<p>According to <a href=\"http://source.android.com/source/code-style.html#follow-field-naming-conventions\" rel=\"nofollow\">Android coding style guidelines</a>, protected and private class members names should start from \"m\" letter, like mGameLogic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T01:27:44.767", "Id": "65372", "Score": "0", "body": "Can you point me at the guidelines that state this, I would like to know their reasoning behind it? I've run a quick google and not found anything (yet)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T02:05:56.067", "Id": "65374", "Score": "0", "body": "@catharsis take a look [here](http://source.android.com/source/code-style.html)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T02:20:06.320", "Id": "65376", "Score": "1", "body": "You should include a link to the guidelines in this answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T05:26:38.027", "Id": "65391", "Score": "0", "body": "@syb0rg, http://source.android.com/source/code-style.html#follow-field-naming-conventions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T05:27:29.827", "Id": "65392", "Score": "0", "body": "@RankoR You do know how to format an answer, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T05:28:37.490", "Id": "65393", "Score": "0", "body": "@syb0rg, I've already edited the answer before leaving the comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T05:29:51.820", "Id": "65394", "Score": "1", "body": "@RankoR Yes, by tacking on a link to the end of it. URL's are ugly, use hyperlinks instead. It looks prettier :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T01:09:25.620", "Id": "39070", "ParentId": "36346", "Score": "0" } } ]
{ "AcceptedAnswerId": "36351", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T12:02:01.160", "Id": "36346", "Score": "4", "Tags": [ "java", "game", "android" ], "Title": "Android GameWatch game for learning/review" }
36346
<p>I'm developing a Java EE project which uses Redis through the Jedis library. I'm retrieving the chat history of a particular channel from the servlet context and if absent, from Redis. </p> <p>The PMD plugin of Netbeans shows me a message that the Cyclomatic Complexity of the code is 15 which is very large. I wish to reduce that and I need to know if there is a better mechanism which can be used.</p> <pre><code>private transient final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(HistoryRetriever.class); private transient final JedisHelper jedisHelper = new JedisHelper(); public String retrieveHistory(final JSONObject data) { final ServletContext context = ContextManager.getContext(); JSONObject object = new JSONObject(); final Jedis jedis = jedisHelper.getJedisObjectFromPool(); try { String key1, key2, channel, timestamp, count; key1 = data.getString("key1"); key2 = data.getString("key2"); channel = key2 + "_" + data.getString("channel-id"); timestamp = ""; count = ""; int historyType = 0; LOGGER.info("History requested for " + channel + " belonging to subkey: " + key2); if (jedisHelper.checkValidity(key1, key2)) { if (data.has("timestamp")) { historyType = 1; timestamp = data.getString("timestamp"); } if (data.has("count")) { historyType = 2; count = data.getString("count"); } ConcurrentHashMap history = (ConcurrentHashMap) context.getAttribute("history"); if (null == history) { history = new ConcurrentHashMap&lt;Object, Object&gt;(); context.setAttribute("history", history); object = getHistoryFromRedis(timestamp, count, channel, historyType); } else { ConcurrentSkipListMap&lt;Long, String&gt; myHistory = (ConcurrentSkipListMap&lt;Long, String&gt;) history.get(channel); if (null == myHistory) { LOGGER.info("History for this channel not found in Context"); myHistory = new ConcurrentSkipListMap&lt;Long, String&gt;(); history.put(channel, myHistory); object = getHistoryFromRedis(timestamp, count, channel, historyType); } else { /* Check for history in context */ if (historyType == 1) { final Map&lt;Long, String&gt; channelHistory = myHistory.tailMap(Long.parseLong(timestamp)); if (!channelHistory.isEmpty()) { for (Map.Entry&lt;Long, String&gt; entry : channelHistory.entrySet()) { object.put(String.valueOf(entry.getKey()), entry.getValue()); } } } if (historyType == 2) { final Map&lt;Long, String&gt; channelHistory = myHistory.descendingMap(); if (!channelHistory.isEmpty()) { int counter = 0; final int i = Integer.parseInt(count); for (Map.Entry&lt;Long, String&gt; entry : channelHistory.entrySet()) { if (counter &gt;= i) { break; } object.put(String.valueOf(entry.getKey()), entry.getValue()); counter++; } } } } } } else { LOGGER.info("Invalid Keys or keys deactivated"); } } catch (JSONException ex) { LOGGER.error("JSON Exception: " + ex); } catch (NumberFormatException ex) { LOGGER.error("NumberFormatException: " + ex); } finally { jedisHelper.returnJedisObjectToPool(jedis); LOGGER.info("History is: " + object.toString()); } return object.toString(); } private JSONObject getHistoryFromRedis(final String timestamp, final String count, final String channelId, final int type) { LOGGER.info("get history from redis"); Set&lt;Tuple&gt; set = null; JSONObject history = new JSONObject(); try { final Jedis jedis = jedisHelper.getJedisObjectFromPool(); if (type == 1 &amp;&amp; timestamp != null &amp;&amp; !timestamp.isEmpty() &amp;&amp; !"0".equals(timestamp)) { set = jedis.zrangeByScoreWithScores(channelId, timestamp, String.valueOf(System.currentTimeMillis())); } if (type == 2 &amp;&amp; !"0".equals(count)) { final int limit = Integer.parseInt(count); set = jedis.zrevrangeByScoreWithScores(channelId, "+inf", "-inf", 0, limit); } if (set != null) { history = new JSONObject(set); } jedisHelper.returnJedisObjectToPool(jedis); } catch (NumberFormatException ex) { LOGGER.error("Exception in returning history from Redis: " + ex); } return history; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:01:28.997", "Id": "59578", "Score": "0", "body": "what's up with your indentation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:04:05.450", "Id": "59579", "Score": "0", "body": "You haven't called `returnJedisObjectToPool` in the second method from a `finally` block, so that is a resource leak hazard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:04:05.497", "Id": "59580", "Score": "0", "body": "Indentation is okay in the IDE that I use. I couldn't fix it in the editor here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:07:31.743", "Id": "59581", "Score": "0", "body": "@abuzittingillifirca Ya, got it." } ]
[ { "body": "<p>The easiest, and <em>what I also believe is the best as well,</em> way to reduce cyclomatic complexity is to <strong>extract methods</strong>. Your method suffers from one particular <a href=\"http://en.wikipedia.org/wiki/Code_smell\">code smell</a></p>\n\n<blockquote>\n <p>Long method: a method, function, or procedure that has grown too large.</p>\n</blockquote>\n\n<p>Below, I have tried to refactor your code by extracting inner sections into their own methods. The way I have done it here might not be optimal, it might not even be functional, but it will give you an idea of what to do with your code. I have not done the fun part of defining and passing the parameters needed to the separate methods (and making them return something useful).</p>\n\n<p>Essentially what you need to do is to make sure that <strong>one method</strong> does <strong>one thing</strong>. \"Retrieve history\" seems to be a big tasks that needs to be broken down into several subtasks. That is what the new methods should be for.</p>\n\n<p>Here's what I did to reduce your cyclomatic complexity:</p>\n\n<pre><code>public String retrieveHistory(final JSONObject data) {\n\n final ServletContext context = ContextManager.getContext();\n JSONObject object = new JSONObject();\n final Jedis jedis = jedisHelper.getJedisObjectFromPool();\n\n try {\n String key1, key2, channel;\n\n key1 = data.getString(\"key1\");\n key2 = data.getString(\"key2\");\n channel = key2 + \"_\" + data.getString(\"channel-id\");\n\n LOGGER.info(\"History requested for \" + channel + \" belonging to subkey: \" + key2);\n\n verifyAndDoSomething(key1, key2);\n } catch (JSONException ex) {\n LOGGER.error(\"JSON Exception: \" + ex);\n } catch (NumberFormatException ex) {\n LOGGER.error(\"NumberFormatException: \" + ex);\n } finally {\n jedisHelper.returnJedisObjectToPool(jedis);\n LOGGER.info(\"History is: \" + object.toString());\n }\n return object.toString();\n} \n\nprivate void doSomething(/* parameters needed goes here */) {\n if (!jedisHelper.checkValidity(key1, key2)) {\n LOGGER.info(\"Invalid Keys or keys deactivated\");\n return;\n }\n String timestamp = \"\";\n String count = \"\";\n int historyType = 0;\n\n if (data.has(\"timestamp\")) {\n historyType = 1;\n timestamp = data.getString(\"timestamp\");\n }\n if (data.has(\"count\")) {\n historyType = 2;\n count = data.getString(\"count\");\n }\n\n ConcurrentHashMap history = (ConcurrentHashMap) context.getAttribute(\"history\");\n if (null == history) {\n history = new ConcurrentHashMap&lt;Object, Object&gt;();\n context.setAttribute(\"history\", history);\n\n object = getHistoryFromRedis(timestamp, count, channel, historyType);\n\n } else {\n doMoreStuff();\n }\n}\n\n\nprivate void doMoreStuff(/* parameters needed goes here */) {\n ConcurrentSkipListMap&lt;Long, String&gt; myHistory = (ConcurrentSkipListMap&lt;Long, String&gt;) history.get(channel);\n\n if (null == myHistory) {\n LOGGER.info(\"History for this channel not found in Context\");\n myHistory = new ConcurrentSkipListMap&lt;Long, String&gt;();\n history.put(channel, myHistory);\n\n object = getHistoryFromRedis(timestamp, count, channel, historyType);\n\n } else {\n /* Check for history in context */\n if (historyType == 1) {\n performHistoryType1();\n }\n if (historyType == 2) {\n performHistoryType2();\n }\n }\n}\n\n\nprivate void performHistoryType1(/* needed parameters goes here */) {\n final Map&lt;Long, String&gt; channelHistory = myHistory.tailMap(Long.parseLong(timestamp));\n if (!channelHistory.isEmpty()) {\n for (Map.Entry&lt;Long, String&gt; entry : channelHistory.entrySet()) {\n object.put(String.valueOf(entry.getKey()), entry.getValue());\n }\n }\n}\n\nprivate void performHistoryType2(/* same as before, needed parameters goes here */) {\n final Map&lt;Long, String&gt; channelHistory = myHistory.descendingMap();\n\n if (!channelHistory.isEmpty()) {\n int counter = 0;\n final int i = Integer.parseInt(count);\n\n for (Map.Entry&lt;Long, String&gt; entry : channelHistory.entrySet()) {\n if (counter &gt;= i) {\n break;\n }\n object.put(String.valueOf(entry.getKey()), entry.getValue());\n counter++;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T13:08:36.293", "Id": "36352", "ParentId": "36349", "Score": "6" } }, { "body": "<p>Metrics like the <em>cyclomatic complexity</em> are only useful when taken in the context of your code. For example, your <code>retrieveHistory()</code> method has numerous calls to JSONObject where it could throw a JSONException. Each of these calls adds one to the complexity (or should do). On the other hand, I think your exceptions are not overly complicated, and the code looks fine.</p>\n\n<p>So, in this case, I would look at the code, and note that with 5 calls to <code>JSONObject.getString(...)</code> and at least 8 <code>if</code> conditionals, that's already a complexity of 13... Then the additional 2 catch blocks, brings you to 15.</p>\n\n<p>For the method, as I look at it, it seems just fine (the complexity does, anyway).</p>\n\n<p>I would be more concerned about two other things (bugs)....</p>\n\n<p>You have a concurrency bug (same bug twice), and a poor Logging bug (multiple times).</p>\n\n<h1>Concurrency Bug</h1>\n\n<p>Your code:</p>\n\n<pre><code>ConcurrentHashMap history = (ConcurrentHashMap) context.getAttribute(\"history\");\nif (null == history) {\n history = new ConcurrentHashMap&lt;Object, Object&gt;();\n context.setAttribute(\"history\", history);\n ...\n} else { .... }\n</code></pre>\n\n<p>This implies that your context is a central store for this <code>history</code> Map, and the Map is used in a multithreaded way.</p>\n\n<p>Unfortunately, I have to ask 'Which Map?`.....</p>\n\n<p>If two threads are each running your code, they may <strong>both</strong> find that <code>history</code> is null, and they may <strong>both</strong> create a new instance of <code>history = new ConcurrentHashMap&lt;Object, Object&gt;();</code> and they may both call <code>context.setAttribute(\"history\", history);</code>... one thread will override the value of the other, and the 'history' for the one thread will be 'lost'. You should create a method/system on your context that uses a synchronized way (or Locks) to ensure that only one thread can get or create a history instance at any one time.</p>\n\n<h1>Logging</h1>\n\n<p>Your issue here is that you are not logging any exceptions, just the string value of the exceptions. All your lines like:</p>\n\n<pre><code>LOGGER.error(\"JSON Exception: \" + ex);\n</code></pre>\n\n<p>should instead be:</p>\n\n<pre><code>LOGGER.error(\"JSON Exception: \" + ex.getMessage(), ex);\n</code></pre>\n\n<p>which will actually log the stack trace of the exception, not just the message. Exceptions without traces are almost useless...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T13:26:38.920", "Id": "59566", "Score": "0", "body": "As far as I know, calling `JSONObject.getString` any number of times doesn't add complexity, it is the **catch (SomeKindOfException)** that adds complexity. [Source](http://metrics.sourceforge.net/) (see \"McCabe Cyclomatic Complexity\")" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T13:34:46.130", "Id": "59567", "Score": "0", "body": "`catch` is not what adds cyclomatic complexity, it is `throw` (or `throws`) which adds the execution-path-branch" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T13:37:20.840", "Id": "59568", "Score": "0", "body": "@SimonAndréForsberg - that reference is incomplete.... it should include throw and throws (I imagine the for-money version is complete though)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T14:08:22.107", "Id": "59573", "Score": "0", "body": "Your concern about concurrency is exactly why we use ConcurrentHashMap for storing the messages. This is the retrieval code. And thanks for the `ex.getMessage()` part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:30:58.420", "Id": "59583", "Score": "2", "body": "@GauravBhor: the fact that you're using ConcurrentHashMap in this situation does not protect you from the race condition. See the answer to this question: http://stackoverflow.com/questions/11778550/concurrenthashmap-in-servlet" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T16:03:32.400", "Id": "59589", "Score": "0", "body": "@GauravBhor - I have put together an example of how it can go wrong: http://ideone.com/PKvCSd" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T16:22:44.340", "Id": "59590", "Score": "0", "body": "For potential future readers: I asked a [question about the cyclomatic complexity thing](http://programmers.stackexchange.com/questions/219872/cyclomatic-complexity-when-calling-same-method-multiple-times) on programmers" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:33:24.953", "Id": "59614", "Score": "0", "body": "@ShivanDragon thank you for that piece of information. I'll reconsider using the ServletContext for storing my data. All this assimilated, what can be a better alternative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:35:14.150", "Id": "59615", "Score": "0", "body": "@rolfl I understood your point and example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:35:57.137", "Id": "59617", "Score": "0", "body": "@SimonAndréForsberg Thank you for the reference. It helped." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T09:23:24.957", "Id": "59657", "Score": "0", "body": "@GauravBhor you should use whatever servlet context is appropriate for your particular situation, just make sure that you synchronize (on it) when adding/removing attributes to/from it" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T13:21:37.127", "Id": "36353", "ParentId": "36349", "Score": "5" } }, { "body": "<p>Simon's answer got the basic idea right and got my vote, but I think his answer left many problems intact, and may not have given enough details to actually do the method extraction. </p>\n\n<p>Note the following:</p>\n\n<ul>\n<li><p>In the <code>retrieveHistory</code> method <code>jedis</code> was not being used, which became obvious after refactoring.</p></li>\n<li><p>By <code>getJedisObjectFromPool</code> and <code>returnJedisObjectToPool</code> is called through a new method <code>doWithRedis</code> so that you need not remember to add the <code>finally</code> block each time. (This method can be moved to <code>JedisHelper</code> class, which seems to be its natural home.)</p></li>\n<li><p>Single return statements, declaring variable at the top of the method, and Yoda conditionals are <strong>C</strong> archaisms. The do not do you <strong><em>any</em></strong> good in Java. And just make your code <strong><em>much</em></strong> harder to read.</p></li>\n</ul>\n\n<p>I could go over anything you might want elaborated, until then here is the code:</p>\n\n<pre><code>public String retrieveHistory(final JSONObject data) {\n\n final ServletContext context = ContextManager.getContext();\n\n final String defaultResult = new JSONObject().toString();\n\n try {\n String key1 = data.getString(\"key1\");\n String key2 = data.getString(\"key2\");\n String channel = key2 + \"_\" + data.getString(\"channel-id\");\n\n LOGGER.info(\"History requested for \" + channel\n + \" belonging to subkey: \" + key2);\n\n if (!jedisHelper.checkValidity(key1, key2)) {\n LOGGER.info(\"Invalid Keys or keys deactivated\");\n return defaultResult;\n }\n\n if (data.has(\"timestamp\")) {\n String timestamp = data.getString(\"timestamp\");\n return retrieveHistoryByTimestamp(context, channel, timestamp).toString();\n }\n\n if (data.has(\"count\")) {\n String count = data.getString(\"count\");\n return retrieveHistoryByCount(context, channel, count).toString();\n }\n\n return defaultResult;\n\n } catch (JSONException ex) {\n LOGGER.error(\"JSON Exception: \" + ex);\n return defaultResult;\n } catch (NumberFormatException ex) {\n LOGGER.error(\"NumberFormatException: \" + ex);\n return defaultResult;\n }\n}\n\nprivate JSONObject retrieveHistoryByTimestamp(final ServletContext context,\n String channel, String timestamp) {\n\n NavigableMap&lt;Long, String&gt; myHistory = getHistory(context, channel);\n\n if (myHistory != null) {\n return getHistoryFromContextByTimestamp(timestamp, myHistory);\n }\n\n return getHistoryFromRedisByTimestamp(timestamp, channel);\n}\n\nprivate JSONObject retrieveHistoryByCount(final ServletContext context,\n String channel, String count) {\n NavigableMap&lt;Long, String&gt; myHistory = getHistory(context, channel);\n\n if (myHistory != null) {\n return getHistoryFromContextByCount(count, myHistory);\n }\n\n return getHistoryFromRedisByCount(count, channel);\n\n}\n\nprivate JSONObject getHistoryFromContextByTimestamp(String timestamp,\n NavigableMap&lt;Long, String&gt; myHistory) {\n JSONObject object = new JSONObject();\n\n final Map&lt;Long, String&gt; channelHistory = myHistory\n .tailMap(Long.parseLong(timestamp));\n if (!channelHistory.isEmpty()) {\n for (Map.Entry&lt;Long, String&gt; entry : channelHistory\n .entrySet()) {\n object.put(String.valueOf(entry.getKey()),\n entry.getValue());\n }\n }\n\n return object;\n}\n\nprivate JSONObject getHistoryFromContextByCount(String count,\n NavigableMap&lt;Long, String&gt; myHistory) {\n JSONObject object = new JSONObject();\n final Map&lt;Long, String&gt; channelHistory = myHistory\n .descendingMap();\n\n if (!channelHistory.isEmpty()) {\n int counter = 0;\n final int i = Integer.parseInt(count);\n\n for (Map.Entry&lt;Long, String&gt; entry : channelHistory\n .entrySet()) {\n if (counter &gt;= i) {\n break;\n }\n object.put(String.valueOf(entry.getKey()),\n entry.getValue());\n counter++;\n }\n }\n\n return object;\n}\n\nprivate JSONObject getHistoryFromRedisByTimestamp(final String timestamp, final String channelId) {\n\n return doWithRedis(jedisHelper, new JedisCallback&lt;JSONObject&gt;() {\n @Override\n public JSONObject call(Jedis jedis) {\n LOGGER.info(\"get history from redis\");\n\n if (timestamp != null &amp;&amp; !timestamp.isEmpty()\n &amp;&amp; !\"0\".equals(timestamp)) {\n Set&lt;Tuple&gt; set = jedis.zrangeByScoreWithScores(channelId, timestamp,\n String.valueOf(System.currentTimeMillis()));\n if (set != null) {\n return new JSONObject(set);\n }\n }\n return new JSONObject();\n }\n });\n\n}\n\nprivate JSONObject getHistoryFromRedisByCount(final String count, final String channelId) {\n\n return doWithRedis(jedisHelper, new JedisCallback&lt;JSONObject&gt;() {\n @Override\n public JSONObject call(Jedis jedis) {\n LOGGER.info(\"get history from redis\");\n\n if (!\"0\".equals(count)) {\n try {\n final int limit = Integer.parseInt(count);\n Set&lt;Tuple&gt; set = jedis.zrevrangeByScoreWithScores(channelId, \"+inf\",\n \"-inf\", 0, limit);\n if (set != null) {\n return new JSONObject(set);\n }\n } catch (NumberFormatException ex) {\n LOGGER.error(\"Exception in returning history from Redis: \" + ex);\n }\n }\n\n return new JSONObject();\n }\n });\n\n}\n\nprivate NavigableMap&lt;Long, String&gt; getHistory(\n final ServletContext context, String channel) {\n @SuppressWarnings(\"unchecked\")\n ConcurrentHashMap&lt;Object, Object&gt; history = (ConcurrentHashMap&lt;Object, Object&gt;) context\n .getAttribute(\"history\");\n if (null == history) {\n history = new ConcurrentHashMap&lt;Object, Object&gt;();\n context.setAttribute(\"history\", history);\n } \n\n @SuppressWarnings(\"unchecked\")\n NavigableMap&lt;Long, String&gt; myHistory = (NavigableMap&lt;Long, String&gt;) history\n .get(channel);\n\n if (myHistory == null) {\n LOGGER.info(\"History for this channel not found in Context\");\n history.put(channel, new ConcurrentSkipListMap&lt;Long, String&gt;());\n }\n\n return myHistory;\n}\n\n\ninterface JedisCallback&lt;T&gt; {\n T call(Jedis jedis);\n}\n\nprivate static &lt;T&gt; T doWithRedis(JedisHelper jedisHelper, JedisCallback&lt;T&gt; callback) {\n Jedis jedis = null;\n try {\n jedis = jedisHelper.getJedisObjectFromPool();\n return callback.call(jedis );\n } finally {\n if (jedis != null) {\n jedisHelper.returnJedisObjectToPool(jedis);\n }\n\n}\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Note that after the refactoring only multiple returns you have that is not either \n - when validating parameters\n - when checking if a method returned null and we cannot continue</p>\n\n<p>is in the outermost method. Which we cannot eliminate as I did eliminating <code>historyType</code> dispatch parameter. Maybe you can if you know at the calling site whether you want to call with <code>count</code> or <code>timestamp</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:18:10.470", "Id": "59864", "Score": "0", "body": "I'm using PMD and Checkstyle which prompt me to have only single exit points for a function. So, are they outdated?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:22:53.443", "Id": "59871", "Score": "1", "body": "[It is in the controversial package](http://pmd.sourceforge.net/pmd-5.0.5/xref/net/sourceforge/pmd/lang/java/rule/controversial/OnlyOneReturnRule.html) of PMD because many do not agree with it. Replacing nested `if`s with multiple `return`s is [a standard refactoring](http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T08:53:35.157", "Id": "36493", "ParentId": "36349", "Score": "4" } } ]
{ "AcceptedAnswerId": "36493", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T12:41:23.180", "Id": "36349", "Score": "5", "Tags": [ "java", "redis" ], "Title": "Chat logger using Redis" }
36349
<p>I have designed a proxy server which has the feature to manage miniature separate networks. Each network has space to have up to 500 nodes or 500 IPs. The code for getting a new virtual IP is based on a bit flag based approach. I have used an array of DWORD (Blocks) so as to skip entire 32 IP chunks, if the block is fully set. I have also divided the DWORD further into byte based checking. so as to forgo checking of all 32 bits as much as possible. The code also skips any addresses with the lower octet being 0 or 1. The code only gets the lower two octets while the higher two octets are fixed to 10.0.</p> <p>I know the problem with this approach is that the higher the IP, the slower it gets found. So how can I diminish the slow down? Should I go higher towards LongWORD for one block? Should I check the Block byte by byte or in smaller/bigger chunks? Or just abandon this and find some other algorithm?</p> <p>The limit to be 500 is more of a marketing move than a technical one. We currently have to manage 1800 such networks. These networks are academic in nature and have very anomalous behavior patterns, as such that we are seeing almost 10000 requests per second in peak times.</p> <pre><code>--- var fIPPool : array [0..15] of DWORD; --- constructor xxxx; begin fIPPool [0] := $00000003; // Skips 0.0 and 0.1 fIPPool [7] := $80000000; // Skips 0.255 fIPPool [8] := $00000003; // Skips 1.0 and 1.1 fIPPool [15] := $FE000000; // Skips 1.249-1.255 end; --- function GetIP: DWORD; var Block, Cell : Byte; Mask : DWORD function GetCell ( const ABlock: DWORD; var AMask: DWORD; const ACell : Byte ) : Byte; inline; begin Result := ACell; while ( ABlock and AMask ) &lt;&gt; 0 do begin Result := Result + 1; AMask := AMask shl 1; end; end; begin Result := 0; for Block := 0 to 15 do begin if fIPPool [Block] &lt;&gt; $FFFFFFFF then begin if ( fIPPool [Block] and $000000FF ) &lt; $000000FF then begin Mask := $00000001; Cell := GetCell ( fIPPool [Block], Mask, 0 ) end else if ( fIPPool [Block] and $0000FFFF ) &lt; $0000FFFF then begin Mask := $00000100; Cell := GetCell ( fIPPool [Block], Mask, 8 ) end else if ( fIPPool [Block] and $00FFFFFF ) &lt; $00FFFFFF then begin Mask := $00010000; Cell := GetCell ( fIPPool [Block], Mask, 16 ); end else begin Mask := $01000000; Cell := GetCell ( fIPPool [Block], Mask, 24 ); end; Result := ( Block * 32 ) + Cell; fIPPool [Block] := fIPPool [Block] or Mask; break; end; end; end; // one can use the following line to get the IPs if run in a for-loop for 500 times Memo1.Lines.Add ( IntToStr ( ( IP and $FF00 ) shr 8 ) +'.'+ IntToStr ( IP and $00FF )); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T16:40:48.773", "Id": "59592", "Score": "0", "body": "Can you add some detail about why you have 500 and not 512 addresses in each block?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T16:45:25.440", "Id": "59593", "Score": "0", "body": "Also, how many of these networks do you have?" } ]
[ { "body": "<p>I have performed some benchmarks to get the optimum combination of block and slice sizes using 32-bit and 64-bit compiler. 64-bit because we are also developing an optimized 64-bit implementation on the sidelines. Here are the results for generating 320000 IPs on our server with all the server applications also running, the values are in Milli-seconds and floored over 5 runs;</p>\n\n<pre><code>Block-Slice 32-bit 64-bit\n32-0 3479 3120\n32-16 3464 5912\n64-0 2059 2980\n64-16 2028 1606\n64-32 2013 1622\n</code></pre>\n\n<p>The algorithm gave the worst results with 8-bit slices.\nSo the best bets are 64-32 for 32-bit and 64-16 for 64-bit for this algorithm.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T10:38:12.937", "Id": "36404", "ParentId": "36360", "Score": "1" } } ]
{ "AcceptedAnswerId": "36404", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:32:08.383", "Id": "36360", "Score": "3", "Tags": [ "optimization", "delphi", "networking" ], "Title": "Optimizing an IP generation method" }
36360
<p>This program is supposed to be a player VS player Tic-Tac-Toe game. The computer then checks whether you've won, lost, or tied. The code does work, but I don't want it to work through hacking; I want it to be done the right way.</p> <pre><code>Sub Main() 'Initialise variables Dim StrCoordinate(3, 3) As String Dim BooGameOver As Boolean = False Dim BooIsNextANaught As Boolean = False Dim IntLoopCounterX As Integer = 0 Dim IntLoopCounterY As Integer = 0 Dim IntTempStorage As Integer = 1 Dim StrPlayAgain As String Dim IntTempStorage2 As Integer = 0 Dim BooIsInputValid As Boolean = False Do 'Set all coordinates' contents to "-" For IntLoopCounterY = 0 To 2 For IntLoopCounterX = 0 To 2 StrCoordinate(IntLoopCounterX, IntLoopCounterY) = ("-") Next Next 'Display Instructions Console.WriteLine("╔═════════════════════════════════════════════╗") Console.WriteLine("║Welcome to this tic-tac-toe game! ║") Console.WriteLine("║Please enter the coordinates as you are told ║") Console.WriteLine("║in order to place your X or 0 there. ║") Console.WriteLine("╚═════════════════════════════════════════════╝") Console.WriteLine() Console.WriteLine("Coordinates are as follows:") Console.WriteLine(vbTab &amp; "╔═══╦═══╦═══╗") Console.WriteLine(vbTab &amp; "║1,1║2,1║3,1║") Console.WriteLine(vbTab &amp; "╠═══╬═══╬═══╣") Console.WriteLine(vbTab &amp; "║1,2║2,2║3,2║") Console.WriteLine(vbTab &amp; "╠═══╬═══╬═══╣") Console.WriteLine(vbTab &amp; "║1,3║2,3║3,3║") Console.WriteLine(vbTab &amp; "╚═══╩═══╩═══╝") Console.ReadKey() Console.WriteLine("Press any key once you have understood the instructions.") Console.Clear() Do 'Display Empty Table Console.WriteLine() Console.WriteLine(vbTab &amp; "╔═══╦═══╦═══╗") For IntLoopCounterY = 0 To 2 Console.Write(vbTab &amp; "║ ") For IntLoopCounterX = 0 To 2 Console.Write(StrCoordinate(IntLoopCounterX, IntLoopCounterY) &amp; " ║ ") Next Console.WriteLine() If IntLoopCounterY = 2 Then Console.WriteLine(vbTab &amp; "╚═══╩═══╩═══╝") Else Console.WriteLine(vbTab &amp; "╠═══╬═══╬═══╣") End If Next Console.WriteLine() 'As player one or two for input If BooIsNextANaught = False Then Do 'Ask player 1 for input Console.ForegroundColor = ConsoleColor.Cyan Console.WriteLine(" PLAYER ONE") Console.WriteLine("═══════════════════════════════════════════════════════════════════════════") Console.WriteLine("Please enter coordinate X, then enter. Then enter coordinate Y, then enter.") Console.WriteLine("Coordinates range from 1 to 3.") 'Input coordinates for X Do Console.Write("X (Column)&gt; ") IntTempStorage = Console.ReadLine Console.Write("Y (Row)&gt; ") IntTempStorage2 = Console.ReadLine Loop Until IntTempStorage &gt; 0 And IntTempStorage &lt; 4 And IntTempStorage2 &gt; 0 And IntTempStorage2 &lt; 4 'Check input Select Case StrCoordinate((IntTempStorage - 1), (IntTempStorage2 - 1)) 'Is input being used allready? Case Is = ("X"), ("0") BooIsInputValid = False Console.Clear() Console.BackgroundColor = ConsoleColor.DarkRed Console.WriteLine("══════════════════") Console.WriteLine("ALREADY USED SPACE") Console.WriteLine("Please try again: ") Console.WriteLine("══════════════════") Console.WriteLine() Console.WriteLine() Console.WriteLine(vbTab &amp; "╔═══╦═══╦═══╗") For IntLoopCounterY = 0 To 2 Console.Write(vbTab &amp; "║ ") For IntLoopCounterX = 0 To 2 Console.Write(StrCoordinate(IntLoopCounterX, IntLoopCounterY) &amp; " ║ ") Next Console.WriteLine() If IntLoopCounterY = 2 Then Console.WriteLine(vbTab &amp; "╚═══╩═══╩═══╝") Else Console.WriteLine(vbTab &amp; "╠═══╬═══╬═══╣") End If Next Console.WriteLine() Console.BackgroundColor = ConsoleColor.Black Case Is = ("-") 'Set StrCoordinate(input) with X StrCoordinate((IntTempStorage - 1), (IntTempStorage2 - 1)) = ("X") BooIsInputValid = True BooIsNextANaught = True 'check if winner: For IntLoopCounterY = 0 To 2 'check all rows: If StrCoordinate(0, IntLoopCounterY) = ("X") And StrCoordinate(1, IntLoopCounterY) = ("X") And StrCoordinate(2, IntLoopCounterY) = ("X") Then BooGameOver = True Console.WriteLine("══Player 1 wins══") Console.ReadKey() 'check both diagonals: ElseIf StrCoordinate(0, 0) = ("X") And StrCoordinate(1, 1) = ("X") And StrCoordinate(2, 2) = ("X") Then BooGameOver = True Console.WriteLine("══Player 1 wins══") Console.ReadKey() ElseIf StrCoordinate(0, 2) = ("X") And StrCoordinate(1, 1) = ("X") And StrCoordinate(3, 1) = ("X") Then BooGameOver = True Console.WriteLine("══Player 1 wins══") Console.ReadKey() 'check all columns ElseIf StrCoordinate(IntLoopCounterY, 0) = ("X") And StrCoordinate(IntLoopCounterY, 1) = ("X") And StrCoordinate(IntLoopCounterY, 2) = ("X") Then BooGameOver = True Console.WriteLine("══Player 1 wins══") Console.ReadKey() End If Next Case Else Console.WriteLine("It's Dead, Jim!") End Select Console.ResetColor() Loop Until BooIsInputValid = True Else Do 'Ask player 2 for input Console.ForegroundColor = ConsoleColor.Yellow Console.WriteLine(" PLAYER TWO") Console.WriteLine("═══════════════════════════════════════════════════════════════════════════") Console.WriteLine("Please enter coordinate X, then enter. Then enter coordinate Y, then enter.") Console.WriteLine("Coordinates range from 1 to 3.") Do Console.Write("X (Column)&gt; ") IntTempStorage = Console.ReadLine Console.Write("Y (Row)&gt; ") IntTempStorage2 = Console.ReadLine Loop Until IntTempStorage &gt; 0 And IntTempStorage &lt; 4 And IntTempStorage2 &gt; 0 And IntTempStorage2 &lt; 4 Select Case StrCoordinate((IntTempStorage - 1), (IntTempStorage2 - 1)) Case Is = ("X"), ("0") BooIsInputValid = False Console.Clear() Console.BackgroundColor = ConsoleColor.DarkRed Console.WriteLine("══════════════════") Console.WriteLine("ALREADY USED SPACE") Console.WriteLine("Please try again: ") Console.WriteLine("══════════════════") Console.WriteLine() Console.BackgroundColor = ConsoleColor.Black Console.WriteLine(vbTab &amp; "╔═══╦═══╦═══╗") For IntLoopCounterY = 0 To 2 Console.Write(vbTab &amp; "║ ") For IntLoopCounterX = 0 To 2 Console.Write(StrCoordinate(IntLoopCounterX, IntLoopCounterY) &amp; " ║ ") Next Console.WriteLine() If IntLoopCounterY = 2 Then Console.WriteLine(vbTab &amp; "╚═══╩═══╩═══╝") Else Console.WriteLine(vbTab &amp; "╠═══╬═══╬═══╣") End If Next Console.WriteLine() Case Is = ("-") StrCoordinate((IntTempStorage - 1), (IntTempStorage2 - 1)) = ("0") BooIsInputValid = True BooIsNextANaught = False 'check if winner: For IntLoopCounterY = 0 To 2 'check all rows: If StrCoordinate(0, IntLoopCounterY) = ("0") And StrCoordinate(1, IntLoopCounterY) = ("0") And StrCoordinate(2, IntLoopCounterY) = ("0") Then BooGameOver = True Console.WriteLine("══Player 2 wins══") Console.ReadKey() 'check both diagonals: ElseIf StrCoordinate(0, 0) = ("0") And StrCoordinate(1, 1) = ("0") And StrCoordinate(2, 2) = ("0") Then BooGameOver = True Console.WriteLine("══Player 2 wins══") Console.ReadKey() ElseIf StrCoordinate(0, 2) = ("0") And StrCoordinate(1, 1) = ("0") And StrCoordinate(3, 1) = ("0") Then BooGameOver = True Console.WriteLine("══Player 2 wins══") Console.ReadKey() 'check all columns ElseIf StrCoordinate(IntLoopCounterY, 0) = ("0") And StrCoordinate(IntLoopCounterY, 1) = ("0") And StrCoordinate(IntLoopCounterY, 2) = ("0") Then BooGameOver = True Console.WriteLine("══Player 2 wins══") Console.ReadKey() End If Next Case Else Console.WriteLine("It's Dead, Jim!") End Select If Not StrCoordinate((IntTempStorage - 1), (IntTempStorage2 - 1)) = ("-") Then Else StrCoordinate((IntTempStorage - 1), (IntTempStorage2 - 1)) = ("0") BooIsInputValid = True BooIsNextANaught = False End If Console.ResetColor() Loop Until BooIsInputValid = True End If IntTempStorage = 0 IntTempStorage2 = 0 Console.Clear() If BooGameOver = False Then For IntLoopCounterY = 0 To 2 For IntLoopCounterX = 0 To 2 If Not StrCoordinate(IntLoopCounterX, IntLoopCounterY) = ("-") Then IntTempStorage2 = IntTempStorage2 + 1 End If Next Next If IntTempStorage2 = 9 Then BooGameOver = True Console.WriteLine("It's a draw") End If IntTempStorage = 0 IntTempStorage2 = 0 End If Loop Until BooGameOver = True Console.WriteLine("Would you like to play again? Y/N") StrPlayAgain = UCase(Console.ReadLine) Select Case StrPlayAgain Case Is = ("Y") BooGameOver = False Case Else BooGameOver = True End Select Loop Until BooGameOver = True REM End Console.WriteLine() Console.ForegroundColor = ConsoleColor.Blue Console.Write("EndOfProgram. ") Console.ForegroundColor = ConsoleColor.DarkBlue Console.Write("Enter any key to close.") Console.WriteLine() Console.ReadKey() Console.ResetColor() End Sub </code></pre>
[]
[ { "body": "<p>You have a big bad block of monolithic code here, stuffed in a does-it-all <code>Main()</code> procedure that is <em>begging</em> to be broken down into smaller, more focused procedures and functions.</p>\n\n<p>You need to first <strong>identify concerns</strong>:</p>\n\n<ul>\n<li><strong>Writing</strong> to console</li>\n<li><strong>Reading</strong> from console</li>\n<li><strong>Evaluating</strong> game state</li>\n</ul>\n\n<p>Writing to the console involves several distinct operations:</p>\n\n<ul>\n<li>Rendering the game title/instructions screen.</li>\n<li>Rendering the game screen (the 3x3 grid).</li>\n<li>Rendering the <em>game over</em> screen.</li>\n</ul>\n\n<p>Reading from the console also involves several distinct operations:</p>\n\n<ul>\n<li>Displaying a message and waiting for <kbd>Enter</kbd> to be pressed.</li>\n<li>Displaying a message and getting valid coordinates from the user.</li>\n<li>Displaying a message and getting a <kbd>Y</kbd> or <kbd>N</kbd> answer from the user.</li>\n</ul>\n\n<p>Create <strong>classes</strong> to <em>encapsulate</em> each concern, and write methods for each operation. As far as <em>best practices</em> are concerned, I'm biased with IoC and <a href=\"/questions/tagged/dependency-injection\" class=\"post-tag\" title=\"show questions tagged &#39;dependency-injection&#39;\" rel=\"tag\">dependency-injection</a>, so my <code>Sub Main()</code> would probably look something like this:</p>\n\n<pre><code>Public Class Program\n\n Sub Main()\n\n Dim ConsoleReader As New ConsoleUserInputProvider()\n Dim Game As New TicTacToeGame(ConsoleReader)\n Game.Run()\n\n End Sub\n\nEnd Class\n</code></pre>\n\n<p>The <code>Game</code> object encapsulates the game's <em>logic</em>; the <code>ConsoleUserInputProvider</code> exposes methods that <code>TicTacToeGame</code> uses to get the user's input. It implements some <code>IUserInputProvider</code> interface, which could just as well be implemented by some <code>WinFormsUserInputProvider</code> or <code>WpfUserInputProvider</code> if you wanted some fancypants GUI instead of just a console; the way you have your code, the concerns of <em>game logic</em> and <em>console input/output</em> are so tightly coupled it could very well be simpler to just rewrite the application from scratch to give it a new UI.</p>\n\n<hr>\n\n<p>Your <strong>naming</strong> style is - I'll be gentle - from another era. <a href=\"http://en.wikipedia.org/wiki/Hungarian_notation\"><em>Hungarian Notation</em></a> is outdated and doesn't contribute in any way to make your code more readable: <em>drop those type prefixes!</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-15T21:34:08.247", "Id": "101952", "Score": "2", "body": "Small point in defence of the OP, I've personally mentored his computing class, and I can confirm that the teacher is from another era. Hungarian Notation is but one of his sins, and he has enforced his coding peculiarities onto the whole class." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T00:21:34.953", "Id": "36477", "ParentId": "36361", "Score": "7" } } ]
{ "AcceptedAnswerId": "36477", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:49:40.390", "Id": "36361", "Score": "6", "Tags": [ "vb.net", "tic-tac-toe" ], "Title": "Player VS player Tic-Tac-Toe game" }
36361
<p>I am currently working on a course project and have been assigned to write a GUI. I've written it and it's about 2000 lines of code. It will be bigger when I add the SQL codes and new panels. So, I've successfully divided it into different classes for each screen. My question is: how do I improve that solution? Here is the first shape of code. I'll just write a small part of code for better clarity.</p> <pre><code> /** *When the program starts, first I call passScreen. GUI class extends the JFrame by the way. */ public class GUI extends JFrame{ public GUI() { passScreen(); setSize(700,700); setResizable(true); setTitle("KARGO"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } /** *When a user clicks login button, I simply making panelG invisible, calling client method and *then removing it. I am not writing user_id and password control codes for the sake of clarity */ private void passScreen(){ final JPanel panelG = new JPanel(); ... ... JButton login = new JButton("Login"); login.addActionListener(new ActionListener){ panelG.setVisible(false); client(); getContentPane().remove(panelG); panelG.removeAll(); }}; setContentPane(panelG); } /** *When the user clicks exit, I make the current pane invisible, calling *passScreen method. */ private void client(){ final JPanel panelG = new JPanel(); ... ... JButton exit = new JButton(); exit.addActionListener(new ActionListener){ panelG.setVisible(false); passScreen(); getContentPane().remove(panelG); panelG.removeAll(); }}; setContentPane(panelG); } } </code></pre> <p>Then, I put <code>passScreen()</code> and <code>client()</code> methods to separate classes and modified GUI and the methods slightly:</p> <p>GUI:</p> <pre><code>public class GUI extends JFrame{ public GUI() { new PassScreen().passScreen(this);// I sent current frame object to passScreen method setSize(700,700); setResizable(true); setTitle("KARGO"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } } </code></pre> <p>PassScreen:</p> <pre><code>public class PassScreen{ /** *I made changes and set the content pane via JFrame object coming from GUI class. */ public void passScreen(final JFrame g){ final JPanel panelG = new JPanel(); ... ... JButton login = new JButton("Login"); login.addActionListener(new ActionListener){ panelG.setVisible(false); new Client().client(g);// Sending current frame object to Client class--&gt; g.getContentPane().remove(panelG);//for changing screen panelG.removeAll(); }}; g.setContentPane(panelG); } } </code></pre> <p>Client:</p> <pre><code>public class Client{ public void client(final JFrame g){ final JPanel panelG = new JPanel(); ... ... JButton exit = new JButton(); exit.addActionListener(new ActionListener){ panelG.setVisible(false); new PassScreen().passScreen(g); g.getContentPane().remove(panelG); panelG.removeAll(); }}; g.setContentPane(panelG); } } </code></pre> <p>I don't like it because, for access, I have to make <code>passScreen</code> and client methods public. Is there any better way of separating GUI parts?</p>
[]
[ { "body": "<p>Typically with Swing (and other GUI) applications the way to do it is to make your smaller class extend the component you are working on. For example, your <code>PassScreen</code> class should rather be something like:</p>\n\n<pre><code>class PassPanel extends JPanel {\n public PassPanel(....) {\n // set up all your pass panel sub-components.....\n }\n} \n</code></pre>\n\n<p>then in your calling class you can:</p>\n\n<pre><code>....\nPassPanel passpane = new PassPanel(...);\n....\n</code></pre>\n\n<p>There is a lot of code-simplicity that can be gained by extending the component rather than creating a seperate instance of it... for example, the complicated internal action-listener <code>setVisible(false)</code> becomes <code>passpane.setVisible(false)</code>, and you can still create your own methods on the child classes that do 'compound' operations, like accept, and validate the password.</p>\n\n<p>EDIT: to extend my answer, and to show you real examples of what I mean, consider the <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/examples/components/index.html\" rel=\"nofollow\">examples in the Swing tutorials</a>...</p>\n\n<ul>\n<li>The <a href=\"http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/ButtonDemoProject/src/components/ButtonDemo.java\" rel=\"nofollow\">ButtonDemo.java</a> example</li>\n<li>The <a href=\"http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableDialogEditDemoProject/src/components/TableDialogEditDemo.java\" rel=\"nofollow\">TableDialogEdit.java</a> example</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T17:29:47.477", "Id": "59598", "Score": "0", "body": "cant upvote you because of low rating, thank you for your answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:01:48.750", "Id": "59602", "Score": "0", "body": "The examples you linked don't extend `JFrame` though, which the OP already has done. This means that basically they still have only one class for all the GUI functionality." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T17:22:29.733", "Id": "36366", "ParentId": "36363", "Score": "1" } }, { "body": "<p>I have to disagree with rolfl's approach here. I do not think it is necessary to <code>extend</code> the classes. I have brought this issue up <a href=\"https://codereview.stackexchange.com/questions/36220/java-swing-gui-design/36225#36225\">in an answer here</a>.</p>\n\n<p>I would say that your first version of code is better than the second version. What you are doing in your new code is that you are creating <code>new Client()</code> and then directly calling a method on that object (<code>Client</code> isn't the only example here).</p>\n\n<p>Instead, you could create an utility method anywhere that either can give you a <code>JPanel</code> without actually adding it to the <code>JFrame</code> (in my opinion, this is better, <em>it should be up to the caller to determine what to do with the returned object</em>) or a method can work like you are using it now (both creating and adding it - although I do not recommend this). You <strong>don't need</strong> to <code>extend</code> any classes for this (or create one class for each utility method, which is essentially what you have done). These utility method does not need to be public, and they can all be placed within the same class!</p>\n\n<p>Here is an example (since I do not know all your code, this is similar to the way you used it).</p>\n\n<p>Because you say that you want to avoid having methods <code>public</code>, and also you want to avoid having everything in the same class, you can create a <code>MyComponents</code> class where you can put <code>static</code> methods.</p>\n\n<pre><code>public class MyComponents {\n // using default visibility so that it is only visible to the same package\n static void createClientPanel(final JFrame g){\n\n final JPanel panelG = new JPanel();\n ...\n ... \n JButton exit = new JButton();\n exit.addActionListener(new ActionListener){\n panelG.setVisible(false);\n new PassScreen().passScreen(g);\n g.getContentPane().remove(panelG);\n panelG.removeAll();\n\n }};\n g.setContentPane(panelG);\n }\n}\n</code></pre>\n\n<p>Now you just need to call this method, so <code>new Client().client(g);</code> could be changed to <code>MyComponents.createClientPanel(g);</code></p>\n\n<p>I do think you should apply this on your classes so that in the end, the <code>GUI</code> class and this <code>MyComponents</code> class is all that you have left.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T17:53:37.413", "Id": "59600", "Score": "0", "body": "thanks firstly, should createClientPanel return panelG object or is there a syntax mistake ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T17:57:21.613", "Id": "59601", "Score": "0", "body": "@nihirus Sorry, my mistake. I do think returning the `panelG` object would be better, and use `g.setContentPane(MyComponents.createClientPanel());` - this is the more flexible approach. I think you should try to avoid passing your `JFrame` to these utility methods entirely. Try to make your methods that create components independent from the rest of your code (if possible)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:18:46.917", "Id": "59606", "Score": "0", "body": "Hmm it seems its better to use your first approach. if I made the method static, have to define all class variables static.In addition, where should I use g frame object if I dont take it as a parameter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:22:12.513", "Id": "59607", "Score": "0", "body": "@nihirus Yes, static class variables is a good thing to avoid. How many class variables do you have? (And which ones?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:28:23.187", "Id": "59608", "Score": "0", "body": "Actually, all buttons,labels etc. but I can define it in the method. I defined as a class variable to see them(buttons,labels) easily and modify them without going through the whole code. Also, maybe you miss out my edit, where to define and use g frame object(g.setContentPane(MyComponents....)) if I don't take it as a parameter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:53:55.320", "Id": "59611", "Score": "0", "body": "I rearranged the code in a direction of your comments: http://rifers.org/paste/show/2449 is it better now?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T17:43:08.343", "Id": "36367", "ParentId": "36363", "Score": "3" } } ]
{ "AcceptedAnswerId": "36367", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T17:10:02.823", "Id": "36363", "Score": "5", "Tags": [ "java", "swing", "gui", "user-interface", "awt" ], "Title": "Splitting the GUI into smaller classes" }
36363
<p>Up until now, I've been using a 14-pixel reset in my theme's main CSS file, but after looking online, I see that a lot of web developers prefer a 10-pixel reset;</p> <p><strong>Here is what I'm currently using:</strong></p> <pre><code>/* reset.css */ * { font-size: 1em; } /* dark-theme.css */ body { font-size: 0.875em; } /* 14 pixels equals 1.0em */ </code></pre> <p><strong>Here is what I've seen preferred by others:</strong></p> <pre><code>/* reset.css */ * { font-size: 1em; } /* dark-theme.css */ body { font-size: 0.625em; } /* Now, 14 pixels equals 1.4em; easy! */ </code></pre> <p>With a simple decimal calculation, I can see the latter method being easier to work with. Other than that, is there any real upside to the 10px method, or any downside to my 14px method?</p> <p>I use 14 pixels because I find that Tahoma and Segoe UI are both at optimum reading size for the majority of users, with text resize options available if required. A 16-pixel font size looks too cluttered for my personal taste.</p>
[]
[ { "body": "<p>The answer is <em>neither</em>. The idea that 1em = 16px is only true in two scenarios:</p>\n\n<ul>\n<li>The browser's default font-size is 16px and the user has not adjusted it</li>\n<li>The user has specified that they want a default font-size of 16px because the browser's default was something other than 16px</li>\n</ul>\n\n<p><em>There is no way to accurately convert between em and px.</em> If you genuinely want a 14px font-size because your chosen font looks best at 14px, then specify that size:</p>\n\n<pre><code>html { /* or body, doesn't matter */\n font: 14px Tahoma, sans-serif;\n}\n</code></pre>\n\n<p>You're still free to use relative font-sizes elsewhere if that's what you desire (I recommend that you do: you will only have 1 location where you have to adjust your font-size). Just keep in mind that your specified font may not be available on the user's device and the fallback font might have very different characteristics than you're expecting (eg. the letters might be the same height, but have a different width or vice versa). You also might make your user upset because text is too small for them to read.</p>\n\n<p>Honestly, the later example is a terrible practice that should have stopped a long time ago. The idea that scaling everything to 10px makes math easier is a fallacy, especially when you consider that it is never safe to assume that 1em = 16px.</p>\n\n<hr>\n\n<p>Here's a pretty common scenario showing why this important to understand:</p>\n\n<p>Imagine your typical 2-column blog. Sidebar on the left, blog content on the right. How big do you make the sidebar? You think to yourself, \"300px sounds good\", so you do the math: <code>300 / 16 = 18.75</code> and use 18.75em as your sidebar's width. Now you want to add an image to your sidebar that's 300px wide. Does it fit? How well does it fit?</p>\n\n<p>If the user's font-size is smaller (rare, but it could happen. I've seen one source claim that iOS browsers have a default of 14px, but couldn't find anything confirming this), then the image overflows out of the sidebar. If the user's font-size is larger because they have poor vision, then it fits with lots of extra space. Extra space is usually ok, but you need to make sure you understand that this <em>can</em> happen and that you need to be able to plan for these scenarios.</p>\n\n<p>Related:</p>\n\n<ul>\n<li><a href=\"http://filamentgroup.com/lab/how_we_learned_to_leave_body_font_size_alone/\">http://filamentgroup.com/lab/how_we_learned_to_leave_body_font_size_alone/</a></li>\n<li><a href=\"http://csswizardry.com/2011/05/font-sizing-with-rem-could-be-avoided/\">http://csswizardry.com/2011/05/font-sizing-with-rem-could-be-avoided/</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:23:04.227", "Id": "59613", "Score": "0", "body": "Hi Cimmanon, thanks for the very detailed answer. Concerning my layout, I have the content on the left and sidebar on the right, with both having set widths using percentages. The background is a simple color. This ensures that users always reach the content before the sidebar content, which is obviously less relevant to the page. I'm only using the `em` value for anything text-related, such as font size, margin and padding. And I plan on separating the desktop theme from the mobile theme via CSS media queries, thus providing separate, larger font sizes for mobile devices with an easier layout" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:36:06.727", "Id": "59618", "Score": "0", "body": "... so that I give the best experience possible on smaller screens with higher PPIs. And also from the articles you gave, I can see that the second method is a pretty bad idea. I defined the base font as 14px because that's what I want, although at the same time, I also want relative font sizes. I forgot to mention that my website also incorporates a method for users to adjust the text size, if they don't want to use the browser zoom function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:58:00.753", "Id": "36370", "ParentId": "36364", "Score": "8" } } ]
{ "AcceptedAnswerId": "36370", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T17:17:58.630", "Id": "36364", "Score": "3", "Tags": [ "css" ], "Title": "Which is the more preferable font size reset?" }
36364
<p>I've started learning Python recently and I wanted to test myself. So, can you tell me how many I would get out of 10 and how I could improve my future coding?</p> <pre><code>import random import time print('Welcome to Rock, Paper, Scissors') print(' '*25) wins = 0 loses = 0 draws = 0 point= int(input('How many rounds do you want to play?')) list = ['r','p','s'] for x in range (1,(point+1)): computer = random.choice(list) human=str(input('Choose (R)ock, (P)aper, or (S)cissors?')) if human == computer: draws = draws + 1 print('''Human: {} Computer: {} A draw Wins = {} Loses = {} Draws = {}'''.format(human,computer,wins,loses,draws)) print(' '*25) elif human == 'r' and computer == 'p': loses = loses + 1 print('''Human: ROCK Computer: PAPER Computer wins Wins = {} Loses = {} Draws = {}'''.format(wins,loses,draws)) print(' '*25) elif human == 'r' and computer == 's': wins = wins + 1 print('''Human: ROCK Computer: SCISSORS Human wins Wins = {} Loses = {} Draws = {}'''.format(wins,loses,draws)) print(' '*25) elif human == 'p' and computer == 's': loses = loses + 1 print('''Human: PAPER Computer: SCISSORS Computer wins Wins = {} Loses = {} Draws = {}'''.format(wins,loses,draws)) print(' '*25) elif human == 'p' and computer == 'r': wins = wins + 1 print('''Human: PAPER Computer: ROCK Human wins Wins = {} Loses = {} Draws = {}'''.format(wins,loses,draws)) print(' '*25) elif human == 's' and computer == 'p': wins = wins + 1 print('''Human: SCISSORS Computer: PAPER Human wins Wins = {} Loses = {} Draws = {}'''.format(wins,loses,draws)) print(' '*25) elif human == 's' and computer == 'r': loses = loses + 1 print('''Human: SCISSORS Computer: ROCK Computer wins Wins = {} Loses = {} Draws = {}'''.format(wins,loses,draws)) print(' '*25) else: print('Error') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T15:51:25.437", "Id": "59742", "Score": "5", "body": "The purpose of code review is to improve the quality of the code, not to evaluate the coder, so I would hope that no-one actually starts giving marks out of ten." } ]
[ { "body": "<ul>\n<li><p>There is no overall structure to this program, just an undifferentiated mass of code.</p></li>\n<li><p>There is a lot of redundancy to the 'if... elif... elif...' structure which could be pulled out into a function; better yet, find a way to structure the decision-making regularities as a calculation.</p></li>\n<li><p><code>print(' '*25)</code> is very strange; <code>print()</code> would suffice.</p></li>\n<li><p><code>list</code> is not a good variable name because it shadows the built-in function <code>list()</code>.</p></li>\n</ul>\n\n<p>Here is a rewritten version:</p>\n\n<pre><code>from random import choice\nimport sys\n\n# compatibility shim for Python 2/3\nif sys.hexversion &gt;= 0x3000000:\n inp = input\n rng = range\nelse:\n inp = raw_input\n rng = xrange\n\ndef get_int(prompt):\n while True:\n try:\n return int(inp(prompt))\n except ValueError:\n pass\n\ndef get_ch(prompt):\n while True:\n res = inp(prompt).strip()\n if res:\n return res[:1]\n\nclass RockPaperScissors():\n moves = 'rps'\n names = {\n 'r': 'ROCK',\n 'p': 'PAPER',\n 's': 'SCISSORS'\n }\n win_string = {\n 0: 'Draw',\n 1: 'Human wins',\n 2: 'Computer wins'\n }\n\n def __init__(self):\n self.wins = 0\n self.draws = 0\n self.losses = 0\n\n def play(self):\n cmove = choice(RockPaperScissors.moves)\n hmove = get_ch('Choose [r]ock, [p]aper, [s]cissors: ').lower()\n win_state = (RockPaperScissors.moves.index(hmove) - RockPaperScissors.moves.index(cmove)) % 3\n [self.draw, self.win, self.lose][win_state]()\n print('Human plays {:&lt;12s} Computer plays {:&lt;12s} {}'.format(RockPaperScissors.names[hmove], RockPaperScissors.names[cmove], RockPaperScissors.win_string[win_state]))\n\n def win(self):\n self.wins += 1\n\n def draw(self):\n self.draws += 1\n\n def lose(self):\n self.losses += 1\n\ndef main():\n print('Welcome to Rock, Paper, Scissors')\n\n game = RockPaperScissors()\n rounds = get_int('How many rounds do you want to play? ')\n for round in rng(rounds):\n game.play()\n print('{} wins {} draws {} losses\\n'.format(game.wins, game.draws, game.losses))\n\nif __name__==\"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T01:03:57.783", "Id": "59626", "Score": "0", "body": "This is in some respects worse than the original code, particularly the lack of transparency in how the winner is decided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T01:09:01.030", "Id": "59627", "Score": "0", "body": "@Stuart: um... sorry? I thought it was pretty dead-obvious; you index into the 'rock-paper-scissors' cycle, subtract the human's move from the computer's, and modulo 3. The answer is then 0 = draw, 1 = human wins, 2 = human loses. You then use that answer to call the appropriate method to update the score." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T01:30:51.183", "Id": "59628", "Score": "0", "body": "You have lost readability by using modulos, a mysterious variable called \"res\", and a look up in tables. Why not use `if...elif...else`? Also, your class structure is overly complicated for the nature of the programme. This would make sense only if the plan is to extend it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T01:48:46.243", "Id": "59629", "Score": "0", "body": "@Stuart: yes, res is not a great name; I should probably have called it something like win_state. I could have then used 6 lines of if-else to call the appropriate methods - and if the operation were less cleanly structured I would have - but frankly I think this looks cleaner. The class properties are probably overkill - too used to Java-style setters - but I doubt it took you more than two seconds to figure out what they do; and inheritance is not the only reason to use classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:02:28.840", "Id": "59630", "Score": "0", "body": "Removed properties, renamed res." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T20:10:33.317", "Id": "36374", "ParentId": "36368", "Score": "3" } }, { "body": "<p>You can reduce <code>if...elif...</code> by noting that there are only three possible outcomes and finding a simple way to describe the conditions for each outcome. You can store the outcome (win, lose, draw) in a variable and avoid repeating the same print command. You could also use a dictionary to store the three options and their abbreviations. </p>\n\n<pre><code>import random\nprint('Welcome to Rock, Paper, Scissors\\n')\nwins = 0\nloses = 0\ndraws = 0\noptions = {'r': 'rock', 'p': 'paper', 's': 'scissors'}\nrounds = int(input('How many rounds do you want to play?'))\nfor _ in range(rounds):\n computer = random.choice(list(options.keys()))\n human = str(input('Choose (R)ock, (P)aper, or (S)cissors?')).lower()\n if human == computer:\n outcome = 'A draw'\n draws += 1\n elif (human, computer) in (('r', 'p'), ('p', 's'), ('s', 'r')):\n outcome = 'Computer wins'\n loses += 1\n else:\n outcome = 'Human wins'\n wins += 1\n print(\"Human: {}\\tComputer: {}\\t{}\".format(options[human], options[computer], outcome))\n print(\"Wins = {}\\tLoses = {}\\tDraws = {}\".format(wins, loses, draws))\n</code></pre>\n\n<p>If you want to improve the programme further, consider adding error checking in case the user enters the wrong type of input, e.g.:</p>\n\n<pre><code>while True:\n try:\n rounds = int(input('How many rounds do you want to play?'))\n if rounds &lt;= 0:\n raise ValueError\n break\n except ValueError:\n print (\"Please enter a positive whole number.\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:09:38.303", "Id": "59631", "Score": "0", "body": "`random.choice(options.keys())` is redundant; `random.choice(options)` will do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:21:10.910", "Id": "59632", "Score": "0", "body": "@HughBothwell no, random.choice takes a sequence. I don't think it works with a dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:29:09.887", "Id": "59633", "Score": "0", "body": "my bad; I was thinking of how `for k in mydict:` iterates on the keys, but you are right, random.choice won't. Actually, in Python 3, it won't accept `random.choice(mydict.keys())` either, it has to be `random.choice(list(mydict))` or `random.choice(list(mydict.keys()))`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:33:52.570", "Id": "59634", "Score": "0", "body": "Thanks have edited - I think `random.choice(list(mydict.keys()))` will work" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:07:07.357", "Id": "36389", "ParentId": "36368", "Score": "3" } }, { "body": "<p>Rather than making the <em>game</em> a class, consider making the choices a class. This makes it easy to define the behaviors:</p>\n\n<pre><code>import sys\nfrom random import choice\n\nclass RPS(object):\n def __init__(self, name, rank, *lose_to):\n self.Name = name\n self.Rank = rank\n self.LoseTo = lose_to\n\n def fight(self, other):\n if self.Rank in other.LoseTo: return 'wins'\n if other.Rank in self.LoseTo: return 'loses'\n return 'draws'\n\n def __str__(self):\n return self.Name\n\nROCK = RPS('rock', 0, 1)\nPAPER = RPS('paper', 1, 2)\nSCISSORS = RPS('scissors', 2, 0)\nOPTIONS = {'r':ROCK, 'p':PAPER, 's':SCISSORS} \nPROMPT = \"\\nEnter [r]ock, [p]aper, [s]cissors or [q]uit :\"\nresults = []\n\nwhile True:\n choice_string = raw_input(PROMPT)\n try:\n player_choice = OPTIONS[choice_string]\n computer_choice = choice(OPTIONS.values())\n results.append(player_choice.fight(computer_choice))\n sys.stdout.writelines(\"\\tplayer: %s\\n\\tcomputer: %s\\n\\tresult: player %s\\n\" % (player_choice, computer_choice, results[-1]))\n\n except KeyError: # something other than 'r', 'p' or 's' was entered...\n if choice_string == 'q':\n break # exits the game\n else:\n sys.stdout.writelines(\"'%s' is not a valid choice\" % choice_string)\n\n# print an exit summary\nsys.stdout.writelines(\"\\nThanks for playing!\\n\")\nsys.stdout.writelines(\"\\t%i wins\\n\" % results.count('wins'))\nsys.stdout.writelines(\"\\t%i losses\\n\" % results.count('loses'))\nsys.stdout.writelines(\"\\t%i draws\\n\" % results.count('draws'))\n</code></pre>\n\n<p>The advantage of pushing the comparison down into the RPS class is that the behavior can be extended without going ELIF crazy. For example the above can be changed like so:</p>\n\n<pre><code>ROCK = RPS('rock', 0, 1, 4)\nPAPER = RPS('paper', 1, 2, 3)\nSCISSORS = RPS('scissors', 2, 0, 4)\nLIZARD = RPS('lizard', 3, 0, 2)\nSPOCK = RPS('spock', 4, 1, 3)\nOPTIONS= {'r':ROCK, 'p':PAPER, 's':SCISSORS, 'l':LIZARD, 'k':SPOCK } \nPROMPT = \"\\nEnter [r]ock, [p]aper, [s]cissors, [l]izard, Spoc[k] or [q]uit :\" \n</code></pre>\n\n<p>with minimal effort and no changes to the overalls structure of the program. In a real application you'd probably return something more definitive from the 'fight' method than a string - a result class with its own message, or something -- but by keeping the details of the comparison out of the main flow of the program it's easier to extend as needs change. Overkill for rock paper scissors, but a big plus for rock, paper, scissors, lizard, spock. Unfortunately real life is more like the latter than the former ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T07:14:11.250", "Id": "36446", "ParentId": "36368", "Score": "0" } }, { "body": "<p>Your program is adequate, but it doesn't \"scale\". Each player can choose from 3 moves; of those 9 possibilities, the 3 ties can be handled in common, for a total of 7 code branches. Handling all those cases with cut-and-paste code violates the \"Don't Repeat Yourself\" principle, and it makes the code hard to maintain.</p>\n\n<p>I would start by introducing a class to represent the moves, and define how they relate to each other:</p>\n\n<pre><code>from collections import namedtuple\n\nclass RPSMove(namedtuple('RPSMove', ['name', 'short_name', 'beats'])):\n def __gt__(self, other):\n return self.beats == other.short_name\n\n def __lt__(self, other):\n return not(self == other or self &gt; other)\n\n def __str__(self):\n return self.name\n\n all = dict()\n\nRPSMove.all['r'] = RPSMove('rock', short_name='r', beats='s')\nRPSMove.all['p'] = RPSMove('paper', short_name='p', beats='r')\nRPSMove.all['s'] = RPSMove('scissors', short_name='s', beats='p')\n</code></pre>\n\n<p>Next, I would extract the way the computer and human take their turns into functions:</p>\n\n<pre><code>import random\nfrom sys import exit\n\ndef computer_play():\n return random.choice(list(RPSMove.all.values()))\n\ndef human_play():\n while True:\n try:\n choice = input('Choose (R)ock, (P)aper, or (S)cissors? ')\n return RPSMove.all[choice[0].lower()]\n except EOFError:\n print('')\n exit(0)\n except:\n print('Error')\n</code></pre>\n\n<p>The <code>human_play()</code> function is more complex than your original due to handling of invalid choices and end-of-file (<kbd>Control</kbd>+<kbd>D</kbd> in Unix or <kbd>Control</kbd>+<kbd>Z</kbd> in Windows).</p>\n\n<p>With those preliminaries out of the way, the heart of the game can look quite nice.</p>\n\n<pre><code>random.seed()\nhuman_wins, computer_wins, draws = 0, 0, 0\n\nprint('Welcome to Rock, Paper, Scissors')\nprint('')\nrounds = int(input('How many rounds do you want to play? '))\nfor _ in range(rounds):\n human_move, computer_move = human_play(), computer_play()\n if human_move &gt; computer_move:\n result = 'Human wins'\n human_wins += 1\n elif human_move &lt; computer_move:\n result = 'Computer wins'\n computer_wins += 1\n else:\n result = 'A draw'\n draws += 1\n\n print('Human: %-17s Computer: %-17s %s' %\n (human_move, computer_move, result))\n print('Human wins = %-11d Computer wins = %-11d Draws = %-11d' %\n (human_wins, computer_wins, draws))\n print('')\n</code></pre>\n\n<p>I've renamed <code>wins</code> and <code>loses</code> to <code>human_wins</code> and <code>computer_wins</code> to avoid anthropocentrism.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T07:24:29.447", "Id": "36685", "ParentId": "36368", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:11:12.013", "Id": "36368", "Score": "4", "Tags": [ "python", "beginner", "game", "python-3.x", "rock-paper-scissors" ], "Title": "Rock paper scissors" }
36368
<p>I want to read multidimensional double array from file into a single pointer variable. The number of rows and columns are not known and need to be determined when reading the file in order to allocate memory for the array. I wrote the following code and it works fine with me. I want to know if someone has more efficient solution for such case:</p> <pre><code>//Initialize variables and open the file size_t count=1000; char *line = malloc(1000); FILE *file= fopen("g.txt", "r"); if(file==NULL) { printf("Error in Opening file"); return EXIT_FAILURE; } double *data=(double*) malloc(1000*sizeof(double)); if(data==NULL) { printf("Error in allocating memory"); return EXIT_FAILURE; } // Read number of columns and number of rows getline(&amp;line, &amp;count, file); int read=-1,cur=0,columCount=0; while(sscanf(line+cur, "%lf%n", &amp;data[columCount],&amp;read)==1) {cur+=read;columCount=columCount+1;} int rowCount=1; while(getline(&amp;line, &amp;count, file)!=-1) {rowCount=rowCount+1;} rewind(file); // Reinitialize array using the number of rows and number of columns free(data); data=(double*) malloc(columCount*rowCount*sizeof(double)); if(data==NULL) { printf("Error in allocating memory"); return EXIT_FAILURE; } // Read file and store values int i=0; while(getline(&amp;line, &amp;count, file)!=-1) { read=-1,cur=0; while(sscanf(line+cur, "%lf%n", &amp;data[i],&amp;read)==1) {cur+=read;i=i+1;} } fclose(file); return EXIT_SUCCESS; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:35:24.327", "Id": "59616", "Score": "2", "body": "1. Harmonize your coding style! This especially includes the positions of braces and the number of spaces contained in one indention level (2 or 4?). 2. [Do **not** cast the result of malloc()](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)!" } ]
[ { "body": "<p>You have written everything in one function (<code>main</code> probably) but it is better\nsplit into its components. Essentially what you want to do is:</p>\n\n<pre><code>open input file\nget column count\nget line count\nrewind file\nallocate memory for the array\nread array data\n</code></pre>\n\n<p>Some of these stages could and probably should be in separate functions.</p>\n\n<p>Taking it from the top, you open the input file, with the file name\nhard-coded. A better approach is to get the filename from the command line -\n<code>argv[1]</code>. You have checked for failure to open the file, which is good.\nThe normal error handling is to use <code>perror</code> and the name of the failed file:</p>\n\n<pre><code>FILE *f = fopen(argv[1], \"r\");\nif (!f) {\n perror(argv[1]);\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<p>You then allocate buffer <code>data</code> (again the error handling should use\n<code>perror</code>). You then use this buffer in a read loop to count the entries in\neach line, but you really don't need to save the values in the buffer at all\nat this stage - you discard them anyway. Your read loop could equally be:</p>\n\n<pre><code>while (sscanf(line+cur, \"%*lf%n\", &amp;read) == 1) {\n cur += read;\n columCount++;\n}\n</code></pre>\n\n<p>Notice that the format string uses a '*' to suppress assignment of the\nfloating point value read. Note also the improved formatting and the use of\n<code>++</code> in <code>columCount++</code>. Note also that you don't check for failure in reading\nthe first line.</p>\n\n<p><hr>\n<strong>Edit:</strong> Abbas pointed out that adding the '*' to suppress assignment means that we must check for 0 returned from <code>sscanf</code>, not 1. But <code>sscanf</code> also returns 0 when it fails to read anything (in this case the read count in <code>read</code> would also contain 0). Hence a bad character in the line will cause the loop to hang. So we must either not suppress the assignment:</p>\n\n<pre><code>double d;\nwhile (sscanf(line+cur, \"%lf%n\", &amp;d, &amp;read) == 1) {\n cur += read;\n columCount++;\n}\n</code></pre>\n\n<p>or we must check <code>read</code>. </p>\n\n<pre><code>while ((sscanf(line+cur, \"%*lf%n\", &amp;read) == 0) &amp;&amp; (read != 0)) {\n cur += read;\n columCount++;\n}\n</code></pre>\n\n<p>I think I would go for the first. End of edit.</p>\n\n<hr>\n\n<p>You then count the lines by looping through them. Note that you use a fixed\nsize buffer <code>line</code>, allocated at the beginning, to read each line. To be\ncompletely flexible, you should handle lines of arbitrary length. Your lines\nare fixed at 1000 chars and anything beyond that breaks the code. Since you\nare using <code>getline</code> (which is non-standard, but useful) I would make use of its \nability to allocate a line for you by passing a zero size.</p>\n\n<pre><code>char *line = NULL;\nsize_t count = 0; // EDIT: Abbas pointed out we need to add count=0\ngetline(&amp;line, &amp;count, file);\n// use the line\nfree(line);\n</code></pre>\n\n<p>In this, <code>line</code> is just a pointer. <code>getline</code> allocates a buffer large enough\nto hold the line of text and places a pointer to the buffer in <code>line</code>. You\n<strong>must</strong> free that line later.</p>\n\n<p>So now you have the column and row count. Those two stages (reading the two\nsizes) would be better extracted into a separate function.</p>\n\n<p>You now rewind the file and allocate the real array. As stated above, this\nshould be the first allocation of the program. Following this you read the\ndata into the array. This might be better split into a separate function. \nThe read loop can be simpler than yours - you\ndon't need to get a line and then scan it - just scan it directly:</p>\n\n<pre><code>int ndata = 0;\nwhile (scanf(\"%lg\", &amp;data[ndata++]) == 1) {\n // nothing\n}\nndata -= columCount * rowCount;\nif (ndata != 0) {\n printf(\"%s data values in input\\n\", ndata &gt; 0 ? \"Too few\" : \"Too many\");\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<p>And remember to check that the number of doubles read matches what you were\nexpecting.</p>\n\n<p>Note that <code>scanf</code> and its associates do not react well to malformed input. There are other ways of reading text but in the simple case (of properly formed data) they are more complicated. Someone else might give you some examples/alternatives.</p>\n\n<p>Finally note that your formatting is inconsistent, as if bits have been cut\nand pasted from elsewhere. Copying code from your previous work is not\nnecessarily bad, but make sure you make the whole thing looks as if it belongs\ntogether.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T11:58:06.910", "Id": "59660", "Score": "0", "body": "Thanks for the excellent and comprehensive answer. However, when I applied your code hints, I found some bugs, and I corrected them as follows:\nFirst) getline requires that the first two parameters to be assigned to null and 0, respectively, before calling the function. So, getline(&line, 0, file) gave me an error, however, char *line=NULL; int count=0; getline(&line, &count, file); works.\nSecond) The value 1 should be replaced by 0 in while (sscanf(line+cur, \"%*lf%n\", &read) == 1).\nThird) The value 0 should be replaced by 1 in if (ndata != 0).\n\nIs what I did correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:05:26.690", "Id": "59667", "Score": "0", "body": "Oops! Your first point is correct. Your second is correct but throws up the problem that a bad character in the input will cause and endless loop. I'll edit my answer to comment on this. The third, I can't see why `ndata` should be 1 at the end of the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:39:29.017", "Id": "59679", "Score": "0", "body": "Thanks @William Morris. Regarding the third point: it is because you put data[ndata++] in the while condition, so, if the array has 20 elements, after executing the while loop ndata will have the value 22 (This is because the ++ executed even if the while condition result is false).\nOne final note: in the while loop, you put it scanf, but, it should be fscanf(f,\"%lg\",....)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T19:01:34.577", "Id": "59688", "Score": "0", "body": "Ah yes, you are right. The perils of using a `while` loop when a `for` would have been more appropriate :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T23:41:55.977", "Id": "36384", "ParentId": "36372", "Score": "3" } } ]
{ "AcceptedAnswerId": "36384", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:06:03.753", "Id": "36372", "Score": "2", "Tags": [ "c", "array" ], "Title": "Read multidimensional array from file in C" }
36372
<p>I want to check the existence of various API endpoints by doing serial URL request. If the first one fails, I want to try the second one, if the second fails I want to try the third one, etc.</p> <p>Here is some code I use to do this:</p> <pre><code>self.apiEndpoint = kApiAjaxEndpoint; [self testEndpointWithBlock:^(id response, NSError *error) { if (error) { self.apiEndpoint = kApiAjaxLegacyEndpoint; [self testEndpointWithBlock:^(id response, NSError *error) { if (error) { self.apiEndpoint = kApiRestEndpoint; } [self saveApiEndpoint]; }]; } else { [self saveApiEndpoint]; } }]; </code></pre> <p>So for now I'm only testing for 2 API endpoints but the moment I add a new endpoint I would need to add another call to <code>testEndpointWithBlock:</code> with error handling code.</p> <p>I was wondering if you can think of a more elegant way of doing this?</p>
[]
[ { "body": "<ol>\n<li>Create several instances of <code>NSOperation</code></li>\n<li>Set dependencies so that one runs after another.</li>\n<li>Add to a private <code>NSOperationQueue</code>. </li>\n<li>Cancel all operations in a queue if a match is found.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T07:26:56.403", "Id": "64679", "Score": "0", "body": "This seems like a nice, lightweight solution, and gets the URL requests off the main thread if testEndpointWithBlock: doesn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-14T16:46:37.863", "Id": "298613", "Score": "0", "body": "Even if you use NSOperations and dependencies, you must run asynchronous NSOperations, please see [this blog post](http://swiftgazelle.com/2016/03/asynchronous-nsoperation-why-and-how/) (it's for Swift, but you can get the idea)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T22:54:03.407", "Id": "36382", "ParentId": "36373", "Score": "3" } }, { "body": "<blockquote>\n<p>I was wondering if you can think of a more elegant way of doing this?</p>\n</blockquote>\n<p>Asynchronous problems getting quickly more complicated than one would expect. If you don't mind to utilize a third party library, you can find an easy solution to those kind of problems:</p>\n<p>The third party library would implement a <a href=\"http://en.wikipedia.org/wiki/Futures_and_promises\" rel=\"nofollow noreferrer\">Promise</a>. A promise represents the <em>eventual</em> result of an asynchronous operation. Your asynchronous method for testing any endpoint may then look as shown below:</p>\n<pre><code>- (Promise*) testEndpoint:(Endpoint*)endpoint;\n</code></pre>\n<p>Note: no completion handler. Notifying the call-site is solved differently, through registering a success and an error handler via a <code>then</code> method (or property). The success handler passes the result back to the call-site, and the error handler passes the error back to the call-site:</p>\n<pre><code>Promise* promise = [self testEndpoint:endpoint];\n\npromise.then(mySuccessHandler, myErrorHandler);\n</code></pre>\n<p>And shorter:</p>\n<pre><code>[self testEndpoint:endpoint]\n.then(id^(id result){\n // result is the eventual result of the asynchronous task\n return nil; \n}, id^(NSError* error){\n // error is the failure reason of the asynchronous task\n return nil;\n});\n \n</code></pre>\n<p>Note: <code>then(mySuccessHandler, myErrorHandler)</code> will return a Promise. The returned Promise's value becomes the return value of the handler (either of the success or failure handler).</p>\n<p>So, given</p>\n<pre><code>Promise* promise = task().then(^(id result){ return @&quot;OK&quot;}, nil);\n</code></pre>\n<p>then, when the task succeeds, the below statement will eventually become true:</p>\n<pre><code>`[promise get] isEqualToString: @&quot;OK&quot;`\n</code></pre>\n<p>Otherwise, if the error handler equals <code>nil</code> as above, errors will be propagated to the child promise:</p>\n<pre><code>`[[promise get] isKindOfClass:[NSError class]]`\n</code></pre>\n<p>For example, using a helper method <code>all:</code>:</p>\n<h3>A) Run <em>all</em> tests in <em>parallel</em> and return an array of the results:</h3>\n<p>If the test succeeds, return a string <code>@&quot;OK&quot;</code>, otherwise return <code>@&quot;not reachable&quot;</code>.</p>\n<p>Create an array of Promises, whose associated task is already running:</p>\n<pre><code>NSArray* requests = @{\n [self testEndpoint:A].then(^id(id result){return @&quot;OK&quot;;}, ^id(NSError* error){return @&quot;not reachable&quot;;}),\n [self testEndpoint:B].then(^id(id result){return @&quot;OK&quot;;}, ^id(NSError* error){return @&quot;not reachable&quot;;}),\n [self testEndpoint:C].then(^id(id result){return @&quot;OK&quot;;}, ^id(NSError* error){return @&quot;not reachable&quot;;}),\n [self testEndpoint:D].then(^id(id result){return @&quot;OK&quot;;}, ^id(NSError* error){return @&quot;not reachable&quot;;}),\n};\n</code></pre>\n<p>When <em>all</em> tests are finished <em>then</em> execute the handler:</p>\n<pre><code>[Promise all:requests].then(^id(id results){\n // results is a NSArray containing the result of each \n // task above in the same order .\n ...\n return nil;\n}, nil);\n</code></pre>\n<p>Likewise, using a helper method <code>any:</code>:</p>\n<h3>B) Run <em>all</em> tests in <em>parallel</em>. When the <em>first</em> finished return its result and stop the other tasks:</h3>\n<pre><code>NSArray* requests = ...; // same as above\n\n[Promise any:requests].then(^id(id result){\n // Parameter result is the result of the first task that finished.\n ...\n return nil;\n}, nil);\n</code></pre>\n<p>When the first task finished, all other promises will be send a <code>cancel</code> message, which (if implemented) cancels the underlying asynchronous task.</p>\n<p>Or,</p>\n<h3>C) Run tasks in sequence until a break condition becomes true:</h3>\n<pre><code>NSArray* endpoints = ...;\n\nconst NSUInteger count = [endpoints count];\n__block NSUInteger i = 0;\n__block BOOL done = NO;\n[RXPromise repeat:^RXPromise *{\n if (i &gt;= count || done) {\n return nil; // returning nil breaks the asynchronous loop\n }\n return [self testEndpoint:endpoints[i]].then(^id(id result){\n // found endpoint\n ++i;\n done = YES;\n return nil;\n }, ^id(NSError* error){\n ++i;\n return nil; // nil continues, returning an error would break the loop\n });\n}];\n</code></pre>\n<p>For a more detailed overview of Promises and a list of implementations you may read here: <a href=\"https://softwareengineering.stackexchange.com/questions/184597/success-failure-blocks-vs-completion-block/219929#219929\">https://softwareengineering.stackexchange.com/questions/184597/success-failure-blocks-vs-completion-block/219929#219929</a></p>\n<p><strong>Disclosure:</strong> the code snippets above used the API of the <a href=\"https://github.com/couchdeveloper/RXPromise\" rel=\"nofollow noreferrer\">RXPromise library</a>. Other libraries may have slightly differing APIs, and may or may not provide the same functionality. I'm the author of RXPromise.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T12:50:07.460", "Id": "36636", "ParentId": "36373", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T19:34:29.770", "Id": "36373", "Score": "5", "Tags": [ "objective-c", "api", "ios", "url" ], "Title": "Multiple serial URL requests in Objective-C / iOS" }
36373
<p>I'm trying to get my head around C-string processing. I've decided to try my hand at making a dirt-simple magnet link generator. The format that a magnet link needs is</p> <pre><code>magnet:?xt=&lt;hash&gt;&amp;tr=tracker1url&amp;tr=tracker2url&amp;....&amp;tr=trackerNurl </code></pre> <p>This program takes a hash as an argument on the command line, and takes lines on standard input which are either empty lines or the URLs of trackers.</p> <p>Am I doing this in a sane way? What can I do better? Please note that I'm fairly new to C, so if you see anything weird or dangerous, let me know about that as well.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define SIZE 4096 /* * Exit with the given code, and print an error * message if ec != 0 */ void die(int ec, char *message) { if (ec) { fprintf(stderr, "ERROR: %s\n", message); } exit(ec); } /* * takes one input argument -- the hash code * of the thing you're looking to generate a * magnet link for, on the command line, and * then a list of trackers on the stdin stream. */ int main(int argc, char **argv) { // If there is no if (argc &lt; 2) die(1, "No hash code given!"); // buf is the internal buffer. bufEnd is supposed // to be a pointer to the very end of the string // to prevent linear time string concatenation. char buf[SIZE]; char *bufEnd; // line is a buffer for each line of standard in char line[SIZE]; // 20 is the number of chars in "magnet:?xt=..." // magic number is bad but i don't know a better way if (20 + strlen(argv[1]) &gt;= SIZE) die(1, "buffer overflow detected"); // Here we initialize buffer bufEnd = buf + snprintf(buf, SIZE, "magnet:?xt=urn:btih:%s", argv[1]); // keep reading input lines, adding "&amp;tr=..." params // to the magnet link for non-empty lines while (fgets(line, SIZE, stdin)) { int len = strlen(line); // find out how big this line is // check for empty line. skip it if it's empty if (!(strcmp(line, "\n"))) continue; // check to see if there's room left in the array // and if so, then add the next arg. if (SIZE - (bufEnd - buf + len + 4) &gt; 0) { bufEnd += sprintf(bufEnd, "&amp;tr=%s", line) - 1; } else die(1, "buffer overflow detected"); } // change the trailing newline into a nul byte if (bufEnd - buf &lt; SIZE) { *bufEnd = '\0'; } else die(2, "crazy buffer overflow detected"); // output it with backwards brackets (to show whitespace... // debugging purposes) fprintf(stdout, "&gt;%s&lt;\n", buf); fflush(stdout); return EXIT_SUCCESS; } </code></pre>
[]
[ { "body": "<p>Your code is nicely written and you have checked for errors well. It\nis perhaps a little over-commented, many of the comments explaining\nthe obvious (and hence being just 'noise').</p>\n\n<p>String handling in C is messy and there are always many ways of\nachieving the same thing. There's nothing really wrong with using\n<code>snprintf</code> although it can be less efficient than using <code>strcat</code> and\nfriends. Since you are using <code>snprintf</code> I'll concentrate on\nhow you use it and ignore any alternatives. Someone else might like\nto comment on them.</p>\n\n<p>You first append the command line parameter:</p>\n\n<pre><code>if (20 + strlen(argv[1]) &gt;= SIZE)\n die(1, \"buffer overflow detected\");\n\nbufEnd = buf + snprintf(buf, SIZE, \"magnet:?xt=urn:btih:%s\", argv[1]);\n</code></pre>\n\n<p>In this you have traversed <code>argv[1]</code> twice, once in the <code>strlen</code> call\nand then again in <code>snprintf</code>. You could avoid one of these:</p>\n\n<pre><code>const char *limit = buf + sizeof buf;\nchar *in = buf;\n\nin += snprintf(in, limit-in, \"magnet:?xt=urn:btih:%s\", argv[1]);\nif (in &gt;= limit) {\n die(1, \"buffer overflow detected\");\n}\n</code></pre>\n\n<p>This is more efficient and also avoids embedding the magic number 20\n(embedded constants are usually best avoided). It uses the fact the\n<code>snprintf</code> returns the number of bytes needed for the string it wanted\nto print but doesn't overflow the buffer. So if it returns a number \ngreater than or equal to the space available , you know there was an \noverflow. I also changed <code>bufEnd</code> to <code>in</code>, used <code>limit</code> to mark the \nend of the buffer and added braces around the call to <code>die</code></p>\n\n<p>Within your <code>while</code> loop you also traverse each string twice. The\nsame technique as above can be used to avoid this. Also your check\nfor blank lines does not trap lines that contains white-space as well\nas a \\n. For that you might use:</p>\n\n<pre><code>const char *s = line + strspn(line, \" \\t\\r\\n\");\nif (*s == '\\0')\n continue;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T16:54:59.117", "Id": "36417", "ParentId": "36380", "Score": "3" } } ]
{ "AcceptedAnswerId": "36417", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T22:42:25.280", "Id": "36380", "Score": "2", "Tags": [ "c", "strings", "beginner" ], "Title": "C String Processing -- magnet link example" }
36380
The tool called "make" is a build manager which compares the last modification times of various files and performs user specified actions (commands) when the "target" files are found to be older than their dependencies.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T00:34:34.140", "Id": "36386", "Score": "0", "Tags": null, "Title": null }
36386
<p>I was wondering if there's any way I can improve this code's execution. I want to use it on a 9*9 grid, but it takes too long to solve this as 4*4. This program takes as input a 4*4 matrix represented as a 1D matrix and returns the solution to the puzzle in the variable solution. Any comments?</p> <pre><code>subset([],_). subset([H|T],List):- !, member(H,List), subset(T,List). different([]). different([H|T]):- \+member(H,T), different(T),!. valid([]). valid([Head|Tail]) :- different(Head), valid(Tail),!. sudoku(Puzzle, Solution) :- Solution = Puzzle, Puzzle = [S11, S12, S13, S14, S21, S22, S23, S24, S31, S32, S33, S34, S41, S42, S43, S44], subset(Solution, [1,2,3,4]), Row1 = [S11, S12, S13, S14], Row2 = [S21, S22, S23, S24], Row3 = [S31, S32, S33, S34], Row4 = [S41, S42, S43, S44], Col1 = [S11, S21, S31, S41], Col2 = [S12, S22, S32, S42], Col3 = [S13, S23, S33, S43], Col4 = [S14, S24, S34, S44], Square1 = [S11, S12, S21, S22], Square2 = [S13, S14, S23, S24], Square3 = [S31, S32, S41, S42], Square4 = [S33, S34, S43, S44], valid([Row1, Row2, Row3, Row4, Col1, Col2, Col3, Col4, Square1, Square2, Square3, Square4]). </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T00:49:51.037", "Id": "59623", "Score": "1", "body": "Just so you know, sudoku is a 9x9 grid ... ;-) just saying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T00:56:57.753", "Id": "59624", "Score": "0", "body": "I'm trying to do it 9X9, the problem is that the 4X4 solution is too slow" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T01:00:37.637", "Id": "59625", "Score": "0", "body": "Your question says you want to do it on 10x10...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:57:18.163", "Id": "59638", "Score": "0", "body": "I take it [my advice](http://stackoverflow.com/questions/20209315/sudoku-on-prolog-taking-too-long-to-solve/20212312#20212312) was too abstract." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:59:47.660", "Id": "59639", "Score": "0", "body": "How do you invoke this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T03:01:09.713", "Id": "59640", "Score": "1", "body": "sudoku([_,9,_,_,_,5,_,_,4,4,2,1,_,_,_,_,_,9,8,_,5,4,9,2,_,_,6,_,_,_,_,1,4,_,_,2,_,_,8,7,_,9,6,_,_,1,_,_,6,2,_,_,_,_,7,_,_,2,4,6,9,_,8,5,_,_,_,_,_,2,6,1,9,_,_,8,_,_,_,3,_],Solution)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T03:01:30.967", "Id": "59641", "Score": "0", "body": "This is an example of an incomplete sudoku. and it takes forever to be solved" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T03:05:21.700", "Id": "59642", "Score": "0", "body": "You should format that in backticks so I can copy-paste it without having to re-add all your underscores." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T03:36:23.457", "Id": "59644", "Score": "0", "body": "`sudoku([_,9,_,_,_,5,_,_,4,4,2,1,_,_,_,_,_,9,8,_,5,4,9,2,_,_,6,_,_,_,_,1,4,_,_,2,_,_,8,7,_,9,6,_,_,1,_,_,6,2,_,_,_,_,7,_,_,2,4,6,9,_,8,5,_,_,_,_,_,2,6,1,9,_,_,8,_,_,_,3,_],Solution).`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T03:39:37.907", "Id": "59645", "Score": "0", "body": "sorry about that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T05:54:30.923", "Id": "59951", "Score": "0", "body": "Please don't remove the code from the question; it'll invalidate answers and render the question off-topic. If there's an issue, please flag for moderator attention." } ]
[ { "body": "<p><sup>Well, copying my answer from SO.</sup></p>\n\n<p>Think about the number of outputs of subset/4, if every cell of Solution is unbound in the beginning. There are 4<sup>4*4</sup> = 4,294,967,296 outputs. Now you might know why your code is so slow.</p>\n\n<p>You should call valid/1 inside of subset/2. Test if the puzzle is still valid after inserting one number:</p>\n\n<pre><code>subset(_,[],_).\nsubset(RCS,[H|T],List):-\n member(H,List),\n valid(RCS),\n subset(RCS,T,List).\n\n% Like \\+member(H,T) but unbound cells are ignored\nnonmember(_, []).\nnonmember(H1, [H2|T]) :-\n (var(H2); H1 \\= H2),\n nonmember(H1, T).\n\ndifferent([]).\ndifferent([H|T]):-\n (var(H); nonmember(H,T)),\n different(T),!.\n\nvalid([]).\nvalid([Head|Tail]) :- \n different(Head), \n valid(Tail),!.\n\nsudoku(Puzzle) :-\n Puzzle = [S11, S12, S13, S14,\n S21, S22, S23, S24,\n S31, S32, S33, S34,\n S41, S42, S43, S44],\n\n Row1 = [S11, S12, S13, S14],\n Row2 = [S21, S22, S23, S24],\n Row3 = [S31, S32, S33, S34],\n Row4 = [S41, S42, S43, S44],\n\n Col1 = [S11, S21, S31, S41],\n Col2 = [S12, S22, S32, S42],\n Col3 = [S13, S23, S33, S43],\n Col4 = [S14, S24, S34, S44],\n\n Square1 = [S11, S12, S21, S22],\n Square2 = [S13, S14, S23, S24],\n Square3 = [S31, S32, S41, S42],\n Square4 = [S33, S34, S43, S44], \n\n RCS = [Row1, Row2, Row3, Row4, \n Col1, Col2, Col3, Col4, \n Square1, Square2, Square3, Square4],\n\n subset(RCS, Puzzle, [1,2,3,4]).\n</code></pre>\n\n<p>Next optimization would be not to test all rows, columns and squares after every insert, but only the affected ones (3 instead of 12):</p>\n\n<pre><code>subset([], _).\nsubset([(P,RCS) | T], List):-\n member(P, List),\n valid(RCS),\n subset(T, List).\n\n% Like \\+member(H,T) but unbound cells are ignored\nnonmember(_, []).\nnonmember(H1, [H2|T]) :-\n (var(H2); H1 \\= H2),\n nonmember(H1, T).\n\ndifferent([]).\ndifferent([H|T]):-\n (var(H); nonmember(H,T)),\n different(T),!.\n\nvalid([]).\nvalid([Head|Tail]) :- \n different(Head), \n valid(Tail),!.\n\nsudoku(Puzzle) :-\n Puzzle = [S11, S12, S13, S14,\n S21, S22, S23, S24,\n S31, S32, S33, S34,\n S41, S42, S43, S44],\n\n Row1 = [S11, S12, S13, S14],\n Row2 = [S21, S22, S23, S24],\n Row3 = [S31, S32, S33, S34],\n Row4 = [S41, S42, S43, S44],\n\n Col1 = [S11, S21, S31, S41],\n Col2 = [S12, S22, S32, S42],\n Col3 = [S13, S23, S33, S43],\n Col4 = [S14, S24, S34, S44],\n\n Square1 = [S11, S12, S21, S22],\n Square2 = [S13, S14, S23, S24],\n Square3 = [S31, S32, S41, S42],\n Square4 = [S33, S34, S43, S44],\n\n RCS11 = (S11, [Row1, Col1, Square1]),\n RCS12 = (S12, [Row1, Col2, Square1]),\n RCS13 = (S13, [Row1, Col3, Square2]),\n RCS14 = (S14, [Row1, Col4, Square2]),\n RCS21 = (S21, [Row2, Col1, Square1]),\n RCS22 = (S22, [Row2, Col2, Square1]),\n RCS23 = (S23, [Row2, Col3, Square2]),\n RCS24 = (S24, [Row2, Col4, Square2]),\n RCS31 = (S31, [Row3, Col1, Square3]),\n RCS32 = (S32, [Row3, Col2, Square3]),\n RCS33 = (S33, [Row3, Col3, Square4]),\n RCS34 = (S34, [Row3, Col4, Square4]),\n RCS41 = (S41, [Row4, Col1, Square3]),\n RCS42 = (S42, [Row4, Col2, Square3]),\n RCS43 = (S43, [Row4, Col3, Square4]),\n RCS44 = (S44, [Row4, Col4, Square4]),\n\n RCS = [RCS11, RCS12, RCS13, RCS14,\n RCS21, RCS22, RCS23, RCS24,\n RCS31, RCS32, RCS33, RCS34,\n RCS41, RCS42, RCS43, RCS44],\n\n subset(RCS, [1,2,3,4]).\n</code></pre>\n\n<p>Now you should be able to increase the puzzle size to 9×9 and still have a reasonably fast solver.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T06:15:59.477", "Id": "36398", "ParentId": "36387", "Score": "2" } }, { "body": "<p>This is blazing fast version of your code which finds solution in miliseconds:</p>\n\n<pre><code>sudoku(Puzzle, Solution) :-\n Solution = Puzzle,\n Puzzle = [S11, S12, S13, S14,\n S21, S22, S23, S24,\n S31, S32, S33, S34,\n S41, S42, S43, S44],\n\n Row1 = [S11, S12, S13, S14],\n Row2 = [S21, S22, S23, S24],\n Row3 = [S31, S32, S33, S34],\n Row4 = [S41, S42, S43, S44],\n\n Col1 = [S11, S21, S31, S41],\n Col2 = [S12, S22, S32, S42],\n Col3 = [S13, S23, S33, S43],\n Col4 = [S14, S24, S34, S44],\n\n Square1 = [S11, S12, S21, S22],\n Square2 = [S13, S14, S23, S24],\n Square3 = [S31, S32, S41, S42],\n Square4 = [S33, S34, S43, S44],\n\n Sets = [Row1, Row2, Row3, Row4,\n Col1, Col2, Col3, Col4,\n Square1, Square2, Square3, Square4],\n\n maplist(permutation([1,2,3,4]), Sets).\n</code></pre>\n\n<p>Firstly, I removed all your predicates. Not only they do what you can accomplish with <code>maplist/2</code> (your <code>valid(X)</code> is equivalent to <code>maplist(difference, X)</code> and <code>subset(Solution, [1,2,3,4])</code> is equivalent to <code>maplist(between(1,4), Solution)</code>), but their combination is just VERY inefficent equivalent of <code>permutation/2</code>.</p>\n\n<p>I don't know if <code>permutation/2</code> is ISO-Prolog, but can be found in SWI-Prolog, GNU Prolog and others. What's more, <code>permutation/2</code> can be replaced with even more efficent <code>permute/2</code> (which doesn't follow lexicographic order):</p>\n\n<pre><code>permute([], []).\npermute([X|Rest], L) :-\n permute(Rest, L1),\n select(X, L, L1).\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T18:06:31.387", "Id": "49553", "ParentId": "36387", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T00:38:31.707", "Id": "36387", "Score": "4", "Tags": [ "performance", "sudoku", "matrix", "prolog" ], "Title": "Prolog Sudoku solver taking too long" }
36387
<p>I'm working on my framework constructor. First I tried to look into jQuery and understand it, but it's so out of my league. Instead I googled and put this code together. Though there aren't many posts about creating a framework. Anyway, since I'm not a guru I might be doing it the wrong way or missing things. Can I take your opinions, suggestions to make it a little more stable?</p> <p><a href="http://jsfiddle.net/dXTy4/" rel="nofollow"><strong>FIDDLE</strong></a></p> <pre><code>var optionalSelector = "$"; (function () { (this[arguments[0]] = function constructor(input) { if (!(this instanceof constructor)) { return new constructor(input); } var regExp_id = /^#/; var regExp_class = /^\./; var regExp_tag = /[^#]|[^.]/; var typeOfInput; function isElement(obj) { if (obj !== null &amp;&amp; typeof obj === "object") { return obj; } } if (isElement(input)) { return input; } // this else { if (input.search(regExp_id) != -1) { typeOfInput = "id"; } else if (input.search(regExp_class) != -1) { typeOfInput = "class"; } else if (input.search(regExp_tag) != -1) { typeOfInput = "tag"; } switch (typeOfInput) { case "id": if (document.getElementById(input.replace(/#/, ""))) { return document.getElementById(input.replace(/#/, "")); } else { console.log("Invalid id: " + input); return false; } break; case "class": if (document.getElementsByClassName(input.replace(/./, "")).length &gt; 0) { return document.getElementsByClassName(input.replace(/./, "")); } else { console.log("Invalid class: " + input); return false; } break; case "tag": if (document.getElementsByTagName(input).length &gt; 0) { return document.getElementsByTagName(input); } else { console.log("Invalid tag: " + input); return false; } break; } } }) })(optionalSelector); </code></pre>
[]
[ { "body": "<p>First of all, nice effort for the code. But I highly go against it because there's <a href=\"http://jquery.com/\" rel=\"nofollow\">jQuery</a>. And if you don't like jQuery because it's heavy, then I suggest going for <a href=\"http://sizzlejs.com/\" rel=\"nofollow\">Sizzle</a>.</p>\n\n<p>But anyways, back to your code. First I notice this one:</p>\n\n<pre><code>var optionalSelector = \"$\";\n</code></pre>\n\n<p>Never use <code>$</code>. It's being abused already by frameworks. Use another namespace to avoid collisions with mainstream libraries, something unique, like <code>MyVeryAmazingDomLibrary</code> or <code>MVADL</code> for short. Hehehe. </p>\n\n<p>Also, I notice this namespace declaration happens to be outside the library. Do include it inside the library's module:</p>\n\n<pre><code>;(function(window){\n ...\n window.myNamespace = myLibraryStuffHere;\n ...\n}(window));\n</code></pre>\n\n<p>So far, your code looks ok. Everything is pretty much covered. I also see that it works only with single selectors at the moment. However, I notice you are using <code>replace</code> to remove the <code>#</code> and <code>.</code>:</p>\n\n<pre><code>document.getElementById(input.replace(/#/, \"\"));\n</code></pre>\n\n<p>RegExp is heavy for trivial operations such as this. You can remove the <em>first character</em> using <code>substr</code> or <code>substring</code>. That way, you avoid RegExp.</p>\n\n<pre><code>document.getElementById(input.substr(1));\n</code></pre>\n\n<p>Now, in the demo, I see this:</p>\n\n<pre><code>a[0].onclick = function() { alert(\"you clicked the classes\"); }\na[1].onclick = function() { alert(\"you clicked the classes\"); }\n</code></pre>\n\n<p>If you had a hundred elements, would you do this still? I assume you'd do a loop, right? But wouldn't it be neat if the library took care of that? Yes?</p>\n\n<p>So there's a reason they call it a \"jQuery object\". jQuery objects are basically arrays (array-like to be exact, normally called a set or collection) that applies operations to each item in the collection.</p>\n\n<p>So to get you on the right track, think of this code:</p>\n\n<pre><code>a.on('click',someFunction);\n</code></pre>\n\n<p><code>a</code> is the jQuery object, and <code>on</code> is a method of jQuery that attaches a <code>click</code> handler to each item in set <code>a</code>. <code>on</code> would look like:</p>\n\n<pre><code>myAmazingLibraryObject.prototype.on = function(event,handler){\n\n //assuming \"this\" represents the current collection and \"elements\"\n //is an array of elements, a result of getting by tag or by class.\n //Let's say we are standards compliant and ES5 compliant, \n //we use forEach to loop through the set, and addEventListener to \n //add the handlers.\n\n this.elements.forEach(function(element){\n element.addEventListener(event,handler,false);\n });\n}\n</code></pre>\n\n<p>Now, you can do this:</p>\n\n<pre><code>var elements = myAmazingLibrary('a'); //get all &lt;a&gt;\n\nelements.on('click',function(event){\n event.preventDefault();\n console.log('clicked');\n});\n</code></pre>\n\n<p>An advantage of using a jQuery-like object, where the results are contained in an array, is that even when your collection is empty, the code does not break. If we used <code>on</code> on an empty collection, nothing will go wrong. Empty set, no loop, no element access, no error.</p>\n\n<p>Lastly, don't just <code>console.log</code> or return false on errors. Throw meaningful errors instead. Use <code>Error</code> objects so that <code>try-catch</code> can collect them and inspect them. The last thing you would want from your code is to have it running broken and not know about it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T21:02:27.997", "Id": "59916", "Score": "1", "body": "Thanks for the suggestions. I'm not coding for living, but for fun. That's why I try to avoid using libraries. With libraries work gets done but you don't know what's going on. I wanted to create my own framework to practise and get a better understanding. Last state of [the code](http://jsfiddle.net/dXTy4/2/). Also will add the `try-catch` method. Oh, and about handling arrays. Of course I'd use a loop. I have methods for these :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:30:13.313", "Id": "36390", "ParentId": "36388", "Score": "4" } } ]
{ "AcceptedAnswerId": "36390", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T00:58:01.670", "Id": "36388", "Score": "3", "Tags": [ "javascript", "constructor", "framework" ], "Title": "Framework constructor" }
36388
<p>I need to prepend N spaces to a string to make it 10 characters in length. I came up with the following method, but since it is going to be called often, I want to ensure it is optimized. Could this be made more efficient?</p> <pre><code>public static string PrependSpaces(string str) { StringBuilder sb = new StringBuilder(); sb.Append(str); for (int i = 0; i &lt; (10 - str.Length); i++) { sb.Insert(0, " "); } return sb.ToString(); } </code></pre>
[]
[ { "body": "<p>If you need to prepend a number of characters to a string you might consider <a href=\"http://msdn.microsoft.com/en-us/library/system.string.padleft(v=vs.110).aspx\" rel=\"nofollow noreferrer\">String.PadLeft()</a>.</p>\n\n<p>For example:</p>\n\n<pre><code>string str = \"abc123\";\nConsole.WriteLine(str);\nstr = str.PadLeft(10);\nConsole.WriteLine(str);\n</code></pre>\n\n<p>Will produce:</p>\n\n<pre><code>abc123\n abc123\n</code></pre>\n\n<p>On the efficiency of your example, <code>StringBuilder.Append()</code> is more efficient than <code>StringBuilder.Insert()</code>, so you might try something like:</p>\n\n<pre><code>public static string PrependSpaces2(string str)\n{\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; (10 - str.Length); i++)\n {\n sb.Append(\" \");\n }\n sb.Append(str);\n return sb.ToString();\n}\n</code></pre>\n\n<p><strong>EDIT</strong> As svick suggested, <a href=\"http://msdn.microsoft.com/en-us/library/yxyxbz2e(v=vs.110).aspx\" rel=\"nofollow noreferrer\">Append(char, repeat)</a> is simpler and faster on the order of the native Pad methods:</p>\n\n<pre><code>public static string PrependSpaces3(string str)\n StringBuilder sb = new StringBuilder();\n if((NUM - str.Length) &gt; 0)\n {\n sb.Append(' ', (NUM - str.Length));\n }\n sb.Append(str);\n return sb.ToString();\n}\n</code></pre>\n\n<p>Which when tested with this:</p>\n\n<pre><code>string str = \"abc123\";\nConsole.WriteLine(\"str: \" + str);\n\nint iterations = 100000;\n\nstring result = string.Empty;\nStopwatch s1 = Stopwatch.StartNew();\nfor (int i = 0; i &lt; iterations; i++)\n{\n result = PrependSpaces(str);\n}\ns1.Stop();\nConsole.WriteLine(iterations + \" calls to PrependSpaces took: {0:0.00 ms}\", s1.Elapsed.TotalMilliseconds);\n\nstring result2 = string.Empty;\nStopwatch s2 = Stopwatch.StartNew();\nfor (int i = 0; i &lt; iterations; i++)\n{\n result2 = PrependSpaces2(str);\n}\ns2.Stop();\nConsole.WriteLine(iterations + \" calls to PrependSpaces2 took: {0:0.00 ms}\", s2.Elapsed.TotalMilliseconds);\n\nstring result3 = string.Empty;\nStopwatch s3 = Stopwatch.StartNew();\nfor (int i = 0; i &lt; iterations; i++)\n{\n result3 = str.PadLeft(NUM, ' ');\n}\ns3.Stop();\nConsole.WriteLine(iterations + \" calls to String.PadLeft(\" + NUM + \", ' ') took: {0:0.00 ms}\", s3.Elapsed.TotalMilliseconds);\n\nstring result4 = string.Empty;\nStopwatch s4 = Stopwatch.StartNew();\nfor (int i = 0; i &lt; iterations; i++)\n{\n result4 = PrependSpaces3(str);\n}\ns4.Stop();\nConsole.WriteLine(iterations + \" calls to PrependSpaces3 took: {0:0.00 ms}\", s3.Elapsed.TotalMilliseconds);\n</code></pre>\n\n<p>returns this (benchmarks for prepending 1000 characters):</p>\n\n<pre><code>str: abc123\n100000 calls to PrependSpaces took: 20190.16 ms\n100000 calls to PrependSpaces2 took: 1025.87 ms\n100000 calls to String.PadLeft(1000, ' ') took: 84.32 ms\n100000 calls to PrependSpaces3 took: 84.32 ms\n</code></pre>\n\n<p>for prepending 10 characters:</p>\n\n<pre><code>100000 calls to PrependSpaces took: 31.02 ms\n100000 calls to PrependSpaces2 took: 11.41 ms\n100000 calls to String.PadLeft(10, ' ') took: 4.53 ms\n100000 calls to PrependSpaces3 took: 4.53 ms\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T03:44:57.397", "Id": "59646", "Score": "2", "body": "Instead of the `Append()` loop, you can use `sb.Append(' ', 10 - str.Length)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T03:19:50.393", "Id": "36393", "ParentId": "36391", "Score": "14" } } ]
{ "AcceptedAnswerId": "36393", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T02:38:08.293", "Id": "36391", "Score": "13", "Tags": [ "c#", "strings" ], "Title": "Adding N characters to a string" }
36391
<p>The following is a program that lets a Human play "Rock Paper Scissors Lizard Spock" against the computer... (almost playable at: <a href="http://ideone.com/EBDlga" rel="nofollow noreferrer">http://ideone.com/EBDlga</a>)</p> <p><strong>Note</strong> I have <a href="https://codereview.stackexchange.com/questions/36438/rock-paper-scissors-lizard-spock-revisited/36512">posted a follow-up question</a> incorporating the suggestions that have been made in answers and comments on this question.</p> <p>Comments, critiques, suggestions are welcome and encouraged.</p> <pre><code>import java.util.Arrays; import java.util.Random; import java.util.Scanner; /** * Rock Paper Scissors Lizard Spock * &lt;p&gt; * http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock * &lt;p&gt; * Interface for a human to play against the computer. */ public class RPSLS { /** * Set up the rules for the game. * What are the moves, and what beats what! */ public enum Move { Rock, Paper, Scissors, Lizard, Spock; static { Rock.willBeat(Scissors, Lizard); Paper.willBeat(Rock,Spock); Scissors.willBeat(Paper, Lizard); Lizard.willBeat(Spock,Paper); Spock.willBeat(Rock,Scissors); } // what will this move beat - populated in static initializer private Move[] ibeat; private void willBeat(Move...moves) { ibeat = moves; } /** * Return true if this Move will beat the supplied move * @param move the move we hope to beat * @return true if we beat that move. */ public boolean beats(Move move) { // use binary search in case someone wants to set up crazy rules. return Arrays.binarySearch(ibeat, move) &gt;= 0; } } // This is a prompt that is set up just once per JVM private static final String MOVEPROMPT = buildOptions(); private static String buildOptions() { StringBuilder sb = new StringBuilder(); sb.append(" -&gt; "); // go through the possible moves, and make a prompt string. for (Move m : Move.values()) { sb.append(m.ordinal() + 1).append(") ").append(m.name()).append(" "); } // include a quit option. sb.append(" q) Quit"); return sb.toString(); } /** * get some input from the human. * @param scanner What we read the input from. * @param prompt What we prompt the user for. * @param defval If the user just presses enter, what do we return. * @return the value the user entered (just the first char of it). */ private static final char prompt(Scanner scanner, String prompt, char defval) { // prompt the user. System.out.print(prompt + ": "); // it would be nice to use a Console or something, but running from Eclipse there isn't one. String input = scanner.nextLine(); if (input.isEmpty()) { return defval; } return input.charAt(0); } /** * Simple conditional that prompts the user to play again, and returns true if we should. * @param scanner the scanner to get the input from * @return true if the user wants to continue. */ private static boolean playAgain(Scanner scanner) { return ('n' != prompt(scanner, "\nPlay Again (y/n)?", 'y')); } /** * Prompt the user for a move. * @param scanner The scanner to get the move from * @return the move the user wants to do. */ private static Move getHumanMove(Scanner scanner) { // loop until we get some valid input. do { char val = prompt(scanner, MOVEPROMPT, 'q'); if ('q' == val) { // user does not want to make a move... or just presses enter too fast. return null; } int num = (val - '0') - 1; if (num &gt;= 0 &amp;&amp; num &lt; Move.values().length) { // we got valid input. Return. return Move.values()[num]; } System.out.println("Invalid move " + val); } while (true); } /** * Run the game.... Good Luck! * @param args these are ignored. */ public static void main(String[] args) { final Random rand = new Random(); final Move[] moves = Move.values(); final Scanner scanner = new Scanner(System.in); int htotal = 0; int ctotal = 0; do { System.out.println("\nBest of 3.... Go!"); int hscore = 0; int cscore = 0; bestofthree: do { final Move computer = moves[rand.nextInt(moves.length)]; final Move human = getHumanMove(scanner); if (human == null) { System.out.println("Human quits Best-of-3..."); // quit the best-of-three loop break bestofthree; } if (human == computer) { System.out.printf(" DRAW... play again!! (%s same as %s)\n", human, computer); } else if (human.beats(computer)) { hscore++; System.out.printf(" HUMAN beats Computer (%s beats %s)\n", human, computer); } else { cscore++; System.out.printf(" COMPUTER beats Human (%s beats %s)\n", computer, human); } // play until someone scores 2.... } while (hscore != 2 &amp;&amp; cscore != 2); // track the total scores. if (hscore == 2) { htotal++; } else { // perhaps the human quit while ahead, computer wins that too. ctotal++; } String winner = hscore == 2 ? "Human" : "Computer"; System.out.printf("\n %s\n **** %s wins Best-Of-Three (Human=%d, Computer=%d - game total is Human=%d Computer=%d)\n", winner.toUpperCase(), winner, hscore, cscore, htotal, ctotal); // Shall we play again? } while (playAgain(scanner)); System.out.printf("Thank you for playing. The final game score was Human=%d and Computer=%d\n", htotal, ctotal); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T04:39:22.393", "Id": "59648", "Score": "1", "body": "Ha! Mine says \"Spock vaporizes Rock. You lose!\" +1 anyway :)" } ]
[ { "body": "<p>I suggest that you get rid of most of the static methods, and then refactor this code using MVC design to allow the code to be the model of any type of view you desire, be it Swing, console, SWT, Android, or what have you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T16:51:25.793", "Id": "36416", "ParentId": "36394", "Score": "2" } }, { "body": "<ul>\n<li><p>You seem to like <code>static</code> things, but this gives me a feeling that your code is more procedural-oriented than object-oriented.</p></li>\n<li><p>Although not an issue in your actual implementation, I think <code>willBeat</code> should call <code>Arrays.copyOf</code> to create a copy of the input. If you would call <code>someMove.willBeat(someArray)</code> and then later change the indexes in <code>someArray</code>, you would change the rules of the game.</p></li>\n<li><p>The documentation of <code>Arrays.binarySearch</code> states:</p>\n\n<blockquote>\n <p>The array must be sorted (as by the sort(byte[]) method) prior to making this call. If it is not sorted, the results are undefined</p>\n</blockquote>\n\n<p>Your code does not guarantee that the items are sorted. (It might work correctly anyway since your arrays only contains two items, but it still feels wrong) The values for <code>Lizard</code> are not sorted in the same way the others are.</p></li>\n<li><p>You are using <code>htotal</code> and <code>ctotal</code>, <code>hscore</code> and <code>cscore</code>, <code>Move computer</code> and <code>Move human</code>. Assuming <code>htotal</code> stands for \"Human Total\", player classes would be useful here.</p></li>\n<li><p><code>2</code> and <code>3</code> are very <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29\">Magic numbers</a>.</p></li>\n<li><p>The variable names <code>htotal</code> and <code>hscore</code> is a bit confusing.</p></li>\n<li><p>Your <code>main</code> method is quite long and does a lot of things. Some of these things could be extracted into other methods/objects. Your <code>main</code> method currently is responsible for:</p>\n\n<ul>\n<li>Keeping score</li>\n<li>Keeping score (of a single \"best of three\")</li>\n<li>Randomize a computer move</li>\n<li>Determine who wins a game</li>\n</ul></li>\n<li><p>I like your <code>playAgain</code> method and the way you are handling user input-output.</p></li>\n<li><p>Overall, your code is not very abstracted. It seems to work, and it seems to do it's job well though.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T18:46:38.360", "Id": "59684", "Score": "0", "body": "Thanks... I think you are right on all points... (including procedural thinking) except the Arrays.copyOf()... that is all squarely contained within the enum. There's no way for (in a real situation where the Enum would be a separate file and not embedded) anything outside the Enum to mess with the arrays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T19:18:10.783", "Id": "59692", "Score": "0", "body": "@rolfl Yes, that's true. I was thinking ahead. As long as you don't pass an array and change the indexes in the array later, there is of course no harm done." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T18:25:27.570", "Id": "36423", "ParentId": "36394", "Score": "9" } } ]
{ "AcceptedAnswerId": "36423", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T04:20:06.170", "Id": "36394", "Score": "11", "Tags": [ "java", "game", "community-challenge", "rock-paper-scissors" ], "Title": "Rock Paper Scissors Lizard Spock as a code-style and challenge" }
36394
<blockquote> <p>"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." </p> <p>-- Dr. Sheldon Cooper</p> </blockquote> <p>So these are the rules.</p> <h3>Building blocks</h3> <p>The first thing I thought was "I need a way to compare the possible selections" - this sounded like <code>IComparable&lt;T&gt;</code>, so I started by implementing that interface in a <code>SelectionBase</code> class. Now because I knew I'd derive <code>Rock</code>, <code>Paper</code>, <code>Scissors</code>, <code>Lizard</code> and <code>Spock</code> classes from this, I decided to include a <code>Name</code> property that returns the type name, and since I also needed a way to display different verbs depending on the type of the opponent's selection, I also included a <code>GetWinningVerb</code> method:</p> <pre><code>public abstract class SelectionBase : IComparable&lt;SelectionBase&gt; { public abstract int CompareTo(SelectionBase other); public string Name { get { return GetType().Name; } } public abstract string GetWinningVerb(SelectionBase other); } </code></pre> <p>The base class is implemented by each of the possible selections:</p> <pre><code>public class Rock : SelectionBase { public override string GetWinningVerb(SelectionBase other) { if (other is Scissors) return "crushes"; if (other is Lizard) return "crushes"; throw new InvalidOperationException("Are we playing the same game?"); } public override int CompareTo(SelectionBase other) { if (other is Rock) return 0; if (other is Paper) return -1; if (other is Scissors) return 1; if (other is Lizard) return 1; if (other is Spock) return -1; throw new InvalidOperationException("Are we playing the same game?"); } } public class Paper : SelectionBase { public override string GetWinningVerb(SelectionBase other) { if (other is Rock) return "covers"; if (other is Spock) return "disproves"; throw new InvalidOperationException("Are we playing the same game?"); } public override int CompareTo(SelectionBase other) { if (other is Rock) return 1; if (other is Paper) return 0; if (other is Scissors) return -1; if (other is Lizard) return -1; if (other is Spock) return 1; throw new InvalidOperationException("Are we playing the same game?"); } } public class Scissors : SelectionBase { public override string GetWinningVerb(SelectionBase other) { if (other is Paper) return "cuts"; if (other is Lizard) return "decapitates"; throw new InvalidOperationException("Are we playing the same game?"); } public override int CompareTo(SelectionBase other) { if (other is Rock) return -1; if (other is Paper) return 1; if (other is Scissors) return 0; if (other is Lizard) return 1; if (other is Spock) return -1; throw new InvalidOperationException("Are we playing the same game?"); } } public class Lizard : SelectionBase { public override string GetWinningVerb(SelectionBase other) { if (other is Paper) return "eats"; if (other is Spock) return "poisons"; throw new InvalidOperationException("Are we playing the same game?"); } public override int CompareTo(SelectionBase other) { if (other is Rock) return -1; if (other is Paper) return 1; if (other is Scissors) return -1; if (other is Lizard) return 0; if (other is Spock) return 1; throw new InvalidOperationException("Are we playing the same game?"); } } public class Spock : SelectionBase { public override string GetWinningVerb(SelectionBase other) { if (other is Rock) return "vaporizes"; if (other is Scissors) return "smashes"; throw new InvalidOperationException("Are we playing the same game?"); } public override int CompareTo(SelectionBase other) { if (other is Rock) return 1; if (other is Paper) return -1; if (other is Scissors) return 1; if (other is Lizard) return -1; if (other is Spock) return 0; throw new InvalidOperationException("Are we playing the same game?"); } } </code></pre> <h3>User Input</h3> <p>Then I needed a way to get user input. I knew I was going to make a simple console app, but just so I could run unit tests I decided to create an <code>IUserInputProvider</code> interface - the first pass had all 3 methods in the interface, but since I wasn't using them all, I only kept one; I don't think getting rid of <code>GetUserInput(string)</code> would hurt:</p> <pre><code>public interface IUserInputProvider { string GetValidUserInput(string prompt, IEnumerable&lt;string&gt; validValues); } public class ConsoleUserInputProvider : IUserInputProvider { private string GetUserInput(string prompt) { Console.WriteLine(prompt); return Console.ReadLine(); } private string GetUserInput(string prompt, IEnumerable&lt;string&gt; validValues) { var input = GetUserInput(prompt); var isValid = validValues.Select(v =&gt; v.ToLower()).Contains(input.ToLower()); return isValid ? input : string.Empty; } public string GetValidUserInput(string prompt, IEnumerable&lt;string&gt; validValues) { var input = string.Empty; var isValid = false; while (!isValid) { input = GetUserInput(prompt, validValues); isValid = !string.IsNullOrEmpty(input) || validValues.Contains(string.Empty); } return input; } } </code></pre> <h3>The actual program</h3> <pre><code>class Program { /* "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 */ static void Main(string[] args) { var consoleReader = new ConsoleUserInputProvider(); var consoleWriter = new ConsoleResultWriter(); var game = new Game(consoleReader, consoleWriter); game.Run(); } } </code></pre> <h3>IResultWriter</h3> <pre><code>public interface IResultWriter { void OutputResult(int comparisonResult, SelectionBase player, SelectionBase sheldon); } public class ConsoleResultWriter : IResultWriter { public void OutputResult(int comparisonResult, SelectionBase player, SelectionBase sheldon) { var resultActions = new Dictionary&lt;int, Action&lt;SelectionBase, SelectionBase&gt;&gt; { { 1, OutputPlayerWinsResult }, { -1, OutputPlayerLosesResult }, { 0, OutputTieResult } }; resultActions[comparisonResult].Invoke(player, sheldon); } private void OutputPlayerLosesResult(SelectionBase player, SelectionBase sheldon) { Console.WriteLine("\n\tSheldon says: \"{0} {1} {2}. You lose!\"\n", sheldon.Name, sheldon.GetWinningVerb(player), player.Name); } private void OutputPlayerWinsResult(SelectionBase player, SelectionBase sheldon) { Console.WriteLine("\n\tSheldon says: \"{0} {1} {2}. You win!\"\n", player.Name, player.GetWinningVerb(sheldon), sheldon.Name); } private void OutputTieResult(SelectionBase player, SelectionBase sheldon) { Console.WriteLine("\n\tSheldon says: \"Meh. Tie!\"\n"); } </code></pre> <h3>The actual <em>game</em></h3> <p>I didn't bother with building a complex AI - we're playing against Sheldon Cooper here, and he systematically plays Spock.</p> <pre><code>public class Game { private readonly Dictionary&lt;string, SelectionBase&gt; _playable = new Dictionary&lt;string, SelectionBase&gt; { { "1", new Rock() }, { "2", new Paper() }, { "3", new Scissors() }, { "4", new Lizard() }, { "5", new Spock() } }; private readonly IUserInputProvider _consoleInput; private readonly IResultWriter _resultWriter; public Game(IUserInputProvider console, IResultWriter resultWriter) { _consoleInput = console; _resultWriter = resultWriter; } public void Run() { while (true) { LayoutGameScreen(); var player = GetUserSelection(); if (player == null) return; var sheldon = new Spock(); var result = player.CompareTo(sheldon); _resultWriter.OutputResult(result, player, sheldon); Pause(); } } private void Pause() { Console.WriteLine("\nPress &lt;ENTER&gt; to continue."); Console.ReadLine(); } private void LayoutGameScreen() { Console.Clear(); Console.WriteLine("Rock-Paper-Scissors-Lizard-Spock 1.0\n{0}\n", new string('=', 40)); foreach (var item in _playable) Console.WriteLine("\t[{0}] {1}", item.Key, item.Value.Name); Console.WriteLine(); } private SelectionBase GetUserSelection() { var values = _playable.Keys.ToList(); values.Add(string.Empty); // allows a non-selection var input = _consoleInput.GetValidUserInput("Your selection? &lt;ENTER&gt; to quit.", values); if (input == string.Empty) return null; return _playable[input]; } } </code></pre> <hr> <h3>Output</h3> <ul> <li><code>Rock</code>: "Spock vaporizes Rock. You lose!"</li> <li><code>Paper</code>: "Paper disproves Spock. You win!"</li> <li><code>Scissors</code>: "Spock smashes Scissors. You lose!"</li> <li><code>Lizard</code>: "Lizard poisons Spock. You win!"</li> <li><code>Spock</code>: "Meh. Tie!"</li> </ul>
[]
[ { "body": "<p>We could perhaps do away with the bulk of the children class code by implementing a bit of logic in the base class.</p>\n\n<p>A starting point for discussion would be something along the lines of:</p>\n\n<pre><code>public abstract class SelectionBase : IComparable&lt;SelectionBase&gt;\n{\n private readonly List&lt;WinningPlay&gt; _winsAgainst;\n\n protected SelectionBase(List&lt;WinningPlay&gt; winsAgainst)\n {\n _winsAgainst = winsAgainst;\n }\n\n public virtual int CompareTo(SelectionBase other)\n {\n if (GetType() == other.GetType()) return 0; // draws against itself\n\n if (_winsAgainst.Any(p =&gt; p.Winner == other.GetType())) return 1; // wins\n\n return -1; // otherwise loses.\n }\n\n public virtual string Name { get { return GetType().Name; } }\n\n public virtual string GetWinningVerb(SelectionBase other)\n {\n var winner = _winsAgainst.SingleOrDefault(p =&gt; p.Winner == other.GetType());\n\n if (winner == null)\n throw new InvalidOperationException(\"Are we playing the same game?\");\n else\n return winner.Verb;\n }\n\n protected class WinningPlay\n {\n public Type Winner { get; private set; }\n public string Verb { get; private set; }\n\n public WinningPlay(Type type, string verb)\n {\n Winner = type;\n Verb = verb;\n }\n}\n</code></pre>\n\n<p>And the children classes become:</p>\n\n<pre><code>public class Rock : SelectionBase\n{\n\n public Rock() \n : base(new List&lt;WinningPlay&gt;\n {\n new WinningPlay(typeof(Scissors), \"crushes\"),\n new WinningPlay(typeof(Lizard), \"crushes\")\n })\n {\n }\n}\n\npublic class Paper : SelectionBase\n{\n public Paper()\n : base(new List&lt;WinningPlay&gt;\n {\n new WinningPlay(typeof (Rock), \"covers\"),\n new WinningPlay(typeof (Spock), \"disproves\")\n })\n {\n }\n}\n\npublic class Scissors : SelectionBase\n{\n public Scissors()\n : base(new List&lt;WinningPlay&gt;\n {\n new WinningPlay(typeof (Rock), \"cuts\"),\n new WinningPlay(typeof (Spock), \"decapitates\")\n })\n {\n }\n}\n\npublic class Lizard : SelectionBase\n{\n public Lizard()\n : base(new List&lt;WinningPlay&gt;\n {\n new WinningPlay(typeof (Paper), \"eats\"),\n new WinningPlay(typeof (Spock), \"poisons\")\n })\n {\n }\n}\n\npublic class Spock : SelectionBase\n{\n public Spock()\n : base(new List&lt;WinningPlay&gt;\n {\n new WinningPlay(typeof (Rock), \"Vaporizes\"),\n new WinningPlay(typeof (Scissors), \"smashes\")\n })\n {\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T07:55:53.750", "Id": "59652", "Score": "0", "body": "Amazing. I was exactly 2 seconds away from submitting an edit that would have totally mootinated this superb answer! I mean, this is **_almost_ exactly** the code I was just about to commit - it's the next logical refactoring step. I actually also got rid of `GetWinningVerb` and all these useless exceptions. You're reading my mind!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T08:17:07.777", "Id": "59653", "Score": "0", "body": "@retailcoder cheers. it's a start. I guess good think about refactoring is doing it once, taking a step back and then doing it again. I sort of wonder. Do you even need children classes. Would a simple Enum do?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T07:51:37.130", "Id": "36401", "ParentId": "36395", "Score": "7" } }, { "body": "<p>Let's look at your code from an extensibility point of view:</p>\n\n<p>If Sheldon decides to add a new item to the game then you have to go to <code>n</code> classes to adjust the comparisons and winning verbs. I usually try to avoid such designs because whenever you require a developer to change stuff in <code>n</code> places when something new is added then he/she is bound to forget one place.</p>\n\n<p>So how can we change the design? Well, a game seems to be suited for a rules approach especially since the rules are fairly simple and always of the same structure in this case:</p>\n\n<pre><code>enum Item\n{\n Rock, Paper, Scissors, Lizard, Spock\n}\n\nclass Rule\n{\n public readonly Item Winner;\n public readonly Item Loser;\n public readonly string WinningPhrase;\n\n public Rule(item winner, string winningPhrase, item loser)\n {\n Winner = winner;\n Loser = loser;\n WinningPhrase = winningPhrase;\n }\n\n public override string ToString()\n {\n return string.Format(\"{0} {1} {2}\", Winner, WinningPhrase, Loser);\n }\n}\n</code></pre>\n\n<p>Assuming you have a list of rules somewhere:</p>\n\n<pre><code> static List&lt;Rule&gt; Rules = new List&lt;Rule&gt; {\n new Rule(Item.Rock, \"crushes\", Item.Scissors),\n new Rule(Item.Spock, \"vaporizes\", Item.Rock),\n new Rule(Item.Paper, \"disproves\", Item.Spock),\n new Rule(Item.Lizard, \"eats\", Item.Paper),\n new Rule(Item.Scissors, \"decapitate\", Item.Lizard),\n new Rule(Item.Spock, \"smashes\", Item.Scissors),\n new Rule(Item.Lizard, \"poisons\", Item.Spock),\n new Rule(Item.Rock, \"crushes\", Item.Lizard),\n new Rule(Item.Paper, \"covers\", Item.Rock),\n new Rule(Item.Scissors, \"cut\", Item.Paper)\n }\n</code></pre>\n\n<p>You now can make a decision:</p>\n\n<pre><code>class Decision\n{\n private bool? _HasPlayerWon;\n private Rule _WinningRule;\n\n private Decision(bool? hasPlayerWon, Rule winningRule)\n {\n _HasPlayerWon = hasPlayerWon;\n _WinningRule = winningRule;\n }\n\n public static Decision Decide(item player, item sheldon)\n {\n var rule = FindWinningRule(player, sheldon);\n if (rule != null)\n {\n return new Decision(true, rule);\n }\n\n rule = FindWinningRule(sheldon, player);\n if (rule != null)\n {\n return new Decision(false, rule);\n }\n\n return new Decision(null, null);\n }\n\n private static Rule FindWinningRule(item player, item opponent)\n {\n return Rules.FirstOrDefault(r =&gt; r.Winner == player &amp;&amp; r.Loser == opponent);\n }\n\n public override string ToString()\n {\n if (_HasPlayerWon == null)\n {\n return \"Meh. Tie!\";\n }\n else if (_HasPlayerWon == true)\n {\n return string.Format(\"{0}. You win!\", _WinningRule);\n }\n else\n {\n return string.Format(\"{0}. You lose!\", _WinningRule);\n }\n }\n}\n</code></pre>\n\n<p>If you want to add another item to the game then you add another entry into the <code>enum</code> and some additional rules and you are done.</p>\n\n<p>One thing to improve with my version is that rules just effectively define winning rules and all other cases are implicitly ties which in the context of this game makes sense but could be made more explicit. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T08:50:12.840", "Id": "59656", "Score": "1", "body": "@dreza: Yeah, first I had the constructor as `(winner, loser, phrase)` but then I was writing the rules and thought, well that would read better if swapped :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T11:04:26.553", "Id": "59659", "Score": "0", "body": "This is pretty clearly a better factoring of the problem than OP and dreza's answers. It makes the decision complex the operative entity, separate from the choice data." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T08:37:46.730", "Id": "36402", "ParentId": "36395", "Score": "44" } }, { "body": "<blockquote>\n <p>this sounded like <code>IComparable&lt;T&gt;</code></p>\n</blockquote>\n\n<p>But it's not. <a href=\"http://msdn.microsoft.com/en-us/library/43hc6wht\">The documentation of <code>Compare()</code></a> states that the relation has to be <a href=\"https://en.wikipedia.org/wiki/Transitive_relation\">transitive</a>:</p>\n\n<blockquote>\n <p>If <code>A.CompareTo(B)</code> returns a value <em>x</em> that is not equal to zero, and <code>B.CompareTo(C)</code> returns a value <em>y</em> of the same sign as <em>x</em>, then <code>A.CompareTo(C)</code> is required to return a value of the same sign as <em>x</em> and <em>y</em>.</p>\n</blockquote>\n\n<p>This isn't true in your case, which means that your types shouldn't implement <code>IComparable&lt;T&gt;</code> and that ideally, the comparing method shouldn't be called <code>CompareTo()</code> to avoid confusion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T11:50:37.203", "Id": "36407", "ParentId": "36395", "Score": "15" } }, { "body": "<p>I'm somewhat old-school in that I don't think OO is the right answer to every problem. Here's my effort:</p>\n\n<pre><code>void Main()\n{\n foreach (var left in Enumerable.Range(0, (int)A.Count).Cast&lt;A&gt;()) {\n foreach (var right in Enumerable.Range(0, (int)A.Count).Cast&lt;A&gt;()) {\n Result result;\n string report;\n Play(left, right, out result, out report);\n Console.WriteLine(left + \" vs \" + right + \": \" + report + \" -- \" + result);\n }\n }\n}\n\nenum A { Rock, Paper, Scissors, Lizard, Spock, Count };\n\nstatic string[,] Defeats;\n\nstatic void InitDefeats()\n{\n Defeats = new string[(int)A.Count, (int)A.Count];\n Action&lt;A, string, A&gt; rule = (x, verb, y) =&gt; { Defeats[(int)x, (int)y] = verb; };\n rule(A.Rock, \"crushes\", A.Lizard);\n rule(A.Rock, \"blunts\", A.Scissors);\n rule(A.Paper, \"wraps\", A.Rock);\n rule(A.Paper, \"disproves\", A.Spock);\n rule(A.Scissors, \"cut\", A.Paper);\n rule(A.Scissors, \"decapitates\", A.Lizard);\n rule(A.Lizard, \"poisons\", A.Spock);\n rule(A.Lizard, \"eats\", A.Paper);\n rule(A.Spock, \"smashes\", A.Scissors);\n rule(A.Spock, \"vaporizes\", A.Rock);\n}\n\nenum Result { LeftWins, Tie, RightWins };\n\nstatic void Play(A left, A right, out Result result, out string report)\n{\n if (Defeats == null) InitDefeats();\n var lr = Defeats[(int)left, (int)right];\n var rl = Defeats[(int)right, (int)left];\n if (lr != null) {\n result = Result.LeftWins;\n report = (left + \" \" + lr + \" \" + right).ToLower();\n return;\n }\n if (rl != null) {\n result = Result.RightWins;\n report = (right + \" \" + rl + \" \" + left).ToLower();\n return;\n }\n result = Result.Tie;\n report = (left + \" vs \" + right + \" is a tie\").ToLower();\n}\n</code></pre>\n\n<p>Which prints out:</p>\n\n<pre><code>Rock vs Rock: rock vs rock is a tie -- Tie\nRock vs Paper: paper wraps rock -- RightWins\nRock vs Scissors: rock blunts scissors -- LeftWins\nRock vs Lizard: rock crushes lizard -- LeftWins\nRock vs Spock: spock vaporizes rock -- RightWins\nPaper vs Rock: paper wraps rock -- LeftWins\nPaper vs Paper: paper vs paper is a tie -- Tie\nPaper vs Scissors: scissors cut paper -- RightWins\nPaper vs Lizard: lizard eats paper -- RightWins\nPaper vs Spock: paper disproves spock -- LeftWins\nScissors vs Rock: rock blunts scissors -- RightWins\nScissors vs Paper: scissors cut paper -- LeftWins\nScissors vs Scissors: scissors vs scissors is a tie -- Tie\nScissors vs Lizard: scissors decapitates lizard -- LeftWins\nScissors vs Spock: spock smashes scissors -- RightWins\nLizard vs Rock: rock crushes lizard -- RightWins\nLizard vs Paper: lizard eats paper -- LeftWins\nLizard vs Scissors: scissors decapitates lizard -- RightWins\nLizard vs Lizard: lizard vs lizard is a tie -- Tie\nLizard vs Spock: lizard poisons spock -- LeftWins\nSpock vs Rock: spock vaporizes rock -- LeftWins\nSpock vs Paper: paper disproves spock -- RightWins\nSpock vs Scissors: spock smashes scissors -- LeftWins\nSpock vs Lizard: lizard poisons spock -- RightWins\nSpock vs Spock: spock vs spock is a tie -- Tie\n</code></pre>\n\n<p>EDIT 14-Jul-2014: in response to Malachi's comment, I've rewritten the <code>Play</code> method to return an object rather than two <code>out</code> parameters. The code is the same length and it's arguable whether it's any clearer. Here's the updated version:</p>\n\n<pre><code>void Main()\n{\n foreach (var left in Enumerable.Range(0, (int)A.Count).Cast&lt;A&gt;()) {\n foreach (var right in Enumerable.Range(0, (int)A.Count).Cast&lt;A&gt;()) {\n var outcome = Play(left, right);\n Console.WriteLine(left + \" vs \" + right + \": \" + outcome.Report + \" -- \" + outcome.Result);\n }\n }\n}\n\nenum A { Rock, Paper, Scissors, Lizard, Spock, Count };\n\nstatic string[,] Defeats;\n\nstatic void InitDefeats() \n{\n Defeats = new string[(int)A.Count, (int)A.Count];\n Action&lt;A, string, A&gt; rule = (x, verb, y) =&gt; { Defeats[(int)x, (int)y] = verb; };\n rule(A.Rock, \"crushes\", A.Lizard);\n rule(A.Rock, \"blunts\", A.Scissors);\n rule(A.Paper, \"wraps\", A.Rock);\n rule(A.Paper, \"disproves\", A.Spock);\n rule(A.Scissors, \"cut\", A.Paper);\n rule(A.Scissors, \"decapitates\", A.Lizard);\n rule(A.Lizard, \"poisons\", A.Spock);\n rule(A.Lizard, \"eats\", A.Paper);\n rule(A.Spock, \"smashes\", A.Scissors);\n rule(A.Spock, \"vaporizes\", A.Rock);\n}\n\nclass Outcome {\n internal string Report;\n internal Result Result;\n internal Outcome(A left, A right, string lr, string rl)\n {\n Report = ( lr != null ? left + \" \" + lr + \" \" + right\n : rl != null ? right + \" \" + rl + \" \" + left\n : left + \" vs \" + right + \" is a tie\"\n ).ToLower();\n Result = ( lr != null ? Result.LeftWins\n : rl != null ? Result.RightWins\n : Result.Tie\n );\n }\n}\n\nenum Result { LeftWins, Tie, RightWins };\n\nstatic Outcome Play(A left, A right)\n{\n if (Defeats == null) InitDefeats();\n var lr = Defeats[(int)left, (int)right];\n var rl = Defeats[(int)right, (int)left];\n return new Outcome(left, right, lr, rl);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T02:53:03.943", "Id": "68862", "Score": "1", "body": "I +1'd because I find your answer brings an interesting point of view. However a downvote was also compelling, because this answer could just as well be posted as a new question for reviewing - it's not a *review*, it's a *rewrite*... and FWIW I really don't like the enum type being called `A`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T03:37:14.457", "Id": "68874", "Score": "0", "body": "@lol.upvote, fair comment -- today I've been rattling off code on this forum in coffee breaks, which is perhaps against the point! I did have a point to make, though, which is that the usual OO approach (classes, interfaces, design pattern, etc.) can lead you away from the simplest/er solutions. That's what I was trying to demonstrate. Re: `A`, I chose `A` to read nicely, albeit tongue in cheek." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T03:59:12.270", "Id": "68880", "Score": "0", "body": "@syb0rg, I see no guidelines on this site indicating that replies should not present alternative approaches for consideration. If such guidelines exist and I have missed them, then you have my apologies. If not, then I think my contribution is valid." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T01:10:37.900", "Id": "40815", "ParentId": "36395", "Score": "4" } } ]
{ "AcceptedAnswerId": "36402", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T04:38:09.980", "Id": "36395", "Score": "42", "Tags": [ "c#", "game", "dependency-injection", "community-challenge", "rock-paper-scissors" ], "Title": "Rock-Paper-Scissors-Lizard-Spock Challenge" }
36395
<pre><code>import javax.swing.JOptionPane; public class DividedBy10v2{ public static void main( String[] args ){ int block[][] = new int[3][3]; int DetermineRow = 0; // The variable assigned for counting rows int DetermineColumn = 0; // The variable assigned for counting columns int blockRow,blockColumn; int score = 0; String inputRow, inputColumn; //random a set of number int randomSet[] = new int[100]; for(int i=0;i&lt;randomSet.length;i++){ randomSet[i] = (int) (Math.random() * 9) + 1; } int round = 0 ;//for counting the round of the game while( true ){ ++round; //print out the title and score System.out.println( "-------------------------" ); System.out.println( "Divided by 10 - Mini Game" ); System.out.printf( "---- Score:%8d ----\n\n", score ); //show game board System.out.println( " 0 1 2 " ); for(DetermineRow=0;DetermineRow&lt;block.length;DetermineRow++){ System.out.print( DetermineRow + " "); for(DetermineColumn=0;DetermineColumn&lt;block.length;DetermineColumn++){ if(block[DetermineRow][DetermineColumn]!=0){ System.out.print( block[DetermineRow][DetermineRow] + " " ); }else{ System.out.print( "_ " ); } } System.out.println(); } //display the coming value System.out.printf( "Coming value : %d &gt; %d &gt; %d \n\n", randomSet[round], randomSet[(round + 1)], randomSet[(round + 2)] ); //check over checking if(block[0][0]&gt;0&amp;&amp;block[0][1]&gt;0&amp;&amp;block[0][2]&gt;0){ if(block[1][2]&gt;0&amp;&amp;block[1][1]&gt;0&amp;&amp;block[1][2]&gt;0){ if(block[2][0]&gt;0&amp;&amp;block[2][1]&gt;0&amp;&amp;block[2][2]&gt;0){ System.out.println( "------ Game Over ------" ); //continue check int ContinueCheck = JOptionPane.showConfirmDialog(null, "Do you want to continue ?", "Continue?", JOptionPane.YES_NO_OPTION); if( ContinueCheck == JOptionPane.YES_OPTION){ //initialize the game board for(DetermineRow=0;DetermineRow&lt;block.length;DetermineRow++) for(DetermineColumn=0;DetermineColumn&lt;block.length;DetermineColumn++) block[DetermineRow][DetermineColumn]=0; continue; }else{if(ContinueCheck == JOptionPane.NO_OPTION){ System.out.println( "-------------------------" ); System.out.println("Good Bye !"); break;} } } } } //input value while(true){ inputRow = JOptionPane.showInputDialog( "The number of row you want to put the number" ); blockRow = Integer.parseInt(inputRow); inputColumn = JOptionPane.showInputDialog( "The number of column you want to put the number" ); blockColumn = Integer.parseInt(inputColumn); if(blockRow&gt;=block.length || blockRow&lt;0 || blockColumn&gt;=block.length || blockColumn&lt;0){ JOptionPane.showMessageDialog(null , "The block you want to enter the number does not exist." , "Error" , JOptionPane.ERROR_MESSAGE ); continue; }else{ if(block[blockRow][blockColumn]!=0){ JOptionPane.showMessageDialog(null , "The block you want to enter the number has been entered an number." , "Error" , JOptionPane.ERROR_MESSAGE ); continue; }else{ block[blockRow][blockColumn] = randomSet[round]; break; } } } //score got check int modSumBlock[] = {-1,-1,-1,-1,-1,-1,-1,-1};//to store the remainder of the sum of 3 block if(block[0][0] != 0 &amp;&amp; block[0][1] != 0 &amp;&amp; block[0][2] != 0) modSumBlock[0] = (block[0][0] + block[0][1] + block[0][2]) % 10; if(block[1][0] != 0 &amp;&amp; block[1][1] != 0 &amp;&amp; block[1][2] != 0) modSumBlock[1] = (block[1][0] + block[1][1] + block[1][2]) % 10; if(block[2][0] != 0 &amp;&amp; block[2][1] != 0 &amp;&amp; block[2][2] != 0) modSumBlock[2] = (block[2][0] + block[2][1] + block[2][2]) % 10; if(block[0][0] != 0 &amp;&amp; block[1][0] != 0 &amp;&amp; block[2][0] != 0) modSumBlock[3] = (block[0][0] + block[1][0] + block[2][0]) % 10; if(block[0][1] != 0 &amp;&amp; block[1][1] != 0 &amp;&amp; block[2][1] != 0) modSumBlock[4] = (block[0][1] + block[1][1] + block[2][1]) % 10; if(block[0][2] != 0 &amp;&amp; block[1][2] != 0 &amp;&amp; block[2][2] != 0) modSumBlock[5] = (block[0][2] + block[1][2] + block[2][2]) % 10; if(block[0][0] != 0 &amp;&amp; block[1][1] != 0 &amp;&amp; block[2][2] != 0) modSumBlock[6] = (block[0][0] + block[1][1] + block[2][2]) % 10; if(block[0][2] != 0 &amp;&amp; block[1][1] != 0 &amp;&amp; block[2][0] != 0) modSumBlock[7] = (block[0][2] + block[1][1] + block[2][0]) % 10; //all 'if' is used for checking if all block in the same row/column/diagonal are filled in number //counting how many score got and where should be cleared by 8bit (in decimal) int scoreCount = 0; for(int n=0;n&lt;8;n++){ if(modSumBlock[n]==0){ score += 10; scoreCount += (int) Math.pow(2,n); }else{ continue; } } //start clear game board if(scoreCount&gt;=128){ block[0][2] = 0; block[1][1] = 0; block[2][0] = 0; scoreCount -= 128; } if(scoreCount&gt;=64){ block[0][0] = 0; block[1][1] = 0; block[2][2] = 0; scoreCount -= 64; } if(scoreCount&gt;=32){ block[0][2] = 0; block[1][2] = 0; block[2][2] = 0; scoreCount -= 32; } if(scoreCount&gt;=16){ block[0][1] = 0; block[1][1] = 0; block[2][1] = 0; scoreCount -= 16; } if(scoreCount&gt;=8){ block[0][0] = 0; block[1][0] = 0; block[2][0] = 0; scoreCount -= 8; } if(scoreCount&gt;=4){ block[2][0] = 0; block[2][1] = 0; block[2][2] = 0; scoreCount -= 4; } if(scoreCount&gt;=2){ block[1][0] = 0; block[1][1] = 0; block[1][2] = 0; scoreCount -= 2; } if(scoreCount&gt;=1){ block[0][0] = 0; block[0][1] = 0; block[0][2] = 0; scoreCount -= 1; } } } } </code></pre> <p>The above code is a mini-game I made which consists of a 3x3 game board. Integer values range from 1-9 and are generated by the system and stored in an array. If all the values have been used, it will start again from the first element of the array. In each round, the next three coming numbers are shown to player, so the player know the value that is going to put not only in the current round, but also the coming two rounds.</p> <p>Note that each position in the game board allows only one value. The program should check if the input position is already allocated. If so, player should be prompted to input again. At the end of a round, the system will check the three rows, the three columns and the two diagonals of the game board; if the sum of a set is divisible by 10, the sum can be added to the score and values can be removed from the game board. The empty slot is counted as 0, the game is over when the game board is full.</p> <p>I want to simplify the code as it looks too messy and complicated. Is there a way to shorten the code using other methods? How do I also allow players to choose from different size of game board (e.g. starting of the game it will ask players if they want to play 3vs3 4vs4 or 5vs5)? You may try compile the code and play the game to see how it works.</p>
[]
[ { "body": "<p>I think, when I run your program, that the combination of text-console and swing user input leads to a bad experience.</p>\n\n<p>Really, given that you have the GUI input boxes, why do I have to type the row/column that you want entered? Why not present me with a grid of buttons, and I have the number I can add to the grid, and I just click where the number should go?</p>\n\n<p>Doing such a grid would potentially even be easier than the text output you put on the console.</p>\n\n<p>Despite that, I do appreciate that the code is runnable, and works.... until I press the cancel button, at which point the code throws a <code>NumberFormatException</code>.</p>\n\n<p>As for the code style, it seems awfully complicated, with a lot of code repetition and <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\">'magic numbers'</a>. Changing the size of the grid would be very frustrating.... it is all hard-coded in.</p>\n\n<p>So, you should set up a constant, say 'gridsize' and use that in many places:</p>\n\n<pre><code>final int gridsize = 3;\n</code></pre>\n\n<p>Then you can fix a lot of places where you have magic numbers:</p>\n\n<pre><code>int block[][] = new int[gridsize][gridsize];\n....\n randomSet[i] = (int) (Math.random() * gridsize * gridsize) + 1;\n</code></pre>\n\n<p>and so on.</p>\n\n<p>The Show-Game-Board will become some form of loop:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nfor (int i = 0; i &lt; gridsize; i++) {\n sb.append(String.format(\"%4d\", i));\n}\n</code></pre>\n\n<p>Also, having variable names with capital-letters is not good java coding convention... The line:</p>\n\n<pre><code>for(DetermineRow=0;DetermineRow&lt;block.length;DetermineRow++){ ....\n</code></pre>\n\n<p>is very off-putting to Java 'regulars'. For small loops like that, something simple like:</p>\n\n<pre><code>for (int row = 0; row &lt; gridsize; row++) { ...\n</code></pre>\n\n<p>would be much more understandable. Note that I declared the row variable inside the for loop (<code>int row = 0</code>). This is the normal way to define variables in for loops. It is not essential, but it actually leads to fewer bugs when the loop-variable is contained entirely inside the loop... (i.e. <code>row</code> is not visible outside the loop).</p>\n\n<p>Now, inside that display loop, because you have complicated names, it has made a bug hard to see..... This is your code:</p>\n\n<pre><code> for(DetermineRow=0;DetermineRow&lt;block.length;DetermineRow++){\n System.out.print( DetermineRow + \" \");\n for(DetermineColumn=0;DetermineColumn&lt;block.length;DetermineColumn++){\n if(block[DetermineRow][DetermineColumn]!=0){\n System.out.print( block[DetermineRow][DetermineRow] + \" \" );\n }else{\n System.out.print( \"_ \" );\n }\n }\n System.out.println();\n }\n</code></pre>\n\n<p>I will simply rename your variables.... and we can see a bug much more easily:</p>\n\n<pre><code> for(row=0;row&lt;block.length;row++){\n System.out.print( row + \" \");\n for(column=0;column&lt;block.length;column++){\n if(block[row][column]!=0){\n System.out.print( block[row][row] + \" \" );\n }else{\n System.out.print( \"_ \" );\n }\n }\n System.out.println();\n }\n</code></pre>\n\n<p>Can you see the bug now?</p>\n\n<pre><code>System.out.print( block[row][row] + \" \" );\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>System.out.print( block[row][column] + \" \" );\n</code></pre>\n\n<p>Similarly, because you have complicated if-statements on the game-check, you have another bug there:</p>\n\n<pre><code> if(block[0][0]&gt;0&amp;&amp;block[0][1]&gt;0&amp;&amp;block[0][2]&gt;0){\n if(block[1][2]&gt;0&amp;&amp;block[1][1]&gt;0&amp;&amp;block[1][2]&gt;0){\n if(block[2][0]&gt;0&amp;&amp;block[2][1]&gt;0&amp;&amp;block[2][2]&gt;0){\n</code></pre>\n\n<p>That should, on the second line be a 0 (I have marked the position with a '^'):</p>\n\n<pre><code> if(block[0][0]&gt;0&amp;&amp;block[0][1]&gt;0&amp;&amp;block[0][2]&gt;0){\n if(block[1][2]&gt;0&amp;&amp;block[1][1]&gt;0&amp;&amp;block[1][2]&gt;0){\n ^\n if(block[2][0]&gt;0&amp;&amp;block[2][1]&gt;0&amp;&amp;block[2][2]&gt;0){\n</code></pre>\n\n<p>Using a loop (preferably in a method) would be better:</p>\n\n<pre><code>private static final boolean isComplete(int[][] grid) {\n for (int row = 0; row &lt; grid.length; row++) {\n for (int col = 0; col &lt; grid[row].length; col++) {\n if (grid[row][col] == 0) {\n return false;\n }\n }\n }\n return true; // all celss have values.\n}\n</code></pre>\n\n<p>You can then, instead, call:</p>\n\n<pre><code> //check over checking\n if(isComplete(block)){\n int ContinueCheck = JOptionPane.showConfirmDialog(null, \"Do you want to continue ?\", \"Continue?\", JOptionPane.YES_NO_OPTION);\n if( ContinueCheck == JOptionPane.YES_OPTION){\n ...\n continue;\n }else if(ContinueCheck == JOptionPane.NO_OPTION) {\n System.out.println( \"-------------------------\" );\n System.out.println(\"Good Bye !\");\n break;\n }\n } \n</code></pre>\n\n<p><strong>Note</strong></p>\n\n<p>Note how, at this point I have never referenced the actual size of the grid as being 3...? So all the code I have changed so far will work with a grid of any size....</p>\n\n<p>Then, the final part, is getting the scores..... This part is slightly more challenging, but, can be done with a few loops... first, the <code>int modSumBlock[] = {-1,-1,-1,-1,-1,-1,-1,-1}</code> is another 'magic number' (8), and should be:</p>\n\n<pre><code>int modSumBlock[] = new int[gridsize + gridsize + 2]; // rows, columns, and diagonals\n</code></pre>\n\n<p>Then your loops are:</p>\n\n<pre><code>for (int row = 0; row &lt; gridsize; row++) {\n modSumBlock[ 0 + row] = getRowScore(block, row);\n}\nfor (int col = 0; col &lt; gridsize; col++) {\n modSumBlock[gridsize + col] = getColumnScore(block, col);\n}\nmodSumBlock[gridsize + gridsize] = getSlashDiagonalScore(block);\nmodSumBlock[gridsize + gridsize + 1] = getBackslashDiagonalScore(block);\n</code></pre>\n\n<hr>\n\n<p>At this point you should have some idea of the other changes you should make....</p>\n\n<p>have fun!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T16:59:19.673", "Id": "59665", "Score": "0", "body": "hi, i've read through your answer, im new to programming, first time using java. the part which u mentioned \"int block[][] = new int[gridsize][gridsize];\n....\n randomSet[i] = (int) (Math.random() * gridsize * gridsize) + 1;\" and \" StringBuilder sb = new StringBuilder();\nfor (int i = 0; i < gridsize; i++) {\n sb.append(String.format(\"%4d\", i));\n} \" how does it work, i mean where do i start. mhy programming teacher did not teach me about stringbuilder. help" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:12:37.657", "Id": "59671", "Score": "0", "body": "the 4 dots .... , is it intended or do i have to write the arrays?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:26:18.140", "Id": "59673", "Score": "0", "body": "@Hecton - the dots are just to show that there's more code afterwards. As for your other comment/question, I don't thing the things I have suggested are that much more complicated than your original question, so I feel there is a gap somewhere... You need to sit with someone (your teacher?) and go through with them. This is not the right forum. As for StringBuilder, you can read up on it here: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html it is just a faster way to join String values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:26:44.143", "Id": "59675", "Score": "0", "body": "i seem to be getting alot of errors with this method, too confusing, such as illegal start of expression private static.." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T16:24:43.913", "Id": "36413", "ParentId": "36409", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T14:54:46.513", "Id": "36409", "Score": "5", "Tags": [ "java", "game" ], "Title": "Game divide by 10" }
36409
<p>I've done this piece of code for creating all possible samples without repetitions, but I think that it is a so heavy algorithm because every time I call this recursive function I create a new vector that is passed to it. What means create any samples without repetitions? it means creating every combination given a population. Is there a way for making this algorithm faster?</p> <p>Here is the algorithm and the description:</p> <p>As already said, this function creates samples without repetitions recursively. If n, that is the number of elements that should be found, is equals 0 I print the sample.</p> <p>Else to the sample that is passed I add the elements of the population that there aren't yet in the combination in a way that there should't be samples that are equals between every samples(I have to create a vector for everyone of this new samples), and I call the function with this new sample and n(the number of element to be found) decremented and incrementing the element from wich I'll start to add.</p> <pre><code>private static void distribuzioneInBlocco(int n, int firstElementConsidered, Vector&lt;Float&gt; population, Vector&lt;Float&gt; sample){ // exit condition, when n equals 0 the fuction doesn't self-calls if(n==0){ JOptionPane.ShowMessageDialog(null, sample); return; } // for every element of the population the function adds this element // at the previous combination for(int x = firstElementConsidered; x&lt;population.size();x++){ Vector&lt;Float&gt; aggiunta = new Vector&lt;Float&gt;(sample); aggiunta.add(population.elementAt(x)); distribuzioneInBlocco(n-1, x+1, population, aggiunta); } } </code></pre> <p>for example if I give as population the vector <code>0 2 4 6</code> and <code>n = 3</code> the answer will be</p> <pre><code>0 2 4 0 2 6 0 4 6 2 4 6 </code></pre> <p>if I give the same population but <code>n = 2</code> the result will be:</p> <pre><code>0 2 0 4 0 6 2 4 2 6 4 6 </code></pre> <p>if <code>n = 4</code></p> <pre><code>0 2 4 6 </code></pre> <p>Moreover is there a way for doing it without recursion?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T16:51:29.593", "Id": "59664", "Score": "2", "body": "Related to, but not complete duplicate of [*Better way to create samples*](http://programmers.stackexchange.com/q/219918/60357) on *programmers*. Many points outlined in my answer there still hold here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:34:03.570", "Id": "59677", "Score": "0", "body": "this is different because there are combination instead permutation, and I fint it more difficult to do it without recursion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T18:57:15.630", "Id": "59687", "Score": "0", "body": "Could you provide an example of how to use this method? I seriously don't understand how it works. And there are actually two compiler errors in your code: `campione` is not declared, and it's called `return (SEMICOLON)`, not `return (COLON)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T22:55:00.283", "Id": "59709", "Score": "0", "body": "I have corrected and added some example." } ]
[ { "body": "<p>Your solution requires that you create a new Vector for every combination. You are right that there is no better algorithm. The way you have it implemented though, is not as efficient as it should be.</p>\n\n<p>Float should be a primitive.... <code>float</code>. Using a Float object instead of the primitive <code>float</code> will require a lot more memory than you should need.</p>\n\n<p>The Java <code>Vector</code> class is a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html\" rel=\"nofollow\">synchronized implementation</a>. Use of the Vector class is discouraged. If you need synchronization then use one of the <code>java.util.concurrent.*</code> classes. I would also use an array-of-primitives for the input population too):</p>\n\n<pre><code>private static void distribuzioneInBlocco(int n, int firstElementConsidered, float[] population, float[] sample){\n // not sure what this is.....\n// exit condition, when n equals 0 the function doesn't self-calls\n //if(n==0){ \n // JOptionPane.ShowMessageDialog(null, campione);\n // return:\n //}\n\n // for every element of the population the function adds this element\n // at the previous combination\n for(int x = firstElementConsidered; x &lt; population.length; x++) {\n float[] aggiunta = Arrays.copyOf(sample, sample.length + 1);\n aggiunta[aggiunta.length - 1] = population[x];\n distribuzioneInBlocco(n-1, x+1, population, aggiunta);\n }\n}\n</code></pre>\n\n<p>So, using an array of primitive will make a big difference for your performance.</p>\n\n<p>I note that you are not keeping any of these samples. If you do not need to actually keep the <code>agguinta</code> array, it is possible that you can save a lot of time by moving the initialization to be outside the loop:</p>\n\n<pre><code>private static void distribuzioneInBlocco(int n, int firstElementConsidered, float[] population, float[] sample){\n // not sure what this is.....\n// exit condition, when n equals 0 the function doesn't self-calls\n //if(n==0){ \n // JOptionPane.ShowMessageDialog(null, campione);\n // return:\n //}\n\n // for every element of the population the function adds this element\n // at the previous combination\n // move the array initialization outside the loop, and reuse it for each\n // recursion at this depth.\n float[] aggiunta = Arrays.copyOf(sample, sample.length + 1);\n for(int x = firstElementConsidered; x &lt; population.length; x++) {\n aggiunta[aggiunta.length - 1] = population[x];\n distribuzioneInBlocco(n-1, x+1, population, aggiunta);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T20:00:39.203", "Id": "59695", "Score": "0", "body": "\"using an array of primitives, and using something like ArrayList instead of Vector will make a big difference for your performance\", even though that's correct, it's not possible to use both at the same time. Java doesn't support primitives as generic types." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T19:50:17.610", "Id": "36427", "ParentId": "36410", "Score": "3" } } ]
{ "AcceptedAnswerId": "36427", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T15:22:22.680", "Id": "36410", "Score": "3", "Tags": [ "java", "recursion", "combinatorics" ], "Title": "Better way to create samples" }
36410
<p>Last night I made this image uploading class. It was the first time I made a file uploader to be used on a real site, so I thought I would share it here and <a href="https://github.com/simon-eQ/BulletProof/blob/master/BulletProof.php" rel="nofollow noreferrer">on Github</a> to get some reviews, hoping if I can perfect it with your help, I will use the class in all my future projects.</p> <pre><code>&lt;?php /** * A small, secure &amp; fast image uploader class written in all-static * class to give an extra boost in performance. * @author Simon _eQ &lt;https://github.com/simon-eQ&gt; * @license Public domain. Do anything you want with it. * Don't ever forget to use at your own risk. */ class BulletProof { /** * User defined, allowed image extensions to upload. ex: 'jpg, png, gif' * @var */ static $allowedMimeTypes; /** * Set a max. height and Width of image * @var */ static $allowedFileDimensions; /** * Max file size to upload. Must be less than server/browser * MAX_FILE_UPLOAD directives * @var */ static $allowedMaxFileSize; /** * Set the new directory / folder to upload new image into. * @var */ static $directoryToUpload; /** * MIME type of the upload image/file * @var */ static $fileMimeType; /** * A new name you have chosen to give the image * @var */ static $newFileName; /** * Set of rules passed by user to choose what/where/how to upload. * @param array $allowedMimeTypes * @param array $allowedFileDimensions * @param $allowedMaxFileSize * @param $directoryToUpload */ static function options(array $allowedMimeTypes, array $allowedFileDimensions, $allowedMaxFileSize, $directoryToUpload) { /** * Globalize the score of the directives, so we can call them from another method. */ self::$allowedMimeTypes = $allowedMimeTypes; self::$allowedFileDimensions = $allowedFileDimensions; self::$allowedMaxFileSize = $allowedMaxFileSize; self::$directoryToUpload = $directoryToUpload; } /** * Native and possible PHP errors provided by the $_FILES[] super-global. * @return array */ static function commonFileUploadErrors() { /** * We can use the key identifier from $_FILES['error'] to match this array's key and * output the corresponding errors. Damn I'm good! */ return array( UPLOAD_ERR_OK =&gt; "...", UPLOAD_ERR_INI_SIZE =&gt; "File is larger than the specified amount set by the server", UPLOAD_ERR_FORM_SIZE =&gt; "Files is larger than the specified amount specified by browser", UPLOAD_ERR_PARTIAL =&gt; "File could not be fully uploaded. Please try again later", UPLOAD_ERR_NO_FILE =&gt; "File is not found", UPLOAD_ERR_NO_TMP_DIR =&gt; "Can't write to disk, as per server configuration", UPLOAD_ERR_EXTENSION =&gt; "A PHP extension has halted this file upload process" ); } /** * There are many reasons for a file upload not work, other than from the information we * can get of the $_FILES array. So, this function tends to debug server environment for * a possible cause of an error (if any) * @param null $newDirectory optional directory, if not specified this class will use tmp_name * @return string */ static function checkServerPermissions($newDirectory = null) { $uploadFileTo = $newDirectory ? $newDirectory : init_get("file_uploads"); /** * if the directory (if) specified by user is indeed dir or not */ if(!is_dir($uploadFileTo)) { return "Please make sure this is a valid directory, or php 'file_uploads' is turned on"; } /** * Check http header to see if server accepts images */ if(stripos('image', $_SERVER['HTTP_ACCEPT']) !== false) { return "This evil server does not seem to accept images"; } /** * Check if given directory has write permissions */ // if(!substr(sprintf('%o', fileperms($uploadFileTo)), -4) != 0777) // { // return "Sorry, you don't have her majesty's permission to upload files on this server"; // } } /** * Upload given files, after a series of validations * @param $fileToUpload * @param $newFileName * @return bool|string */ static function upload($fileToUpload, $newFileName = null) { /** * check if file's MIME type is specified in the allowed MIME types */ $fileMimeType = substr($fileToUpload['type'], 6); if(!in_array($fileMimeType, self::$allowedMimeTypes)) { return "This file type is not allowed."; } self::$fileMimeType = $fileMimeType; /** * show if there is any error */ if($fileToUpload['error']) { $errors = self::commonFileUploadErrors(); return $errors[$fileToUpload['error']]; } /** * Check if size of the file is greater than specified */ if($fileToUpload['size'] &gt; self::$allowedMaxFileSize) { return "File size must be less than ".(self::$allowedMaxFileSize / 100)." Kbytes"; } /** * Checking image dimension is an enhancement as a feature but a must &amp; wise check from * a security point of view. */ list($width, $height, $type, $attr) = getimagesize($fileToUpload['tmp_name']); if($width &gt; self::$allowedFileDimensions['max-width'] || $height &gt; self::$allowedFileDimensions['max-height']) { return "Image must be less than ". self::$allowedFileDimensions['max-width']."pixels wide and ". self::$allowedFileDimensions['max-height']."pixels in height"; } /** * No monkey business */ if($height &lt;= 1 || $width &lt;= 1) { return "This is invalid Image type"; } /** * If user has provided a new file name, assign it. Otherwise, * use a default uniqid id, to avoid name collision */ if($newFileName) { self::$newFileName = $newFileName; } else { self::$newFileName = uniqid(); } /** * Upload file. */ $newUploadDir = self::$directoryToUpload; $upload = move_uploaded_file($fileToUpload['tmp_name'], $newUploadDir.'/'.self::$newFileName.'.'.self::$fileMimeType); if($upload) { return true; } else { /** * If file upload fails, the debug server enviroment as a last resort before giving 'Unknown error' */ $systemErrorCheck = self::checkServerPermissions($newUploadDir); return $systemErrorCheck ? $systemErrorCheck : "Unknown error occured. Please try again later"; } } } </code></pre> <p>In between the time I finished the it, and right now, I have began to have doubts about some things I did/should have done like:</p> <ul> <li>Is making the methods static really appropriate for this class? There is no need for unit testing, so in my opinion, I would say, there is nothing with using static class here. <ul> <li>Should I create custom exceptions to handle the errors instead of returning error messages (note: I am also trying to make the script faster)?</li> </ul></li> <li>Should I be extending the <code>SplFileInfo</code> class handle verification the file types better?</li> <li>Is it better to use <code>finfo_open(FILEINFO_MIME_TYPE);</code> to check file type, or is <code>$_FILES['file']['type']</code> or SplFileInfo's<a href="http://www.php.net/manual/en/splfileinfo.getextension.php" rel="nofollow noreferrer">getFileExtension</a>?</li> </ul> <p>This is the usage of the class:</p> <pre><code>BulletProof::set(array('png', 'jpeg', 'gif', 'jpg'), array('max-width'=&gt;150, 'max-height'=&gt;150), 30000, 'pictures/' ); if($_FILES){ $upload = BulletProof::upload($_FILES['profile_pic'], 'simon'); if($upload !== true) { echo "ERROR: ".$upload; } } </code></pre> <p>I am still thinking if <code>BulletProof::upload()</code> should take in all the augments, if user wants to upload different files with different types/sizes/dimensions instead of creating a global option style.</p> <p>I have a lot of questions/doubts, but I am in a need of any type of review.</p>
[]
[ { "body": "<ul>\n<li><p>Using static methods is not appropriate if your only good reason for doing so is performance. I can confidently say that outside of a benchmark, neither you nor anyone else will ever notice the difference in performance.</p></li>\n<li><p>HTTP_ACCEPT tells you what the <em>client</em> accepts. IE: what types of files you can return. <em>Your script</em> is the one that decides whether you accept images.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T20:17:54.330", "Id": "59696", "Score": "0", "body": "Ok, I'll think about those. Any more points? I thought this would get about 100 points about why it is bad :D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T20:03:58.580", "Id": "36430", "ParentId": "36411", "Score": "1" } }, { "body": "<p><strong><em>Update</em></strong><Br/>\nAfter a quick look at your updated github code, one thing that struck me as quite odd was line 94:</p>\n\n<pre><code>if(!substr(sprintf('%o', fileperms($uploadFileTo)), -4) != 0777)\n</code></pre>\n\n<p>In order for a file to be uploaded to some directory, I'd not expect that dir to be chmodded to xwr. If anything, I would consider it somewhat insecure to allow uploaded files to be moved to a rwx-all directory. I'd disallow execution for anyone except the actual owner, and set it to <code>0755</code>, and even that'd be liberal, <code>0655</code> would work, too<br/>\nI'm at work now, and have quite a lot to do, but, to coin a phrase: <em>\"stay tuned\"</em> for future updates.</p>\n\n<p>Your main questions are:</p>\n\n<blockquote>\n <p>Is making the methods static really appropriate for this class? There is no need for unit testing, so imho, I would say, there is nothing [wrong] with using statics here.</p>\n</blockquote>\n\n<p>I would have to disagree with you on that one. Since neigh on everything in your class is <code>static</code>, what's the point of having a class? Especially since you're trying to improve performance. Classes were never meant to improve performance of code, they were introduced to improve performance of development: a good class is reusable, easy to maintain and to some extend it documents itself (type-hinting, short, concise and to the point methods &amp; method-names).<br/>\nIn PHP, which is by design, stateless, statics are often just globals in OO-drag. That's, in my view, evidence of bad design. Not only is it hard to unit-test (you know that already), it greatly reduces the chances of your code being re-usable. Thus effectively reducing its OO interface to noise/syntactic sugar or even clutter.</p>\n\n<p>Lastly, if you're trying to improve performance, then <code>static</code> methods should be right out, really. As I said, they're mostly global functions in drag anyway, with 1 crucial difference: a call to a <code>static</code> method requires PHP to lookup the <code>zend_object*</code> pointer, and then use the <code>zend_object_value</code> to get to the <code>zend_object_handlers</code> in which it can <em>finally</em> look for the method you're calling. Which <a href=\"http://www.micro-optimization.com/global-function-vs-static-method\" rel=\"nofollow noreferrer\">creates considerable overhead</a> if you're interested in <em>micro-optimizations</em>.</p>\n\n<p>So global functions will be faster, but even a non-static will be faster <a href=\"http://www.vanylla.it/tests/static-method-vs-object.php\" rel=\"nofollow noreferrer\">as you can see from this benchmark script</a>. The reasons are a bit too complicated for me to explain here, but the bottom line is that an instance of any class references the <code>zend_object_handlers</code> directly, whereas a static call doesn't have an instance to begin with: the call doesn't start from a variable, so there's no <code>zval *</code> to start from. What is used instead is the <code>zend_class_entry</code> which was created at compilation time. The engine uses sifts through all sorts of things (global, calling scope, context specific stuff...), just to get to the <code>zend_class_entry *</code>, just to get to the method... That's hardly efficient, now is it?</p>\n\n<blockquote>\n <p>Should I create costume [custom] exceptions to handle the errors instead of returning error messages</p>\n</blockquote>\n\n<p>It all depends. Personally, I'm in favour of custom exceptions, that are grouped together neatly in a distinct namespace. Your code deals with file-uploads, and thus with request data. All code that deals with request data, be it in its <em>\"raw\"</em> for or not, should use request-specific exceptions IMO. That makes the entire code so much more clean, and reusable.<br/>\nIn the end, it's probably a matter of taste/opinion, but I find that if there's an error <code>throw</code> simply beats <code>return false</code> or <code>return self::SOME_CONSTANT</code> hands down, because the latter relies on the user of that code <em>to check the return value</em>. Getting people to do that is a struggle, even in languages like C, where the return value is all you have to go on, in some cases.</p>\n\n<blockquote>\n <p>Should I be extending the SplFileInfo class handle verification the file types better</p>\n</blockquote>\n\n<p>While one of the first examples on the doc pages on php.net shows a class extending the <code>SplFileInfo</code> class, I'm not too keen on that. I've always said that it's best to <em>not extend from code you don't own</em>. It's much the same as:</p>\n\n<pre><code>class MyDB extends \\PDO\n{\n}\n</code></pre>\n\n<p>This code is completely harmless. It just changes the name of <code>PDO</code> to <code>MyDB</code>, and slows you down (every call to a method is a call to <code>MyDB::parend::&lt;method&gt;</code> now).<br/>\nBut it's too tempting to write code like:</p>\n\n<pre><code>class BadDB extends \\PDO\n{\n public function __construct(\n $dsn = 'mysql:dbname=default;host=127.0.0.1',\n $user = 'root',\n $pass = 'yourPAss',\n array $opts = array(\n self::ATTR_ERRMODE =&gt; self::ERRMODE_EXCEPTION\n )\n )\n {\n return parent::__construct($dsn, $user, $pass, $opts);\n }\n\n public function insert($query, array $data)\n {\n $stmt = parent::prepare($query);\n $stmt-&gt;execute($data);\n return $this-&gt;lastInsertID();\n }\n}\n</code></pre>\n\n<p>You may be wondering what's wrong with that, well, I've been <a href=\"https://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class/29394#29394\">quite verbose on the matter</a>, here, you'll find just a few reasons why this isn't a good idea.<br/>\nThe examples given here, and on the linked post aren't even the worst that can happen, imagine if I were to set the default options to include:</p>\n\n<pre><code>self::ATTR_EMULATE_PREPARES =&gt; false\n</code></pre>\n\n<p>And some poor fellow would use <code>MyDB</code>, test his code locally, using a version of MySQL that supported prepared statements, and then deploy the code on a server that is still running MySQL 4 (yes, they still exists, and these kinds of absurdities happen).</p>\n\n<p>Anyway, back to <code>SplFileInfo</code>: I wouldn't extend from it. Your class has a clear task: process uploaded files. <code>SplFileInfo</code>, too, has a clear task: its job is to represent, and offer a clean way of working with files. Those are 2 different jobs. A class should have one and only one reason to change (or job). Combine 2 or more jobs, and you're dealing with a module.</p>\n\n<blockquote>\n <p>Is it better to use finfo_open(FILEINFO_MIME_TYPE); to check file type, or is $_FILES['file']['type'] or SplFileInfo'sgetFileExtension Which one is safer, or better..</p>\n</blockquote>\n\n<p>The short answer is <code>SplFileGetInfo::getFileExtension</code> is the safest bet, but it's not perfect still. I'll have a quick look 'round, but I think I have some code on this machine that deals with that...<br/>\nNope, it's a Symfony2 project, so it's not of much help here. However <a href=\"https://stackoverflow.com/questions/4166762/php-image-upload-security-check-list\">you may want to take a look at these answers here</a>, some of the tips and tricks still apply today (there's one about checking the first n bytes of a file, to be absolutely sure the mime-type matches the extension, for example).<br/></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T18:43:02.860", "Id": "59767", "Score": "0", "body": "Thanks. Really awesome review. I couldn't have asked for more. I will change the class by applying most of what you have said. b/c I have no clue about some the things you said, .ie. Zend or core of PHP and how it works, as I am still a newbie. But, this will be a good reference in the future. For now, I will have to use `SplFileGetInfo::getFileExtension` which leaves me again having to extend the SplFileInfo class. Because without it, I don't know what is the safest way to check the FILE type. Anyway, I'll think more about this. Thank you so much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:48:08.963", "Id": "59774", "Score": "0", "body": "@Qǝuoɯᴉs: I will grant you this: the `SplFileInfo` class was probably made to be extended from the off, so it's not ass bad as extending the `PDO` class. Still, the surest way to determine the file-type is matching extension, mime-type _and_ binary read and see if they all converge on the same time. When in doubt, go for hives (no extension)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:59:34.120", "Id": "59776", "Score": "0", "body": "Exactly. That is what I was thinking. Matching all outputs to see if there is something fishy or not. One last question, I am sure you against extending the PDO class, and I can clearly see your point. But, I have extended PDO once, ([you can check it here](https://github.com/simon-eQ/PdoWrapper)) just to write less, and instead of fiddling the exception, I was able to catch the errors with `&reference` which ended up shortening that every `try{}catch(){}` block to just a simple variable. So, I was thinking, what would be the downside of using the same approach to catch errors for this class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T06:38:03.850", "Id": "59819", "Score": "0", "body": "@Qǝuoɯᴉs: I'd not extend PDO, even in the way you did so: your constructor doesn't take a fourth argument (the array of options you can set, like I've shown in my example). Besides, your function _\"lies\"_ (google side-effects are lies). The way you get errors (using a reference var) implies the user knows to pass that var to the method call, and he has to check its value after each call. If you forget to do that just once, your code will blunder along, happily unaware that there was an error. That's not too good" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T06:39:15.403", "Id": "59820", "Score": "0", "body": "Besides: the reason why you're unable to catch errors in the constructor is because you've not passed that fourth argument to the parent constructor (`array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)`), so it doesn't throw errors when the connection fails..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:02:24.803", "Id": "59892", "Score": "0", "body": "Thanks. I understand now, why it was giving me errors. But, I still believe despite not being a good idea to extend the PDO class, it is not as bad as others out there. the reference `$e` to check errors is much more simpler/cleaner than using the entire `try{}catch(){}` on every query. Maybe it is the noobnes talking, and I'll learn more in the future." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:09:39.073", "Id": "59895", "Score": "0", "body": "Btw: Since I improved the file uploader class a bit, I need more reviews, so I placed a bounty of `50` feel free to throw away some wisdom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:34:18.407", "Id": "60044", "Score": "0", "body": "Thanks for the update. I know that I am doing that wrong. I had commented it out before, because it was giving me errors. I will change it `0665` now." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T15:50:26.767", "Id": "36457", "ParentId": "36411", "Score": "1" } } ]
{ "AcceptedAnswerId": "36457", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T15:56:12.643", "Id": "36411", "Score": "1", "Tags": [ "beginner", "php", "security", "static", "network-file-transfer" ], "Title": "Secure image upload class" }
36411
<h3>The Challenge</h3> <p><a href="http://chat.stackexchange.com/transcript/message/12408541#12408541">Create an implementation</a> of "Rock - Paper - Scissors - Lizard - Spock".</p> <p>The rules:</p> <blockquote> <p>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</p> </blockquote> <h3>My approach</h3> <p>I wanted to make the game <strong>flexible</strong> and <strong>general</strong>. It should not be necessary to change much to create a "normal" Rock-Paper-Scissors implementation. It should also be possible to add elements such as <a href="http://www.youtube.com/watch?v=o_xH__mg03w">Water balloon</a> if you'd like. Technically, it should also be possible without too much effort to modify the elements at runtime (this is currently not supported in the below implementation, but there's not many changes needed to make it a reality).</p> <p>Players. All players have a score that gets increased when they win. A player should have a method to return which item the player chooses, this implementation can vary (a human can write input, an AI can return something random, some other AIs should perhaps always choose SPOCK...)</p> <h3>Code</h3> <p>Because I am lazy, I have put all the classes/interfaces in the same file. Of course, all of them could be placed in their own files as <code>public</code>. The code is stand-alone, just copy it and paste it to your favorite IDE (Eclipse) and run it as a JUnit test case.</p> <pre><code>interface IItem { /** * To allow configuration "from both sides", use an int instead of a boolean.&lt;br&gt; * For example, if SCISSORS have -1 edge against ROCK, it will lose as long as ROCK doesn't have an edge below -1 against SCISSORS.&lt;br&gt; * This way, it is possible to configure both "beats" and "gets beaten by". It is also possible to return a randomized value here to allow for more complex game styles. */ int edge(IItem opponent); } abstract class ItemPlayer { public abstract IItem chooseOne(IItem[] possibles); private int score = 0; public void wonAGame() { score++; } public int getScore() { return score; } } enum Items implements IItem { SCISSORS, PAPER, ROCK, LIZARD, SPOCK; private final Set&lt;IItem&gt; beats = new HashSet&lt;IItem&gt;(); void beat(IItem... items) { this.beats.addAll(new HashSet&lt;IItem&gt;(Arrays.asList(items))); } @Override public int edge(IItem opponent) { return beats.contains(opponent) ? 1 : 0; } } public class StackExchange { private static final IItem NO_WINNER = null; public static IItem fight(IItem first, IItem second) { int firstEdge = first.edge(second) - second.edge(first); if (firstEdge == 0) return NO_WINNER; return firstEdge &gt; 0 ? first : second; } public static class AIInput extends ItemPlayer { private final Random random = new Random(); @Override public IItem chooseOne(IItem[] possibles) { if (possibles.length == 0) throw new IllegalArgumentException("Possibles needs to contain at least one element"); return possibles[random.nextInt(possibles.length)]; } @Override public String toString() { return "AI"; } } public static class HumanInput extends ItemPlayer implements Closeable { private final Scanner scanner; public HumanInput() { this.scanner = new Scanner(System.in); } @Override public void close() { this.scanner.close(); } @Override public IItem chooseOne(IItem[] possibles) { if (possibles.length == 0) throw new IllegalArgumentException("Possibles needs to contain at least one element"); do { System.out.println("Choose one of the following: " + Arrays.toString(possibles)); String str = scanner.nextLine(); for (IItem item : possibles) { if (item.toString().equals(str)) { return item; } } System.out.println("Incorrect input."); } while (true); } @Override public String toString() { return "Human"; } } @Before public void setup() { // This configures what beats what. Items.SCISSORS.beat(Items.PAPER); Items.PAPER.beat(Items.ROCK); Items.ROCK.beat(Items.LIZARD); Items.LIZARD.beat(Items.SPOCK); Items.SPOCK.beat(Items.SCISSORS); Items.SCISSORS.beat(Items.LIZARD); Items.LIZARD.beat(Items.PAPER); Items.PAPER.beat(Items.SPOCK); Items.SPOCK.beat(Items.ROCK); Items.ROCK.beat(Items.SCISSORS); } @Test public void assertions() { assertEquals(NO_WINNER, fight(Items.SCISSORS, Items.SCISSORS)); assertEquals(Items.SPOCK, fight(Items.SPOCK, Items.SCISSORS)); assertTrue(Items.ROCK.edge(Items.SCISSORS) &gt; 0); assertTrue(Items.SCISSORS.edge(Items.ROCK) == 0); assertEquals(Items.ROCK, fight(Items.SCISSORS, Items.ROCK)); } @Test public void challenge() { HumanInput human = new HumanInput(); ItemPlayer comp = new AIInput(); final int GAMES = 42; // we play 42 games, just because it's 42 of course. for (int i = 1; i &lt;= GAMES; i++) { System.out.println("Game " + i + " of " + GAMES); // choose the items IItem first = human.chooseOne(Items.values()); IItem second = comp.chooseOne(Items.values()); // determine which item wins IItem fightResult = fight(first, second); // show result System.out.println(first + " vs. " + second + ": " + fightResult); ItemPlayer winner = null; if (fightResult == NO_WINNER) System.out.println("Tie!"); else { winner = fightResult == first ? human : comp; winner.wonAGame(); System.out.println("Winner is: " + winner); } System.out.println("Score is now " + human.getScore() + " - " + comp.getScore()); System.out.println(); } human.close(); } } </code></pre>
[]
[ { "body": "<p><code>ItemPlayer</code> is a really good idea. Keeping the logic and score centralized in an abstract class for the AI and Human player is a good design, but, you have not taken the idea far enough.</p>\n\n<p>The abstract class should have a <code>name</code> field, and a constructor that takes the name:</p>\n\n<pre><code>abstract class ItemPlayer {\n private final String name;\n\n ItemPlayer(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n}\n</code></pre>\n\n<p>Using the <code>toString()</code> on the concrete classes to get the name is not a great option. Instead, for example, the AI class should be:</p>\n\n<pre><code>public static class AIInput extends ItemPlayer {\n\n AIInput() {\n super(\"AI\");\n }\n\n ....\n}\n</code></pre>\n\n<p>Similarly, the <code>HumanInput</code> can be changed..... but, with the Human input, I like how you've made it <code>Closable</code>.... but then, why didn't you use a try-with-resources structure in your main loop?</p>\n\n<p>Finally, I like the use of the <code>Enum</code> for the valid moves (and I did something similar), but having the rules for the moves outside of the enum is cumbersome. using a static initializer block inside the enum class would solve that problem instead of having to have the <code>setup()</code> method call</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T16:46:53.223", "Id": "36414", "ParentId": "36412", "Score": "12" } }, { "body": "<p>In addition to <em>rolfl</em>'s comments on your excellent code:</p>\n\n<ul>\n<li>The <code>fight</code> method does not belong into the main <code>StackExchange</code> class. Instead, its logic belongs into <code>Items</code>. The <code>edge</code> method is slightly superfluous, and its name is not immediately obvious. (The name comes from your mental model of the relationships between <code>IItem</code>s, not from the domain at hand. Putting a comment with the word “graph” somewhere would solve this, otherwise <code>item.beats(otherItem)</code> might read better).</li>\n<li>Similar, parts of <code>challenge</code> might be a better fit for <code>ItemPlayer</code>. Especially the <em>strategy</em>-like invocation of <code>chooseOne</code> and the score bookkeeping seem to indicate this.</li>\n<li><p>I understand why <code>possibles</code> is an <code>IItem[]</code>. However, an object with methods <code>contains</code> and <code>pickAny</code> could be more elegant here:</p>\n\n<pre><code>class ItemChoices {\n private final Set&lt;IItem&gt; asSet;\n private final List&lt;IItem&gt; asList;\n private final Random rng = new Random();\n\n public ItemChoices(IItem[] choices) {\n if (choices.length == 0) throw IllegalArgumentException(...);\n this.asList = Arrays.asList(choices);\n this.asSet = new HashSet&lt;IItem&gt;(this.asList);\n }\n\n public boolean contains(IItem item) {\n return this.asSet.contains(item);\n }\n\n public IItem pickAny() {\n return this.asList.get(rng.nextInt(this.asList.size()));\n }\n}\n</code></pre>\n\n<p>Initialize once by <code>ItemChoices choices = new ItemChoices(Items.values())</code>, and both <code>chooseOne</code> implementations can be simplified.</p>\n\n<p>Then again, this would only simplify three small parts of the code, so you could weigh this differently.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:56:59.990", "Id": "59681", "Score": "0", "body": "You're right that `fight` doesn't belong in that class, I don't think it belongs in `Items` though, since it works on all `IItem`s. You're also right that a `challenge` method would be useful in `ItemPlayer`. What I should have done is to create a `Game` class, but I got stuck in the [get-it-done-fast trap](http://chat.stackexchange.com/rooms/8595/conversation/the-get-it-done-fast-trap). I don't think an `ItemChoices` class would be necessary here... I think the `pickAny` implementation belongs in the AI implementation and not in some utility class for all the options." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T18:10:31.850", "Id": "59682", "Score": "1", "body": "@SimonAndréForsberg You raise some good counter-points. You are right about where `fight` *really* belongs. Add it to the interface along `edge`? It would be *really* nice to have traits here. WRT `pickAny` – There Is More Than One Way To Do It, and my way does indeed seem unnecessarily complicated. In retrospect it does show that you “deferred” the design, but I wouldn't call that a “trap” (its *agile*, hah ha). Compared with what this site sees at other times, your's still is some beautiful and extremely well-factored code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:35:34.983", "Id": "36419", "ParentId": "36412", "Score": "7" } } ]
{ "AcceptedAnswerId": "36414", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T15:59:20.840", "Id": "36412", "Score": "12", "Tags": [ "java", "game", "community-challenge", "rock-paper-scissors" ], "Title": "Another Rock Paper Scissors Lizard Spock implementation" }
36412
<p>I have an algorithm that evaluates in input <code>byte[]</code> with a source <code>byte[]</code>. Several conditions can be encountered:</p> <ul> <li>Match found</li> <li>No match found</li> <li>End of input array</li> <li>End of source array </li> <li>Input wildcard (*) matches against any source byte</li> </ul> <p>All of these conditions are dealt with in this algorithm. Having been my first pass at this algorithm, I know there are improvements that can be made. Not only am I looking for cleaner code and possibly refactoring to find re-usable bits, this needs to be as efficient as possible. Right now this will compare an 18 byte input array against an 1170 byte source array in 2ms.</p> <p>Here is the current implementation of the algorithm:</p> <pre><code>private bool HasMatchBytes(byte[] bytes, out int length, ref int position) { var hasMatch = false; var isComplete = false; var b = position; var end = position; // - this loop depends on internal advancement of the counter [v] for (var v = 0; v &lt; bytes.Length; ) { var isMatch = false; // - this loop depends on internal advancement of the counter [b] while (b &lt; mByteStream.Length &amp;&amp; !isComplete) { // wildcard doesn't care the value if (bytes[v] == '*') { isMatch = true; } else { isMatch = bytes[v] == mByteStream[b]; } // only advance positions if hasMatch is currently false if (isMatch &amp;&amp; !hasMatch) { hasMatch = true; position = b++; ++v; } // current position does not match and invalidates previous buffers else if (!isMatch &amp;&amp; hasMatch) { hasMatch = false; // reset v (bytes array) v = 0; // advance b (stream array) ++b; } // any other condition should advance b (stream array) // and v (bytes array) else { // advance v (bytes array) if (isMatch &amp;&amp; hasMatch) { ++v; } // we could have reached the end of v if (v &lt; bytes.Length) { if (hasMatch) { end = ++b; } else { ++b; } } // if so, force completion else { isComplete = true; } } } // isMatch means the current byte indexes match // assumptions: // wherever the buffer position is, the results are // true to the current start position. if (hasMatch &amp;&amp; v &lt; bytes.Length) { ++v; end = ++b; if (b &gt;= mByteStream.Length) { hasMatch = false; } } // with match and at end of bytes length algorithm is complete if (hasMatch &amp;&amp; v &gt;= bytes.Length) { isComplete = true; end = ++b; } // if end of source reached then shut down algorithm if (b &gt;= mByteStream.Length) { v = bytes.Length; isComplete = true; end = mByteStream.Length; } } length = end - position; return hasMatch; } </code></pre> <p>...using .Net 4.5 if that helps.</p> <p><strong>Edit</strong> <em>per comment</em> </p> <p>In all cases, the algorithm will return true if the source sequence contains a match against the full input array sequence. Each byte must match specifically in sequence except where a wildcard <code>(*)</code> is specified.</p> <p>This algorithm is intended to continue reading until end of the source array. If the end of the source array is reached before another full iterative match of the input array, the algorithm would return false. But the calling method uses the returned position plus the length of the input sequence to determine if there could possibly be another match in the source. </p> <p>Here is the calling code:</p> <pre><code> public IEnumerable&lt;IMetaToken&gt; Matches(IMatchToken matchToken) { var bytes = matchToken.GetValues(); var length = 0; var position = 0; while ((position + bytes.Length) &lt; mByteStream.Length) { if (HasMatchBytes(bytes, out length, ref position)) { var start = position; position += length; var token = new MetaToken(start, length); yield return token; } else { position += length; } } } </code></pre> <p><strong>FWIW:</strong> This is part of a <code>Regex</code><em>-like</em> class that handles expressions against byte arrays. First you have to create a format object and then have the <code>ByteRegex</code> class find <code>Matches</code> against the supplied source sequence.</p> <hr> <p>I've decided to take @svick's advice ...well, somewhat. I've already worked on renaming the indexes, etc.</p> <p>I have another class that manipulates a <code>MemoryStream</code> and I could use that to encapsulate this operation. At least the code would be in a class with the same order of operations.</p> <p>I am also going to refactor this huge method into 2 static iterator methods: <code>IterateNeedle(...)</code> and <code>IterateHaystack(...)</code>. Names are likely to be changed to protect the innocent but you get the idea. I'll post some code once I have it reworked. </p> <p><strong>UPDATE</strong> <em>Iterators to the rescue</em><br> I don't know if I should post my refactors as an answer. Might be helpful for people to see implementation of the <code>IEnumerator</code> state machine. I'll post explanation as an answer. There is a lot of code though and it is specialized so I'm hesitant because it might draw a lot of questions that are off topic.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T20:46:47.667", "Id": "59698", "Score": "0", "body": "Could you explain what exactly should the method return? Especially in the “end of array” cases." } ]
[ { "body": "<ol>\n<li><p>If I understand this correctly, your code doesn't work. This is because when some characters match and then you find a character that doesn't match, you can't continue checking with the current character, you need to go back to the second character of the current partial match.</p>\n<p>An example is <code>mByteStream = new byte[] { 0, 0, 1 }</code>, <code>bytes = new byte[] { 0, 1 }</code>. For this input, the correct result is <code>true</code>, but your code returns <code>false</code>.</p>\n</li>\n<li><p>It looks like this method is part of a type that does other things. I think it would be cleaner if it was in a separate type, taking both arrays as parameters.</p>\n</li>\n<li><p>When reading the code, it's very easy to confuse <code>bytes</code> and <code>mByteStream</code>, <code>b</code> and <code>v</code>. Those names don't mean anything. Much better names would be for example <code>needle</code>, <code>haystack</code>, <code>needleIndex</code> and <code>haystackIndex</code>. Having different variables names <code>hasMatch</code> and <code>isMatch</code> is also very confusing.</p>\n</li>\n<li><p>A method that's this complicated would benefit greatly from detailed XML documentation. That way, callers of the method don't need to read its code to know what it does.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T22:26:24.717", "Id": "59700", "Score": "0", "body": "Thanks @svick: Helpful information. The method has passed on the unit tests I've used. Not sure that I covered this use-case though. I will take into consideration to make this a class. Are there logical separations I can make from this algorithm that will help test the logic?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T04:40:34.983", "Id": "60128", "Score": "0", "body": "Good advice and after a couple of days thinking about it, I was inspired a bit on how to do this. This is going to get a lot more complicated really quick. So I've got to make sure the methods operate effectively with a variety of behaviors. I might think of a sort of state machine for this ...hhhmmm ...." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T20:38:16.440", "Id": "36431", "ParentId": "36418", "Score": "5" } }, { "body": "<p>@svick is right in suggesting separate classes/objects. These objects come in the form of custom iterator objects. There are two <em>stacks</em> that must be iterated:</p>\n\n<ol>\n<li>a collection of mask tokens (each token really nothing more than byte[])</li>\n<li>full sequence matches (i.e. a start/length of match)</li>\n</ol>\n\n<p>For the mask tokens:</p>\n\n<pre><code>private struct MaskSequenceIterator : IMaskSequenceIterator\n</code></pre>\n\n<p>For the matches:</p>\n\n<pre><code>private struct MatchSequenceIterator : IMatchSequenceIterator\n</code></pre>\n\n<p><code>IMatchSequenceIterator</code> does all the real work and quite easily. The magic is all in the <code>MoveNext()</code> method: </p>\n\n<pre><code> public bool MoveNext() {\n // gets the next mask token\n var continueMatching = mMaskIterator.MoveNext();\n // determine if there is enough stream to keep matching\n if (continueMatching) {\n continueMatching &amp;= mCurrentPosition + mMaskToken[mMaskIterator.Index].Length &lt;= mRegex.mByteStream.Length;\n }\n\n // check to see if the sequence matches - nvm the out var atm\n var sequenceMatches = TryGetNextMatch(continueMatching, out mCurrent);\n\n // set iterator properties\n mIsSequenceMatch = sequenceMatches;\n mEndOfStream = mCurrentPosition &gt;= mRegex.mByteStream.Length;\n\n // true if matches\n return sequenceMatches;\n }\n</code></pre>\n\n<p>This greatly simplified my outer logic in both a single <code>Match</code> method as well as the multiple <code>Matches</code> method:</p>\n\n<pre><code> IMatchSequenceIterator matchIterator = new MatchSequenceIterator(this, maskToken, position);\n var sumLength = 0L;\n var isComplete = false;\n\n // Match\n while ((!isComplete) &amp;&amp;\n (hasMatch = matchIterator.MoveNext())) {\n // get the sum length\n sumLength += matchIterator.Current.Length;\n\n // MaskIterator is constructed by the MatchIterator\n if (matchIterator.MaskIterator.IsFirst()) {\n position = matchIterator.Current.Start;\n }\n\n // debug points\n var index = matchIterator.MaskIterator.Index;\n var isLast = matchIterator.MaskIterator.IsLast();\n\n isComplete = isLast || matchIterator.EndOfSequence;\n\n }\n\n // this comparison tells us if we matched all sequences\n if (isComplete &amp;&amp; matchIterator.MaskIterator.IsLast()) {\n return new MetaToken(position, sumLength);\n }\n\n // Matches\n while ((!isComplete) &amp;&amp;\n (hasMatch = matchIterator.MoveNext())) {\n sumLength += matchIterator.Current.Length;\n\n if (matchIterator.MaskIterator.IsFirst()) {\n position = matchIterator.Current.Start;\n }\n\n var index = matchIterator.MaskIterator.Index;\n var isLast = matchIterator.MaskIterator.IsLast();\n\n isComplete = matchIterator.EndOfSequence;\n\n if (!isComplete &amp;&amp; isLast) {\n // yield the current match meta data\n yield return new MetaToken(position, sumLength);\n // reset counters;\n position += sumLength;\n sumLength = 0;\n // we want to keep finding matches so reset the internal mask iterator\n matchIterator.MaskIterator.Reset();\n // reset has match flag\n hasMatch = false;\n }\n\n }\n</code></pre>\n\n<p><strong>Why my own custom iterator interfaces instead of implementing <code>IEnumerable&lt;T&gt;</code></strong><br>\n<em>I felt this should be addressed in depth -- added as a matter of interest</em><br>\nThe problem is iterating two sequences (<code>seqA</code>, a.k.a. <code>Source</code> and seqB, a.k.a. <code>Mask</code>) </p>\n\n<ul>\n<li>The <code>Mask</code> must be satisfied in whole (byte for byte in sequence)</li>\n<li>Reset <code>Mask</code> stack when matching fails on a sequence</li>\n<li>Increment the <code>Mask</code> stack as <code>Source</code> sequences match</li>\n<li>Stop matches if <code>Source</code> stack is at the end</li>\n</ul>\n\n<p>This boils down to needing 2 state machines to handle the logic of iterating an inner set of conditions (a.k.a. <code>maskToken</code>s) for evaluation. A <code>maskToken</code> is then used to match against a specified <code>Source</code> sequence - which is iterated by the outer state machine. </p>\n\n<p>I used interfaces to build two rudimentary state-machines implementing <code>IEnumerator&lt;T&gt;</code>. For the record, I am weighing the implementation of <code>IEnumerable&lt;T&gt;</code>; at the time of design I was not convinced of how intuitive the interface would be when considering the assumptions made while using an <code>IEnumerable&lt;T&gt;</code>. </p>\n\n<p>The inner state machine - <code>MaskIterator</code> - doesn't really have any special logic but exposes some additional members:</p>\n\n<pre><code>// `ControlChar` is a custom value type representing a byte[4]\ninterface IMaskSequenceIterator : IEnumerator&lt;ControlChar&gt; {\n\n #region properties\n\n ControlChar Current { get; }\n\n int Index { get; }\n\n IMaskToken MaskToken { get; }\n\n #endregion\n\n\n #region members\n\n void Dispose();\n\n bool IsFirst();\n\n bool IsLast();\n\n long Length();\n\n void MoveFirst();\n\n bool MoveNext();\n\n void Reset();\n\n #endregion\n\n}\n</code></pre>\n\n<p>The outer state machine - <code>MatchIterator</code> - has quite a bit more logic:</p>\n\n<p>A. Manipulate and Interpret <code>MaskIterator</code> properties<br>\nB. Find Match Sequence: <em>logic black box</em> </p>\n\n<pre><code>// IMetaToken holds [start, length] info of sequence matches\ninterface IMatchSequenceIterator : IEnumerator&lt;IMetaToken&gt; {\n\n #region properties\n\n IMetaToken Current { get; }\n\n bool EndOfSequence { get; set; }\n\n bool IsSequenceMatch { get; }\n\n IMaskSequenceIterator MaskIterator { get; }\n\n #endregion\n\n\n #region members\n\n void Dispose();\n\n bool MoveNext();\n\n void Reset();\n\n #endregion\n}\n</code></pre>\n\n<p>Basically, I am taking advantage of the state-machine characteristics of the IEnumerator (as a pattern, so to speak). The idea of this project is that I can build a mask, or sequence of bytes - say, 91-00-00-00; 16-00-00-00; 58-00-00-00 - and match a source byte stream looking for every occurrence of 91-00-00-00-16-00-00-00-58-00-00-00. </p>\n\n<p>The mask formatter can use wildcards specifying a length so I can format something like:\n91-00-00-00\n42-42\n42-42-16-00\n58-00-00-00</p>\n\n<p>... where <code>42</code> is <code>*</code>. The <code>MatchIterator</code> will return meta data for anything that matches the pattern 91-00-00-00-42-42-42-42-16-00-58-00-00-00 and 42 can be replaced by any byte. </p>\n\n<p>Feedback is welcome!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T15:52:28.877", "Id": "61011", "Score": "0", "body": "Why are you using a custom iterator interface and not `IEnumerable<T>`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T16:52:50.853", "Id": "61019", "Score": "0", "body": "Because I have some methods in my iterators that `IEnumerable` and `IEnumerator` do not provide: e.g. `IsFirst()`, `IsLast()`, `Index`, `Length()` and `EndOfSequence`. I am simply taking advantage of the state machine operation of the iterator (`yield return`) and the iterator can provide states via the extra properties/methods I added to the interface. Make sense? I am not saying that this is the completed implementation but it is much easier to debug and maintain than the method in my OP." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T14:50:40.747", "Id": "37046", "ParentId": "36418", "Score": "3" } } ]
{ "AcceptedAnswerId": "36431", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:33:31.770", "Id": "36418", "Score": "8", "Tags": [ "c#", "algorithm", ".net", "array" ], "Title": "Simplification of byte array comparison algorithm" }
36418
<p>I have the following MySQL <code>SELECT</code> statement. It is working fine except that the code is too long. I have been looking throughout the Internet to figure out how I can make it shorter.</p> <pre><code> SELECT regd, Subject, Section, date, SUM(CASE WHEN (Name_of_exam = 'First Unit Exam' OR Name_of_exam = 'Second Unit Exam' OR Name_of_exam = 'Third Unit Exam') THEN (Mark_score / Full_mark) *25 END) AS t_scored, SUM(CASE WHEN (Name_of_exam = 'First Unit Exam' OR Name_of_exam = 'Second Unit Exam' OR Name_of_exam = 'Third Unit Exam') THEN (Full_mark) END) AS t_fm, SUM(CASE WHEN (Name_of_exam = 'First Term Weekly Test' OR Name_of_exam = 'Second Term Weekly Test' OR Name_of_exam = 'Third Term Weekly Test' OR Name_of_exam = 'Final Term Weekly Test') THEN (Mark_score / Full_mark) *25 END ) AS w_scored, SUM(CASE WHEN (Name_of_exam = 'First Term Weekly Test' OR Name_of_exam = 'Second Term Weekly Test' OR Name_of_exam = 'Third Term Weekly Test' OR Name_of_exam = 'Final Term Weekly Test') THEN (Full_mark) END ) AS w_fm, SUM(CASE WHEN Name_of_exam = 'Final Unit Exam' THEN (Mark_score / Full_mark) *25 END ) AS f_scored, SUM(CASE WHEN Name_of_exam = 'Final Unit Exam' THEN (Mark_score) END ) AS score_m, SUM(CASE WHEN Name_of_exam = 'CCE' THEN (Mark_score / Full_mark) *25 END ) AS cce_scored, SUM(CASE WHEN Name_of_exam = 'CCE' THEN (Full_mark) END ) AS cce_fm FROM exam_mark WHERE regd='23' AND Section='A' AND date BETWEEN '2013-11-01' AND '2013-11-15' GROUP BY Subject </code></pre> <p>Any suggestion is welcome. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T17:19:54.307", "Id": "59757", "Score": "3", "body": "this Query appears to be untested and not working correctly, if it is working correctly please show results, table schema, etc so that we can set up a [SQLFiddle](http://www.sqlfiddle.com)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T04:49:33.550", "Id": "59810", "Score": "0", "body": "Added Fiddle for MySQL - it messes up the dates: http://www.sqlfiddle.com/#!2/7afb6/1 (there should be two dates for MDATE))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T04:50:16.380", "Id": "59811", "Score": "0", "body": "Added Fiddle for SQLServer - it fails with group-by problems: http://www.sqlfiddle.com/#!6/4ea0f" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T08:46:18.713", "Id": "59831", "Score": "0", "body": "@rolfl, my code is working fine in mysql 5 any way. I used it in my project, and I found no problem except that it is very long." } ]
[ { "body": "<p>This kind of expression</p>\n\n<pre><code> (Name_of_exam = 'First Term Weekly Test'\n OR Name_of_exam = 'Second Term Weekly Test'\n OR Name_of_exam = 'Third Term Weekly Test'\n OR Name_of_exam = 'Final Term Weekly Test') \n</code></pre>\n\n<p>can usually be shortened to an IN clause.</p>\n\n<pre><code>(Name_of_exam in ('First Term Weekly Test', 'Second Term Weekly Test', etc.))\n</code></pre>\n\n<p>But there's enough conditional logic in here that I'd have to ask myself, \"Am I trying to write a report in SQL?\" Reports are better implemented with a report writer.</p>\n\n<p>This doesn't have to do with your question, but a GROUP BY statement that includes only one of 'n' unaggregated columns is almost always a syntax error in standard SQL. MySQL treats this like a feature, but it's a feature best avoided. </p>\n\n<p>It's <em>almost</em> always a syntax error, because standard SQL allows you to group on one of 'n' unaggregated colums when the unaggregated columns are functionally dependent on the grouped column.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T18:52:03.680", "Id": "59686", "Score": "0", "body": "Thank you. But What do you mean by feature best avoided? Does it mean there can be any possible error in the query?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T19:13:58.770", "Id": "59690", "Score": "3", "body": "The relational model is deterministic. SQL is deterministic. MySQL's GROUP BY is not deterministic." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T18:40:29.273", "Id": "36424", "ParentId": "36421", "Score": "8" } }, { "body": "<p>You actually don't have to use the <code>SUM</code> function. I re-wrote the first part of your query.</p>\n\n<pre><code>SELECT \n regd\n , Subject\n , Section\n , date\n , CASE WHEN (Name_of_exam IN ('First Unit Exam','Second Unit Exam','Third Unit Exam')) \n THEN (Mark_score / Full_mark) *25 END) AS t_scored\n , CASE WHEN (Name_of_exam IN 'First Unit Exam','Second Unit Exam','Third Unit Exam')) \n THEN (Full_mark) END) AS t_fm\n</code></pre>\n\n<p>I also implemented the accepted answer as well.</p>\n\n<p>I think that losing the <code>SUM</code> function will also speed up your Query.</p>\n\n<hr>\n\n<p>There isn't really a reason to <code>Group By Subject</code> you probably want to <code>ORDER BY Subject</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T12:05:48.827", "Id": "59728", "Score": "0", "body": "Uhm, you *do* Need to have the SUM... this makes no sense... The OP has a broken query (group-by not matching the un-aggregated columns) now this suggestion to not use sum at all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T16:43:47.050", "Id": "59753", "Score": "0", "body": "@rolfl, why do you need `SUM`? he will get the same data for every cell in that column, the original query is bad with the `SUM` in it, the `GROUP BY` is wrong as well, OP probably wants an `ORDER BY`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T17:04:24.940", "Id": "59756", "Score": "1", "body": "You and I are looking at it from different sides. Perhaps we see the OP as having different objectives. Essentially his OP select is broken, and there is thus no correct answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T05:52:14.373", "Id": "59817", "Score": "0", "body": "@Malachi I need to use Group because one subject appears more than once in the subject column." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:13:46.617", "Id": "66705", "Score": "0", "body": "if you are grouping by subject that means you don't want one of them show up or you want them to be merged. so this means that the subject column data is not as atomic as it should be. pretty sure that you need to fix the data in the table to get rid of this Duplicate in the Subject field. if you showed us more of what is going on with the Database and the tables involved it would be easier to say exactly what you need to do with it" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T06:31:51.107", "Id": "36445", "ParentId": "36421", "Score": "4" } } ]
{ "AcceptedAnswerId": "36424", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T17:42:15.957", "Id": "36421", "Score": "5", "Tags": [ "mysql", "sql" ], "Title": "Exam score query for many types of exams" }
36421
<p><strong>This post is following-up on <a href="https://codereview.stackexchange.com/questions/36395/rock-paper-scissors-lizard-spock-challenge">Rock-Paper-Scissors-Lizard-Spock Challenge</a></strong></p> <p>I had a gut feeling that I was somehow abusing <code>IComparable&lt;T&gt;</code>, @svick's answer confirmed that.</p> <p>As @dreza was posting his answer I was in the process of proceeding with exactly that refactoring: stuffing the <code>SelectionBase</code> class with most of the functionality, effectlvely turning the derived classes into more or less useless, combersome objects that would be best implemented as an <code>enum</code>.</p> <p>Building on @ChrisWue's answer, I came up with the following code:</p> <h3>Selections</h3> <p>Turned into enums:</p> <pre><code>public enum Selection { Rock, Paper, Scissors, Lizard, Spock } </code></pre> <h3>GameRule</h3> <p>Designed to be represented as a string that looks exactly how Sheldon enumerates them:</p> <pre><code>public class GameRule { private readonly Selection _winner; private readonly Selection _loser; private readonly string _verb; public GameRule(Selection winner, string verb, Selection loser) { _winner = winner; _loser = loser; _verb = verb; } public Selection Winner { get { return _winner; } } public Selection Loser { get { return _loser; } } public override string ToString() { return string.Format("{0} {1} {2}", _winner, _verb, _loser); } } </code></pre> <h3>GameResult</h3> <p>Rather than going <code>static</code> all the way, I chose an <code>Evaluate</code> factory method with a private constructor, and instead of having a <code>bool</code> that tracks whether the player wins, I've included the player's selection as a parameter of that constructor. The <code>InvalidOperationException</code> thrown in the <code>ToString</code> method is never hit, but it satisfies the compiler's need for all paths to return a value while eliminating a "default" <code>else</code> branch that would make a result be implicitly defined:</p> <pre><code>public class GameResult { private readonly GameRule _outcome; private readonly Selection _player; private GameResult(GameRule outcome, Selection player) { _outcome = outcome; _player = player; } public override string ToString() { if (_outcome == null) return "Meh. Tie!"; if (_player == _outcome.Winner) return string.Format("{0}. You win!", _outcome); if (_player == _outcome.Loser) return string.Format("{0}. You lose!", _outcome); throw new InvalidOperationException(); } public static GameResult Evaluate(IEnumerable&lt;GameRule&gt; rules, Selection player, Selection sheldon) { var rule = rules.FirstOrDefault(r =&gt; r.Winner == player &amp;&amp; r.Loser == sheldon || r.Winner == sheldon &amp;&amp; r.Loser == player); return new GameResult(rule, player); } } </code></pre> <p>This invited refactoring my <code>Game</code> class to look like this:</p> <pre><code>public class Game { private readonly IUserInputProvider _consoleInput; private readonly IResultWriter _resultWriter; private readonly IEnumerable&lt;GameRule&gt; _rules; public Game(IUserInputProvider console, IResultWriter resultWriter, IEnumerable&lt;GameRule&gt; rules) { _consoleInput = console; _resultWriter = resultWriter; _rules = rules; } public void Run() { while (true) { LayoutGameScreen(); var player = GetUserSelection(); if (player == null) return; var sheldon = Selection.Spock; var result = GameResult.Evaluate(_rules, player.Value, sheldon); _resultWriter.OutputResult(result); Pause(); } } private void Pause() { Console.WriteLine("\nPress &lt;ENTER&gt; to continue."); Console.ReadLine(); } private void LayoutGameScreen() { Console.Clear(); Console.WriteLine("Rock-Paper-Scissors-Lizard-Spock 1.1\n{0}\n", new string('=', 40)); foreach (var item in Enum.GetValues(typeof(Selection))) Console.WriteLine("\t[{0}] {1}", (int)item + 1, item); Console.WriteLine(); } private Selection? GetUserSelection() { var playable = Enum.GetValues(typeof(Selection)); var values = playable.Cast&lt;int&gt;() .Select(item =&gt; (item + 1).ToString()) .ToList(); values.Add(string.Empty); // allows a non-selection var input = _consoleInput.GetValidUserInput("Your selection?", values); if (input == string.Empty) { var confirm = _consoleInput.GetValidUserInput("Giving up already? (Y/N)", new[] { "Y", "N" }); if (confirm.ToUpper() == "Y") return null; } int selection; var isValidSelection = int.TryParse(input, out selection) &amp;&amp; playable.Cast&lt;int&gt;().Contains(selection - 1); if (!isValidSelection) return GetUserSelection(); return playable.Cast&lt;Selection&gt;().Single(item =&gt; (int)item == selection - 1); } } </code></pre> <p>One thing I'm not sure I like, is the +1/-1 and the casting going on here, in order to display 1-based menu items; I refuse to explicitly assign an <code>int</code> value to each possible <code>Selection</code>.</p> <p>The refactoring has greatly simplified the <code>ConsoleResultWriter</code> class:</p> <pre><code>public interface IResultWriter { void OutputResult(GameResult outcome); } public class ConsoleResultWriter : IResultWriter { public void OutputResult(GameResult outcome) { Console.WriteLine("\n\tSheldon says: \"{0}\"\n", outcome); } } </code></pre> <p>...and left the <code>Main</code> method looking like this:</p> <pre><code> static void Main(string[] args) { var consoleReader = new ConsoleUserInputProvider(); var consoleWriter = new ConsoleResultWriter(); var rules = new[] { new GameRule(Selection.Scissors, "cuts", Selection.Paper), new GameRule(Selection.Paper, "covers", Selection.Rock), new GameRule(Selection.Rock, "crushes", Selection.Lizard), new GameRule(Selection.Lizard, "poisons", Selection.Spock), new GameRule(Selection.Spock, "smashes", Selection.Scissors), new GameRule(Selection.Scissors, "decapitates", Selection.Lizard), new GameRule(Selection.Lizard, "eats", Selection.Paper), new GameRule(Selection.Paper, "disproves", Selection.Spock), new GameRule(Selection.Spock, "vaporizes", Selection.Rock), new GameRule(Selection.Rock, "crushes", Selection.Scissors) }; var game = new Game(consoleReader, consoleWriter, rules); game.Run(); } </code></pre> <p>AI aside, can it get any better? Is there anything weird still going on? How's the naming? Any KISS-shredding interfaces?</p>
[]
[ { "body": "<ol>\n<li><blockquote>\n <p>I chose an Evaluate factory method with a private constructor</p>\n</blockquote>\n\n<p>I think that <code>GameResult.Evaluate()</code> doesn't logically make much sense, this logic belongs to a method in <code>Game</code>, which means the constructor of <code>GameResult</code> would be public. Also, why does <code>GameResult</code> contain <code>Selection player</code>? Something like <code>bool playerWon</code> would be enough.</p></li>\n<li><pre><code>Console.WriteLine(\"Rock-Paper-Scissors-Lizard-Spock 1.1\\n{0}\\n\", new string('=', 40));\n</code></pre>\n\n<p>I think this would be cleaner as several separate <code>WriteLine</code>s:</p>\n\n<pre><code>Console.WriteLine(\"Rock-Paper-Scissors-Lizard-Spock 1.1\");\nConsole.WriteLine(new string('=', 40));\nConsole.WriteLine();\n</code></pre></li>\n<li><blockquote>\n <p>One thing I'm not sure I like, is the +1/-1 and the casting going on here, in order to display 1-based menu items</p>\n</blockquote>\n\n<p>I agree. I think a better solution would be to create a structure that maps numbers to <code>Selection</code>s. <code>Dictionary</code> is probably not a good idea, because you want to output the selections in order and <code>Dictionary</code> is unordered. Instead, you can use for example <code>List&lt;KeyValuePair&lt;int, Selection&gt;&gt;</code>:</p>\n\n<pre><code>var selections = Enum.GetValues(typeof(Selection));\n_selectionsMap = Enumerable.Range(1, selections.Length)\n .Zip(selections,\n (index, selection) =&gt; new KeyValuePair&lt;int, Selection&gt;(index, selection));\n</code></pre>\n\n<p>You could use this structure both in <code>LayoutGameScreen()</code> and <code>GetUserSelection()</code>.</p></li>\n<li><pre><code>new GameRule(Selection.Scissors, \"cuts\", Selection.Paper)\nnew GameRule(Selection.Scissors, \"decapitates\", Selection.Lizard)\n</code></pre>\n\n<p>These are incorrect grammatically, they should be <code>\"cut\"</code> and <code>\"decapitate\"</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T02:23:00.683", "Id": "59802", "Score": "0", "body": "@rolfl I just followed the specs: http://www.youtube.com/watch?v=iapcKVn7DdY" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T02:34:54.633", "Id": "59804", "Score": "0", "body": "@retailcoder Then you have a bug in the spec. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T02:38:26.440", "Id": "59805", "Score": "0", "body": "@retailcoder - The wiki page is more official (and I edited the grammar to match - just kidding): http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock#Rules" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T04:58:17.307", "Id": "59813", "Score": "0", "body": "@rolfl interestingly, it seems **scissors** is also singular: http://en.wiktionary.org/wiki/scissors" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T21:13:20.943", "Id": "36433", "ParentId": "36426", "Score": "8" } }, { "body": "<p>Minor addition to @svick's answer:</p>\n\n<p>If you change your <code>enum</code> to </p>\n\n<pre><code>public enum Selection\n{\n Rock = 1,\n Paper,\n Scissors,\n Lizard,\n Spock\n}\n</code></pre>\n\n<p>Then you have it one-based and don't need to do the +1/-1 dance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T03:50:35.630", "Id": "59719", "Score": "3", "body": "I don't like this much, because I think it ties the model too tightly with presentation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T01:49:17.333", "Id": "36442", "ParentId": "36426", "Score": "4" } } ]
{ "AcceptedAnswerId": "36433", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T19:44:31.807", "Id": "36426", "Score": "11", "Tags": [ "c#", "game", "dependency-injection", "community-challenge", "rock-paper-scissors" ], "Title": "Rock-Paper-Scissors-Lizard-Spock Challenge, take 2" }
36426
<p><a href="http://meta.codereview.stackexchange.com/a/1066/23788">How to deal with Follow-up questions</a></p> <p>A follow-up question should <strong>clearly state</strong> that it is a <strong>follow-up question to a previously-asked question.</strong></p> <p>A <strong>good</strong> follow-up question should include:</p> <ul> <li><strong>Which</strong> question it is a follow-up to</li> <li><strong>What</strong> changes has been made in the code since the last question</li> <li><strong>Why</strong> a new review is being asked for</li> </ul> <p>Follow-up questions that don't address these 3 points can be closed as duplicates.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T19:53:50.453", "Id": "36428", "Score": "0", "Tags": null, "Title": null }
36428
Use this tag when posting a question that is a follow-up of a previous post. State which question you're following-up on, what has changed, and why a new review is needed.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T19:53:50.453", "Id": "36429", "Score": "0", "Tags": null, "Title": null }
36429
<p>This script works for what I need it to do, but I'm not all that proficient with Python yet, so I was wondering if any of the more seasoned python veterans would go about it differently.</p> <pre><code>import os import string import re '''This script will take in an input list of strictly stellar IDs, and compare those IDs to a master file with IDs AND photometric data. It will then write to a file, the lines from the master file that correspond to the known IDs in the IDs list.''' def pullIDs(file_input): '''Pulls Mon-IDs from input file.''' arrayID = [] with open(file_input,'rU') as user_file: for line in user_file: arrayID.append(re.findall('Mon\-\d{6}',line)) return arrayID def pullLines(file_input): '''Creates an array component for each line in the input file.''' arrayLines = [] with open(file_input,'rU') as info: for item in info: item.split arrayLines.append(item) return arrayLines def getHeader(file_input): '''Assuming the file-header begins with a '#', this will pull the header line.''' with open(file_input,'rU') as title: for line in title: if line.startswith('#'): header = line return header known_stars = raw_input("Enter your ID list: ") master_list = raw_input("Enter your master list: ") results_list = raw_input("Name your output file: ") with open(results_list,"w+") as output: output.write(getHeader(master_list)) for item in pullIDs(known_stars): for items in pullLines(master_list): if items[:10] in item: output.write(items) output_fileSIZE = os.stat(results_list).st_size if output_fileSIZE &gt; 0: print "\nYour output file has been written to.\n" else: print "\nThere was an error writing to your file.\n" </code></pre> <p>This essentially takes a list of known animals, say, <code>cat</code> and <code>dog</code>, and compares that list to a master list of animals and their respective information.</p> <p>For example:</p> <blockquote> <pre><code>cat female 2 gray playful dog male 9 black aggressive giraffe male 12 tall hungry elephant male 33 gray lonely etc. </code></pre> </blockquote> <p>By creating two arrays for both lists, it searches for an animal that exists in both files and, once found, prints all of the more in-depth results from the 'master list' to a file.</p> <p>So my file would look like this:</p> <blockquote> <pre><code>cat female 2 gray playful dog male 9 black aggressive </code></pre> </blockquote> <p>because I only had a 'known list' of cats and dogs. </p> <p>I'm just looking for tips on how to make this script better. It also prints a header for the column information.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T16:05:35.743", "Id": "59747", "Score": "0", "body": "As written I don't believe `pullLines` does what you expect. Because there is no call to the line's member `item.split`, and even if there was its return would be ignored, it appears to be equivalent to `with open(file_input,'rU') as info: return info.readlines()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T00:44:24.640", "Id": "59795", "Score": "0", "body": "The program gives me back the info I was expecting, so I assume the `item.split` line is redundant?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T01:25:46.040", "Id": "59800", "Score": "0", "body": "Yes. `item.split` retrieves the bound split method, but does not call it. Having that code there distracts from the actual intention, making it look like perhaps you wanted `items = item.split(); arrayLines.append(items)`." } ]
[ { "body": "<p>This is the sort of thing that Python is really good at. Your code seems like it functions, but it will be very inefficient for large data sets. For each input value you have to check every line in the the master list -- and the way you have it set up here you're going to read the master list off disk for each input value as well, so it will be really slow.</p>\n\n<p>The first step obvious fix is to load the master list into memory and keep it around for the duration of a session. This is a fairly simple change to your existing code. First, change your pull_lines so it returns a dictionary instead of a list:</p>\n\n<pre><code>def pullLines(file_input):\n '''returns a dictionary of the entries in &lt;file_input&gt; keyed by the first item in each line'''\n master_dict = {}\n with open(file_input,'rU') as info:\n for eachline in info.readlines():\n tokens = eachline.split()\n master_dict[tokens[0]] = tokens[1:]\n</code></pre>\n\n<p>Then, you move pull lines out of the inner loop:</p>\n\n<pre><code>lookup = pull_lines(path_to_file)\nwith open(results_list,\"w+\") as output:\n output.write(getHeader(master_list))\n for item in pullIDs(known_stars):\n if item in lookup:\n output.write(lookup[item])\n</code></pre>\n\n<p>This has a couple of advantages</p>\n\n<p>1) not hitting the disk for every query will be much faster</p>\n\n<p>2) the dictionary lookup faction is much faster than straight for loop comparison, since the dictionary uses hashed values instead of more expensive string compares.</p>\n\n<p>As an aside, you should look into <a href=\"http://docs.python.org/2/tutorial/inputoutput.html\" rel=\"nofollow\">readlines</a>, which the usual pythonic way of reading text files with info on lines.</p>\n\n<p>For the longer term this is a great application for Python's built in database functionality (with the sqllite module). You could convert your existing text files into a sqllite database and then your lookups can be much more flexible and precise ('find spectrum and power for stars with id > X and &lt; Y' sort of thing). You probably also want to set this file up so you could call it from the command line, which would involve using the <a href=\"http://docs.python.org/2.7/library/argparse.html#module-argparse\" rel=\"nofollow\">argparse</a> module to grab command line arguments and out them into known_stars, master_list and output_file</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T16:08:30.550", "Id": "59748", "Score": "2", "body": "I disagree with the suggestion that `for line in afile.readlines(): ...` is more pythonic than `for line in afile: ...`, but other than that I agree with this. Note also that depending on the later usage, it may make more sense to do `key, value = eachline.split(1)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:06:22.713", "Id": "59768", "Score": "0", "body": "@MichaelUrman `split(1)` is a `TypeError`, you mean `split(None, 1)` instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T01:16:42.893", "Id": "59798", "Score": "0", "body": "@JanneKarila You're spot on. My mistake! I'd fix it if I could." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T03:44:49.703", "Id": "59807", "Score": "0", "body": "@MichaelUrman What would be the benefit of using `split(None,1)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:10:34.827", "Id": "60011", "Score": "1", "body": "@Matt It all depends on what you need in theodox's example `master_dict`. If you want the remainder of the line split similarly (mapping the key to list of items), the original code is more useful; if you want to handle the remainder of the line as a single token (mapping the key to the rest of the line) `split(None, 1)` gets you there instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:48:35.547", "Id": "60047", "Score": "0", "body": "I see. That would be ideal if I understand the point correctly. I'd never split up the columns other than `Mon-IDs` and `the rest of them`. I think I should practice with the dictionary stuff more, I haven't ventured into that python territory yet. Thanks." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T01:11:00.183", "Id": "36439", "ParentId": "36432", "Score": "4" } } ]
{ "AcceptedAnswerId": "36439", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T20:41:33.033", "Id": "36432", "Score": "2", "Tags": [ "python" ], "Title": "Comparing a list of known animals to a master list of animals" }
36432
<p>I'd like a review on anything including optimizations, corrections, suggestions for robustness, adherence to good coding practices, etc.</p> <p>I also request verification of the complexity: O(n<sup>n</sup>), where <em>n</em> is the row length or column length.</p> <pre><code>public final class Sudoku { private Sudoku() {} private static void printSolution (int[][] board) { for (int i = 0; i &lt; board.length; i++) { for (int j = 0; j &lt; board[0].length; j++) { System.out.print(board[i][j] + " : "); } System.out.println(); } } private static Set&lt;Integer&gt; getNumber(int[][] board, int row, int col) { final Set&lt;Integer&gt; intsToAvoid = new HashSet&lt;Integer&gt;(); // check - row for (int i = 0; i &lt; board[0].length; i++) { if (board[row][i] &gt; 0) { intsToAvoid.add(board[row][i]); } } // check - col for (int i = 0; i &lt; board.length; i++) { if (board[i][col] &gt; 0) { intsToAvoid.add(board[i][col]); } } // check - cube int lowerRowIndex = (row / 3) * 3; int lowerColumnIndex = (col / 3) * 3; for (int i = lowerRowIndex; i &lt; lowerRowIndex + 3; i++) { for (int j = lowerColumnIndex; j &lt; lowerColumnIndex + 3; j++) { if (board[i][j] &gt; 0) { intsToAvoid.add(board[i][j]); } } } final Set&lt;Integer&gt; candidateInts = new HashSet&lt;Integer&gt;(); for (int i = 1; i &lt;= board.length; i++) { if (!intsToAvoid.contains(i)) { candidateInts.add(i); } } return candidateInts; } private static boolean solveSudoku (int[][] board, int row, int col) { // traversing the matrix.. go to next row once all columns in current row are traversed. if (col == board[0].length) { row++; if (row == board.length) { printSolution(board); return true; } col = 0; } if (board[row][col] &gt; 0) { return solveSudoku(board, row, col + 1); } else { for (int i : getNumber(board, row, col)) { board[row][col] = i; if (solveSudoku(board, row, col + 1)) return true; board[row][col] = 0; } } return false; } /** * Expects an n * n matrix and returns true and prints sudoku solution for valid input. * * @param sudoku the n*n matrix to solve * @return true or false, true indicating the solution to solve. */ public static boolean solve (int[][] sudoku) { return solveSudoku(sudoku, 0, 0); } public static void main(String[] args) { int[][] board = {{3, 0, 6, 5, 0, 8, 4, 0, 0}, {5, 2, 0, 0, 0, 0, 0, 0, 0}, {0, 8, 7, 0, 0, 0, 0, 3, 1}, {0, 0, 3, 0, 1, 0, 0, 8, 0}, {9, 0, 0, 8, 6, 3, 0, 0, 5}, {0, 5, 0, 0, 9, 0, 6, 0, 0}, {1, 3, 0, 0, 0, 0, 2, 5, 0}, {0, 0, 0, 0, 0, 0, 0, 7, 4}, {0, 0, 5, 2, 0, 6, 3, 0, 0}}; System.out.println(solve (board)); } } </code></pre>
[]
[ { "body": "<p><strong>Private constructor</strong></p>\n\n<p>It is considered good style throw an error in a constructor if they are not supposed to be called, even not from within the class where a private instructor could be invoked from:</p>\n\n<pre><code>private Sudoko() {\n throw new AssertionError();\n}\n</code></pre>\n\n<p><strong>Use the for-each loop instead of explicit iteration</strong></p>\n\n<p>For example:</p>\n\n<pre><code>private static void printSolution(int[][] board) {\n for (int[] row : board) {\n for (int value : row) {\n System.out.print(value + \" : \");\n }\n System.out.println();\n }\n}\n</code></pre>\n\n<p>This is true for all other loops in your application. Specifically for the above iteration: Did you really want to only iterate over row 1?</p>\n\n<p><strong>It is better object-oriented style to use instances instead of implement static delegates</strong></p>\n\n<p>You could consider an API like that:</p>\n\n<pre><code>int[][] grid = { ... };\nSolvedSudoku solvedSudoku = new SudokuSolver(grid).solve();\nsolvedSudoku.printResult(System.out);\nint[][] solvedSudokuGrid = solvedSudoku.getSolvedGrid();\n</code></pre>\n\n<p>where you provide rich information and better adapt changes in the future. It would further allow you to change functionality by overriding methods in the future. Moreover, it makes your program more readable.</p>\n\n<p><strong>Consider using an enum type</strong></p>\n\n<p>It might be a little awkward in the beginning, but an enum type would increase your application's type safety. Consider this:</p>\n\n<ol>\n<li>Use of <code>int</code>: Your grid contains a value of <code>19</code> or <code>-7</code>. Your program can at best throw an exception at runtime.</li>\n<li>Use of an <code>enum</code>: Your compiler will prevent a grid with a value of <code>19</code> from being compiled. You could have a <code>enum SudokuValue { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, UNDEFINED }</code>. This would also allow you to implement methods for these values such as for example <code>SudokuValue#isDefined()</code>. As another benefit, enums can be stored in <code>EnumSet</code>s quite efficiently what is not true for your boxing <code>Set&lt;Integer&gt;</code>.</li>\n</ol>\n\n<p>Further, this would increase the readability of your code.</p>\n\n<p><strong>Consider implementing a type for your board / grid</strong> </p>\n\n<p>This would allow you to define methods such that instead of</p>\n\n<pre><code>getNumber(board, row, col)\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code>board.getNumber(row, col)\n</code></pre>\n\n<p>This would again improve the readability of your code. Also, you could prevent the construction of invalid grids where different rows were for example of different size. Also, you would allow the implementation of other grid implementations as for example a lazy grid that loads values on demand, since you would only require a certain type which would not necessarily need to be represented by an array.</p>\n\n<p><strong>Use immutability as much as possible</strong></p>\n\n<p>You should create a new array as a result grid instead of altering the existing one. This way, you could for example allow different solving algorithms to run concurrently on the same grid without fearing to run into concurrency issues. Consider this also when returning <code>Set</code>s. Maybe you want to cache values one day? Make it explicit that these sets are not to be altered, i.e. immutable, and make this part of the method's explicit contract by wrapping the return values into a <code>Collections#immutableSet</code>. Also, use the <code>final</code> keyword whenever possible if you consider changing your solutions to using specified types.</p>\n\n<p><strong>As for optimization</strong> </p>\n\n<p>Don't do it (now)! Do such (micro-)optimizations when you find out that speed is an issue. It is more important to make your code readable and understandable. Apart from algorithmic considerations, you should allow the JIT compiler to handle micro-optimizations for you. Some people might recommend you to use <code>static</code> handles for improving run time behavior but this is in general not true. Trust the JVM, it is smarter than you might think it is, it does not need your help with this. What you should optimize is algorithmic complexity what brings me to the last hint.</p>\n\n<p><strong>Algorithm complexity</strong></p>\n\n<p>Your methods are of the following complexity:</p>\n\n<ol>\n<li><p><code>print</code>: Iterates over the matrix: <code>O(n^2)</code>. (This is the same complexity as building the array though, so this is a minimum for this program anyways.)</p></li>\n<li><p><code>getNumber</code>: Iterates only over a row: <code>O(n)</code></p></li>\n<li><p><code>solveSudoku</code>: In the worst case, you are making on average <code>(n-2)^2</code> recursive calls for <code>n</code> while iterating over worst <code>n</code> values of a row. (This is quite <a href=\"http://en.wikipedia.org/wiki/Algorithmics_of_sudoku\" rel=\"nofollow\">inefficient</a>.) Writing this relation down:</p>\n\n<p>T(0) = 1</p>\n\n<p>T(n + 1) = n^3 T(n) + 1</p></li>\n</ol>\n\n<p>If you resolve this equation system, you find out that your complexity is indeed of O(n<sup>n</sup>).</p>\n\n<p>This means that your overall implementation is also of this complexity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T13:51:36.347", "Id": "61184", "Score": "2", "body": "It's not surprising that the overall complexity is exponential: generalized Sudoku is NP-hard!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T13:52:55.237", "Id": "61186", "Score": "0", "body": "True, there are however algorithms that can solve the problem faster which only succeed most likely." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T10:38:17.240", "Id": "37120", "ParentId": "36434", "Score": "3" } } ]
{ "AcceptedAnswerId": "37120", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T21:31:41.543", "Id": "36434", "Score": "2", "Tags": [ "java", "sudoku", "matrix" ], "Title": "Java: Sudoku solver" }
36434
<p>Here's my take at the <em>Rock-Paper-Scissors-Lizard-Spock</em> challenge. The outcomes are as follows:</p> <blockquote> <ul> <li>Scissors cuts paper</li> <li>paper covers rock</li> <li>rock crushes lizard</li> <li>lizard poisons Spock</li> <li>Spock smashes scissors</li> <li>scissors decapitate lizard</li> <li>lizard eats paper</li> <li>paper disproves Spock</li> <li>Spock vaporizes rock</li> <li>rock crushes scissors</li> </ul> </blockquote> <p>I've decided to implement this in procedural form, partly because it's just one player against another. The program doesn't output any of the above outcomes, just generic ones, but I may try to figure out the former at another time. Points are awarded to the winner each turn with the total displayed upon termination. I've also used <code>std::rand()</code> instead of something "better" (such as <code>std::mt19937</code> and <code>std::uniform_int_distribution</code>) since this is a simple program.</p> <p>My main concerns:</p> <ul> <li>I feel that there can be a good substitute to <code>possibleMoves</code>; it looks quite large.</li> <li>I couldn't find a good STL function to do the searching in <code>determineOutcome()</code>, although what I have now may suffice.</li> <li>Not enough/not good enough validation to avoid breaking the game.</li> </ul> <p>Other than that, nothing else sticks out to me. Please do criticize anything you may find.</p> <pre><code>#include &lt;array&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;iostream&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;utility&gt; enum Weapon { ROCK=1, PAPER, SCISSORS, LIZARD, SPOCK }; enum Outcome { WIN, LOSE, DRAW }; typedef std::pair&lt;Weapon, Weapon&gt; PlayerMoves; const std::array&lt;PlayerMoves, 10&gt; possibleMoves = { std::make_pair(SCISSORS, PAPER), std::make_pair(PAPER, ROCK), std::make_pair(ROCK, LIZARD), std::make_pair(LIZARD, SPOCK), std::make_pair(SPOCK, SCISSORS), std::make_pair(SCISSORS, LIZARD), std::make_pair(LIZARD, PAPER), std::make_pair(PAPER, SPOCK), std::make_pair(SPOCK, ROCK), std::make_pair(ROCK, SCISSORS) }; std::istream&amp; operator&gt;&gt;(std::istream&amp; in, Weapon&amp; weapon) { int val; if (in &gt;&gt; val) weapon = static_cast&lt;Weapon&gt;(val); else throw std::logic_error("invalid weapon"); return in; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Weapon const&amp; weapon) { switch (weapon) { case ROCK: return out &lt;&lt; "rock"; case PAPER: return out &lt;&lt; "paper"; case SCISSORS: return out &lt;&lt; "scissors"; case LIZARD: return out &lt;&lt; "lizard"; case SPOCK: return out &lt;&lt; "Spock"; default: throw std::logic_error("invalid weapon"); } } Weapon getPlayerWeapon() { std::cout &lt;&lt; "\n\n(1) -&gt; Rock\n"; std::cout &lt;&lt; "(2) -&gt; Paper\n"; std::cout &lt;&lt; "(3) -&gt; Scissors\n"; std::cout &lt;&lt; "(4) -&gt; Lizard\n"; std::cout &lt;&lt; "(5) -&gt; Spock\n\n"; Weapon weapon; do { std::cout &lt;&lt; "Your move: "; std::cin &gt;&gt; weapon; } while (weapon &lt; ROCK || weapon &gt; SPOCK); return weapon; } Weapon getOpponentWeapon() { return static_cast&lt;Weapon&gt;(1 + std::rand() % 5); } Outcome determineOutcome(PlayerMoves const&amp; playerMoves) { if (playerMoves.first == playerMoves.second) return DRAW; for (auto iter = possibleMoves.cbegin(); iter != possibleMoves.cend(); ++iter) { if (playerMoves == *iter) return WIN; } return LOSE; } int main() { std::srand(static_cast&lt;unsigned int&gt;(std::time(nullptr))); std::cout &lt;&lt; "Rock, Paper, Scissors, Lizard, Spock\n"; unsigned int playerScore = 0; unsigned int opponentScore = 0; for (;;) { Weapon playerWeapon = getPlayerWeapon(); Weapon opponentWeapon = getOpponentWeapon(); PlayerMoves playerMoves = std::make_pair(playerWeapon, opponentWeapon); std::cout &lt;&lt; "\n\nYou've picked : " &lt;&lt; playerWeapon; std::cout &lt;&lt; "\nComputer picked: " &lt;&lt; opponentWeapon; Outcome outcome = determineOutcome(playerMoves); switch (outcome) { case WIN: std::cout &lt;&lt; "\n\nYou win! Point awarded to you."; playerScore++; break; case LOSE: std::cout &lt;&lt; "\n\nYou lose! Point awarded to opponent."; opponentScore++; break; case DRAW: std::cout &lt;&lt; "\n\nIt's a draw! No points awarded."; break; default: throw std::logic_error("\n\ninvalid outcome"); break; } std::cout &lt;&lt; "\n\nPlay again (Y/N)? "; char choice; std::cin &gt;&gt; choice; if (choice == 'n' || choice == 'N') break; } std::cout &lt;&lt; "\n\nFinal Scores:\n\n"; std::cout &lt;&lt; "Player : " &lt;&lt; playerScore; std::cout &lt;&lt; "\nOpponent: " &lt;&lt; opponentScore; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T16:33:53.663", "Id": "59751", "Score": "0", "body": "If you reordered your enum to { Rock, Spock, Paper, Lizard, Scissors } you could use modular arithmetic to determine the winner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:33:35.837", "Id": "59772", "Score": "0", "body": "@MichaelUrman, how do you figure that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T01:22:12.853", "Id": "59799", "Score": "6", "body": "@Malachi, look at the winning combos. For clarity, repeat it out: Rock, Spock, Paper, Lizard, Scissors, Rock, Spock. With that ordering, each item loses to the next two in the list (or wins against the two right before it). So for example `bool defeats(Weapon2& a, Weapon2& b) { return ((5 + a - b) % 5) < 3; }`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T02:29:02.683", "Id": "59803", "Score": "0", "body": "I see what you mean. @MichaelUrman that is very interesting. I will have to look into that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T13:39:47.317", "Id": "59855", "Score": "0", "body": "@MichaelUrman Clever, but I don't think it's a winner in terms of extensibility. Picture updating the code to *Rock-Paper-Scissors-Lizard-Spock-Batman-SpiderMan-Wizard-Glock*.. still appealing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:21:40.650", "Id": "60012", "Score": "0", "body": "@retailcoder It's a tradeoff (and often the *worse* choice these days): harder to implement or read, but faster and smaller. Figuring out the pattern might be difficult, but for any set with a consistent pattern, you should be able to handle it with a `switch`. Once you leave consistent patterns, you need the full set of winning (or losing) combinations (or at least the exceptions). Still I find it enlightening to *consider* the transform; if RPSLSBSWG has a consistent pattern (was that the one with the wheel-like picture?), it would still be smaller and faster once properly ordered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-05T00:04:31.097", "Id": "106257", "Score": "0", "body": "@Mat'sMug Extending is a set difference exercise. Choose a symbol (Rock) and get the symbols it loses to (Paper, Spock). Get the symbols that each of those lose to and do a set difference against your chosen symbol (Paper={Lizard, Scissors}, Spock={Lizard}). The difference size defines your ordering ({Rock, Spock, Paper}). Use the calculated differences to generate the rest. Get the smallest difference list with an element, extract the element from all lists, and add the element to your result. Repeat until all lists are processed. RPSLSBSWG = {Rck, Spk, Bat, Glk, Ppr, Liz, Wiz, Spi, Sci}" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T07:48:28.183", "Id": "436905", "Score": "0", "body": "@MathieuGuindon It's in fact perfectly extensible. See http://www.umop.com/rps25.htm (there are variants with up to 101 \"weapons\"). ;-)" } ]
[ { "body": "<p>A few minor things:</p>\n\n<ol>\n<li><p>If you add a new weapon you have to remember to adjust the input loop</p>\n\n<pre><code>while (weapon &lt; ROCK || weapon &gt; SPOCK)\n</code></pre>\n\n<p>A solution to this problem is to have a <code>LAST</code> enum as well and new weapons should be inserted before that. Then the loop is</p>\n\n<pre><code>while (weapon &lt; ROCK || weapon &gt;= LAST)\n</code></pre></li>\n<li><p>I wouldn't call it <code>possibleMoves</code>. <code>(ROCK, ROCK)</code> is a possible move but it's not in the list. <code>winningMoves</code> would be more appropriate.</p></li>\n<li><p>You should be able to use <code>std::find</code> to find a winning move:</p>\n\n<pre><code>if (std::find(possibleMoves.cbegin(), possibleMoves.cend(), playerMoves) != possibleMoves.cend())\n return WIN;\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T01:56:46.077", "Id": "59715", "Score": "0", "body": "Ah, so that's how `std::find` should be used here. I was trying it myself, but I couldn't get it to work. The naming and `enum` are good points, too. It does look like a good idea to work with different weapons." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T01:44:02.557", "Id": "36440", "ParentId": "36435", "Score": "5" } }, { "body": "<p>The array does not seem like the logical choice for container.<br>\nYou are going to spend most of the time looking things up. This suggests that you need some form of map. Because of its size I would just use std::map. But you only have the true values stored so we only need to check for existence so we can use std::set instead.</p>\n\n<pre><code>const std::set&lt;PlayerMove&gt; possibleMoves =\n { std::make_pair(SCISSORS, PAPER),\n std::make_pair(PAPER, ROCK),\n std::make_pair(ROCK, LIZARD),\n std::make_pair(LIZARD, SPOCK),\n std::make_pair(SPOCK, SCISSORS),\n std::make_pair(SCISSORS, LIZARD),\n std::make_pair(LIZARD, PAPER),\n std::make_pair(PAPER, SPOCK),\n std::make_pair(SPOCK, ROCK),\n std::make_pair(ROCK, SCISSORS)\n };\n</code></pre>\n\n<p>Your test is now simplified too:</p>\n\n<pre><code>Outcome determineOutcome(PlayerMoves const&amp; playerMoves)\n{\n if (playerMoves.first == playerMoves.second)\n return DRAW;\n\n return possibleMoves.find(playerMoves) == possibleMoves.end()\n ? LOSE\n : WIN;\n}\n</code></pre>\n\n<p>I have a template to handle enum (so I don't need to re-write the same code all the time).</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;algorithm&gt;\n\nnamespace Serializer\n{\n template&lt;typename T&gt;\n struct SerializeTraits\n {};\n\n template&lt;typename T&gt;\n struct EnumSerializer\n {\n T value;\n EnumSerializer(T const&amp; v) : value(v) {}\n };\n template&lt;typename T&gt;\n struct EnumDeSerializer\n {\n T&amp; value;\n EnumDeSerializer(T&amp; v) : value(v) {}\n };\n\n template&lt;typename T&gt;\n EnumSerializer&lt;T&gt; makeEnumSerializer(T const&amp; v) {return EnumSerializer&lt;T&gt;(v);}\n template&lt;typename T&gt;\n EnumDeSerializer&lt;T&gt; makeEnumDeSerializer(T&amp; v) {return EnumDeSerializer&lt;T&gt;(v);}\n\n template&lt;typename T&gt;\n std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, EnumSerializer&lt;T&gt; const&amp; val)\n {\n return stream &lt;&lt; SerializeTraits&lt;T&gt;::names[static_cast&lt;int&gt;(val.value)];\n }\n template&lt;typename T&gt;\n std::istream&amp; operator&gt;&gt;(std::istream&amp; stream, EnumDeSerializer&lt;T&gt; const&amp; val)\n {\n typedef std::vector&lt;std::string&gt;::const_iterator Iter;\n\n std::string value;\n stream &gt;&gt; value;\n\n Iter find = std::find(std::begin(SerializeTraits&lt;T&gt;::names), std::end(SerializeTraits&lt;T&gt;::names), value);\n if (find == std::end(SerializeTraits&lt;T&gt;::names))\n { \n stream.setstate(std::ios::failbit);\n }\n else\n {\n val.value = static_cast&lt;T&gt;(std::distance(std::begin(SerializeTraits&lt;T&gt;::names), find));\n }\n\n return stream;\n }\n}\n</code></pre>\n\n<p>To use it you just need to declare a <code>SerializeTraits&lt;&gt;</code> for the enum type. In your case it looks like this:</p>\n\n<pre><code>enum Weapon {ROCK=1, PAPER, SCISSORS, LIZARD, SPOCK};\nnamespace Serializer\n{\n template&lt;&gt;\n struct SerializeTraits&lt;Weapon&gt;\n {\n static const std::vector&lt;std::string&gt; names;\n };\n}\nconst std::vector&lt;std::string&gt; Serializer::SerializeTraits&lt;Weapon&gt;::names = {\"\", \"ROCK\", \"PAPER\", \"SCISSORS\", \"LIZARD\", \"SPOCK\"};\n</code></pre>\n\n<p>Then reading and writting enum's become the same everywhere (and its handeled for you).</p>\n\n<pre><code>int main()\n{\n using namespace Serializer;\n std::cout &lt;&lt; makeEnumSerializer(ROCK);\n\n Weapon x;\n std::cin &gt;&gt; makeEnumDeSerializer(x);\n\n std::cout &lt;&lt; makeEnumSerializer(x);\n}\n</code></pre>\n\n<p>Also has the advantage that as you update the Weapons (and the associated name string) you do not need to modify code it will always stay in sync.</p>\n\n<h2>Answers to comments:</h2>\n\n<blockquote>\n <p>Unfortunately, I cannot std::set or std::vector with initialization I still don't have full access to C++11.</p>\n</blockquote>\n\n<h3>Alternative to Initialization list</h3>\n\n<pre><code>class MySetWithInit: public std::list\n{\n public: MySetWithInit()\n {\n insert(std::make_pair(SCISSORS, PAPER));\n insert(std::make_pair(PAPER, ROCK));\n insert(std::make_pair(ROCK, LIZARD));\n insert(std::make_pair(LIZARD, SPOCK));\n insert(std::make_pair(SPOCK, SCISSORS));\n insert(std::make_pair(SCISSORS, LIZARD));\n insert(std::make_pair(LIZARD, PAPER));\n insert(std::make_pair(PAPER, SPOCK));\n insert(std::make_pair(SPOCK, ROCK));\n insert(std::make_pair(ROCK, SCISSORS));\n }\n} possibleMoves; // Note variable declaration here.\n // This indicates type is being declared for this usage\n // only.\n</code></pre>\n\n<p>Note: normally you should not inherit from standard containers. This is a case where it is OK as there are no plans to re-use the type and it is not being deleted via a pointer to the base class. This should be placed in *.cpp file not a header.</p>\n\n<blockquote>\n <p>Until then, I'll either have to stay with std::array or just retrieve the set from a function (which I know is not efficient).</p>\n</blockquote>\n\n<h3>Is initialization from a function less effecient.</h3>\n\n<p>No. Not really. All modern C++ compilers have RVO and NRVO optimization as standard. This means if a function returns by value the compiler will more than likely elide the copy of the value out of the function, ie it effectively builds the value in place and no intermediate copies are used (this works through multiple levels of copying).</p>\n\n<blockquote>\n <p>I don't quite know what all this does, but I'll still try to learn.</p>\n</blockquote>\n\n<h3>Good.</h3>\n\n<p>But really there are just a couple of common tricks.</p>\n\n<ol>\n<li><p>Template traits class.<br>\nThe templatized version holds nothing (see <code>SerializeTraits</code>). But the code depends on particular values being there. So if you try and use it then compilation will fail. Thus to use the code you need to actually declare a template specialization explicitly for your class (see <code>SerializeTraits&lt;Weapon&gt;</code>).</p></li>\n<li><p>make_X function<br>\ntemplate functions can deduce their type based on the parmaeters passed to the function. While a class can not. So you can use template functions to create objects of the correct type without having to be explicit about it.</p></li>\n</ol>\n\n<blockquote>\n <p>As for the Serializer code, I assume this should go into a header and included</p>\n</blockquote>\n\n<h3>Yes just put the serialize code in a header file.</h3>\n\n<p>It will then work for all enum types you want.</p>\n\n<blockquote>\n <p>Now I just have to put in good input validation</p>\n</blockquote>\n\n<h3>Validation code with custom stream inputter.</h3>\n\n<p>When you write the stream input operator <code>operator&gt;&gt;</code> you should validate input and set the streams failbit as appropriate (I changed the code from yesterday to do this).</p>\n\n<p>Now detecting bad input and correcting for it is the same as any other type.</p>\n\n<pre><code>std::cout &lt;&lt; \"What Weapon do you want\\n\";\n\nWeapon weapon;\nstd::cin &gt;&gt; makeEnumDeSerializer(weapon);\nwhile(std::cin.fail())\n{\n std::cout &lt;&lt; \"That is not a valid Weapon\\n\";\n std::cin.clear();\n std::cin &gt;&gt; makeEnumDeSerializer(weapon);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T05:58:38.697", "Id": "59721", "Score": "0", "body": "Thanks. I don't quite know what all this does, but I'll still try to learn. Unfortunately, I cannot `std::set` or `std::vector` with initialization I still don't have full access to C++11. Until then, I'll either have to stay with `std::array` or just retrieve the set from a function (which I know is not efficient). As for the Serializer code, I assume this should go into a header and included." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T08:36:09.360", "Id": "59723", "Score": "0", "body": "There is an alternative for C++03 initialization (that initialization list replaces (because it is neater and shorter))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T18:03:57.743", "Id": "59759", "Score": "0", "body": "Okay, I have it working. It took me a while to realize that I'm now supposed to input the actual moves instead of corresponding numbers, which is nice. Now I just have to put in good input validation so that I can prevent the game from crashing. I may post a follow-up question sometime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T18:30:52.980", "Id": "59760", "Score": "0", "body": "@Jamal: Another update on input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T05:43:06.043", "Id": "59816", "Score": "0", "body": "Okay, now the input validation works! I just now caught your note about the change in the earlier code. That also explains why I kept getting an exception. I'll surely hold onto this `Serializer` for other uses." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T05:19:47.800", "Id": "36444", "ParentId": "36435", "Score": "12" } } ]
{ "AcceptedAnswerId": "36444", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T21:39:58.303", "Id": "36435", "Score": "18", "Tags": [ "c++", "game", "c++11", "community-challenge", "rock-paper-scissors" ], "Title": "Rock-Paper-Scissors-Lizard-Spock challenge in C++" }
36435
<p>Can anyone review my program and state where I could improve it, even in terms of comments, validation, etc?</p> <pre><code>package assessed_practical_2; //Importing Resources (Random) import java.util.Random; //Importing Resources (Scanner) import java.util.Scanner; public class Assignment2 { /** * Scanner used for input within program */ public static Scanner scanner = new Scanner(System.in); /** * Main method that provides user with a menu in which each number * represents a different method (e.g addtion) that they can carry out */ public static void main(String[] args) { try { // Declare variable for user's option and defaulting to 0 int menuOption = 0; do { // Setting menuOption equal to return value from showMenu(); menuOption = showMenu(); // Switching on the value given from user switch (menuOption) { case 1: add(); break; case 2: subtract(); break; case 3: guessRandomNumber(); break; case 4: printLoop(); break; case 5: System.out.println("Quitting Program..."); break; default: System.out.println("Sorry, please enter valid Option"); }// End of switch statement } while (menuOption != 5); // Exiting message when user decides to quit Program System.out.println("Thanks for using this Program..."); } catch (Exception ex) { // Error Message System.out.println("Sorry problem occured within Program"); // flushing scanner scanner.next(); } finally { // Ensuring that scanner will always be closed and cleaning up // resources scanner.close(); } }// End of main Method /** * Method that prints menu to screen and gets returns user's option from menu * @return Returns user Option */ public static int showMenu() { // Declaring var for user option and defaulting to 0 int option = 0; // Printing menu to screen System.out.println("Menu:"); System.out.println("1.Add"); System.out.println("2.Subtract"); System.out.println("3.Guess a Random Number"); System.out.println("4. Print many times"); System.out.println("5. Quit Program"); // Getting user option from above menu System.out.println("Enter Option from above..."); option = scanner.nextInt(); return option; }// End of showMenu /** * Method that adds two random numbers (from 1-100) and take a user guess * for the addition.Then outputs certain statements dependent if user guess * is correct or not. */ public static void add() { // Setting up new random Random random = new Random(); // Declaring Integers int num1; int num2; int result; int input; //defaulting input to 0 input = 0; // Declaring boolean for valid user answer (Defaulted to false) boolean validAnswer = false; //Declaring boolean for correct user answer (default to false) boolean correctAnswer=false; do { // Create two random numbers between 1 and 100 num1 = random.nextInt(100); num1++; num2 = random.nextInt(100); num2++; //Do while loop that loops until user gives valid input do { //validAnswer set to true to avoid infinite loop validAnswer = true; // Displaying numbers for user and getting user input for answer System.out.println("Adding numbers..."); System.out.printf("What is: %d + %d? Please enter answer below", num1,num2); result = num1 + num2; try { input = scanner.nextInt(); } catch (Exception ex) { // Print error message System.out.println("Sorry, Invalid entry for Addition...Please Retry!"); // flush scanner scanner.next(); validAnswer = false; } } while (!validAnswer); // Line break for code clarity System.out.println(); // if else statement to determine if answer is correct if (result == input) { System.out.println("Well done, you guessed corectly!"); correctAnswer = true; } else { System.out .println("Sorry incorrect, Please guess another Addition"); correctAnswer = false; } } while (!correctAnswer); }// End of add /** * Method that subtracts two random numbers (from 1-100) and takes a user * guess for the subtraction. Then outputs certain statements dependent if * user guess is correct or not. */ public static void subtract() { // Setting up random Random random = new Random(); // Declaring Integers int num1; int num2; int result; int input; //set input to 0 input = 0; // Declaring boolean for validity of userAnswer (Defaulted to false) boolean validAnswer = false; //Declaring boolean for correct user answer (default to false) boolean correctAnswer=false; do { // Create two random numbers between 1 and 100 num1 = random.nextInt(100); num1++; num2 = random.nextInt(100); num2++; do { // Set correctAnwer to true to avoid infinite iterations validAnswer = true; // Displaying numbers for user and getting user input for answer System.out.println("Subtracting numbers..."); System.out.printf("What is: %d - %d? Please enter answer below", num1,num2); result = num1 - num2; try { input = scanner.nextInt(); } catch (Exception ex) { // Print error message System.out.println("Sorry, Invalid entry entry for subtraction...Please retry!"); // flush scanner scanner.next(); validAnswer = false; } } while (!validAnswer); // Line break for code clarity System.out.println(); // if else statement to determine if answer is correct if (result == input) { System.out.println("Well done, you guessed corectly!"); correctAnswer = true; } else { System.out.println("Sorry incorrect, Please attempt another subtraction"); correctAnswer = false; } } while (!correctAnswer); }// end of subtract /** * A method that generates a random number between 1 and 10 * @return randomNumber (Returns random number between 1 and 10 inclusive) */ public static int generateRandomNumber() { //setting up random Random random = new Random(); // Declaring int for random number and defaulting to 0 int randomNumber = 0; // Assigning randomNumber between 1 and 10 randomNumber = random.nextInt(10); randomNumber++; //Trace code, Remember to take out! System.out.println("Trace: Random no is:" + randomNumber); return randomNumber; }// end of generateRandomNumber /** * Method that allows user to guess a random number between a set range. A * message will then be displayed on screen to let them know if they were * correct or not. */ public static void guessRandomNumber() { // declare var for user guess and default to zero int userGuess = 0; // declare boolean relating to if number is valid boolean validNumber = false; // declare boolean relating to if guess is correct boolean correctGuess = false; // declaring int equal to return value from generateRandomNumber(); int secretNumber = generateRandomNumber(); //Do while loop that runs until user guesses correctly do { //Do while loop that runs until a valid entry is given (i.e. int) do { try { //do while loop ensuring that user guess is between 1 and 10 do { // Get user guess (between 1 and 10) System.out.println("Please enter a number between 1 and 10..."); userGuess = scanner.nextInt(); if (userGuess &lt; 1 || userGuess &gt; 10) { validNumber = false; System.out.println("Please Ensure number is between 1 and 10"); }else { validNumber=true; } } while (!validNumber); } catch (Exception ex) { //Print error message System.out.println("Sorry invalid entry..."); // Flush scanner scanner.next(); validNumber = false; } } while (!validNumber); //If else statement that outputs a message informing user if guess correct if (userGuess == secretNumber) { System.out.println("Guess correct, well done!"); correctGuess = true; } else { System.out.println("Sorry guess Incorrect please try again!"); correctGuess = false; } } while (!correctGuess); }// end ofGuessRandomNumber /** * Method that allows user to enter a string they want and print it a * certain no of times */ public static void printLoop() { // Declaring and initialising Variables int noOfTimes = 0; String print = null; try { System.out.println("Please enter what you would like to print"); print = scanner.next(); } catch (Exception ex) { //error message System.out.println("Please give a Valid Entry..."); // flush scanner scanner.next(); } System.out.println("Please enter how many times you wish to print..."); noOfTimes = scanner.nextInt(); for (int counter = 0; counter &lt; noOfTimes; counter++) { System.out.println(print); } }// End of printLoop }// End of Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T22:30:30.310", "Id": "59701", "Score": "1", "body": "Have you handed in this homework yet?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T22:36:23.740", "Id": "59704", "Score": "0", "body": "No no yet lol, Why do you ask?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T23:31:49.470", "Id": "59712", "Score": "0", "body": "I'm grateful that you accepted my answer. But, I would suggest that you hold off on accepting so soon -- when people see that an answer is accepted it reduces their incentive to answer themselves. So, in future, think about waiting a bit to see if more answers (hopefully better ones) come in. Still, thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:28:21.927", "Id": "60221", "Score": "0", "body": "I know Profs an TAs might require you comment *EVERYTHING*, but never put inane comments in your code in real life. Everyone knows `import x` imports x, and `switch(x)` switches on x." } ]
[ { "body": "<p>First thoughts:</p>\n\n<p>You have this whole thing as all static. That's fine for a small simple program like this, but it might be better practice for you to make most of the methods into instance methods, and then in <code>main()</code>, instantiate it and call a driver method on that class. Static things can get messy in java when the logic gets more complicated. So, I would pull out most of the stuff that you have in your main method and put it into an instance method.</p>\n\n<pre><code>public static void main(String[] args) {\n Assignment2 assignment = new Assignment2();\n assignment.start();\n}\n</code></pre>\n\n<p>Also, unless you're required to have your class named Assignment2, I would suggest changing it to something more descriptive (it should tell you what it <em>does</em> not what it <em>is</em>).</p>\n\n<p>Might want to rename a few methods also. For example, <code>showMenu()</code> doesn't just show a menu, it also gets input from the user, so maybe rename that to something like <code>getSelection()</code> (or something).</p>\n\n<p>Let's talk about your <code>add()</code> method.</p>\n\n<pre><code> do {\n num1 = random.nextInt(100);\n num1++;\n num2 = random.nextInt(100);\n num2++;\n\n do {\n validAnswer = true;\n\n System.out.println(\"Adding numbers...\");\n System.out.printf(\"What is: %d + %d? Please enter answer below\", num1,num2);\n result = num1 + num2;\n try {\n input = scanner.nextInt();\n } catch (Exception ex) {\n System.out.println(\"Sorry, Invalid entry for Addition...Please Retry!\");\n scanner.next();\n validAnswer = false;\n }\n } while (!validAnswer);\n</code></pre>\n\n<p>Instead of assigning num1 and num2 on one line, and on the next, incrementing them, put that on one line. </p>\n\n<pre><code>num1 = random.nextInt(100) + 1;\nnum2 = random.nextInt(100) + 1;\n</code></pre>\n\n<p>Also, some minor issues with spacing. Change <code>boolean correctAnswer=false;</code> to <code>boolean correctAnswer = false;</code></p>\n\n<p>Also, it's bad practice to catch <code>Exception</code>. Catch and handle only the ones you expect to deal with -- If Java makes you surround something with a try catch, <em>only catch the ones you need to catch and are prepared to handle</em>. The way you're doing it, if something throws a null pointer exception, your program won't give you useful crash reporting. I <em>think</em> what you really want to catch is <code>InputMismatchException</code>. So, catch that or leave an explanation as to why you're swallowing all exceptions in a comment.</p>\n\n<p>Your <code>add()</code> and <code>subtract()</code> methods are pretty much exactly the same. You should think about making them into one method that accepts an argument for which behaviour to exhibit.</p>\n\n<p>You spend a lot of lines getting and validating input from the user. Think about writing a helper function to do that all in one place:</p>\n\n<pre><code>private int getInt(String message, int low, int high) {\n int num;\n boolean invalid = true;\n\n do {\n System.out.printf(\"Please enter an integer between %d and %d: \");\n\n try {\n num = scanner.nextInt();\n\n if (num &gt;= low &amp;&amp; num &lt;= high) {\n invalid = false;\n }\n }\n catch (InputMismatchException x) {\n System.out.println(\"Invalid entry, please try again\");\n }\n } while (invalid);\n}\n</code></pre>\n\n<p>Something like that (if you need to use a do-while. Personally, I try to avoid them but it looks like you like them, and maybe it's part of your assignment).</p>\n\n<p>Those are just a few things that I would suggest you think about. The main problems I see mostly relate to code duplication, so really think about ways to reduce that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T23:26:00.777", "Id": "59711", "Score": "0", "body": "Note, also, that the way my `getInt()` is written isn't ideal -- in particular, there's no point in having the `invalid` flag since basically it just infinite loops until something valid is entered. That's just meant as a starting point." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T23:15:44.423", "Id": "36437", "ParentId": "36436", "Score": "4" } }, { "body": "<p>Minor comments here since scott_fakename has provided a pretty good start...</p>\n\n<p>Extract the user input part from <code>show_menu</code> into its own method, so that each method is only dealing with one thing.</p>\n\n<p>You have some idea of showing 'tracing' messages for debugging/troubleshooting, ever considered using a logging framework? Not sure if this is beyond what you need to hand in this assignment, just a thought...</p>\n\n<p>I also think using one static class-wide <code>Random</code> instance is good enough for all the random number generation.</p>\n\n<p>As for consolidating <code>add</code> and <code>subtract</code> methods into a single one that takes an extra parameter to control the calculation, you can consider using enumerations to indicate the different modes. E.g.:</p>\n\n<pre><code>enum Mode {\n ADD, SUBTRACT;\n}\n\n...\n\npublic void calculation(Mode mode) {\n ...\n int num1, num2, result;\n ...\n switch (mode) {\n case ADD:\n result = num1 + num2;\n break;\n case SUBTRACT:\n result = num1 - num2;\n break;\n }\n ...\n}\n</code></pre>\n\n<p>In fact you'll probably want to keep this as a simple method itself (similar to your <code>generateRandomNumber</code>, and have an outside method to get the user input (following scott_fakename's suggestion) to do the comparison.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T02:11:24.283", "Id": "36481", "ParentId": "36436", "Score": "2" } } ]
{ "AcceptedAnswerId": "36437", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T22:07:56.580", "Id": "36436", "Score": "6", "Tags": [ "java" ], "Title": "Review of \"Menu program\"" }
36436
<p>Continuing the spirit of the recent Weekend Challenge, here is a revised version of the RPSLS game.</p> <p>This is a follow up to my previous submission:</p> <p><a href="https://codereview.stackexchange.com/questions/36394/rock-paper-scissors-lizard-spock-as-a-code-style-and-challenge">Rock Paper Scissors Lizard Spock as a code-style and challenge</a></p> <p>This version is revised to accommodate the following suggestions:</p> <ol> <li>Model revised to abstract the display mechanism from the game engine.</li> <li>Removed static method calls where appropriate</li> <li>fixed bugs with binary search</li> <li>included the 'verb' component of 'Rock <strong>crushes</strong> Scissors'</li> <li>tracked the scoring inside each player rather than in the main method.</li> <li>removed magic number abuse.</li> </ol> <p>I have implemented both a console-based and GUI (Swing) based interface for the game. This is an image of the GUI. The fine-tuning of the layout is not complete, but that is not a priority for me in terms of a review (The icons here (CC-attribution) <a href="http://en.wikipedia.org/wiki/File:Pierre_ciseaux_feuille_l%C3%A9zard_spock_aligned.svg" rel="nofollow noreferrer">come from Wikipedia</a> ):</p> <p><img src="https://i.stack.imgur.com/sqPNR.png" alt="RPSLS GUI in Swing"></p> <p>To accomodate the suggestions above I have separated the logic in to a number of classes. The following are the core classes (does not include the GUI and Console interfaces). If there's any cool ideas in here that you may feel have been copied from other submissions, then you are probably right... </p> <p><strong>Weapon.java</strong></p> <pre><code>package rpsls; import java.util.HashMap; import java.util.Map; /** * Set up the rules for the game. * What are the moves, and what beats what (and how)! */ public enum Weapon { Rock, Paper, Scissors, Lizard, Spock; static { /* * 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. * Rd. Cooper */ Scissors.will("cut", Paper); Paper.will("covers", Rock); Rock.will("crushes", Lizard); Lizard.will("poisons", Spock); Spock.will("smashes", Scissors); Scissors.will("decapitate", Lizard); Lizard.will("eats", Paper); Paper.will("disproves", Spock); Spock.will("vaporizes", Rock); Rock.will("smashes", Scissors); } // what will this move beat - populated in static initializer // cannot use enummap... recursive constructors otherwise. private final Map&lt;Weapon, String&gt; ibeat = new HashMap&lt;&gt;(); private void will(String verb, Weapon move) { ibeat.put(move, verb); } /** * Return a non-null 'verb' if this Move will beat the supplied move * @param move the move we hope to beat * @return the verb if we beat that move i.e. if we are Rock, we will return 'crushes' if the input move is 'Scissors'. */ public String beats(Weapon move) { // use binary search in case someone wants to set up crazy rules. return ibeat.get(move); } } </code></pre> <p><strong>PlayerListener.java</strong></p> <pre><code>package rpsls; public interface PlayerListener { void wonGame(Player abstractPlayer, Weapon mine, String verb, Weapon theirs); void wonSet(Player abstractPlayer); void resetGames(Player abstractPlayer); } </code></pre> <p><strong>Player.java</strong></p> <pre><code>package rpsls; import java.util.ArrayList; public abstract class Player { private final String name; private int games = 0; private int sets = 0; private final ArrayList&lt;PlayerListener&gt; listeners = new ArrayList&lt;&gt;(); public Player(String name) { this.name = name; } public void addListener(PlayerListener listener) { listeners.add(listener); } @Override public String toString() { return String.format("%s Games %d Sets %d", name, games, sets); } public final void wonGame(Weapon mine, String verb, Weapon theirs) { games++; for (PlayerListener pl : listeners) { pl.wonGame(this, mine, verb, theirs); } } public final void wonSet() { sets++; for (PlayerListener pl : listeners) { pl.wonSet(this); } } public String getName() { return name; } public int getGames() { return games; } public int getSets() { return sets; } public void resetGames() { games = 0; for (PlayerListener pl : listeners) { pl.resetGames(this); } } public abstract Weapon nextMove(); } </code></pre> <p><strong>ComputerPlayer.java</strong></p> <pre><code>package rpsls; import java.util.Random; public class ComputerPlayer extends Player { private final Random random = new Random(); private Weapon[] weapons = Weapon.values(); public ComputerPlayer() { super("Computer"); } @Override public Weapon nextMove() { return weapons[random.nextInt(weapons.length)]; } } </code></pre> <p><strong>HumanPlayer.java</strong></p> <pre><code>package rpsls; public class HumanPlayer extends Player { private final HumanInteraction input; public HumanPlayer(String name, HumanInteraction input) { super(name); this.input = input; } @Override public Weapon nextMove() { return input.getWeapon(); } } </code></pre> <p><strong>HumanInteraction.java</strong></p> <pre><code>package rpsls; public interface HumanInteraction { public Weapon getWeapon(); public boolean playAgain(); public Player getHumanPlayer(); public void draw(Weapon weapon); public void exiting(); } </code></pre> <p>and the main class</p> <p><strong>RPSLS.java</strong></p> <pre><code>package rpsls; /** * Rock Paper Scissors Lizard Spock * &lt;p&gt; * http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock * &lt;p&gt; * Interface for a human to play against the computer. * * @author rolf * */ public class RPSLS { /** * Run the game.... Good Luck! * @param args these are ignored. */ public static void main(String[] args) { final boolean gui = args.length == 0 || "gui".equals(args[0]); final int firstto = 2; // winner is the first to this. final Player computer = new ComputerPlayer(); final HumanInteraction interaction = gui ? new HumanGUI(computer) : new HumanConsole(computer); // human is not created by default because the interaction level can give them their name. final Player human = interaction.getHumanPlayer(); do { // like tennis, with games, and sets. // best of 3 (first to 2) games wins a set. human.resetGames(); computer.resetGames(); setloop: do { // The computer chooses their weapon. final Weapon compweap = computer.nextMove(); // the human chooses thir weapon final Weapon humanweap = human.nextMove(); if (humanweap == null) { // the user quits. break setloop; } String verb = null; if ((verb = humanweap.beats(compweap)) != null) { human.wonGame(humanweap, verb, compweap); } else if ((verb = compweap.beats(humanweap)) != null){ computer.wonGame(compweap, verb, humanweap); } else { interaction.draw(humanweap); } // play until someone scores 2.... best-of-three } while (human.getGames() != firstto &amp;&amp; computer.getGames() != firstto); if (human.getGames() == firstto) { human.wonSet(); } else { // including if human quits. computer.wonSet(); } } while (interaction.playAgain()); interaction.exiting(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:33:38.630", "Id": "59843", "Score": "0", "body": "Who is supposed to listening the `Player`s?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T11:39:39.080", "Id": "59848", "Score": "0", "body": "The human-interface (both the text console and the GUI) listen to each player, and use the events from the player to update the scores and, in the case of the GUI, trigger the 'win' event" } ]
[ { "body": "<ul>\n<li><p>Love the way you're using <code>HashMap</code> to provide the strings for the items. But in the UI, how would it look if you pick Spock and computer picks Lizard? Does it swap the positions for you? Or should it say \"Spock <em>gets poisoned by</em> Lizard\"? (I'm not sure of what's the best way is to solve this myself, but it is something to think about).</p></li>\n<li><p>It is more preferable to declare <code>List</code>s by interface instead of implementation. So that, if you want to switch implementation, it's enough to swap at one place (the <code>new ArrayList</code>) instead of two.</p>\n\n<pre><code>private final ArrayList&lt;PlayerListener&gt; listeners = new ArrayList&lt;&gt;(); // Bad\n\nprivate final List&lt;PlayerListener&gt; listeners = new ArrayList&lt;&gt;(); // Good\n</code></pre></li>\n<li><p>Your <code>RPSLS</code> class only contains one big <code>main</code> method. And I still think that it does too much. <code>RPSLS</code> could instead be the game class, and the <code>main</code> method splitted into a couple of methods within the class.</p></li>\n</ul>\n\n<p>Overall, I'd say your code looks great. Well done. Good use of interfaces. Good use of different classes and methods. It's been a pleasure reading your code. A great improvement compared to the previous version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T15:59:29.543", "Id": "59746", "Score": "1", "body": "In the GUI, it puts the winner's icon first, and puts the winner's name above, so it would say 'Computer Wins' and have Lizard poisons Spock" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T18:34:30.777", "Id": "59761", "Score": "0", "body": "@rolfl Good, then you have already thought about it. As I've already said, well done :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T14:37:50.023", "Id": "36455", "ParentId": "36438", "Score": "6" } }, { "body": "<p>I agree with Simon in that you should extract game logic in a separate class, which would be your <em>Model</em> component of your applications the MVC.</p>\n\n<pre><code>// The computer chooses their weapon.\nfinal Weapon compweap = computer.nextMove();\n// the human chooses thir weapon\nfinal Weapon humanweap = human.nextMove();\nif (humanweap == null) {\n // the user quits.\n break setloop;\n}\n</code></pre>\n\n<p>The game logic shouldn't care whether the players are human or computer (violating Lyskov's substitution principle). For example setting the game up with two computer players should not be just easy, it should be trivial. Also that <code>Player.nextMove()</code> can return null cannot be inferred by looking at the <code>Player</code> class only. A better way is to make <code>nextMove()</code> throw an exception, such as <code>PlayerQuitsException</code>, which not only make the contract explicit, it would also obviate the <code>// the user quits.</code> comment and the labeled break statement with a catch block. Moreover, a <code>Player</code> quitting when we expect his <code>nextMove</code> also sounds like an <code>exception</code>al situation to me.</p>\n\n<p>The following part doesn't read well: </p>\n\n<pre><code>String verb = null; \nif ((verb = humanweap.beats(compweap)) != null) {\n human.wonGame(humanweap, verb, compweap);\n} else if ((verb = compweap.beats(humanweap)) != null){\n computer.wonGame(compweap, verb, humanweap);\n} else {\n interaction.draw(humanweap);\n}\n</code></pre>\n\n<p>Note how data flow of the variable <code>verb</code> is complicated. And doesn't translate to human language. Because it stands in for some other concept <em>left implicit</em> in this snippet, namely a <strong>turn outcome</strong>. </p>\n\n<p>Also note the repetition in the first two if clauses. </p>\n\n<p>Also note that we're passing arguments to the player class that it does not care.</p>\n\n<p>compare:</p>\n\n<pre><code>Outcome outcome = getOutCome(player1, move1, player2, move2);\nraiseEvent(new TurnEnded(outcome)); // update view etc\n\n// you need not call this explicitly \n// if you make the Player a listener of outcome events\n// and handle it there\nif (outcome.isNotDraw()) {\n outcome.getWinner().wonGame();\n}\n</code></pre>\n\n<p>similar problems here:</p>\n\n<pre><code>} while (human.getGames() != firstto &amp;&amp; computer.getGames() != firstto);\nif (human.getGames() == firstto) {\n human.wonSet();\n} else {\n // including if human quits.\n computer.wonSet();\n}\n</code></pre>\n\n<p><code>Player</code> class[es] do both interaction with outside world (IO or random number generator) and score keeping (violating Single responsibility principle). </p>\n\n<p>compare:</p>\n\n<pre><code>} while (scoreKeeper.gameHasNotEnded());\n\nraiseEvent(new GameEnded(scoreKeeper.getGameOutcome())); // update view etc\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:10:59.487", "Id": "59867", "Score": "0", "body": "Huh. Just when you think you've squeezed all the juice out of something, someone manages to squeeze out a bunch more. The Exception-exit from Player is so logical (why did I not think of it). The Outcome and ScoreKeeper classes are also sensible. In my head the main() method is simple, but I can see how these changes would make it even more simple (although, at that point there ends up being more abstraction than program .... ;-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:58:53.563", "Id": "36512", "ParentId": "36438", "Score": "4" } } ]
{ "AcceptedAnswerId": "36455", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T23:59:58.257", "Id": "36438", "Score": "14", "Tags": [ "java", "game", "community-challenge", "rock-paper-scissors" ], "Title": "Rock Paper Scissors Lizard Spock Revisited" }
36438
<p>Time is very important from times immemorial. Doing great things and making it happen in less time is more important as it can mean less effort. So I really like to know which way is faster and more efficient in the following codes, and I would happy to know any other way we can achieve the same code: </p> <pre><code>$month=date('m'); //Using If..else if($month==1){ echo "January"; }elseif($month==2){ echo "February"; }elseif($month==3){ echo "March"; }elseif($month==4){ echo "April"; }elseif($month==5){ echo "May"; }elseif($month==6){ echo "June"; }elseif($month==7){ echo "July"; }elseif($month==8){ echo "August"; }elseif($month==9){ echo "September"; }elseif($month==10){ echo "October"; }elseif($month==11){ echo "November"; }else{ echo "December"; } </code></pre> <pre><code>//Using Switch switch($month){ case 1: echo "January"; break; case 2: echo "February"; break; case 3: echo "March"; break; case 4: echo "April"; break; case 5: echo "May"; break; case 6: echo "June"; break; case 7: echo "July"; break; case 8: echo "August"; break; case 9: echo "September"; break; case 10: echo "October"; break; case 11: echo "November"; break; default: echo "December"; break; } </code></pre> <pre><code>//Using Array $month_s=array(1=&gt;"January",2=&gt;"February",3=&gt;"March",4=&gt;"April",5=&gt;"May",6=&gt;"June", 7=&gt;"July",8=&gt;"August",9=&gt;"September",10=&gt;"October",11=&gt;"November",12=&gt;"December"); echo isset($month_s[$month]) ? $month_s[$month] : ''; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T12:00:20.047", "Id": "59727", "Score": "5", "body": "write a script, use `$start = microtime(true)` and then `microtime(true) - $start` to get a rough idea of the time each approach takes, and you have your answer. Do try with a larger array, too" } ]
[ { "body": "<p>Like I said in my comment: If you want to know which is faster, write a benchmarking script, it's <em>that</em> easy:</p>\n\n<pre><code>$start = microtime(true);\n//if-hell approach\n$ifs = microtime(true) - $start;\n$start = microtime(true);\n//switch\n$switch = microtime(true) - $start;\n$start = microtime(true);\n//array\n$array = microtime(true) - $start;\n</code></pre>\n\n<p>Then compare and echo the results in any way you like.<br/>\nMy gut tells me that in this case, the <code>switch</code> will probably be the faster option. Considering a switch construction is sort of like labeling blocks of code, and then do some sort of eval-go-to thingy.<Br/>\nBranching (<code>if</code>) is faster in terms of compilation, perhaps, but for the month of december, you'll end up performing <em>all</em> if statements.<Br/>\nThe array approach, for this example, doesn't look like the fastest approach you can take in this case, because it's constructing an array, performing a HashTable lookup, evaluate the result of that lookup, then <em>perform the same lookup again</em>, or return an empty string. HashTable lookups are as fast as it gets, of course, but still, you're having to do 2 of them, just <em>after you've constructed the HashTable</em>. The other approaches don't construct to <em>then</em> perform a lookup.</p>\n\n<p>Mind you, This is micro-optimization of the worst kind. It's completely pointless and the speed difference won't be noticeable. Especially if you use some form of OP-Code caching (APC, for example). That should be the first port of call if you're trying to optimize some code.</p>\n\n<p><em>What code should you use?:</em><br/>\nThis is the better question to ask. The efficiency of some snippet of code isn't just determined by the time it takes to execute. Efficient code is good code (is stable, performant, error and notice-free) and is <strong><em>easy to read, update and maintain</em></strong>.<br/>\nIf your determining the name of the month then it's pretty obvious the data-set is limited to 12 valid strings. But in most cases, you might end up with an ever growing <code>switch</code> or <code>if-elseif-else</code> tree. That's <em>not</em> efficient coding. The moment you have to scroll to see a single block of code, you can safely say it's time to think about refactoring your code.</p>\n\n<p>That's why I'd either use the array approach (works just as well when data is coming from a query, so you can create a function that you can reuse). Or, if you <em>are</em> working on dates, I'd give way to <em>normalization</em>, and use <a href=\"http://us3.php.net/manual/en/class.datetime.php\">the <code>DateTime</code> class</a>. when I see <code>new DateTime</code> or <code>$d = DateTime::createFromFormat</code>, I know what to exepct. Even more so when I see:</p>\n\n<pre><code>[public] function doStuff(DateTime $date)\n{\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T13:06:26.883", "Id": "59730", "Score": "0", "body": "thank you very much. I used to think that good codes use less time and effort. The code I provided is just an example. So do I prefer Array. My experience in php is just 11 months old. Does it mean putting codes into functions or objects when you said about 'codes refactoring'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T13:49:27.463", "Id": "59734", "Score": "1", "body": "@MawiaHL: the term _\"refactoring code\"_ can mean a variety of things: A new version of PHP is deployed and some extension (like `mysql_*`) are deprecated, the process of removing all calls to that extension is _refactoring the code_. If some intern wrote a script that doesn't match the coding standards you uphold, that script has to be normalized, in doing so, you tend to optimize some sections of that script, this, too, is refactoring. If you've got some code, and want to make it OO, then you'll have to refactor it, too, but in that case, I'd rather call it a rewrite :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:30:19.803", "Id": "59771", "Score": "0", "body": "A look up array OR a list would be the most efficient way of doing it. I'm tending towards the list more than array tbh though I think that's just personal habit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:45:40.920", "Id": "59773", "Score": "1", "body": "@Dave: A PHP array is what you'd call a list or vector in most other languages. Even so: the lookup will be fast, but you have to take the constructing of that list into account, too. Either way, I'd use an array for this, too: it's the more scalable/maintainable approach for something like this. When the choice is between an ever growing switch or an array, go with the A-team :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T08:53:55.113", "Id": "59832", "Score": "0", "body": "@elias in most other languages array is not the same as list<T> adding/removing/resizing arrays is typically expensive in language terms lists not so much so. Although they look/behave similar to the end user they're distinctly different. However in this instance either would be just fine the discussions of list vs array are for a different time" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T09:06:53.447", "Id": "59833", "Score": "0", "body": "@Dave: Granted. I was referring to, what is called an array in PHP would be a List in languages such as Java (eg an array of objects). An array of zend objects needn't be stored as a contiguous block in memory, yet it'll use an array of pointers instead. It's just one of those internal things you don't (need?) to know about when writing in PHP, but yes, the discussion on what is an array and what is a list is going a tad off-topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T09:24:39.560", "Id": "59834", "Score": "0", "body": "@EliasVanOotegem its actually very amusing with php arrays aren't really arrays so I suppose in terms relevent to this question there's no real advantage to list over array and either would work just fine. I'm a c/c++ and c# before php person so to me they're distinctly different" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T09:32:37.083", "Id": "59835", "Score": "0", "body": "@Dave: To be honest, I started as a PHP developer, but as of late, I've been tinkering with C quite a bit, and I've come to understand what a _well designed_ language actually entails. I, too, prefer C over PHP (who wouldn't), but for the OP, I'm assuming the internals aren't on the table yet, and to be frank, I'm not too _\"at home\"_ in C either to claim I fully understand how PHP implements arrays (HashTable with zval pointers AFAIK... but I could be wrong)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T09:47:17.837", "Id": "59836", "Score": "2", "body": "@EliasVanOotegem still puts you 90% of the way ahead of everyone else though :) I'm fairly new to php only really been using it 6 years or so. Coming from an out of order language though something that always makes me laugh is \"oo php\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:24:13.330", "Id": "59840", "Score": "0", "body": "@Dave: :D PHP was designed by afterthought, so OOP is in some respects a natural addition to the language. Still, for all its down-sides, I've had to work with COBOL in the past, after which PHP still feels like a breath of fresh air. COBOL is the ultimate proof that a designed language isn't necessarily better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:25:17.797", "Id": "59841", "Score": "0", "body": "Indeed just look at java for a poster child of horrible languages :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:28:52.197", "Id": "59842", "Score": "0", "body": "@Dave: Rofl! Just read the _stuff I find to be true_ part on my stackoverflow profile, you'll see how much I loathe Java! But still, in spite of what some prominent people have said, _\"The venom of Java spreadeth\"_" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T12:19:34.133", "Id": "36450", "ParentId": "36447", "Score": "8" } }, { "body": "<p>Neither will be simpler than using the <a href=\"http://php.net/manual/en/function.date.php\">date</a> function's <code>F</code> code, and I'd bet $5* this would be faster than both.</p>\n\n<pre><code>$month = date('F');\n</code></pre>\n\n<p>For example,</p>\n\n<pre><code>&gt; echo date('F');\nNovember\n</code></pre>\n\n<p>* Coincidentally, $5 is the maximum amount of money you should spend trying to optimize this code. ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T20:21:38.233", "Id": "36466", "ParentId": "36447", "Score": "8" } } ]
{ "AcceptedAnswerId": "36450", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T11:57:23.090", "Id": "36447", "Score": "1", "Tags": [ "performance", "php", "datetime", "comparative-review" ], "Title": "Translating month number into month name" }
36447
<p>I know that there are several ways to handle exceptions and probably a good way is to keep the handling consistently and use the pattern which feels comfortable for himself, but I would like to get some advice or hints, what would you do in following situation or how I could improve such a case.</p> <p>I created a custom URLClassLoader which checks the certification and some advanced stuff. With following function I load the X509 certificate into the instance:</p> <pre><code>public boolean loadX509Certificate(File file) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream is = new FileInputStream(file); this.setCertificate(cf.generateCertificate(is)); is.close(); } catch (CertificateException e) { return false; } catch (FileNotFoundException e) { return false; } catch (SecurityException e) { return false; } catch (IOException e) { return false; } return true; } </code></pre> <p>In that function I catch four exceptions, what would you do in this situation? Return false if the certificate cannot load, rethrow the exception or create a custom exception which tells the user what went wrong?</p> <p>In generally the Class will work without the certification, but if the value doesn't exist, the class will not check the classes and resources signature.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:50:29.553", "Id": "59775", "Score": "1", "body": "You may want to wrap `is.close()` in a `try-catch` to separate important I/O errors while reading vs. those you can ignore when closing the stream." } ]
[ { "body": "<p>For Java 7 source code type You could use multicatch.\n<a href=\"http://www.baptiste-wicht.com/2010/05/better-exception-handling-in-java-7-multicatch-and-final-rethrow/\" rel=\"nofollow\">http://www.baptiste-wicht.com/2010/05/better-exception-handling-in-java-7-multicatch-and-final-rethrow/</a></p>\n\n<p>Personally I would log this error and return false.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T23:55:02.687", "Id": "59789", "Score": "1", "body": "I recommend changing the reference document to official, and more complete reference document: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T23:58:10.667", "Id": "59790", "Score": "1", "body": "In fact, I disagree with some of the semantics in that referenced article... catching `Throwable` ... really?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T06:55:27.237", "Id": "59822", "Score": "0", "body": "Why is it bad practice?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T06:58:37.107", "Id": "59823", "Score": "0", "body": "Because it will catch things like `OutOfMemoryError`, `ThreadDeath`, `AssertionError`, `VirtualMachineError`.... and these are things you most certainly do not want to affect. You should only catch exceptions you know how to handle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T07:02:26.213", "Id": "59825", "Score": "0", "body": "I agree with You. I think it is useful when You are debugging." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T12:18:42.580", "Id": "36449", "ParentId": "36448", "Score": "2" } }, { "body": "<p>It depends on your decision if you want to move further when certification fails. You can throw exception if certification is \"must\" and you do not want to proceed if there is any issue with it. </p>\n\n<p>In other case, if you still want the execution to move further when there is any problem with certification then just logging the message would be fine.</p>\n\n<p>Here I have modified your code --</p>\n\n<pre><code>public boolean loadX509Certificate(File file) {\n InputStream is = null;\n boolean isCertificateLoaded = false;\n\n try {\n CertificateFactory cf = CertificateFactory.getInstance(\"X.509\");\n is = new FileInputStream(file);\n\n this.setCertificate(cf.generateCertificate(is));\n\n isCertificateLoaded = true;\n } catch (CertificateException e) {\n // log certification error \n } catch (FileNotFoundException e) {\n // log file not found error \n } catch (SecurityException e) {\n // log security error \n } catch (IOException e) {\n // log i/o error \n } finally {\n if (null != is) { is.close(); }\n }\n\n return isCertificateLoaded;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T12:58:08.430", "Id": "36451", "ParentId": "36448", "Score": "2" } }, { "body": "<p>First, I would separate <em>loading</em> the certificate from <em>storing</em> it.</p>\n\n<ul>\n<li>They are independent concerns.</li>\n<li>It allows multiple ways to load a certificate.</li>\n<li>It improves testability.</li>\n</ul>\n\n<p>As Kinjal suggests, logging the error is a good alternative when failure is recoverable. However, I would throw a custom exception (or use <code>CertificateException</code>) and let the caller decide to log and continue or terminate. I really don't like returning success codes when I can avoid it because it muddies the code with checks.</p>\n\n<p>Finally, instead of setting a certificate or leaving the field blank consider modeling a certificate checking strategy. This would require a simple one-method interface <code>CertificateCheck</code> with two implementations: <code>NullCertificateCheck</code> and <code>BasicCertificateCheck</code>. Again this improves testability by providing a seam for mocking, separating concerns, etc. It also removes the need for <code>if (this.certificate != null)</code> checks and allows for more strategies and certificate types.</p>\n\n<pre><code>public void setupCertificate() {\n try {\n certificateCheck = loadX590Certificate(...);\n }\n catch (InvalidCertificateException e) {\n LOG.warn(\"Skipping certificate check\", e);\n certificateCheck = new NullCertificateCheck();\n }\n}\n\nprivate CertificateCheck loadX509Certificate(File file) throws CertificateException {\n InputStream is = null;\n try {\n CertificateFactory cf = CertificateFactory.getInstance(\"X.509\");\n is = new FileInputStream(file);\n return new BasicCertificateCheck(cf.generateCertificate(is));\n }\n catch (FileNotFoundException e) {\n throw new CertificateException(\"Certificate file not found\", e);\n }\n ... more exceptions ...\n finally {\n IOUtils.closeQuietly(is);\n }\n}\n</code></pre>\n\n<p><strong>Update:</strong> Since you're storing the certificate (or not) so you can check its validity, I assumed you were checking it at a later time and ideally multiple times. If this is the case, extract the logic into a <code>CertificateCheck</code> hierarchy using the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">Strategy pattern</a>. If the certificate is checked once in isolation of any other data, this isn't necessary and I see no reason to store the certificate in an instance field.</p>\n\n<blockquote>\n <p>Note: I'm using <code>Checkable</code> as a stand-in for whatever contains the information that must be checked against the certificate. Your implementation would need to pass whatever is appropriate.</p>\n</blockquote>\n\n<pre><code>public interface CertificateCheck {\n boolean matches(Checkable thing);\n}\n\n// in the absence of a certificate, everything matches\npublic class NullCertificateCheck implements CertificateCheck {\n public boolean matches(Checkable thing) {\n return true;\n }\n}\n\npublic class BasicCertificateCheck implements CertificateCheck {\n private final Certificate cert;\n\n public BasicCertificateCheck(Certificate cert) {\n this.cert = cert;\n }\n\n public boolean matches(Checkable thing) {\n // move the current checks you have here\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T20:49:15.697", "Id": "59782", "Score": "0", "body": "Thanks for your reply! Your suggestion looks interesting, but I'm not sure what NullCertificateCheck and BasicCertificateCheck should implement? I guess cf.generateCertificate(is) returns a valid certificate. It would be nice if you could concrete your suggestion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T00:14:30.183", "Id": "59794", "Score": "0", "body": "@hofmeister - See my update for the details of `CertificateCheck`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T07:13:22.447", "Id": "59827", "Score": "0", "body": "Thanks for your update! I didn't know about the strategy pattern, very nice. I assume the method in `CertificateCheck` is called `matches`. I like to lern new pattern, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:15:53.210", "Id": "59883", "Score": "0", "body": "@hofmeister - Fixed, thanks. HTML forms don't make very good refactoring tools. :D" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T20:15:36.050", "Id": "36465", "ParentId": "36448", "Score": "5" } } ]
{ "AcceptedAnswerId": "36465", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T12:03:11.717", "Id": "36448", "Score": "7", "Tags": [ "java", "exception-handling", "error-handling" ], "Title": "Exceptions handling, what would you do?" }
36448
<p>I have created a class that has many methods for sorting an ArrayList of objects. Each method is somewhat similar in that they employ some kind of sort on an ArrayList and then return the arrayList. They are different in that some have different methods of comparison and they also call different get methods for the object in the ArrayList.</p> <p>As I said it is kind of redundant, so there's a lot of code:</p> <pre><code>import java.util.Collections; import java.util.GregorianCalendar; import java.math.BigDecimal; import java.util.ArrayList; public class OrganizeRegister { ArrayList&lt;BudgetItem&gt; organizableList = new ArrayList&lt;BudgetItem&gt;(); public OrganizeRegister(ArrayList&lt;BudgetItem&gt; organizableList) { this.organizableList = organizableList; } public ArrayList&lt;BudgetItem&gt; dateOldestToNewest() { for(int i = 0; i&lt;organizableList.size(); i++) { for(int j = 1; j&lt;organizableList.size(); j++) { GregorianCalendar g1 = organizableList.get(j-1).getDateOfTransaction(); GregorianCalendar g2 = organizableList.get(j).getDateOfTransaction(); if(g1.after(g2)) { BudgetItem temp = organizableList.get(j-1); organizableList.set(j-1, organizableList.get(j)); organizableList.set(j, temp); } } } return organizableList; } public ArrayList&lt;BudgetItem&gt; dateNewestToOldest() { for(int i = 0; i&lt;organizableList.size(); i++) { for(int j = 1; j&lt;organizableList.size(); j++) { GregorianCalendar g1 = organizableList.get(j-1).getDateOfTransaction(); GregorianCalendar g2 = organizableList.get(j).getDateOfTransaction(); if(g1.before(g2)) { BudgetItem temp = organizableList.get(j-1); organizableList.set(j-1, organizableList.get(j)); organizableList.set(j, temp); } } } return organizableList; } public ArrayList&lt;BudgetItem&gt; fromDateToDate(GregorianCalendar dayOne, GregorianCalendar dayTwo) { ArrayList&lt;BudgetItem&gt; holder = new ArrayList&lt;BudgetItem&gt;(); for(int i = 0; i&lt;organizableList.size(); i++) { GregorianCalendar g = organizableList.get(i).getDateOfTransaction(); if(g.equals(dayOne)||g.equals(dayTwo)||(g.after(dayOne)&amp;&amp;g.before(dayTwo))) { holder.add(organizableList.get(i)); } } organizableList = holder; for(int i = 0; i&lt;organizableList.size(); i++) { for(int j = 1; j&lt;organizableList.size(); j++) { GregorianCalendar g1 = organizableList.get(j-1).getDateOfTransaction(); GregorianCalendar g2 = organizableList.get(j).getDateOfTransaction(); if(g1.after(g2)) { BudgetItem temp = organizableList.get(j-1); organizableList.set(j-1, organizableList.get(j)); organizableList.set(j, temp); } } } return organizableList; } public ArrayList&lt;BudgetItem&gt; onDay(GregorianCalendar day) { ArrayList&lt;BudgetItem&gt; newOrganizableList = new ArrayList&lt;BudgetItem&gt;(); for(int i = 0; i&lt;organizableList.size(); i++) { GregorianCalendar g = organizableList.get(i).getDateOfTransaction(); if(g.equals(day)) { newOrganizableList.add(organizableList.get(i)); } } return newOrganizableList; } public ArrayList&lt;BudgetItem&gt; duringMonth(GregorianCalendar month) { ArrayList&lt;BudgetItem&gt; newOrganizableList = new ArrayList&lt;BudgetItem&gt;(); for(int i = 0; i&lt;organizableList.size(); i++) { GregorianCalendar g = organizableList.get(i).getDateOfTransaction(); if(g.MONTH == month.MONTH) { newOrganizableList.add(organizableList.get(i)); } } return newOrganizableList; } public ArrayList&lt;BudgetItem&gt; duringYear(GregorianCalendar year) { ArrayList&lt;BudgetItem&gt; newOrganizableList = new ArrayList&lt;BudgetItem&gt;(); for(int i = 0; i&lt;organizableList.size(); i++) { GregorianCalendar g = organizableList.get(i).getDateOfTransaction(); if(year.YEAR == year.YEAR) { newOrganizableList.add(organizableList.get(i)); } } return newOrganizableList; } public ArrayList&lt;Expense&gt; expensesOnly() { ArrayList&lt;Expense&gt; newOrganizableList = new ArrayList&lt;Expense&gt;(); for(int i = 0; i&lt;organizableList.size(); i++) { if(organizableList.get(i) instanceof Expense) { Expense e = (Expense) organizableList.get(i); newOrganizableList.add(e); } } return newOrganizableList; } public ArrayList&lt;Income&gt; incomeOnly() { ArrayList&lt;Income&gt; newOrganizableList = new ArrayList&lt;Income&gt;(); for(int i = 0; i&lt;organizableList.size(); i++) { if(organizableList.get(i) instanceof Expense) { Income e = (Income) organizableList.get(i); newOrganizableList.add(e); } } return newOrganizableList; } public ArrayList&lt;Expense&gt; byItemName() { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); Collections.sort(sortableArrayList, Expense.expenseNameComparator); return sortableArrayList; } public ArrayList&lt;Expense&gt; certainItem(String itemName) { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); ArrayList&lt;Expense&gt; returnArrayList = new ArrayList&lt;Expense&gt;(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { if(sortableArrayList.get(i).getItemName().equalsIgnoreCase(itemName)) { returnArrayList.add(sortableArrayList.get(i)); } } return returnArrayList; } public ArrayList&lt;Expense&gt; byQuantity() { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); Collections.sort(sortableArrayList); return sortableArrayList; } public ArrayList&lt;Expense&gt; certainQuantity(int certainQuantity) { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); ArrayList&lt;Expense&gt; returnArrayList = new ArrayList&lt;Expense&gt;(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { if(sortableArrayList.get(i).getQuantity() == certainQuantity) { returnArrayList.add(sortableArrayList.get(i)); } } return returnArrayList; } public ArrayList&lt;Expense&gt; byPlaceOfPurchase() { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); Collections.sort(sortableArrayList, Expense.placeOfPurchaseComparator); return sortableArrayList; } public ArrayList&lt;Expense&gt; fromPlaceOfPurchase(String certainPlace) { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); ArrayList&lt;Expense&gt; returnArrayList = new ArrayList&lt;Expense&gt;(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { if(sortableArrayList.get(i).getPlaceOfPurchase().equalsIgnoreCase(certainPlace)) { returnArrayList.add(sortableArrayList.get(i)); } } return returnArrayList; } public ArrayList&lt;Expense&gt; byMethodOfPay() { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); Collections.sort(sortableArrayList, Expense.methodOfPayComparator); return sortableArrayList; } public ArrayList&lt;Expense&gt; certainMethodOfPay(String certainMethod) { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); ArrayList&lt;Expense&gt; returnArrayList = new ArrayList&lt;Expense&gt;(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { if(sortableArrayList.get(i).getMethodOfPay().equalsIgnoreCase(certainMethod)) { returnArrayList.add(sortableArrayList.get(i)); } } return returnArrayList; } public ArrayList&lt;Expense&gt; priceHighestToLowest() { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { for(int j = 1; j&lt;sortableArrayList.size(); j++) { BigDecimal bd1 = sortableArrayList.get(j-1).getPrice(); BigDecimal bd2 = sortableArrayList.get(j).getPrice(); if(bd1.compareTo(bd2) == 1) { Expense temp = sortableArrayList.get(j-1); sortableArrayList.set(j-1, sortableArrayList.get(j)); sortableArrayList.set(j,temp); } } } return sortableArrayList; } public ArrayList&lt;Expense&gt; priceLowestToHighest() { ArrayList&lt;Expense&gt; sortableArrayList = expensesOnly(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { for(int j = 1; j&lt;sortableArrayList.size(); j++) { BigDecimal bd1 = sortableArrayList.get(j-1).getPrice(); BigDecimal bd2 = sortableArrayList.get(j).getPrice(); if(bd1.compareTo(bd2) == -1) { Expense temp = sortableArrayList.get(j-1); sortableArrayList.set(j-1, sortableArrayList.get(j)); sortableArrayList.set(j,temp); } } } return sortableArrayList; } public ArrayList&lt;Income&gt; byOriginOfIncome() { ArrayList&lt;Income&gt; sortableArrayList = incomeOnly(); Collections.sort(sortableArrayList, Income.originComparator); return sortableArrayList; } public ArrayList&lt;Income&gt; certainOrigin(String originName) { ArrayList&lt;Income&gt; sortableArrayList = incomeOnly(); ArrayList&lt;Income&gt; returnArrayList = new ArrayList&lt;Income&gt;(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { if(sortableArrayList.get(i).getOriginOfIncome().equalsIgnoreCase(originName)) { returnArrayList.add(sortableArrayList.get(i)); } } return returnArrayList; } public ArrayList&lt;Income&gt; byFormOfIncome() { ArrayList&lt;Income&gt; sortableArrayList = incomeOnly(); Collections.sort(sortableArrayList, Income.formComparator); return sortableArrayList; } public ArrayList&lt;Income&gt; byGrossIncome() { ArrayList&lt;Income&gt; sortableArrayList = incomeOnly(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { for(int j = 1; j&lt;sortableArrayList.size(); j++) { BigDecimal bd1 = sortableArrayList.get(j-1).getGrossIncome(); BigDecimal bd2 = sortableArrayList.get(j).getGrossIncome(); if(bd1.compareTo(bd2) == 1) { Income temp = sortableArrayList.get(i); sortableArrayList.set(j-1, sortableArrayList.get(j)); sortableArrayList.set(j,temp); } } } return sortableArrayList; } public ArrayList&lt;Income&gt; byNetIncome() { ArrayList&lt;Income&gt; sortableArrayList = incomeOnly(); for(int i = 0; i&lt;sortableArrayList.size(); i++) { for(int j = 1; j&lt;sortableArrayList.size(); j++) { BigDecimal bd1 = sortableArrayList.get(j-1).getNetIncome(); BigDecimal bd2 = sortableArrayList.get(j).getNetIncome(); if(bd1.compareTo(bd2) == 1) { Income temp = sortableArrayList.get(i); sortableArrayList.set(j-1, sortableArrayList.get(j)); sortableArrayList.set(j,temp); } } } return sortableArrayList; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T13:35:51.383", "Id": "59732", "Score": "1", "body": "I strongly doubt that some of your methods work the way you intended. `certainItem` for example. Do you get the return that you expected from that method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T13:43:05.633", "Id": "59733", "Score": "0", "body": "Okay, maybe I need more background. I did not want to flood you all with all of the classes, because there are about 5-6 different ones that are all pretty fleshed out. If you would like I will post them, and more information on how the program works as a whole." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T13:51:35.613", "Id": "59735", "Score": "0", "body": "As to answer the question from Simon:\n1. User enters a string\n2. Method takes the AL containing SuperClass items\n3. It filters the SubClass objects we need into a new AL\n4. It then loops through the new AL and gets the instance variable itemName\n5. The method then compares it to the user entered string\n6. Finally, it takes any objects that match that string and puts them into a return AL... and now I see your problem with it :) slight bug there" } ]
[ { "body": "<p>It is better to <strong>declare</strong> your variables as <code>List&lt;Something&gt;</code>, and <strong>instantiate</strong> with <code>new ArrayList&lt;Something&gt;()</code> to allow other implementations of <code>List</code>. Like this:</p>\n\n<pre><code>List&lt;Something&gt; someList = new ArrayList&lt;Something&gt;();\n</code></pre>\n\n<hr>\n\n<p>Very often you do something like this:</p>\n\n<pre><code>for(int i = 0; i&lt;organizableList.size(); i++) {\n for(int j = 1; j&lt;organizableList.size(); j++) {\n Something g1 = organizableList.get(j-1)...\n Something g2 = organizableList.get(j)...\n if(... some comparison between g1 and g2...) {\n // Switch positions of the two items\n BudgetItem temp = organizableList.get(j-1);\n organizableList.set(j-1, organizableList.get(j));\n organizableList.set(j, temp);\n }\n }\n}\n</code></pre>\n\n<p>This is a <a href=\"http://en.wikipedia.org/wiki/Bubble_sort\">bubblesort</a> algorithm. However, on some places you use the significantly more effective <code>Collections.sort</code> method. I recommend writing <code>Comparator</code>s for the different ways you want to sort by and then use <code>Collections.sort</code>.</p>\n\n<hr>\n\n<p>Another pattern which I see repeated in your code is a loop to add items from one list to another:</p>\n\n<pre><code>for(int i = 0; i&lt;organizableList.size(); i++) {\n Something g = organizableList.get(i)....;\n if(g.someCondition &amp;&amp; g.otherCondition...) {\n anotherList.add(organizableList.get(i));\n }\n}\n</code></pre>\n\n<p>You can get rid of a lot of code duplication by creating an interface and a method:</p>\n\n<pre><code>public interface FilterInterface&lt;E&gt; {\n /**\n * @param obj Element to check\n * @return True if element should be kept, false otherwise.\n */\n boolean shouldKeep(E obj);\n}\n\n\npublic static List&lt;Something&gt; addToAnotherList(Collection&lt;Something&gt; list, FilterInterface&lt;Something&gt; filter) {\n List&lt;Something&gt; result = new ArrayList&lt;Something&gt;();\n for (Something something : list) {\n if (filter.shouldKeep(something))\n result.add(something);\n }\n return result;\n}\n</code></pre>\n\n<p>An example usage of this would be:</p>\n\n<pre><code>List&lt;BudgetItem&gt; holder = addToAnotherList(organizableList, new FilterInterface&lt;BudgetItem&gt;() {\n @Override\n public boolean shouldKeep(BudgetItem item) {\n GregorianCalendar g = item.getDateOfTransaction();\n if(g.equals(dayOne)||g.equals(dayTwo)||(g.after(dayOne)&amp;&amp;g.before(dayTwo)))\n return true;\n else return false;\n }\n});\n</code></pre>\n\n<hr>\n\n<p>Many of your methods are both returning and modifying the <code>organizableList</code> array. This feels strange to me. It can be more preferable to create a copy of the list and sort it in a specific way and return that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T14:45:31.363", "Id": "59738", "Score": "0", "body": "Would you mind posting how you would write a Comparator for objects? I just now learned how to write them, and I am not sure how they would work specifically for classes such as BigDecimal and GregorianCalendar. Other than that, thank you for the help!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T14:25:50.813", "Id": "36454", "ParentId": "36452", "Score": "5" } }, { "body": "<p>Instead of doing the sort yourself it is much faster and simpler to use the builtin sort routine.</p>\n\n<pre><code>public class OrganizeRegister {\n static final Comparator&lt;BudgetItem&gt; AGE = new Comparator&lt;BudgetItem&gt;() {\n @Override\n public int compare(BudgetItem o1, BudgetItem o2) {\n return o1.getDateOfTransaction().compareTo(o2.getDateOfTransaction());\n }\n };\n\n final List&lt;BudgetItem&gt; organizableList;\n\n public OrganizeRegister(List&lt;BudgetItem&gt; organizableList) {\n this.organizableList = organizableList;\n }\n\n public List&lt;BudgetItem&gt; dateOldestToNewest() {\n Collections.sort(organizableList, AGE);\n return organizableList;\n }\n\n public List&lt;BudgetItem&gt; dateNewestToOldest() {\n Collections.sort(organizableList, Collections.reverseOrder(AGE));\n return organizableList;\n }\n\n public List&lt;BudgetItem&gt; fromDateToDate(GregorianCalendar dayOne, GregorianCalendar dayTwo) {\n List&lt;BudgetItem&gt; holder = new ArrayList&lt;BudgetItem&gt;();\n for (BudgetItem bi : organizableList) {\n GregorianCalendar dot = bi.getDateOfTransaction();\n if (dot.before(dayOne) || dot.after(dayTwo))\n continue;\n holder.add(bi);\n }\n Collections.sort(holder, AGE);\n return holder;\n }\n\n public List&lt;BudgetItem&gt; onDay(GregorianCalendar day) {\n List&lt;BudgetItem&gt; holder = new ArrayList&lt;BudgetItem&gt;();\n for (BudgetItem bi : organizableList) {\n GregorianCalendar dot = bi.getDateOfTransaction();\n if (dot.equals(day)) \n holder.add(bi);\n }\n return holder;\n }\n</code></pre>\n\n<p>BTW GergorianCalendar is a very expensive object. Date most likely does what you want is much, much cheaper and smaller.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T18:06:54.587", "Id": "36717", "ParentId": "36452", "Score": "3" } }, { "body": "<p>A few things which were not mentioned earlier:</p>\n\n<ol>\n<li><p>You have a bug here:</p>\n\n<pre><code> GregorianCalendar g = organizableList.get(i).getDateOfTransaction();\n if (g.MONTH == month.MONTH) {\n newOrganizableList.add(organizableList.get(i));\n }\n</code></pre>\n\n<p><code>MONTH</code> is a constant in the <code>Calendar</code> class:</p>\n\n<pre><code>public abstract class Calendar implements Serializable, \n Cloneable, Comparable&lt;Calendar&gt; {\n\n ...\n public final static int MONTH = 2;\n ...\n}\n</code></pre>\n\n<p>Therefore, the condition will be always true. (There is a similar issue with <code>YEAR</code> in the next method.) Eclipse shows a warning for that.</p>\n\n<p>Furthermore, you might want to compare the year too, not just the month to avoid getting data from the same month but different year.</p></li>\n<li><p>Here I'd rename <code>newOrganizableList</code> to <code>result</code> to express the purpose of the variable:</p>\n\n<blockquote>\n<pre><code>public ArrayList&lt;BudgetItem&gt; duringMonth(GregorianCalendar month) {\n ArrayList&lt;BudgetItem&gt; newOrganizableList = new ArrayList&lt;BudgetItem&gt;();\n for (int i = 0; i &lt; organizableList.size(); i++) {\n GregorianCalendar g = organizableList.get(i).getDateOfTransaction();\n if (g.MONTH == month.MONTH) {\n newOrganizableList.add(organizableList.get(i));\n }\n }\n return newOrganizableList;\n}\n</code></pre>\n</blockquote></li>\n<li><p><code>OrganizeRegister</code> is not the best class name. From Clean Code, page 25: </p>\n\n<blockquote>\n <p>Classes and objects should have noun or noun phrase names like <code>Customer</code>, <code>WikiPage</code>,\n <code>Account</code>, and <code>AddressParser</code>. [...] A class name should not be a verb.</p>\n</blockquote></li>\n<li><p>This field could be private:</p>\n\n<blockquote>\n<pre><code>ArrayList&lt;BudgetItem&gt; organizableList = new ArrayList&lt;BudgetItem&gt;();\n</code></pre>\n</blockquote>\n\n<p>(<a href=\"https://stackoverflow.com/q/5484845/843804\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n<li><p>You might want to create a defensive copy here:</p>\n\n<blockquote>\n<pre><code>public OrganizeRegister(ArrayList&lt;BudgetItem&gt; organizableList) {\n this.organizableList = organizableList;\n}\n</code></pre>\n</blockquote>\n\n<p>It would prohibit malicious clients to modify the internal data of the class and could save you a couple of hours of debugging. (<em>Effective Java, 2nd Edition, Item 39: Make defensive copies when needed</em>)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T20:10:25.003", "Id": "45649", "ParentId": "36452", "Score": "2" } } ]
{ "AcceptedAnswerId": "36454", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T13:23:10.627", "Id": "36452", "Score": "5", "Tags": [ "java", "sorting" ], "Title": "Trying to cut down redundancy in my code" }
36452
<p>I have written a tool for encrypting string using the AesCryptoServiceProvider in .NET. The folllowing parameters are used:</p> <ul> <li>Block Cipher Mode: CBC</li> <li>Initialization Vector: 16 bytes (randomized per encryption operation), stored in last 16 bytes of final message</li> <li>Key/Block size: 128 bit Padding: PKCS #7</li> </ul> <p>Overview of code I have added two functions below. The first prepares a message for encryption, takes the result and appends the Initialization Vector to the cipher message. The second function encrypts the provided message using the specified key and initialization vector.</p> <p>Obviously, i'm interested in any security holes that exist with this code. Also any optimizations are very much appreciated.</p> <p>Side questions. In development I always store bytes as strings in their hex representation, seen below. Is this bad? The only other alternative I see is base64 encoding? Which is better?</p> <pre><code>public void cryptoExample { AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.KeySize = 128; aes.BlockSize = 128; aes.Key = Helper.StringToByteArray("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); // Sample key aes.GenerateIV(); String plainMessage = "Hello AES Crypto!!"; String encryptedMessage = Helper.ByteArrayToString(CryptoHelper.EncryptStringToBytes_Aes(plainMessage, aes.Key, aes.IV)); // Must always use a random IV, meaning it needs to be stored with the cipher message. // Append it to the end. IV is a constant 16 bytes so we just extract and remove it before decryption. String strIv = Helper.ByteArrayToString(aes.IV); String messageToTransmit = encryptedMessage += strIv; } public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV) { // Check arguments. if (plainText == null || plainText.Length &lt;= 0) throw new ArgumentNullException("plainText"); if (Key == null || Key.Length &lt;= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length &lt;= 0) throw new ArgumentNullException("IV"); byte[] encrypted; // Create an AesCryptoServiceProvider object // with the specified key and IV. using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = Key; aesAlg.IV = IV; aesAlg.Mode = CipherMode.CBC; aesAlg.Padding = PaddingMode.PKCS7; // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T17:26:33.267", "Id": "59758", "Score": "0", "body": "Base64 or Hex. Hex coding (with 'smart' algorithms) is slightly faster to encode/decode than Base64, but is about 25% bigger for IO. Base64 encoding/decoding is almost as fast as Hex, but is smaller, so overall could be faster if IO is involved. Huh, JonSkeet answers: http://stackoverflow.com/a/3183880/1305253" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:17:56.093", "Id": "59838", "Score": "0", "body": "Great, I think for basic representation of small data I will go with Hex for readability. Base64 for large blobs. Cheers!" } ]
[ { "body": "<ol>\n<li>You can simplify it by replacing all those streams with a call to <code>encrypter.TransformFinalBlock</code>.</li>\n<li>You don't have a MAC, so an attacker who can send a modifier message to the decrypter can probably exploit a padding oracle to decrypt the message</li>\n<li>Why ask the caller for an IV? You could generate it internally. If you want to keep a deterministic implementation around, at least create an overload without IV.</li>\n<li><code>Helper.ByteArrayToString</code> and <code>StringToByteArray</code> should have a name that says which encoding (hex, Base64, etc.) they use. I'd use <code>BytesToHexString</code> and <code>HexStringToBytes</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:53:43.610", "Id": "59844", "Score": "0", "body": "Thanks for this. I will look into TransformFinalBlock. Could you please describe how to incorporate a MAC? Also, silly me, no need to pass in the IV!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T02:08:31.027", "Id": "73478", "Score": "0", "body": "Generating the IV internally and then also appending it to the crypto string internally is quite smart, given it would ensure that it is unique for each message, rather than relying on the user to implement it correctly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T17:03:54.077", "Id": "36458", "ParentId": "36453", "Score": "6" } }, { "body": "<p>Few tiny notes:</p>\n\n<ol>\n<li><p>In the method <code>cryptoExample</code>, the usage of <code>AesCryptoServiceProvider</code> should be wrapped in a <code>using</code> block much like it is in the <code>EncryptStringToBytes_Aes</code> method.</p></li>\n<li><p>Similarly, <code>ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)</code> in the <code>EncryptStringToBytes_Aes</code> method is an <code>IDisposable</code> resource and should also be wrapped in a <code>using</code> block.</p></li>\n<li><p>The comment above that line says \"create a decryptor\", yet, it's creating an encryptor. Will confuse future readers.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T17:36:09.213", "Id": "36460", "ParentId": "36453", "Score": "5" } } ]
{ "AcceptedAnswerId": "36458", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T13:48:55.690", "Id": "36453", "Score": "6", "Tags": [ "c#", ".net", "security", "cryptography", "aes" ], "Title": "AES Encryption C# .NET" }
36453
<p>Lil' preparation before the interview. This is my solution to the problem in title. The code is pretty straight forward. Requesting suggestions for improvement and also verification of complexity, which I guess is O(26<sup>n</sup>)</p> <pre><code>public class CatToDog { static Set&lt;String&gt; dictionary; static { dictionary = new HashSet&lt;String&gt;(); dictionary.add("camera"); dictionary.add("cat"); dictionary.add("cot"); dictionary.add("cot"); dictionary.add("dome"); dictionary.add("dot"); dictionary.add("dog"); // dictionary = new TreeSet&lt;String&gt;(); // BufferedReader br = null; // try { // try { // br = new BufferedReader(new FileReader("/Users/ameya.patil/Desktop/text.txt")); // String line; // while ((line = br.readLine()) != null) { // dictionary.add(line.split(":")[0]); // } // // } finally { // br.close(); // } // } catch (Exception e) { // throw new RuntimeException("Error while reading dictionary"); // } } private CatToDog () { }; public static List&lt;String&gt; listWords(String startWord, String endWord) { final Queue&lt;String&gt; queue = new LinkedList&lt;String&gt;(); final Map&lt;String, String&gt; backTrack = new HashMap&lt;String, String&gt;(); queue.add(startWord); backTrack.put(startWord, null); while (!queue.isEmpty()) { String currentWord = queue.poll(); if (currentWord.equals(endWord)) { return mapToList(backTrack, endWord); } addValidOneChangeWords(currentWord, queue, backTrack); } return Collections.EMPTY_LIST; } private static void addValidOneChangeWords(String startWord, Queue&lt;String&gt; queue, Map&lt;String, String&gt; backTrack) { for (int i = 0; i &lt; startWord.length(); i++) { char[] endWord = startWord.toCharArray(); for (char ch = 'a'; ch &lt; 'z'; ch++) { endWord[i] = ch; String word = new String(endWord); if (validate(word, backTrack, startWord)) { queue.add(word); backTrack.put(word, startWord); } } } } private static boolean validate(String word, Map&lt;String, String&gt; backTrack, String startWord) { return dictionary.contains(word) &amp;&amp; !backTrack.containsKey(word) &amp;&amp; !word.equals(startWord); } private static List&lt;String&gt; mapToList (Map&lt;String, String&gt; backTrack, String endWord) { final List&lt;String&gt; wordList = new ArrayList&lt;String&gt;(); String word = endWord; while (backTrack.containsKey(word)) { wordList.add(word); word = backTrack.get(word); } Collections.reverse(wordList); return wordList; } public static void main(String[] args) { for (String string : listWords("cat", "dog")) { System.out.println(string); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T20:20:53.460", "Id": "59779", "Score": "2", "body": "I certainly hope the complexity is not O(26^n) ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T21:18:45.923", "Id": "59784", "Score": "0", "body": "@rolfl i could not determined the complexity. maybe mostly i am wrong when i came up with that answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T21:54:14.613", "Id": "59785", "Score": "0", "body": "no it's O(n) check [levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T11:41:03.620", "Id": "59849", "Score": "1", "body": "I must be missing something, to get the \"distance\" from `v` to `w`, can't you first iterate both in parallel (until the end of either word was hit) and increase the distance by 1 for every character which is not the same at the current position in both strings? At the end, just add the difference in length to the distance. I.e. the difference between `camera` and `cat` would be 4, the difference between `cat` and `dog` would be 3, between `dot` and `dog` just 1. That would be O(n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T11:53:48.130", "Id": "59850", "Score": "0", "body": "Should be each word in the sequence differ from the previous word by only one letter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T05:45:03.080", "Id": "59950", "Score": "0", "body": "@cat_baxter yes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T09:49:05.687", "Id": "59990", "Score": "0", "body": "Was the assignment to print each distance or just to compute the distance between the words? A big difference. The latter would be a very simple Levenshtein Distance implementation which would be O(n)." } ]
[ { "body": "<p>I'm not sure about the exact complexity, but it is certainly huge! One-letter edits are fine to <a href=\"http://norvig.com/spell-correct.html\" rel=\"nofollow\">spell check one word given a large dictionary</a>, but does not work if you only have a few words and the edit distance can be arbitrarily large. To look for close words in the dictionary, you should use the Levenshtein distance, as mentioned by ratchet freak. (Implementing the Levenshtein distance is a good idea.)</p>\n\n<pre><code>// dictionary = new TreeSet&lt;String&gt;();\n// ....\n</code></pre>\n\n<p>Please don't post unused code here unless you want it reviewed too.</p>\n\n<pre><code>private CatToDog () { };\n</code></pre>\n\n<p>A default constructor is provided by Java already, only use that if you need to put something in there.</p>\n\n<pre><code>public static List&lt;String&gt; listWords(String startWord, String endWord) {\n final Queue&lt;String&gt; queue = new LinkedList&lt;String&gt;();\n final Map&lt;String, String&gt; backTrack = new HashMap&lt;String, String&gt;();\n queue.add(startWord);\n backTrack.put(startWord, null);\n\n while (!queue.isEmpty()) {\n String currentWord = queue.poll();\n if (currentWord.equals(endWord)) {\n return mapToList(backTrack, endWord);\n }\n addValidOneChangeWords(currentWord, queue, backTrack);\n }\n return Collections.EMPTY_LIST;\n}\n</code></pre>\n\n<p>How do you know this is the shortest path? It feels a lot like depth first search, but I think you want to implement Dijkstra's algorithm instead to be able to notice shorter subpaths.</p>\n\n<pre><code>private static void addValidOneChangeWords(String startWord, Queue&lt;String&gt; queue, Map&lt;String, String&gt; backTrack) {\n for (int i = 0; i &lt; startWord.length(); i++) {\n char[] endWord = startWord.toCharArray();\n for (char ch = 'a'; ch &lt; 'z'; ch++) {\n endWord[i] = ch;\n String word = new String(endWord);\n if (validate(word, backTrack, startWord)) {\n queue.add(word);\n backTrack.put(word, startWord);\n }\n }\n }\n}\n</code></pre>\n\n<p>You're only focusing on one-letter edits here, but what about deletions, insertions and even transpositions (dog -> dgo)? The Damerau-Levenshtein distance handles them. </p>\n\n<p>And finally, <code>mapToList</code> is poorly named: I already know that the type change, I want to know about semantics! Something like <code>editPath</code> would be better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T11:18:43.463", "Id": "59846", "Score": "2", "body": "I don't see a good way to write this recursively. You need a PriorityQueue which in this trivial case degenerates to a Queue, not a Stack. One also needs to keep an already-visited set, which is a bit uglier in recursive code as well. So I prefer the OP's choice of looping over a Queue over a recursive algorithm here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T09:06:54.857", "Id": "59981", "Score": "0", "body": "Thanks for your comment. Unless I'm mistaken again, if it's a BFS (ie. needs a Queue, not a Stack), it's also easy with a recursive function (just decide where you call recursively). The already-visited set can easily be handled as a parameter, but it has to be clear that it's going to be modified \"outside\" of the function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T09:08:54.237", "Id": "59982", "Score": "0", "body": "I can't think of a simple way to write a BFS recursively." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:18:02.507", "Id": "36495", "ParentId": "36463", "Score": "3" } } ]
{ "AcceptedAnswerId": "36495", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:57:32.490", "Id": "36463", "Score": "5", "Tags": [ "java", "strings" ], "Title": "Shortest distance from one word to another. eg: cat -> cot -> dot -> dog" }
36463
<p>This is my first attempt at putting the conceptual knowledge I've gained about graphs into code. When searching for examples they all seem overly complicated, and searching for a tutorial or introduction leads to conceptual information. So here I am trying to code a very simple graph and this is what I have. The vertices represent cities, the edges represent paths and their distances between cities.</p> <p>I have two main questions:</p> <ol> <li>Is this a graph? Am I missing anything? I think I have a decent understanding of them conceptually, so at least for a basic graph I think this suffices.</li> <li>Are the pointers necessary? Is there a better way I could be implementing them? It was my understanding that an <code>Edge</code> is supposed to just contains pointers to vertices.</li> </ol> <p>I believe the code is pretty straightforward: you have your edge, vertex, and graph classes, then main which creates one vertex per city, one pointer per vertex, and one edge per path between cities, most are one way, a couple are bi-directional. Then it just prints the contents of the graph which just prints each city and all paths from that city.</p> <p>I know it's missing a remove function and I plan on making one soon. Just removing the vertex from the graph and removing any edges that lead to/from that vertex, but I just don't have the time at the moment.</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class Vertex; class Edge { public: Edge(Vertex *org, Vertex *dest, int dist) { origin = org; destination = dest; distance = dist; } Vertex* getOrigin() {return origin;} Vertex* getDestination() {return destination;} int getDistance() {return distance;} private: Vertex* origin; Vertex* destination; int distance; }; class Vertex { public: Vertex(string id) { name = id; } void addEdge(Vertex *v, int dist) { Edge newEdge(this, v, dist); edges.push_back(newEdge); } void printEdges() { cout &lt;&lt; name &lt;&lt; ":" &lt;&lt; endl; for (int i = 0; i &lt; edges.size(); i++) { Edge e = edges[i]; cout &lt;&lt; e.getDestination()-&gt;getName() &lt;&lt; " - " &lt;&lt; e.getDistance() &lt;&lt; endl; } cout &lt;&lt; endl; } string getName() {return name;} vector&lt;Edge&gt; getEdges() {return edges;} private: string name; vector&lt;Edge&gt; edges; }; class Graph { public: Graph() {} void insert(Vertex *v) { vertices.push_back(v); } void printGraph() { for (int i = 0; i &lt; vertices.size(); i++) vertices[i]-&gt;printEdges(); } private: vector&lt;Vertex*&gt; vertices; }; int main() { Graph g; Vertex v1 = Vertex("Seattle"); Vertex v2 = Vertex("Portland"); Vertex v3 = Vertex("Everett"); Vertex v4 = Vertex("Lynnwood"); Vertex v5 = Vertex("Northgate"); Vertex v6 = Vertex("Bellevue"); Vertex v7 = Vertex("Arlington"); Vertex v8 = Vertex("Bellingham"); Vertex *vp1 = &amp;v1; Vertex *vp2 = &amp;v2; Vertex *vp3 = &amp;v3; Vertex *vp4 = &amp;v4; Vertex *vp5 = &amp;v5; Vertex *vp6 = &amp;v6; Vertex *vp7 = &amp;v7; Vertex *vp8 = &amp;v8; v1.addEdge(vp2, 100); v1.addEdge(vp6, 20); v2.addEdge(vp1, 100); v3.addEdge(vp1, 30); v3.addEdge(vp4, 10); v3.addEdge(vp7, 20); v4.addEdge(vp5, 15); v5.addEdge(vp1, 10); v6.addEdge(vp1, 20); v8.addEdge(vp7, 45); g.insert(vp1); g.insert(vp2); g.insert(vp3); g.insert(vp4); g.insert(vp5); g.insert(vp6); g.insert(vp7); g.insert(vp8); g.printGraph(); system("PAUSE"); return 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-27T18:28:29.410", "Id": "166894", "Score": "0", "body": "You should return 0 for success-- not 1." } ]
[ { "body": "<p>You're using pointers to local variables. If this were being done in a subroutine as opposed to in <code>main</code>, you'd probably end up pointing at objects that were no longer alive.</p>\n\n<p>Even if you let <code>Graph</code> copy the vertices, you couldn't reliably put them directly in a <code>vector</code> and still point at them -- the instant you add a vertex, the current crop of pointers could be invalidated.</p>\n\n<p>You have two worthwhile choices here: you could either let a <code>Graph</code> own its own <em>dynamically allocated</em> (ie: <code>new</code>) copy of each vertex (ideally using something like <code>std::unique_ptr</code> to manage their lifetime), and point to those, or refer to vertices by ID/name and let the <code>Graph</code> worry about pointers and references and such.</p>\n\n<p>Note that neither solution requires passing a pointer; everywhere you're currently accepting a pointer, you could take either a const reference or an ID/name instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T23:07:55.933", "Id": "36473", "ParentId": "36464", "Score": "5" } }, { "body": "<blockquote>\n<p>is this a graph?</p>\n</blockquote>\n<p>Yes</p>\n<blockquote>\n<p>Am I missing anything?</p>\n</blockquote>\n<p>In terms of a graph: No.<br />\nYou have chosen to make your edges uni-directional (thus two edges are required to mark routes between cities). Not an issue in itself but you could have helper functions that create two edges automatically.</p>\n<p>In terms of good coding: Yes<br />\nYou have completely missed out encapsulation.</p>\n<blockquote>\n<p>I think I have a decent understanding of them conceptually, so at least for a basic graph I think this suffices.</p>\n</blockquote>\n<p>Your understanding of a graph is fine. Your understanding of implementing them needs some work. The whole point of a class and encapsulation is to make sure the object keeps and maintains state. Access to the state is controlled so that it can not be manipulated incorrectly.</p>\n<p>Unfortunately this is not the case in your implementation. You have leaked the state of the object outside the class thus expose yourself to it be manipulated without the graphs consent (this can make maintaining other information very hard).</p>\n<p>Also the state used by the graph may not be scoped in the same way as the graph and thus you can potentially loose state (ie objects dying) thus making the graph invalid.</p>\n<p>Additionally you use pointers very poorly. It is very rare to pass pointers across an interface boundaries as there is not associated concept of ownership. Using pointers internally is perfectly fine (i.e. don't pass pointers through public methods).</p>\n<blockquote>\n<p>are the pointers necessary?</p>\n</blockquote>\n<p>Probably not.<br />\nAlso they are probably not a good idea.</p>\n<blockquote>\n<p>Is there a better way I could be implementing them?</p>\n</blockquote>\n<p>Yes.<br />\nIf you encapsulate your vertices inside the graph then you can give them 'ids' (probably just the index into a vector of vertices). This ids can be universal and need not change. Or you could use the name as the 'id' it all depends on implementation.</p>\n<blockquote>\n<p>It was my understanding that an Edge is supposed to just contains pointers to vertices.</p>\n</blockquote>\n<p>Rather than use the word 'contains pointers to' just use the term 'refer' (so as not to get us confused with the term references).</p>\n<p>An edge has a source and a destination vertex with a value (representing the distance (or cost)) to transfer between them along the edge. How the edge manages that information will depend on implementation.</p>\n<h3>Code Analysis</h3>\n<p>Don't do this:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a></p>\n<p>I would not expose <code>Edge</code> publicly.<br />\nThey are an internal state of the graph. If you expose them you will be unable to change the internal represent of an edge which binds you to this form (i.e. you will not be able to update your class with improvements later).</p>\n<pre><code>class Edge\n</code></pre>\n<p>Do not pass pointers over a public interface:</p>\n<pre><code>public:\n Edge(Vertex *org, Vertex *dest, int dist)\n</code></pre>\n<p>Here you are passing pointers (in a very C like form).</p>\n<ol>\n<li>Are you giving ownership of the objects to the edge (unlikely)?</li>\n<li>Are the vertices going to be NULL (unlikely)?</li>\n</ol>\n<p>So here I would suggest passing them by reference. <strong>BUT</strong> I also know that we will storing the vertices internally as well I would refer change the graph to hold a vector of the vertex and then you only need to pass their index in the vector as a reference.</p>\n<p><strong>BUT</strong> then if we consider that a graph may be huge. We don't want to scan through all the edges when we know a start node. So personally I would have each vertex hold a vector of edges. Since we now know the start node you only need to pass the destination node and cost.</p>\n<p>Same thing for <code>Vertex</code>. No need for it to be public (same reason).</p>\n<pre><code>class Vertex\n</code></pre>\n<p>No problem with a method <code>printEdges()</code> but output is usually done via <code>operator&lt;&lt;</code>.</p>\n<pre><code>void printEdges()\n</code></pre>\n<p>Don't pass pointer through a public interface.<br />\nPersonally I would copy the method used by the standard containers and pass a const reference and copy it into the object (or with C++ pass a r-value reference that can be moved into the object).</p>\n<pre><code>void insert(Vertex *v)\n</code></pre>\n<p>Again with printing. Prefer <code>operator&lt;&lt;</code></p>\n<pre><code>void printGraph()\n</code></pre>\n<p>This is how I would expect the graph to work:</p>\n<pre><code>Graph g;\n// Type one: Add vertices (if they don't exist) and add\n// two edges (one for each way). \ng.addEdges(&quot;Seattle&quot;, &quot;Portland&quot;, 100);\ng.addEdges(&quot;Seattle&quot;, &quot;Bellevue&quot;, 20);\n\n// Type two: Add vertices (if they don't exist) and add\n// one edges\ng.addEdge(&quot;Everett&quot;, &quot;Seattle&quot;, 30);\n\n// Type three: Add new Vertix. \n// Use the id to add edges.\nint id1 = g.addVertix(&quot;Everett&quot;);\nint id2 = g.addVertix(&quot;Lynnwood&quot;);\ng.addEdge(id1, id2, 10);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T07:24:12.717", "Id": "59828", "Score": "2", "body": "I'd pick a different name than `addEdges` for the bidirectional version. It's too close to `addEdge`, to the point where one could easily overlook the difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-20T14:19:20.243", "Id": "165616", "Score": "0", "body": "And I would prefer to access Nodes via pointers and also have the graph itself templated in order to store ordinary types. I prefer pointers over handles, but I am game developer and often we prefer more raw approach." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T07:20:22.200", "Id": "36490", "ParentId": "36464", "Score": "17" } } ]
{ "AcceptedAnswerId": "36490", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T19:59:07.727", "Id": "36464", "Score": "14", "Tags": [ "c++", "graph", "pointers" ], "Title": "Coding and printing a graph" }
36464
<p>I am trying to add parallelism. The following function works. For testing purposes, calculating <code>chunckLength</code> is fine. However, when I allocate more cores, it seems to slow down significantly which seems due to massive overhead. The visualisation shows the average core utilisation during execution. Each run, the function is iterated over 10 times with lists of 10000 elements.</p> <p>I am fairly new to F# (as you can probably tell from the functions structure...), so any suggestions on how to optimise it so I can achieve some speed-up would help greatly.</p> <pre><code>let pmap_tpl_parforlb f (xs:list&lt;_&gt;) = let xs_arr = xs.ToArray() let chunkLength = xs.Length / numProc Parallel.For(0,numProc,fun c -&gt; let x = c * chunkLength let y = (c * chunkLength) + chunkLength for x in 0..y-1 do xs_arr.[x] &lt;- f (xs_arr.[x]) ) |&gt; ignore </code></pre> <p><img src="https://i.stack.imgur.com/XW8fU.png" alt="left : 4 cores, right:1 core"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T16:33:34.403", "Id": "59879", "Score": "1", "body": "I think there isn't enough information here: add your full code, including the test cases and what parameters did you use." } ]
[ { "body": "<p>Have you tried <em>not</em> using explicit chunk sizes? <code>Parallel.For</code> does some fancy chunking (range-splitting) and load-balancing under the hood, which usually gives very good performance on it's own.</p>\n\n<p>In other words, try a simpler solution first, e.g.,:</p>\n\n<pre><code>let mapInPlace (mapping : 'T -&gt; 'T) (array : 'T[]) : unit =\n Parallel.For (0, array.Length, fun i -&gt;\n array.[i] &lt;- mapping array.[i])\n |&gt; ignore\n</code></pre>\n\n<p>Another point -- if you're iterating over lists of 10000 elements, you should convert those lists to an array <em>once</em>, then call your iterative function however many times you need to. I suspect you're losing a non-trivial amount of performance from doing the list-to-array conversion repeatedly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T23:41:21.650", "Id": "36930", "ParentId": "36467", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T20:35:56.143", "Id": "36467", "Score": "2", "Tags": [ "optimization", "performance", "beginner", "f#", "task-parallel-library" ], "Title": "parallel.For function" }
36467
<p>I'm reading <a href="http://www.cs.nott.ac.uk/~gmh/monparsing.pdf" rel="nofollow">monadic parser combinators</a>. On the page 23, they leave an exercise for defining a Gofer block comment parser, and I try to implement it in Haskell.</p> <p>My code is here:</p> <pre><code>import Control.Monad import Data.Char import Data.Maybe newtype Parser a = Parser { runParser :: String -&gt; [(a,String)] } -- return `v` without consuming anything result :: a -&gt; Parser a result v = Parser $ \inp -&gt; [(v,inp)] -- always fails zero :: Parser a zero = --Parser $ \inp -&gt; [] Parser $ const [] -- consume the first char, fail if this is impossible item :: Parser Char item = Parser $ \inp -&gt; case inp of [] -&gt; [] (x:xs) -&gt; [(x,xs)] instance Monad Parser where return = result m &gt;&gt;= f = Parser $ \inp -&gt; do -- apply m on inp, which yields (v, inp') (v,inp') &lt;- runParser m inp -- apply f on v, which ylelds next parser -- run parser on the unconsumned parts inp' runParser (f v) inp' -- consume and test if the first character satisfies -- a predicate sat :: (Char -&gt; Bool) -&gt; Parser Char sat p = do x &lt;- item guard $ p x return x -- consume an exact `x` char :: Char -&gt; Parser Char char x = sat (\y -&gt; x == y) -- test if an Ord is within a given range inBetween :: (Ord a) =&gt; a -&gt; a -&gt; a -&gt; Bool inBetween a b v = a &lt;= v &amp;&amp; v &lt;= b -- consume a digit digit :: Parser Char digit = sat $ inBetween '0' '9' -- consume a lower case char lower :: Parser Char lower = sat $ inBetween 'a' 'z' -- consume a upper case char upper :: Parser Char upper = sat $ inBetween 'A' 'Z' -- use p and q to parse the same string -- return all possibilities plus :: Parser a -&gt; Parser a -&gt; Parser a p `plus` q = Parser $ \inp -&gt; runParser p inp ++ runParser q inp -- consume letters (i.e. lower / upper) letter :: Parser Char letter = lower `plus` upper -- consume alphanum (i.e. letter / digit) alphanum :: Parser Char alphanum = letter `plus` digit -- consume a word (i.e. consecutive letters) word :: Parser String word = many letter -- we have MonadPlus here -- and I think this is equivalent to -- "MonadOPlus" in the paper instance MonadPlus Parser where mzero = zero mplus = plus -- consume a string from input string :: String -&gt; Parser String string "" = return "" string (x:xs) = do char x string xs return (x:xs) -- consume some chars recognized by `p` -- refactor: `many` and `many1` can be defined muturally recursively. many :: Parser a -&gt; Parser [a] many p = force $ orEmpty $ many1 p -- identifiers are lower-case letter followed by -- zero or more alphanum ident :: Parser String ident = do x &lt;- lower xs &lt;- many alphanum return (x:xs) -- same as `many`, but this time we don't produce extra empty seq many1 :: Parser a -&gt; Parser [a] many1 p = do x &lt;- p xs &lt;- many p return (x:xs) -- convert string to int, please make sure `(not $ null xs)` stringToInt :: String -&gt; Int stringToInt xs = foldl1 merge $ map digitToInt xs where merge a i = a * 10 + i -- recognize a natural number nat :: Parser Int nat = liftM digitToInt digit `chainl1` return merge where merge a i = a * 10 + i -- recognize integers (i.e. positive, zero, negative) int :: Parser Int int = do f &lt;- op n &lt;- nat return $ f n where -- either apply a `negate` if `-` is present -- or keep it unchanged (by applying `id`) -- if '-' is recognized, we will have two functions here -- but that is not a problem, because `nat` won't recognize -- anything that begin with a '-' op = (char '-' &gt;&gt; return negate) `plus` return id -- recognize a list of integers ints :: Parser [Int] ints = bracket (char '[') (int `sepby1` char ',') (char ']') -- recognize pattern of `p` `sep` `p` `sep` `p` ... sepby1 :: Parser a -&gt; Parser b -&gt; Parser [a] p `sepby1` sep = do x &lt;- p xs &lt;- many (sep &gt;&gt; p) return (x:xs) -- recognize `open` `p` `close` bracket open p close = do open xs &lt;- p close return xs -- parse something or return empty orEmpty :: Parser [a] -&gt; Parser [a] orEmpty p = p `plus` return [] -- same as `sepby1`, allow empty result sepby :: Parser a -&gt; Parser b -&gt; Parser [a] p `sepby` sep = orEmpty $ p `sepby1` sep -- take `factor` and `op`, consume non-empty seq -- operator should be left associative chainl1 :: Parser a -&gt; Parser (a -&gt; a -&gt; a) -&gt; Parser a -- parse first element by `p` -- parse rest of it by `rest` p `chainl1` op = p &gt;&gt;= rest where rest x = (do f &lt;- op y &lt;- p -- parse and get `f` and `y` -- do the calculate and keep going recursively rest (x `f` y)) -- or we just stop here `plus` return x chainr1 :: Parser a -&gt; Parser (a -&gt; a -&gt; a) -&gt; Parser a -- first parse a single p p `chainr1` op = p &gt;&gt;= rest where rest x = (do -- parse op and parse the rest part recursively f &lt;- op y &lt;- p `chainr1` op -- combine result return $ x `f` y) -- or do nothing `plus` return x -- take as argument a list of pairs -- whose `fst` is a parser that recognize some string of type `a` -- and `snd` is the corresponding result -- this function produces a parser that try to parse something -- of type `a` in parallel and return all possible `b`s ops :: [(Parser a, b)] -&gt; Parser b ops xs = foldr1 plus [ p &gt;&gt; return op | (p,op) &lt;- xs] -- allows consuming nothing chainl :: Parser a -&gt; Parser (a -&gt; a -&gt; a) -&gt; a -&gt; Parser a chainr :: Parser a -&gt; Parser (a -&gt; a -&gt; a) -&gt; a -&gt; Parser a chainl p op v = (p `chainl1` op) `plus` return v chainr p op v = (p `chainr1` op) `plus` return v -- force the first result of a parser, increase laziness force :: Parser a -&gt; Parser a force p = Parser $ \inp -&gt; let x = runParser p inp in head x : tail x -- only return the first result from a parser first :: Parser a -&gt; Parser a first p = Parser $ \inp -&gt; case runParser p inp of [] -&gt; [] (x:_) -&gt; [x] -- `g` is a binary, after `g x y`, we apply `f` (.:) :: (c -&gt; d) -&gt; (a -&gt; b -&gt; c) -&gt; (a -&gt; b -&gt; d) (f .: g) x y = f (g x y) -- lazy `plus`, if the first one succeeds, -- the second one never get evaluated (+++) :: Parser a -&gt; Parser a -&gt; Parser a (+++) = first .: plus -- White-Space, Comments, and Keywords spaces :: Parser () spaces = do many1 (sat isSpace) return () where isSpace x = x `elem` " \n\t" comment :: Parser () comment = do string "--" many $ sat (/= '\n') return () multilineComment :: Parser () multilineComment = do bracket (string "{-") content (string "-}") return () where content = many $ multilineComment +++ notCommentEnd notCommentEnd = do -- anything but '-}' sat (/='-') +++ (sat (=='-') &gt;&gt; sat (/='}')) return () main = print $ runParser multilineComment (unlines [ "{- -- comment" , " {- nested" , " -}" , " -- comment " , "-}code start here" ]) </code></pre> <p>My <code>multilineComment</code> works fine but I'm wondering if there's any decent way to write <code>notCommendEnd</code>. My <code>notCommandEnd</code> can only tell if something is not a <code>-}</code>, which is not flexible.</p> <p>My first attempt is to write a combinator <code>notParser p</code> that invert the result of <code>p</code>:</p> <pre><code>notParser :: Parser a -&gt; Parser () notParser p = Parser $ \inp -&gt; runParser (newParser inp) inp where newParser inp' = case runParser p inp' of -- rejected by p [] -&gt; return () -- accepted by p _ -&gt; zero </code></pre> <p>and define <code>notCommentEnd</code> in terms of <code>notParser</code>:</p> <pre><code>notCommendEnd = notParser $ string "-}" </code></pre> <p>But this leads to a stack overflow, I think that is because my <code>notParser p</code> doesn't actually consume anything and <code>many</code> in this case might not have a chance to terminate.</p> <p>I'll appreciate it if you can give me some suggestion on either my problem or my code.</p>
[]
[ { "body": "<p>I have figured out a better way of writing the code.</p>\n\n<p>Here I have 2 improvements:</p>\n\n<h1>1. Implementing <code>notCommentEnd</code></h1>\n\n<p>Reconsidering my first attempt, the problem is that <code>notParser</code> does not consume anything but <code>many</code> are expecting a parser that at least consumes one character so that it can terminate.</p>\n\n<p>If we make the assumption that the input string is non-empty\nthen after <code>notParser p</code> returns successfully, we can drop one character from input to let <code>many</code> proceed and terminate:</p>\n\n<pre><code>notCommentEnd = do\n -- anything but '-}'\n notParser $ string \"-}\"\n item\n return ()\n</code></pre>\n\n<p>On the other hand, if the input string is empty, <code>notCommentEnd</code> will fail because <code>item</code> need to consume one character, this is the expected behavior.</p>\n\n<h1>2. Removing <code>return ()</code>s</h1>\n\n<p>Observe that there are some <code>return ()</code>s in the code that simply drops the result from parser, we can instead use <a href=\"http://hackage.haskell.org/package/base-4.6.0.1/docs/Control-Monad.html#v%3avoid\" rel=\"nofollow\"><code>void</code></a> from <code>Control.Monad</code> to achieve the same goal with less lines of code.</p>\n\n<pre><code>void :: Functor f =&gt; f a -&gt; f ()\n</code></pre>\n\n<p>What we need is a functor, and the parser is a monad, which is indeed a functor as well:</p>\n\n<pre><code>instance Functor Parser where\n fmap = liftM\n</code></pre>\n\n<p>Now we can use <code>void</code> to replace all tailing <code>return ()</code> to simply the code.</p>\n\n<p>For example, the implementation of <code>comment</code>:</p>\n\n<pre><code>comment :: Parser ()\ncomment = do\n string \"--\"\n many $ sat (/= '\\n')\n return ()\n</code></pre>\n\n<p>can be rewritten as:</p>\n\n<pre><code>comment :: Parser ()\ncomment = void $ do\n string \"--\"\n many $ sat (/= '\\n')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-20T03:38:07.007", "Id": "37800", "ParentId": "36468", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T21:33:39.327", "Id": "36468", "Score": "1", "Tags": [ "haskell", "parsec" ], "Title": "block comment parser implementation for \"monadic parser combinators\"" }
36468
<p>I'm currently implementing an interner in the style of Guava's <a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Interner.html" rel="nofollow"><code>Interner</code></a>, where:</p> <ol> <li>an intern pool is maintained for an immutable class</li> <li>whenever a new instance of that class is created, it's checked to see if it's equal to an existing instance in the intern pool</li> <li>if such an existing instance is found, it's returned, otherwise the new instance is added to the pool and returned</li> </ol> <p>Of course, in Ruby, you can replace methods like <code>new</code> and <code>[]</code>, so my implementation does just that:</p> <pre><code>module Interner def self.extended(obj) intern_pool = Hash.new do |hash, key| # Ideally, this should be a deep freeze, but it's not supported # (see http://bugs.ruby-lang.org/issues/show/2509). if key.respond_to?(:clone) key = key.clone key.freeze if key.respond_to?(:freeze) end hash[key] = key end [:new, :[]].each do |name| if obj.respond_to?(name) obj.singleton_class.module_exec(obj.method(name)) do |orig| define_method name do |*args, &amp;block| intern_pool[orig[*args, &amp;block]] end end end end end end </code></pre> <p>Example usage:</p> <pre><code>Foo = Struct.new :foo, :bar do extend Interner end a = Foo[1, 2] b = Foo[3, 4] c = Foo.new(1, 2) d = Foo.new(3, 4) a.equal?(c) # =&gt; true b.equal?(d) # =&gt; true </code></pre> <p>I realise that my implementation is less than perfect. What improvements can you recommend?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-20T09:31:36.840", "Id": "62874", "Score": "0", "body": "nice little lib :) Maybe you could make it thread-safe, by synchronizing access to intern_pool with a mutex ? also I think the same functionnality could be achieved using a gem like memoist and memoizing ::new on the extended class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T20:11:00.807", "Id": "64467", "Score": "1", "body": "@m_x It's actually different from memoist. Memoist caches values based on the arguments. An interner caches the resulting values themselves. So if two calls (with different arguments) result in equal objects, they should return the same instance. See my example with `Foo[1, 2]` vs `Foo.new(1, 2)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T11:23:06.153", "Id": "64543", "Score": "0", "body": "oh, cool. learned something today :)" } ]
[ { "body": "<p>I can't see much I'd change. It's a pretty neat concept, well done. I wouldn't change much. First, the minor things.</p>\n\n<p>I would consider changing the name of the argument to <code>Interner.extended</code> from <code>obj</code> to <code>klass</code>.</p>\n\n<p>Being a member of the \"lots of tiny methods\" fan club, I'd consider this:</p>\n\n<pre><code> def self.extended(klass)\n intern_pool = make_intern_pool\n ...\n end\n\n def self.make_intern_pool\n Hash.new do |hash, key|\n key = freeze_key(key)\n hash[key] = key\n end\n end\n\n def self.freeze_key(key)\n # Ideally, this should be a deep freeze, but it's not supported\n # (see http://bugs.ruby-lang.org/issues/show/2509).\n if key.respond_to?(:clone)\n key = key.clone\n key.freeze if key.respond_to?(:freeze)\n end\n key\n end\n</code></pre>\n\n<p>Now, on to bigger things. Interner makes a resonable assumption that <code>new</code> is a factory method. However, its assumption that <code>[]</code> is a factory method is less reasonable. That's certainly the case for <code>Struct</code>, and perhaps for many other classes, but not necessarily always. I would prefer to see a way to make explicit the name(s) of the factory methods, so that I have control over which methods are wrapped by Interner. There should still be an easy, default way to use Interner that wraps <code>new</code>, but perhaps there could be another way to use it that lets you specify which methods to wrap.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T17:20:43.410", "Id": "38707", "ParentId": "36470", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-01T22:31:41.960", "Id": "36470", "Score": "3", "Tags": [ "ruby", "meta-programming" ], "Title": "Ruby 1.9 interner" }
36470
<p>The users get permissions to do specific things for a specific group of employees. These employee groups have a self reference. So an employee group (C) can be a child of group (B), and group (B) is child of (A). The user is granted permission to employee group (A), so if I want to check if the permission is granted for that user on employee group (C) it should give me <code>true</code> because the user is granted the permission on the parent or grandparent group. Currently, I am using this method and it works fine but I find it ugly and complicated a bit. Is there a more elegant way to do it?</p> <p>This is the method:</p> <pre><code>public static bool CheckPermission(Session session, string right, int? emplooyeGroupID = null) { using (Context db = new Context()) { bool pass = false; var assigns = db.SecurityAssigns .Where(g =&gt; g.UserID == session.UserID); // if employeeGroupID is supplied we need to do some work here... if (emplooyeGroupID.HasValue) { // first, we get all 'groups' that have the requested SecurityRight assigns = assigns.Where(g =&gt; g.SecurityGroup.SecurityRightsInGroups.Any(r =&gt; r.SecurityRight.Right == right)); foreach (var grp in assigns) { // if the employee group matches, then its a pass if (grp.EmployeeGroupID == emplooyeGroupID) { pass = true; break; } // if we reach here, it means the EmployeeGroupID does not match the EmployeeGroupID assigned for the SecurityRight. // so we need to check if the requested EmployeeGroupID is a child of the EmployeeGroupID assigned to the SecurityRight var curGroup = db.EmployeeGroups.Single(g =&gt; g.ID == emplooyeGroupID); // loop through parents of the requested EmployeeGroup all the way up while (curGroup.ParentGroupID.HasValue) { // is the parent authorized? if (curGroup.ParentGroupID == grp.EmployeeGroupID) { pass = true; break; } // parent is not authorized, go up one more step curGroup = db.EmployeeGroups.Single(g =&gt; g.ID == curGroup.ParentGroupID); } } } else { pass = assigns.Any(g =&gt; g.SecurityGroup.SecurityRightsInGroups.Any(r =&gt; r.SecurityRight.Right == right)); } if (!pass) throw new FaultException(&quot;Not Authorized!&quot;, new FaultCode(Common.ErrorCodes.NOT_AUTHORIZED_ERROR_CODE)); return true; } } </code></pre> <p>This is some the tables I am working with in the code above:</p> <p><img src="https://i.stack.imgur.com/nRX8r.png" alt="enter image description here" /></p> <p>P.S. I am not a programmer and I didn't get any education on programming, it is just a hobby. So go easy on me if my coding is ugly :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T19:44:30.970", "Id": "60092", "Score": "0", "body": "It seems that my question is seriously bad :/" } ]
[ { "body": "<p>No. I don't think your question is bad. It's only hard to answer on, since there are so many different ways to solve the problem your method addresses. And if they are better or not is kind of subjective. With that said here are some comment on your method:</p>\n\n<p>Your method is too long and does too many things. I would recommend breaking it up into smaller method that does one thing; one that get the stuff from the database, one that checks the group permission and one that checks the parent group permission. Then the responsibility of the main method is to invoke the other if needed (and in what order).</p>\n\n<p>I don't think the signature of the method is the best. Having int? emplooyeGroupID = null as a parameter is a clear indication that your method does two different major things; one if int? emplooyeGroupID is null and one if not. I would break it into two methods:</p>\n\n<pre><code>static bool CheckPermission(Session session, string right);\nstatic bool CheckGroupPermission(Session session, string right, int emplooyeGroupID);\n</code></pre>\n\n<p>Then it will be up to the caller (client) to choose the right one. And since the caller knows if the emplooyeGroupID is null or not, the CheckPermission method don't need to \"if\" on it.</p>\n\n<p>Why do you return true on the last line? I would definitely return false!</p>\n\n<p>Otherwise you should be happy if the method does what you want it to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:57:32.687", "Id": "36603", "ParentId": "36478", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T00:40:36.980", "Id": "36478", "Score": "1", "Tags": [ "c#", "security", "recursion" ], "Title": "Checking user permission, where permission is granted for specific EmployeeGroup that has self reference" }
36478
<p>I went with what I know and can use well, not what I know and can't figure the syntax out to make it look good.</p> <p>So please enjoy the code and prepare to school me (probably in the basics) in C#</p> <pre><code>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 */ List&lt;string&gt; listOfGestures = new List&lt;string&gt;(); listOfGestures.Add("rock"); listOfGestures.Add ("paper"); listOfGestures.Add ("scissors"); listOfGestures.Add ("lizard"); listOfGestures.Add ("spock"); int win = 0; int lose = 0; int tie = 0; var newGame = true; while (newGame) { var playerGesture = ""; var validInput = false; while (!validInput) { var playerChoice = -1; Console.WriteLine("Please choose your Gesture "); gameSetup(listOfGestures); try { playerChoice = Convert.ToInt32 (Console.ReadLine()); } catch (FormatException e) { validInput = false; } if (playerChoice &gt; 0 &amp;&amp; playerChoice &lt;= listOfGestures.Count) { playerGesture = listOfGestures[playerChoice - 1]; validInput = true; } else { validInput = false; } } var computerPlay = ComputerGesture(listOfGestures); Console.WriteLine ("Computer: " + computerPlay); Console.WriteLine ("your Gesture: " + playerGesture); if (playerGesture == computerPlay) { tie++; Console.WriteLine ("you have tied with the computer"); Console.WriteLine ("Computer: " + computerPlay); Console.WriteLine ("your Gesture: " + playerGesture); } else { if (playerGesture == "rock") { if (computerPlay == "lizard" || computerPlay == "scissors") { Console.WriteLine ("You Win, " + playerGesture + " Crushes " + computerPlay); win++; } else if (computerPlay == "paper") { Console.WriteLine ("You Lose, Paper Covers Rock"); lose++; } else if (computerPlay == "spock") { Console.WriteLine ("You Lose, Spock Vaporizes Rock"); lose++; } } else if (playerGesture == "paper") { if (computerPlay == "spock") { Console.WriteLine ("You Win, Paper Disproves Spock"); win++; } else if (computerPlay == "rock") { Console.WriteLine ("You Win, Paper Covers Rock"); win++; } else if (computerPlay == "lizard") { Console.WriteLine ("You Lose, Lizard Eats Paper"); lose++; } else if (computerPlay == "scissors") { Console.WriteLine ("You Lose, Scissors Cut Paper"); lose++; } } else if (playerGesture == "scissors") { if (computerPlay == "paper") { Console.WriteLine ("You Win, Scissors Cut Paper"); win++; } else if (computerPlay == "lizard") { Console.WriteLine ("You Win, Scissors Decapitate Lizard"); win++; } else if (computerPlay == "rock") { Console.WriteLine ("You Lose, Rock Crushes Scissors"); lose++; } else if (computerPlay == "spock") { Console.WriteLine ("You Lose, Spock Smashes Scissors"); lose++; } } else if ( playerGesture == "lizard") { if (computerPlay == "paper") { Console.WriteLine ("You Win, Lizard Eats Paper"); win++; } else if (computerPlay == "spock") { Console.WriteLine ("You Win, Lizard Poisons Spock"); win++; } else if (computerPlay == "scissors") { Console.WriteLine ("You Lose, Scissors Decapitates Lizard"); lose++; } else if (computerPlay == "rock") { Console.WriteLine ("You Lose, Rock Crushes Lizard"); lose++; } } else if (playerGesture == "spock") { if (computerPlay == "rock") { Console.WriteLine("You Win, Spock Vaporizes Rock"); win++; } else if (computerPlay == "scissors") { Console.WriteLine ("You Win, Spock Smashes Scissors"); win++; } else if (computerPlay == "paper") { Console.WriteLine ("You Lose, Paper Disproves Spock"); lose++; } else if (computerPlay == "lizard") { Console.WriteLine("You Lose, Lizard Poisons Spock"); lose++; } } } Console.WriteLine ("Your Score is (W:L:T:) : {0}:{1}:{2}", win, lose, tie); Console.WriteLine ("Again? Type 'n' to leave game."); if (Convert.ToString (Console.ReadLine ().ToLower ()) == "n") { Console.WriteLine ("would you like to reset your Score?"); if (Convert.ToString (Console.ReadLine ().ToLower ()) == "y") { win = 0; lose = 0; tie = 0; } Console.WriteLine ("would you like to play another game?"); Console.WriteLine ("if you type 'n' the game will end."); if (Convert.ToString(Console.ReadLine().ToLower()) == "n") { newGame = false; } } } Console.WriteLine("Goodbye"); Console.ReadLine (); } </code></pre> <p>Helper Methods that I used. I could probably use a couple more.</p> <pre><code>public static void gameSetup (List&lt;string&gt; List) { for (int i=0; i&lt;List.Count; i++) { Console.WriteLine ((i+1) + ": " + List[i]); } } </code></pre> <p>With <code>Random</code> here I am not sure that I am using it correctly or if Random should be a static variable in the class scope and I should just be calling <code>rand.next()</code> everytime that I need to use it.</p> <pre><code>public static string ComputerGesture (List&lt;string&gt; options) { Random rand = new Random(); return options[rand.Next(0,options.Count)]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:11:55.840", "Id": "59837", "Score": "4", "body": "I actually like gestures be just a list of strings. Later if/else spaghetti kills the appetite though. ChrisWue is right in pointing out that you are using magic constants all over the place. The payoff logic is a static data structure also, which some other RPSLS implementors here got; and can be factored out just like you did for the gestures, which some other implementors missed." } ]
[ { "body": "<ol>\n<li><p>Some minor syntax detail: C# has collection initializers so one can write:</p>\n\n<pre><code>List&lt;string&gt; listOfGestures = new List&lt;string&gt; {\n \"rock\", \"paper\", \"scissors\", \"lizard\", \"spock\" \n}\n</code></pre></li>\n<li><p>You use magic strings for the gestures all over the place. This can pose a problem if you want to change them. You could do a find and replace but this could inadvertently change a part of a method or variable name which happens to include \"rock\" if you are not careful. </p>\n\n<p>In other solutions to the problem posted before <code>enum</code>s were used instead. If you insist on using strings then make them named constants and use those instead</p>\n\n<pre><code>const string Rock = \"rock\";\nconst string Paper = \"paper\";\n... etc.\n</code></pre></li>\n<li><p>The main problem is that the entire implementation is basically just one big blob of code in the main method. Logic and input/output are totally intertwined. Assume you have to write an automated test case for this - it will drive you insane. </p>\n\n<p>If I were to encounter code like this in production I would very likely kill it and rewrite it - the problem is fairly simple and given it's untestable there aren't any unit tests anyway. If the code were too much to rewrite then I'd start refactoring it. Possible steps:</p>\n\n<ol>\n<li><p>Create a <code>Game</code> class which effectively encapsulates the main <code>while</code> loop up until the line <code>Console.WriteLine (\"Your Score is (W:L:T:) : {0}:{1}:{2}\", win, lose, tie);</code></p>\n\n<ul>\n<li>Dump everything into one method into that class for starters.</li>\n<li>The <code>Game</code> class should also keep track of the score.</li>\n<li>Override <code>ToString</code> to print out the current scores.</li>\n<li>Move the \"ask user if he wants to play another round\" into a method on the <code>Game</code> class</li>\n</ul>\n\n<p>After that the <code>Main</code> should look somewhat like this:</p>\n\n<pre><code>var game = new Game();\nvar continuePlaying = true;\nwhile (continuePlaying)\n{\n game.Play();\n Console.WriteLine(game.ToString());\n continuePlaying = game.ShouldContinue();\n}\n</code></pre></li>\n<li><p>Next step would be to start refactoring the <code>Game</code> class and the methods within.</p>\n\n<ul>\n<li><p>Move the decision logic into it's own internal private method to reduce the bulk of the <code>Play()</code> method.</p></li>\n<li><p>Define an interface for getting user input and another one for writing output. Pass these interfaces into the <code>Game</code> constructor. Provide a console implementation for both interfaces. Change all the input and output to use the interfaces rather than the console.</p></li>\n<li><p>Now <code>Game</code> is decoupled from the specific input and output methods and you can start writing unit tests for the <code>Play()</code> and the <code>ShouldContinue()</code> methods. Once you have done that you can continue refactoring those methods. And because you have just created unit tests you should be able to detect if you create any regressions (introducing bugs) while doing so.</p></li>\n<li><p>Wash, Rinse, Repeat</p></li>\n</ul></li>\n</ol></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:25:55.800", "Id": "59872", "Score": "0", "body": "thank you for giving me the next couple of steps to take, this helps me with the learning process. I won't be able to put up new revised code for a week or so, but you can bet that I will work on this game in a week or so. Thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:29:45.847", "Id": "59884", "Score": "1", "body": "`Console.WriteLine(game.ToString());` This can be simplified to just `Console.WriteLine(game);`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:33:27.787", "Id": "59885", "Score": "0", "body": "Also, when you have strings all over the place, refactoring is an issue, but I think much bigger problem are typos: it's very easy to make a single typo somewhere and it's not trivial to discover bugs like that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T08:28:15.170", "Id": "36491", "ParentId": "36482", "Score": "18" } }, { "body": "<ol>\n<li><p>An enum will serve you much better than a list of strings.</p>\n\n<pre><code>enum Gesture\n{\n Rock = 1,\n Paper = 2,\n Scissors = 3,\n Spock = 4,\n Lizard = 5\n}\n</code></pre></li>\n<li><p>A naming convention. If a variable is a counter and its name describes what is being counted, it should then be plural.</p>\n\n<pre><code>int wins = 0;\nint loses = 0;\nint ties = 0;\n</code></pre></li>\n<li><p>And now at this point, I don't want to just correct small bits of this code, but restructure it to use some OOP. But I won't, just know that next time you make a game, OOP is much better, modularization is the keyword right there (if it even is a word).</p></li>\n<li><p>The Method Name <code>gameSetup</code> should start with a capital letter. Especially because it is public, if it was private you could make it lower-case, though I would still not recommend it.</p></li>\n<li><p>Inside GameSetup you really aren't doing a lot of logic that you would normally want removed from the pretty business logic. On top of that, you are only calling this function in one place in your code, so it benefits you about.... not at all. And now that I've taken away your gesture list I will replace the code that you will need here for that.</p>\n\n<p>Using <code>foreach</code>:</p>\n\n<pre><code>foreach (Gesture gesture in (Gesture[])Enum.GetValues(typeof(Gesture)))\n{\n Console.WriteLine((int)gesture + Enum.GetName(typeof(Gesture), gesture));\n}\n</code></pre>\n\n<p>Using <code>for</code>:</p>\n\n<pre><code>for (int i = 1; i &lt;= 5; i++)\n{\n Console.WriteLine(i + Enum.GetName(typeof(Gesture), i));\n}\n</code></pre>\n\n<p>While either of the above loops will work, I would recommend only using the first one. As the second one only works aslong as you don't change the <code>enum</code> at all, which in any other situation would not work out so well.</p></li>\n<li><p>You mentioned that you weren't sure about how you were using the <code>Random</code> class. You said <code>or if Random should be a static variable in the class scope</code>. Yes, you should move rand to the class scope. However that is not 100% necessary. I want to say though, that as you are declaring rand in a static method, it is a static variable.. infact everything you are doing here is static. If you had gone the way of OOP you would have had some non-static stuff, but.. you didn't.</p></li>\n<li><p><code>ComputerGesture</code> is another example of a method which is only called once and does very little code. This would have been better suited to stay with the rest of the main logic and just had a comment placed above it saying, computer gesture. Also a code change, which is just something I like to do.. replace the contents of that method with. Note... I'm also renaming this to <code>GetComputerGesture()</code>, because.... it gets the computer gesture</p>\n\n<pre><code>return options[new Random().Next(0, options.Count)];\n</code></pre>\n\n<p>however, because I changed your string array to enums, this is what it would have to look like</p>\n\n<pre><code>public static Gesture GetComputerGesture()\n{\n var vals = Enum.GetValues(typeof(Gesture));\n return (Gesture)vals.GetValue(new Random().Next(vals.Length));\n}\n</code></pre>\n\n<hr>\n\n<p>Now lets start on your main loop. </p></li>\n<li><p>This isn't super important, but because you do know that you will be playing atleast one game, you could make your main <code>while</code> loop, a <code>do while</code>. the same goes for your next loop checking to see if the user input is valid.</p></li>\n<li><p>Now user input is something that I personally would separate out into a method. It is a large chunk of code, and though in your case it is only being called once, it is something that you may want to re-use if you add a second user player. So lets do that... </p>\n\n<p>Here is a method I wrote to get an <code>integer</code> value from the user, and reject that value if it did not fall between the given range. Notice how I use <code>int.TryPase()</code> instead of attempting to parse the <code>integer</code> in a <code>try</code> block. I did this because, it is both nicer code, and is more efficient. <code>Exception</code> handling is a costly run-time operation, and relying on an <code>exception</code> to be thrown should be avoided if at all possible. If you have not seen the out keyword before, this would be a good time to do some research. As you can see when I call <code>int.TryParse()</code> it takes an out parameter. These are the C# version of pointers (While pointers do exist... don't use them as long as you don't have to). So instead of <code>TryParse</code> returning the parsed number, it returns whether or not it succeeded, and sends out the parsed value in its <code>out</code> parameter, in this case <code>g</code>.</p>\n\n<p>I should also point out that I used default values in the parameters, this means now whenever you use this method, you can actually not send in parameters and they will default to the specified values. If you wanted to only change the value of prompt when calling this method you would just say this <code>GetIntInRange(prompt: \"Hey this is my new prompt\");</code> and the others will default.</p>\n\n<pre><code>public static int GetIntInRange(int min = int.MinValue, int max = int.MaxValue, string prompt = \"Please enter an Integer: \")\n{\n int g;\n do\n {\n Console.Write(prompt);\n if (int.TryParse(Console.ReadLine(), out g))\n {\n if (g &gt;= min &amp;&amp; g &lt;= max)\n return g;\n Console.WriteLine(\"You entered {0}, but the input must be in the range of ({1} - {2}. Please try again...\", g, min, max);\n }\n else\n Console.WriteLine(\"That is not a real number. Please try again...\");\n } while (true);\n}\n</code></pre></li>\n<li><p>I know earlier I said that it was fairly pointless to have ComputerGesture be its own method, because it was doing very limited things and was only called once. I will say however because I do expect you to change this program to be Object Oriented, or at-least make your next game as such, that an operation like Computer or Player Gesture should be modularized. Its just in your main loop it didn't make a difference. That being said, lets make a super short method called <code>GetPlayerGesture</code>! We can use that GetIntInRange Method we just wrote. Also at this point, I realize we have had to use the list of <code>Gesture</code> <code>enums</code> a lot, so I just decided to add this <code>private</code> <code>static</code> member. So that we don't have to keep creating the list on the fly.</p>\n\n<pre><code>private static Gesture[] _gestures = (Gesture[])Enum.GetValues(typeof(Gesture));\n</code></pre>\n\n<p>And now for the <code>GetPlayerGesture</code> Method.... 1 line :D</p>\n\n<pre><code>public static Gesture GetPlayerGesture()\n{\n return (Gesture)GetIntInRange((int)_gestures.First(), (int)_gestures.Last(), \"Please choose your Gesture: \");\n}\n</code></pre></li>\n<li><p>Progress update on the Main Method (comments removed to not take up too much space)</p>\n\n<pre><code>public static void Main(string[] args)\n{\n int wins = 0;\n int loses = 0;\n int ties = 0;\n\n var newGame = true;\n do\n {\n GameSetup();\n Gesture playerGesture = GetPlayerGesture();\n Gesture computerGesture = GetComputerGesture();\n\n Console.WriteLine(\"Computer: \" + computerGesture);\n Console.WriteLine(\"Your Gesture: \" + playerGesture);\n\n //The rest of the program here\n</code></pre></li>\n<li><p>The one thing that is absolutely needed in here, is to move the code that calculates who won to another method, this is a case where code is just too big to chill with your main logic. If you wanted to, you could just put #region tags around this chunk, and call it good too, but this code should also be made more generic incase you wanted to use 2 players instead of just one and a computer, or have 2 computers duke it out 1,000,000,000 times in a couple seconds. I also feel this code could be written more efficiently... lets try.</p>\n\n<p>In the following method I converted each <code>Gesture</code> to an <code>int</code>, which you will notice were defined when we created the <code>enum</code> at the top. We can also see that every gesture loses to a number which is one higher than itself, but beats any number 2 higher than itself, and this pattern continues to alternate. So if we add up the numbers and the number is odd, that means the player with the higher number wins. At this point there are quite a few ways we could go about this.</p>\n\n<p>This little bit of code adds player1 and player2's enum values together, and gets the remainder when dividing by 2, if there is no remainder, then the sum of these two values is even <code>(p1 + p2) % 2 == 0</code>.</p>\n\n<p>Now we only want to say that player 1 won if player1 chose an even number and the sum of the choice was even, or if the opposite of both of these are true, The logical result we are looking for is called XNOR, which is simply bool == bool. So our Method would look like this.</p>\n\n<pre><code>public static int WhoWon(Gesture player1, Gesture player2)\n{\n if (player1 == player2) return 0;\n\n int p1 = (int)player1;\n int p2 = (int)player2;\n\n bool isEven = (p1 + p2) % 2 == 0;\n bool player1IsHigher = player1 &gt;player2;\n\n if (player1IsHigher == isEven)\n return 1;\n else \n return 2;\n}\n</code></pre>\n\n<p>But, because we like to be concise and complex as programmers, lets collapse some of this together and use a couple inline <code>OR</code>s</p>\n\n<pre><code>public static int WhoWon(Gesture player1, Gesture player2)\n{\n return (player1 == player2) ? 0 : (((int)player1 % 2 == 0) == (((int)player1 + (int)player2) % 2 == 0)) ? 1 : 2;\n}\n</code></pre>\n\n<p>Now we have a simple little method that returns 0 if there is a tie, or 1,2 depending on who the winner is.</p></li>\n<li><p>We need the customized messages revamped now that we changed how we decide the winner. For this I have created a Dictionary, string> with all the possible actions which will happen when a specific Gesture wins over another. I used Tuple objects as keys and strings for values. Instead of only storing the actions, I could have stored the entire response string... but that would have been more typing for me. So here is the dictionary.</p>\n\n<pre><code>private static Dictionary&lt;Tuple&lt;int, int&gt;, string&gt; _actions = new Dictionary&lt;Tuple&lt;int, int&gt;, string&gt;()\n{\n {Tuple.Create&lt;int,int&gt;(1,3), \"Crushes\"},\n {Tuple.Create&lt;int,int&gt;(1,5), \"Crushes\"},\n {Tuple.Create&lt;int,int&gt;(2,1), \"Covers\"},\n {Tuple.Create&lt;int,int&gt;(2,4), \"Disproves\"},\n {Tuple.Create&lt;int,int&gt;(3,2), \"Cuts\"},\n {Tuple.Create&lt;int,int&gt;(3,5), \"Decapitates\"},\n {Tuple.Create&lt;int,int&gt;(4,3), \"Smashes\"},\n {Tuple.Create&lt;int,int&gt;(4,1), \"Vaporizes\"},\n {Tuple.Create&lt;int,int&gt;(5,2), \"Eats\"},\n {Tuple.Create&lt;int,int&gt;(5,4), \"Poisons\"}\n};\n</code></pre>\n\n<p>And here is all you need to retrieve the reason why someone won or lost.</p>\n\n<pre><code>public static string GetReason(Gesture winner, Gesture loser)\n{\n return winner + \" \" + ACTIONS[Tuple.Create((int)winner, (int)loser)] + \" \" + loser;\n}\n</code></pre></li>\n<li><p>I would do the following differently if this was Object Oriented. Just so you know... if you were doing this OO, you would have a Player which remember how many wins and losses that player had. So for this program, we are assuming that wins, loses, ties are playerWins, playerLoses, playerTies.</p>\n\n<p>Here, I've written a Method to simply get Y or N input and not even recognize anything else.</p>\n\n<pre><code>public static bool GetYN(string prompt = \"(y/n): \")\n{\n do\n {\n Console.Write(prompt);\n switch (Console.ReadKey(true).Key)\n {\n case ConsoleKey.Y: Console.Write(\"Y\\n\"); return true;\n case ConsoleKey.N: Console.Write(\"N\\n\"); return false;\n }\n } while (true);\n}\n</code></pre>\n\n<p>Using these last two methods I've refactored the rest of your logic using them, and this is what I got in the end</p>\n\n<pre><code> switch (WhoWon(playerGesture, computerGesture))\n {\n case 0: ties++; Console.WriteLine(\"You have tied with the the computer.\"); break;\n case 1: wins++; Console.WriteLine(\"You win, \" + GetReason(playerGesture, computerGesture)); break;\n case 2: loses++; Console.WriteLine(\"You lose, \" + GetReason(computerGesture, playerGesture)); break;\n }\n\n Console.WriteLine(\"Your Score is (W:L:T:) : {0}:{1}:{2}\", wins, loses, ties);\n\n Console.Write(\"Would you like to play again? \");\n if(!GetYN())\n {\n Console.WriteLine(\"would you like to reset your Score?\");\n if (GetYN())\n {\n wins = loses = ties = 0;\n }\n Console.Write(\"Would you like to play again? \");\n newGame = GetYN();\n }\n Console.WriteLine();\n } while (newGame);\n Console.WriteLine(\"Goodbye\\nPress any key to close...\");\n Console.ReadKey(true);\n}\n</code></pre></li>\n</ol>\n\n<p>In-case I forgot anything, or you just want to grab the sum of the changes, here is the whole dump.</p>\n\n<pre><code>enum Gesture\n{\n Rock = 1,\n Paper = 2,\n Scissors = 3,\n Spock = 4,\n Lizard = 5\n}\n\nclass Program\n{\n private static Gesture[] _gestures = (Gesture[])Enum.GetValues(typeof(Gesture));\n\n private static Dictionary&lt;Tuple&lt;int, int&gt;, string&gt; _actions = new Dictionary&lt;Tuple&lt;int, int&gt;, string&gt;()\n {\n {Tuple.Create&lt;int,int&gt;(1,3), \"Crushes\"},\n {Tuple.Create&lt;int,int&gt;(1,5), \"Crushes\"},\n {Tuple.Create&lt;int,int&gt;(2,1), \"Covers\"},\n {Tuple.Create&lt;int,int&gt;(2,4), \"Disproves\"},\n {Tuple.Create&lt;int,int&gt;(3,2), \"Cuts\"},\n {Tuple.Create&lt;int,int&gt;(3,5), \"Decapitates\"},\n {Tuple.Create&lt;int,int&gt;(4,3), \"Smashes\"},\n {Tuple.Create&lt;int,int&gt;(4,1), \"Vaporizes\"},\n {Tuple.Create&lt;int,int&gt;(5,2), \"Eats\"},\n {Tuple.Create&lt;int,int&gt;(5,4), \"Poisons\"}\n };\n\n public static void Main(string[] args)\n {\n /* Here are your rules: \n \"Scissors cuts paper, \n paper covers rock, \n rock crushes lizard, \n lizard poisons Spock, \n Spock smashes scissors, \n scissors decapitate lizard, \n lizard eats paper, \n paper disproves Spock, \n Spock vaporizes rock. \n And as it always has, rock crushes scissors.\" \n -- Dr. Sheldon Cooper */\n\n int wins = 0;\n int loses = 0;\n int ties = 0;\n\n var newGame = true;\n do\n {\n GameSetup();\n Gesture playerGesture = GetPlayerGesture();\n Gesture computerGesture = GetComputerGesture();\n\n Console.WriteLine(\"Computer: \" + computerGesture);\n Console.WriteLine(\"Your Gesture: \" + playerGesture);\n\n switch (WhoWon(playerGesture, computerGesture))\n {\n case 0: ties++; Console.WriteLine(\"You have tied with the the computer.\"); break;\n case 1: wins++; Console.WriteLine(\"You win, \" + GetReason(playerGesture, computerGesture)); break;\n case 2: loses++; Console.WriteLine(\"You lose, \" + GetReason(computerGesture, playerGesture)); break;\n }\n\n Console.WriteLine(\"Your Score is (W:L:T:) : {0}:{1}:{2}\", wins, loses, ties);\n\n Console.Write(\"Would you like to play again? \");\n if (!GetYN())\n {\n Console.WriteLine(\"Would you like to reset your Score?\");\n if (newGame = GetYN())\n {\n wins = loses = ties = 0;\n }\n if (!newGame)\n break;\n\n Console.Write(\"Would you like to play again? \");\n newGame = GetYN();\n }\n Console.WriteLine();\n } while (newGame);\n Console.WriteLine(\"Goodbye\\nPress any key to close...\");\n Console.ReadKey(true);\n }\n\n public static int WhoWon(Gesture player1, Gesture player2)\n {\n return (player1 == player2) ? 0 : (((int)player1 % 2 == 0) == (((int)player1 + (int)player2) % 2 == 0)) ? 1 : 2;\n }\n\n public static int GetIntInRange(int min = int.MinValue, int max = int.MaxValue, string prompt = \"Please enter an Integer: \")\n {\n int g;\n do\n {\n Console.Write(prompt);\n if (int.TryParse(Console.ReadLine(), out g))\n {\n if (g &gt;= min &amp;&amp; g &lt;= max)\n return g;\n Console.WriteLine(\"You entered {0}, but the input must be in the range of ({1} - {2}. Please try again...\", g, min, max);\n }\n else\n Console.WriteLine(\"That is not a real number. Please try again...\");\n } while (true);\n }\n\n public static bool GetYN(string prompt = \"(y/n): \")\n {\n do\n {\n Console.Write(prompt);\n switch (Console.ReadKey(true).Key)\n {\n case ConsoleKey.Y: Console.Write(\"Y\\n\"); return true;\n case ConsoleKey.N: Console.Write(\"N\\n\"); return false;\n }\n } while (true);\n }\n\n public static void GameSetup()\n {\n foreach (Gesture gesture in _gestures)\n {\n Console.WriteLine((int)gesture + \": \" + Enum.GetName(typeof(Gesture), gesture));\n }\n }\n\n public static Gesture GetComputerGesture()\n {\n return (Gesture)_gestures.GetValue(new Random().Next(_gestures.Length));\n }\n\n public static Gesture GetPlayerGesture()\n {\n return (Gesture)GetIntInRange((int)_gestures.First(), (int)_gestures.Last(), \"Please choose your Gesture: \");\n }\n\n public static string GetReason(Gesture winner, Gesture loser)\n {\n Tuple&lt;int, int&gt; k = _actions.Keys.Where(key =&gt; key.Item1 == (int)winner &amp;&amp; key.Item2 == (int)loser).FirstOrDefault();\n\n foreach (var key in _actions.Keys)\n {\n int w = (int)winner;\n int l = (int)loser;\n if (key.Item1 == w &amp;&amp; key.Item2 == l)\n k = key;\n }\n\n return winner + \" \" + _actions[k] + \" \" + loser;\n }\n}\n</code></pre>\n\n<p><strong>Edit</strong>: I recently realized that using math to determine the winner is all fun and games, but really we created a <code>Dictionary</code> of who beats who called <code>_actions</code>, why not use it? So I've re-written the <code>WhoWon</code> Method, which is now slightly longer, but more easily scaled, and not dependent on the <code>Gesture</code> <code>enums</code> being in a certain order to work. This replaces # 12</p>\n\n<pre><code>public static int WhoWon(Gesture player1, Gesture player2)\n{\n return player1 == player2 ? 0 :_actions.Keys.Where(key =&gt; key.Item1 == (int)player1 &amp;&amp; key.Item2 == (int)player2).FirstOrDefault() != null ? 1 : 2;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-06T22:35:03.843", "Id": "75510", "Score": "2", "body": "Concerning point 5. There is a big theoretic point in doing this: readability / selfdocumentation. It's just not done right. Same applies for point 7, where OP has done it right. Try to respect OP in your reviews and explain why you changed stuff. Also if you recommend not using something, why did you include it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T13:59:55.907", "Id": "75602", "Score": "0", "body": "@Vogel612 Perhaps it is just an opinion, but I don't believe there is any reason to move any less than 4 lines of code to a method unless it is or could be called more than once.\nI included code that I didn't recommend, because I wanted him to be aware of the 2 techniques which produced the same result, and explain why chose to go with what seemed like more complex code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T15:27:38.720", "Id": "75623", "Score": "0", "body": "@BenVlodgi I will strongly disagree with your point point, extracting 4 lines of code in a function even if call once is a good thing! This can demonstrate that those 4 lines of codes are doing something special that is a subset of what the big function is doing. This helps when you read the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T15:39:21.910", "Id": "75624", "Score": "0", "body": "@Marc-Andre In his case, I would have preferred he had just wrapped that code with #region Tags. I do agree that separation of code based on function is good, but I felt that the two places it was done were not the 2 places it NEEDed to be done. To expand more on that, I wouldn't have had such a problem with his extracting 2 lines of code for a method if he had also extracted the 57 lines which determined the winner to a method. To me, that was a much more important change to make in the name of readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T18:37:47.067", "Id": "75663", "Score": "0", "body": "I would rather not use a `do while`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T18:49:54.910", "Id": "75664", "Score": "0", "body": "@Malachi Any particular reason?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T19:22:15.753", "Id": "75668", "Score": "0", "body": "because it is sloppy. what if I want to create an option in the future where I don't want to go into the loop? now I have to change my loop. also, I want to know what is making my loop loop, a `do while` is like walking on a sidewalk with my eyes closed, I know there is a sidewalk there but I don't know how far it goes until I reach the end. or a Roller coaster that doesn't start where it ends." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T19:28:19.957", "Id": "75669", "Score": "0", "body": "@Malachi Do-While loops are not sloppy, they are efficient. While it is true that as the programmer you do not immediately know when this loop is going to end, it does require one less boolean check. This isn't a big deal, I realize, but being in the efficient mindset at all times is a big deal. Feel free to not use a do-while, it will not change how the program runs from a user perspective at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T19:33:36.277", "Id": "75672", "Score": "0", "body": "http://chat.stackexchange.com/rooms/13448/loops" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-06T21:59:58.137", "Id": "43654", "ParentId": "36482", "Score": "14" } }, { "body": "<p>In my <a href=\"https://codereview.stackexchange.com/a/43654/38054\">original review</a> of this program I mentioned I really wanted to re-do this in OO. So I have. I recommend you read my first review to get most of the reasons behind much of the code refactoring I did.</p>\n\n<ol>\n<li><p>Right off the bat I created two <code>enums</code> which will be helpful in the rest of the program. a <code>Gesture</code> <code>enum</code> which holds all possible playable <code>Gestures</code>, and a <code>Performance</code> <code>enum</code> to communicate to a player how they did during a <code>Game</code>.</p>\n\n<pre><code>enum Gesture\n{\n Rock = 1,\n Paper = 2,\n Scissors = 3,\n Spock = 4,\n Lizard = 5\n}\n\nenum Performance\n{\n Lost = -1,\n Tied = 0,\n Won = 1\n}\n</code></pre></li>\n<li><p>I created an <code>abstract</code> <code>Player</code> <code>class</code> which handled the specific player data. From here I created a <code>Human</code> and <code>Computer</code> <code>class</code>, which inherits from <code>Player</code>, and implemented their <code>GetMove</code> methods, because that is the only place where these two types of players differ.</p>\n\n<pre><code>abstract class Player\n{\n public uint Wins { get; private set; }\n public uint Loses { get; private set; }\n public uint Ties { get; private set; }\n\n public abstract Gesture GetMove();\n\n public string GetScoreCard()\n {\n return \"[Wins: \" + Wins + \"] [Loses \" + Loses + \"] [Ties \" + Ties + \"]\";\n }\n\n public void ClearScore()\n {\n Wins = Loses = Ties = 0;\n }\n\n public void GiveResult(Performance performance)\n {\n switch (performance)\n {\n case Performance.Lost: Loses++; break;\n case Performance.Tied: Ties++; break;\n case Performance.Won: Wins++; break;\n }\n }\n}\n\nclass Human : Player\n{\n public override Gesture GetMove()\n {\n Utils.PrintMenu(Game.Gestures.Select(g =&gt; g.ToString()).ToList(), 1);\n return (Gesture)Utils.PromptForRangedInt((int)Game.Gestures.First(), (int)Game.Gestures.Last(), \"Please choose your Gesture: \");\n }\n}\n\nclass Computer : Player\n{\n public override Gesture GetMove()\n {\n return (Gesture)Game.Gestures.GetValue(new Random().Next(Game.Gestures.Length));\n }\n}\n</code></pre></li>\n<li><p>I created a <code>static</code> <code>Game</code> <code>class</code>. This one is <code>static</code> because I didn't think it was necessary to create a new <code>Game</code> <code>object</code> every-time you wanted to play. Instead I implemented a <code>Play</code> method which simply handled all the necessary logic. In the <code>Game</code> <code>class</code>, I enclosed things like, a <code>List</code> of all the <code>Gestures</code>, a <code>Dictionary</code> of <code>Rules</code> (what defeats what and why). A <code>Play</code> method to simulate the RPSLS, a <code>WhoWon</code> method which returns who the winner between two players was, and a <code>GetReason</code> method which returns the reason a particular Gesture won over another.</p>\n\n<pre><code>static class Game\n{\n public static Gesture[] Gestures = (Gesture[])Enum.GetValues(typeof(Gesture));\n\n private static Dictionary&lt;Tuple&lt;int, int&gt;, string&gt; Rules = new Dictionary&lt;Tuple&lt;int, int&gt;, string&gt;()\n {\n {Tuple.Create&lt;int,int&gt;(1,3), \"Crushes\"},\n {Tuple.Create&lt;int,int&gt;(1,5), \"Crushes\"},\n\n {Tuple.Create&lt;int,int&gt;(2,1), \"Covers\"},\n {Tuple.Create&lt;int,int&gt;(2,4), \"Disproves\"},\n\n {Tuple.Create&lt;int,int&gt;(3,2), \"Cuts\"},\n {Tuple.Create&lt;int,int&gt;(3,5), \"Decapitates\"},\n\n {Tuple.Create&lt;int,int&gt;(4,3), \"Smashes\"},\n {Tuple.Create&lt;int,int&gt;(4,1), \"Vaporizes\"},\n\n {Tuple.Create&lt;int,int&gt;(5,2), \"Eats\"},\n {Tuple.Create&lt;int,int&gt;(5,4), \"Poisons\"}\n };\n\n public static void Play(Player player1, Player player2)\n {\n Gesture p1move = player1.GetMove();\n Gesture p2move = player2.GetMove();\n\n Console.Write(\"Player 1 Chose \");\n Utils.WriteLineColored(p1move.ToString(), ConsoleColor.Green);\n Console.Write(\"Player 2 Chose \");\n Utils.WriteLineColored(p2move.ToString(), ConsoleColor.Green);\n\n int result = WhoWon(p1move, p2move);\n switch (result)\n {\n case 0: player1.GiveResult(Performance.Tied); player2.GiveResult(Performance.Tied); break;\n case 1: player1.GiveResult(Performance.Won); player2.GiveResult(Performance.Lost); break;\n case 2: player1.GiveResult(Performance.Lost); player2.GiveResult(Performance.Won); break;\n }\n\n if (result == 0)\n Console.WriteLine(\"It was a tie!\");\n else\n Console.WriteLine(\"Player {0} won, because {1}.\", result, GetReason(result == 1 ? p1move : p2move, result == 1 ? p2move : p1move));\n }\n\n private static int WhoWon(Gesture p1move, Gesture p2move)\n {\n return p1move == p2move ? 0 : Rules.Keys.Where(key =&gt; key.Item1 == (int)p1move &amp;&amp; key.Item2 == (int)p2move).FirstOrDefault() != null ? 1 : 2;\n }\n\n private static string GetReason(Gesture winner, Gesture loser)\n {\n return winner + \" \" + Rules[Tuple.Create((int)winner, (int)loser)] + \" \" + loser;\n }\n}\n</code></pre></li>\n<li><p>For any general utility methods, I enclosed those in a static Utils class</p>\n\n<pre><code>static class Utils\n{\n public static int PromptForRangedInt(int min = int.MinValue, int max = int.MaxValue, string prompt = \"Please enter an Integer: \")\n {\n int g;\n do\n {\n Console.Write(prompt);\n if (int.TryParse(Console.ReadLine(), out g))\n {\n if (g &gt;= min &amp;&amp; g &lt;= max)\n return g;\n Console.WriteLine(\"You entered {0}, but the input must be in the range of ({1} - {2}. Please try again...\", g, min, max);\n }\n else\n Console.WriteLine(\"That is not a number. Please try again...\");\n } while (true);\n }\n\n public static void PrintMenu(List&lt;string&gt; values, int baseIndex = 0)\n {\n values.ForEach(value =&gt; Console.WriteLine(\"{0}: {1}\", baseIndex++, value));\n }\n\n public static void WriteLineColored(string text, ConsoleColor color)\n {\n var curr = Console.ForegroundColor;\n Console.ForegroundColor = color;\n Console.WriteLine(text);\n Console.ForegroundColor = curr;\n }\n}\n</code></pre></li>\n<li><p>This brings me to actually using these classes in a meaningful way to actually play the game. You must create the players you want to pit against each other, this could be 2 computers, 2 humans, or a combination of either. As-long as you hold a reference to these <code>objects</code>, you also are holding onto their scorecard (assuming they didn't clear it).</p>\n\n<pre><code>class Program\n{\n 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}\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p>Here is the entire dump of the program:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace RPSLS\n{\n class Program\n {\n 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 }\n\n enum Gesture\n {\n Rock = 1,\n Paper = 2,\n Scissors = 3,\n Spock = 4,\n Lizard = 5\n }\n\n enum Performance\n {\n Lost = -1,\n Tied = 0,\n Won = 1\n }\n\n abstract class Player\n {\n public uint Wins { get; private set; }\n public uint Loses { get; private set; }\n public uint Ties { get; private set; }\n\n public abstract Gesture GetMove();\n\n public string GetScoreCard()\n {\n return \"[Wins: \" + Wins + \"] [Loses \" + Loses + \"] [Ties \" + Ties + \"]\";\n }\n\n public void ClearScore()\n {\n Wins = Loses = Ties = 0;\n }\n\n public void GiveResult(Performance performance)\n {\n switch (performance)\n {\n case Performance.Lost: Loses++; break;\n case Performance.Tied: Ties++; break;\n case Performance.Won: Wins++; break;\n }\n }\n }\n\n class Human : Player\n {\n public override Gesture GetMove()\n {\n Utils.PrintMenu(Game.Gestures.Select(g =&gt; g.ToString()).ToList(), 1);\n return (Gesture)Utils.PromptForRangedInt((int)Game.Gestures.First(), (int)Game.Gestures.Last(), \"Please choose your Gesture: \");\n }\n }\n\n class Computer : Player\n {\n public override Gesture GetMove()\n {\n return (Gesture)Game.Gestures.GetValue(new Random().Next(Game.Gestures.Length));\n }\n }\n\n static class Game\n {\n public static Gesture[] Gestures = (Gesture[])Enum.GetValues(typeof(Gesture));\n\n private static Dictionary&lt;Tuple&lt;int, int&gt;, string&gt; Rules = new Dictionary&lt;Tuple&lt;int, int&gt;, string&gt;()\n {\n {Tuple.Create&lt;int,int&gt;(1,3), \"Crushes\"},\n {Tuple.Create&lt;int,int&gt;(1,5), \"Crushes\"},\n\n {Tuple.Create&lt;int,int&gt;(2,1), \"Covers\"},\n {Tuple.Create&lt;int,int&gt;(2,4), \"Disproves\"},\n\n {Tuple.Create&lt;int,int&gt;(3,2), \"Cuts\"},\n {Tuple.Create&lt;int,int&gt;(3,5), \"Decapitates\"},\n\n {Tuple.Create&lt;int,int&gt;(4,3), \"Smashes\"},\n {Tuple.Create&lt;int,int&gt;(4,1), \"Vaporizes\"},\n\n {Tuple.Create&lt;int,int&gt;(5,2), \"Eats\"},\n {Tuple.Create&lt;int,int&gt;(5,4), \"Poisons\"}\n };\n\n public static void Play(Player player1, Player player2)\n {\n Gesture p1move = player1.GetMove();\n Gesture p2move = player2.GetMove();\n\n Console.Write(\"Player 1 Chose \");\n Utils.WriteLineColored(p1move.ToString(), ConsoleColor.Green);\n Console.Write(\"Player 2 Chose \");\n Utils.WriteLineColored(p2move.ToString(), ConsoleColor.Green);\n\n int result = WhoWon(p1move, p2move);\n switch (result)\n {\n case 0: player1.GiveResult(Performance.Tied); player2.GiveResult(Performance.Tied); break;\n case 1: player1.GiveResult(Performance.Won); player2.GiveResult(Performance.Lost); break;\n case 2: player1.GiveResult(Performance.Lost); player2.GiveResult(Performance.Won); break;\n }\n\n if (result == 0)\n Console.WriteLine(\"It was a tie!\");\n else\n Console.WriteLine(\"Player {0} won, because {1}.\", result, GetReason(result == 1 ? p1move : p2move, result == 1 ? p2move : p1move));\n }\n\n private static int WhoWon(Gesture p1move, Gesture p2move)\n {\n return p1move == p2move ? 0 : Rules.Keys.Where(key =&gt; key.Item1 == (int)p1move &amp;&amp; key.Item2 == (int)p2move).FirstOrDefault() != null ? 1 : 2;\n }\n\n private static string GetReason(Gesture winner, Gesture loser)\n {\n return winner + \" \" + Rules[Tuple.Create((int)winner, (int)loser)] + \" \" + loser;\n }\n }\n\n static class Utils\n {\n public static int PromptForRangedInt(int min = int.MinValue, int max = int.MaxValue, string prompt = \"Please enter an Integer: \")\n {\n int g;\n do\n {\n Console.Write(prompt);\n if (int.TryParse(Console.ReadLine(), out g))\n {\n if (g &gt;= min &amp;&amp; g &lt;= max)\n return g;\n Console.WriteLine(\"You entered {0}, but the input must be in the range of ({1} - {2}. Please try again...\", g, min, max);\n }\n else\n Console.WriteLine(\"That is not a number. Please try again...\");\n } while (true);\n }\n\n public static void PrintMenu(List&lt;string&gt; values, int baseIndex = 0)\n {\n values.ForEach(value =&gt; Console.WriteLine(\"{0}: {1}\", baseIndex++, value));\n }\n\n public static void WriteLineColored(string text, ConsoleColor color)\n {\n var curr = Console.ForegroundColor;\n Console.ForegroundColor = color;\n Console.WriteLine(text);\n Console.ForegroundColor = curr;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T17:52:29.437", "Id": "44175", "ParentId": "36482", "Score": "12" } } ]
{ "AcceptedAnswerId": "36491", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T02:58:05.340", "Id": "36482", "Score": "19", "Tags": [ "c#", "beginner", "game", "community-challenge", "rock-paper-scissors" ], "Title": "RPSLS Game in C#" }
36482
<p>I am somewhat new to Java. I want to know if this is the proper way to share text with other Android applications, and if I am properly determining if the text is selected. Is there a better way to share the selected text? Is my decision statement proper? The app works just fine.</p> <pre><code>package com.kylelk.sharedemo; import android.app.*; import android.content.*; import android.os.*; import android.view.*; import android.view.View.*; import android.widget.*; public class MainActivity extends Activity { private Button shareBtn; private EditText textToShare; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); shareBtn = (Button) findViewById(R.id.shareText); shareBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v){ //Get the selected text EditText et=(EditText)findViewById(R.id.textToShare); int startSelection=et.getSelectionStart(); int endSelection=et.getSelectionEnd(); String selectedText = et.getText().toString().substring(startSelection, endSelection); //if no text is selected share the entire text area. if(selectedText.length() == 0){ textToShare = (EditText) findViewById(R.id.textToShare); String dataToShare = textToShare.getText().toString(); selectedText = dataToShare; } //Share the text Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, selectedText); sendIntent.setType("text/plain"); startActivity(sendIntent); } }); } } </code></pre> <p>Here is the complete project: <a href="https://github.com/kylelk/ShareDemo" rel="nofollow">https://github.com/kylelk/ShareDemo</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T10:19:16.170", "Id": "59839", "Score": "1", "body": "While Code Review does focus on reviewing working code, I think this specific question would be better answered by Android programmers, it's more about correctly using the API." } ]
[ { "body": "<p>Honestly I believe you have answered this question yourself: <strong>The app works just fine.</strong></p>\n\n<p>From what I can see, you are using the intent <a href=\"http://developer.android.com/training/sharing/send.html\" rel=\"nofollow\">exactly as you are supposed to</a>. You are also using <code>EditText</code> properly. But, because you have come all the way here I guess you want to hear some suggestions/criticism as well so I have tried really hard to come up with something:</p>\n\n<ul>\n<li><p>You're inconsistent in adding spaces to your code. The best practice is to use <code>VariableType variable = something;</code> but in three lines you are writing <code>VariableType variable=something;</code> which makes the code a little bit harder to read.</p></li>\n<li><p>I don't think you need to temporarily store the <code>selectionStart</code> and <code>selectionEnd</code> variables. (If you think it looks cleaner to store them in temporary variables, then by all means continue to do so) This code would be enough:</p>\n\n<pre><code>String selectedText = et.getText().toString().substring(et.getSelectionStart(), et.getSelectionEnd());\n</code></pre>\n\n<p>Or if you think that line is too long, </p>\n\n<pre><code>String text = et.getText().toString();\nString selectedText = text.substring(et.getSelectionStart(), et.getSelectionEnd());\n</code></pre></li>\n<li><p>Consider what would happen if there is nothing at all stored in the <code>EditText</code>, do you still want to start an intent even if the string is empty?</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:40:28.890", "Id": "36575", "ParentId": "36483", "Score": "4" } } ]
{ "AcceptedAnswerId": "36575", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T03:34:13.663", "Id": "36483", "Score": "3", "Tags": [ "java", "android", "beginner" ], "Title": "Android sharing selected text to other apps" }
36483
<p>Say I have the following SQL:</p> <pre><code>SELECT amount, amount*.1, (amount*1)+3, ((amount*1)+3)/2, (((amount*1)+3)/2)+37 FROM table </code></pre> <p>Instead of repeating that identical code every time, I really want to be able to do something like this:</p> <pre><code>SELECT amount, amount*.1 AS A, A+3 AS B, B/2 AS C, C+37 AS D, FROM table </code></pre> <p>But this code doesn't work.</p> <p>So, is there another way to avoid duplication in the working query that I have?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T04:42:12.527", "Id": "59809", "Score": "0", "body": "Not with T-SQL - From: http://technet.microsoft.com/en-us/library/ms176104.aspx ` < select_list > The columns to be selected for the result set.` and `A`, `B`, and `C` are not columns." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T04:55:55.370", "Id": "59812", "Score": "1", "body": "FYI: http://stackoverflow.com/questions/12988637/column-aliases-reference" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T05:28:00.700", "Id": "59815", "Score": "0", "body": "`Is something like this possible?` and the 'this' code does not work. If you are specifically concerned that it was closed 'because it was asking for code to be written', well, it is also required that the code-to-be-reviewed also works: See question 5 here: http://codereview.stackexchange.com/help/on-topic" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:35:47.207", "Id": "59898", "Score": "0", "body": "How are the results from this query used? The calculations look like business logic which belong in a domain object rather than inserted directly into a query. I would only put them in the query if I had no other choice (e.g., building reports)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T21:40:33.867", "Id": "59920", "Score": "0", "body": "In this case, I'm just generating tablular data to be imported into a separate system. There is no domain object. Otherwise, I agree with you. I wouldn't normally want to do this kind of stuf in SQL." } ]
[ { "body": "<p>You could define intermediate views using common table expressions. That would eliminate the redundancy of the calculations, but redundantly introduce a different kind of redundancy.</p>\n\n<pre><code>WITH ATable AS (\n SELECT amount, amount*.1 AS A FROM table\n), BTable AS (\n SELECT amount, A, A+3 AS B FROM ATable\n), CTable AS (\n SELECT amount, A, B, B/2 AS C FROM BTable\n)\nSELECT amount, A, B, C, C+37 AS D FROM CTable;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:47:12.757", "Id": "59888", "Score": "2", "body": "“redundantly introduce a different kind of redundancy.” Isn't that “redundantly” redundant?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:51:31.047", "Id": "59889", "Score": "0", "body": "you said something about the redundancy in your answer and then redundantly commented \"“redundantly introduce a different kind of redundancy.” Isn't that “redundantly” redundant?\" on the Redundancy of the statement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:41:39.907", "Id": "36527", "ParentId": "36485", "Score": "7" } }, { "body": "<p>That's not how SQL works. As mentioned in the SO answer linked by @rolfl:</p>\n\n<blockquote>\n <p>You can only refer to a column alias in an outer select, so unless you recalculate all the previous values for each column you'd need to nest each level, which is a bit ugly</p>\n</blockquote>\n\n<p>Which means:</p>\n\n<pre><code>SELECT amount, A, B, C, C+37 D\nFROM (SELECT amount, A, B, B/2 C\n FROM (SELECT amount, A, A+3 B\n FROM (SELECT amount, amount*0.1 A FROM table) firstPass) secondPass) thirdPass\n</code></pre>\n\n<p>That said, the last comma in your 2<sup>nd</sup> snippet is a <em>pseudo</em> syntax error (given it's a <em>pseudo</em> query)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:42:46.630", "Id": "36528", "ParentId": "36485", "Score": "6" } }, { "body": "<p>If this is SQL Server 2005 or later version, you could use <a href=\"http://msdn.microsoft.com/en-us/library/ms175156.aspx\" rel=\"nofollow noreferrer\" title=\"Using APPLY\">CROSS APPLY</a>:</p>\n\n<pre><code>SELECT\n t.amount,\n a.A,\n b.B,\n c.C,\n d.D\nFROM atable AS t\nCROSS APPLY (SELECT t.amount*.1 AS A) AS a\nCROSS APPLY (SELECT a.A+3 AS B) AS b\nCROSS APPLY (SELECT b.B/2 AS C) AS c\nCROSS APPLY (SELECT c.C+37 AS D) AS d\n;\n</code></pre>\n\n<p>Essentially, every CROSS APPLY here creates a calculated column which can be referenced in subsequent CROSS APPLYs just as well as in the SELECT clause, i.e. this way you are creating re-usable calculated columns.</p>\n\n<p>If this is an older version or Sybase, there's probably no other option apart from the <a href=\"https://codereview.stackexchange.com/a/36528/4061\">one suggested by @retailcoder</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T14:00:25.037", "Id": "39473", "ParentId": "36485", "Score": "3" } } ]
{ "AcceptedAnswerId": "36528", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T04:31:25.297", "Id": "36485", "Score": "5", "Tags": [ "sql", "sql-server" ], "Title": "Remove duplication in SELECT statement" }
36485
<p>I need some opinion if my code below is proper for an async process. This code only reformats text. Please let me know if this implementation is not proper or needs some improvement.</p> <pre><code>static void Main(string[] args) { Task.Factory.StartNew(() =&gt; ReadCharacter("File 1.txt")); Task.Factory.StartNew(() =&gt; ReadCharacter("File 2.txt")); Console.WriteLine("Main Task"); Console.ReadLine(); } static void ReadCharacter(string inputFile) { string result; using (StreamReader sr = new StreamReader(inputFile)) using (StreamWriter sw = new StreamWriter(string.Format("C:\\Out--{0}",inputFile))) { Console.WriteLine("Opening file : {0}", inputFile.ToString()); while (!sr.EndOfStream) { result = sr.ReadLine(); sw.WriteLine(string.Format("{0} --&gt; {1}",result,Task.CurrentId.ToString())); } Console.WriteLine("Finish {0}", inputFile); sr.Close(); sw.Close(); } } </code></pre>
[]
[ { "body": "<p>Well, you start two <code>Task</code>s each reading and writing a file but not the same. So basically it should be ok. Some remarks:</p>\n\n<ol>\n<li><p><code>Task.Factory.StartNew</code> returns a <code>Task</code>. You probably want to wait until the tasks you have started are finished before you quit from main which you can do with <a href=\"http://msdn.microsoft.com/en-us/library/dd270695%28v=vs.110%29.aspx\"><code>Task.WaitAll</code></a>. Something along these lines:</p>\n\n<pre><code>var task1 = Task.Factory.StartNew(() =&gt; ReadCharacter(\"File 1.txt\"));\nvar task2 = Task.Factory.StartNew(() =&gt; ReadCharacter(\"File 2.txt\"));\nConsole.WriteLine(\"Main - waiting for tasks to finish\");\nTask.WaitAll(task1, task2); \nConsole.WriteLine(\"Finished\");\n</code></pre></li>\n<li><p>Your worker method <code>ReadCharacter</code> writes directly to the console. What happens if you want to run this code in a windows service process where this should be logged instead? So you should pass some kind of <code>ILogger</code> to the method and use that to output the status/log messages.</p></li>\n<li><p>You hard-code your output directory to <code>C:\\</code>. This should really be passed in as destination folder.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T08:45:26.710", "Id": "36492", "ParentId": "36487", "Score": "6" } }, { "body": "<p>It may work in this case when you're operating on two different files, but as soon as you are working on the same file you will realize that this is not a \"proper\" implementation of an asynchronous operation.</p>\n\n<p>In cases where you are doing I/O operations on the same file you need to set a <code>lock</code> to prevent race conditions, or you should use the asynchronous methods <code>BeginRead</code>, <code>BeginWrite</code>, etc, as stated <a href=\"http://msdn.microsoft.com/en-us/library/kztecsys%28VS.80%29.aspx\" rel=\"nofollow\">here</a></p>\n\n<ul>\n<li>There is also no need to invoke <code>.close()</code> on the Streams as the <code>using(..) { }</code> block will take care of that for you.</li>\n<li>As you are only using your <code>result</code> variable within the inner-most <code>using(..) { }</code> block I would declare <code>result</code> just before your while-loop in order to minimize the scope. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T11:46:07.443", "Id": "36497", "ParentId": "36487", "Score": "2" } }, { "body": "<p>If you want to wait until all tasks are finished, as @ChrisWue explained, you can create an even simpler one-liner solution using <a href=\"http://msdn.microsoft.com/en-us/library/dd783539%28v=vs.100%29.aspx\" rel=\"nofollow\"><code>Parallel.For</code></a>:</p>\n\n<pre><code>Parallel.For(0, 2, i =&gt; ReadCharacter(\"File \" + i + \".txt\"));\n</code></pre>\n\n<p>This is handy for those situations where you just want to use as many threads possible for a parallel operation, but need to wait until all of them are finished.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T12:39:35.220", "Id": "36500", "ParentId": "36487", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T05:01:27.887", "Id": "36487", "Score": "6", "Tags": [ "c#", "asynchronous" ], "Title": "“Proper” Asynchronous implementation" }
36487
<p>Review this code regarding optimization, cleanup, and best practices.</p> <pre><code>final class EdgePrims&lt;T&gt; { private final T source, target; private final int distance; public EdgePrims(T node1, T node2, int distance) { this.source = node1; this.target = node2; this.distance = distance; } public T getSource() { return source; } public T getTarget() { return target; } public int getDistance() { return distance; } @Override public String toString() { return " first vertex " + source + " to vertex " + target + " with distance: " + distance; } } final class GraphPrims&lt;T&gt; implements Iterable&lt;T&gt; { private final Map&lt;T, Map&lt;T, Integer&gt;&gt; graph; public GraphPrims() { graph = new HashMap&lt;T, Map&lt;T, Integer&gt;&gt;(); } public void addEgde(T vertex1, T vertex2, int distance) { if (vertex1 == null) { throw new NullPointerException("The vertex 1 cannot be null"); } if (vertex2 == null) { throw new NullPointerException("The vertex 2 cannot be null"); } if (!graph.containsKey(vertex1)) { graph.put(vertex1, new HashMap&lt;T, Integer&gt;()); } if (!graph.containsKey(vertex2)) { graph.put(vertex2, new HashMap&lt;T, Integer&gt;()); } graph.get(vertex1).put(vertex2, distance); graph.get(vertex2).put(vertex1, distance); } public Set&lt;T&gt; getVertices() { return Collections.unmodifiableSet(graph.keySet()); // QQ: should this be replaced by DEEP COPy ? } public Map&lt;T, Integer&gt; getEdges(T source) { if (source == null) { throw new NullPointerException("The source cannot be null."); } return Collections.unmodifiableMap(graph.get(source)); } public void removeEdges(T vertex1, T vertex2) { if (vertex1 == null) { throw new NullPointerException("The vertex 1 cannot be null"); } if (vertex2 == null) { throw new NullPointerException("The vertex 2 cannot be null"); } if (!graph.containsKey(vertex1)) { throw new NoSuchElementException("vertex " + vertex1 + " does not exist."); } if (!graph.containsKey(vertex2)) { throw new NoSuchElementException("vertex " + vertex2 + " does not exist."); } graph.get(vertex1).remove(vertex2); graph.get(vertex2).remove(vertex1); } @Override public Iterator&lt;T&gt; iterator() { return graph.keySet().iterator(); } } public class Prims&lt;T&gt; { public static Comparator&lt;EdgePrims&gt; edgeComparator = new Comparator&lt;EdgePrims&gt;() { @Override public int compare(EdgePrims edge1, EdgePrims edge2) { return edge1.getDistance() - edge2.getDistance(); } }; /** * Uses prim's algo to calculate a MST for a connected graph. * A non-connected graph will lead to unpredictable result. * * @param graph a connected graph. * @return a list of edges that constitute the MST */ public static &lt;T&gt; List&lt;EdgePrims&lt;T&gt;&gt; getMinSpanTree(GraphPrims&lt;T&gt; graph) { Queue&lt;EdgePrims&lt;T&gt;&gt; edgesAvailable = new PriorityQueue&lt;EdgePrims&lt;T&gt;&gt;(10, edgeComparator); List&lt;EdgePrims&lt;T&gt;&gt; listMinEdges = new ArrayList&lt;EdgePrims&lt;T&gt;&gt;(); Set&lt;T&gt; unvisitedVertices = new HashSet&lt;T&gt;(); unvisitedVertices.addAll(graph.getVertices()); T sourceVertex = unvisitedVertices.iterator().next(); unvisitedVertices.remove(sourceVertex); while (!unvisitedVertices.isEmpty()) { /* populate all edges for the current vertex */ for (Entry&lt;T, Integer&gt; e : graph.getEdges(sourceVertex).entrySet()) { /* dont add a duplicate edge */ if (unvisitedVertices.contains(e.getKey())) { edgesAvailable.add(new EdgePrims(sourceVertex, e.getKey(), (Integer) e.getValue())); } } /* fetch the edge with least distance */ EdgePrims&lt;T&gt; minEdge = edgesAvailable.poll(); /* if the target is already visited then move to next edge */ while (!unvisitedVertices.contains(minEdge.getTarget())) { minEdge = edgesAvailable.poll(); } listMinEdges.add(minEdge); // this list will contain unique targetvertices. sourceVertex = minEdge.getTarget(); // get the next vertex. unvisitedVertices.remove(sourceVertex); } return listMinEdges; } public static void main(String[] args) { GraphPrims&lt;Character&gt; graphPrims = new GraphPrims&lt;Character&gt;(); graphPrims.addEgde('A', 'B', 10); graphPrims.addEgde('A', 'C', 15); graphPrims.addEgde('C', 'B', 50); graphPrims.addEgde('C', 'D', 20); graphPrims.addEgde('B', 'D', 80); graphPrims.addEgde('B', 'F', 80); // graphPrims.addEgde('x', 'y', 700); for (EdgePrims&lt;Character&gt; edge : getMinSpanTree(graphPrims)) { System.out.println(edge.toString()); } } } </code></pre>
[]
[ { "body": "<ol>\n<li><p><code>public EdgePrims(T node1, T node2, int distance)</code> - What are <code>node1</code> and <code>node2</code>? From reading the source one can see they are source and target node - so they should be named accordingly. The names of the parameters of a function are an important piece of documentation and should convey their meaning.</p></li>\n<li><p>You have created a link between your data structures (<code>GraphPrims</code>, <code>EdgePrims</code>) and an algorithm which seems weird as they have only in common that Prim's is a graph algorithm - meaning you need a graph to run it on but the graph doesn't need the algorithm. I'm pretty sure I could implement Dijkstra's algorithm and run it on a graph of yours.</p>\n\n<p>The problem is that this creates a barrier in your mind for the re-usability of the classes. Also it reads odd if I write </p>\n\n<pre><code>class Dijkstras \n{\n public static &lt;T&gt; List&lt;EdgePrims&lt;T&gt;&gt; getShortestPath(GraphPrims&lt;T&gt; graph, EdgePrims&lt;T&gt; from, EdgePrims&lt;T&gt; to)\n { ... }\n}\n</code></pre></li>\n<li><p>Why do you initialize <code>edgesAvailable</code> with a default initial capacity of 10? According to <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#PriorityQueue%28%29\" rel=\"nofollow\">the Java documentation</a> the default initial capacity is 11. Why is 10 any better?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T09:01:30.710", "Id": "36494", "ParentId": "36488", "Score": "6" } } ]
{ "AcceptedAnswerId": "36494", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T05:58:30.170", "Id": "36488", "Score": "5", "Tags": [ "java", "algorithm", "tree", "graph" ], "Title": "Prims algorithm implementation" }
36488
<p>In my code's package, I have a flag such as:</p> <pre><code>public static final boolean LOGS_VERBOSE = false; </code></pre> <p>And in worker classes (multi threaded <code>Runnable</code> jobs), I have code like:</p> <pre><code>if(XYConstants.LOGS_VERBOSE){ logger.debug("some state info var 1:" + var1 + ", var 2:" + var2); </code></pre> <p>Is this a good idea? Is there any performance gain? Developers say it avoids code going to the log4j level completely, and there is hardly any overhead to check the value of the constant.</p> <p>We do plan to do performance testing, but that is a month away, and I need to show code to the client (who is a developer of 14 years) this Friday. I'm wondering if this should stay or not?</p> <p>We have some debugs without the boolean check too, and those are wanted in all runs as long as log4j is configured in debug level.</p> <p>This code is using log4j 1.2.16.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T03:59:46.447", "Id": "59938", "Score": "0", "body": "Any particular reason why `trace()` is not used, considering there are some debug messages that should always be shown (proper debugging?), and there are those with this boolean check (really verbose)?\nAlso, is your team keen to explore switching to an alternative such as SLF4J that can handle these logging more fluently? You get parameterized log messages too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:00:29.487", "Id": "60017", "Score": "0", "body": "we are in fact using SLF4J (with log4j as the implementor, did not disclose that fact as I thought not pertinent to the questionb). Can use trace but I think we need to upgrade to the next version of SLF4j which has var args" } ]
[ { "body": "<p>This type of practice is common, and works well.</p>\n\n<p>The Java JIT compiler will identify the <code>LOGS_VERBOSE</code> as being a constant, and will know that it is always false, and thus will <code>compile-out</code> the logging entirely.</p>\n\n<p>There is a slight performance hit on any code that has not (yet) been compiled.... but, once the compile has happened, there is no hit at all.</p>\n\n<p>It is relatively common to use a System property to determine whether to log...</p>\n\n<pre><code>public static final boolean LOGS_VERBOSE = Boolean.getBoolean(\"LOGS_VERBOSE\");\n</code></pre>\n\n<p>This behaves in the exact same way (because JIT happens after the property is set)... but, if you start your program as:</p>\n\n<pre><code>java -DLOGS_VERBOSE=true ......\n</code></pre>\n\n<p>then suddenly you have the fully-featured logging.</p>\n\n<p>In many cases this sort of checking can improve performance because it can eliminate expensive 'setup' for log messages</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T13:19:39.913", "Id": "59854", "Score": "0", "body": "thank you will add System.getProperty(\"LOGS_VERBOSE\"), with our own utility function to check if true (we accept Y or \"1\" or \"T\" == \"true\"). will keep question open for 2 days to see if anyone else has opinions they want to share." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:46:12.053", "Id": "60389", "Score": "2", "body": "How about `static final boolean LOGS_VERBOSE = Boolean.getBoolean(\"LOGS_VERBOSE\");`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:52:21.570", "Id": "60390", "Score": "1", "body": "@PeterLawrey +1 You know, every now than then I learn something new.... How is it that I have not seen that before?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:54:02.087", "Id": "60391", "Score": "0", "body": "@rolfl Sometimes I use `int property = Integer.getInteger(\"property\", 100);` instead of `int property = 100;` so I can optionally change it externally." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T13:14:48.457", "Id": "36502", "ParentId": "36501", "Score": "6" } }, { "body": "<p>You want to no only check you flag but the loggers log level.</p>\n\n<pre><code>if(XYConstants.LOGS_VERBOSE &amp;&amp; logger.isDebugEnabled())\n logger.debug(\"some state info var 1:\" + var1 + \", var 2:\" + var2);\n</code></pre>\n\n<p>This prevents you computing a potentially expensive String which will only be discarded anyway. More typically you would just use the debug level of the logger as there is not point turning it on if the logger doesn't print it.</p>\n\n<pre><code>if(logger.isDebugEnabled())\n logger.debug(\"some state info var 1:\" + var1 + \", var 2:\" + var2);\n</code></pre>\n\n<p>The log level can then be controlled by the <code>log4j.properties</code> file.</p>\n\n<p>Most likely your Logger is a static final field, not a field which is different for every instance. In this case you can UPPER_CASE for constants</p>\n\n<pre><code>// Constants are in UPPER_CASE by convention.\nprivate static final Logger LOGGER = Logger.getLogger(MyClass.class);\n\nif(LOGGER.isDebugEnabled())\n LOGGER.debug(\"some state info var 1:\" + var1 + \", var 2:\" + var2);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T17:52:19.360", "Id": "36716", "ParentId": "36501", "Score": "3" } }, { "body": "<p>A few things which were not mentioned earlier:</p>\n\n<blockquote>\n <p>Is this a good idea?</p>\n</blockquote>\n\n<p>It has some drawbacks:</p>\n\n<ul>\n<li>You have to recompile the code to change the log settings and usually you need to restart the whole application. It could make debugging a lot harder.</li>\n<li>Having one or two of these could be OK (if you have a really good reason for that, don't do <a href=\"https://softwareengineering.stackexchange.com/a/80092/36726\">premature optimizations</a>) but it is still increases maintenance costs. It's much easier to configure logging in the usual <code>log4j.xml</code> (or <code>logback.xml</code> for Logback nowadays) than recompiling and redeploying the application. You could even change logging configuration at runtime and Log4j will reconfigure itself.</li>\n<li>Note that <a href=\"https://stackoverflow.com/q/377819/843804\">Java inlines these constants</a>, so you need to recompile both <code>XYConstants</code> and <code>Runnable</code>s.</li>\n</ul>\n\n<p>Other ideas:</p>\n\n<ol>\n<li>Use <code>logger.isDebugEnabled()</code> (as it was mentioned earlier).</li>\n<li><p>Use SLF4J and its <a href=\"https://en.wikipedia.org/wiki/SLF4J\" rel=\"nofollow noreferrer\"><code>{}</code> pattern instead of string concatenation</a>:</p>\n\n<pre><code>logger.debug(\"some state info var 1: {}, var 2: {}\", var1, var2);\n</code></pre>\n\n<p>SLF4J don't call <code>var1.toString()</code> nor <code>var2.toString()</code> and don't do any string concatenation if the debug log level is not enabled.</p></li>\n<li><p>You could create a custom logger to be able to log only a subset of your log statements:</p>\n\n<pre><code>private static final Logger logger = \n LoggerFactory.getLogger(Foo.class.getName() + \".subset\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>private static final Logger logger = \n Logger.getLogger(Foo.class.getName() + \".subset\");\n</code></pre>\n\n<p>Then you can configure Log4j in the usual way although you don't have <code>...Foo.subset</code> package nor class.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T21:09:10.823", "Id": "45653", "ParentId": "36501", "Score": "1" } } ]
{ "AcceptedAnswerId": "36502", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T13:09:43.117", "Id": "36501", "Score": "5", "Tags": [ "java", "performance", "logging" ], "Title": "log4j 1.2 - own check for verbose logs?" }
36501
<p>The next bit of code does exactly what i want it to do, but it is 'rather' unelegant and unpythonic, so the question is quite simple: how can this code be changed into something more elegant </p> <pre><code>import numpy from scipy.stats import nanmean A = [[1, numpy.nan, 2],[2,3,4], [2,3,4], [numpy.nan, 5, 5]] A1 = numpy.array(A) print A1 def dosomething(d2): a0 = d2[0, :] a1 = d2[1, :] a2 = d2[2, :] dnan = ~numpy.isnan(a0+a1+a2) a01 = (a0-numpy.mean(a0[dnan]))/numpy.std(a0[dnan]) a11 = (a1-numpy.mean(a1[dnan]))/numpy.std(a1[dnan]) a21 = (a2-numpy.mean(a2[dnan]))/numpy.std(a2[dnan]) l = nanmean(numpy.array([a01,a11,a21]), axis=0) return l print dosomething(A1) [[ 1. nan 2.] [ 2. 3. 4.] [ 2. 3. 4.] [ nan 5. 5.]] [-1. 0. 1.] </code></pre> <p>Edit: i simplified it a bit more</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:19:58.973", "Id": "59865", "Score": "0", "body": "yeah, i know, but i just gave the 3x3 sample to make it easier ofc-" } ]
[ { "body": "<p>You can use <code>d2[:, dnan]</code> to select the wanted columns. (I'm assuming you want to process all rows unlike your current code)</p>\n\n<pre><code>def dosomething(d2):\n dnan = ~numpy.isnan(d2.sum(axis=0))\n validcols = d2[:, dnan]\n normalized = numpy.transpose((d2.T - numpy.mean(validcols, axis=1)) / numpy.std(validcols, axis=1))\n l = nanmean(normalized, axis=0)\n return l\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:33:22.210", "Id": "59969", "Score": "0", "body": "looks nice, but you returned l will have the length of the dnan instead of the length of the initial array? (the index of each point should be the same index after the method)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T08:13:04.157", "Id": "59975", "Score": "0", "body": "@usethedeathstar Added transposes to the normalization. The problem with my previous version was that when I take the row-wise mean I get an 1D array as result, which NumPy treats as a row when subtracting from `d2`, while I want to subtract a column." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T08:28:49.673", "Id": "59976", "Score": "0", "body": "thanks, that works and looks a lot more elegant than what it was before" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:09:17.883", "Id": "36526", "ParentId": "36503", "Score": "3" } }, { "body": "<p>If you just want to avoid all rows with NaNs, prefilter with a list comprehension to get rid of the rows you don't want, along the lines of:</p>\n\n<pre><code>filtered_rows = [r for r in all_rows where not numpy.nan in r]\n</code></pre>\n\n<p>and then do your work on <code>filtered_rows</code>. If memory is a problem, you could replace that with a function that yields only valid rows:</p>\n\n<pre><code>def filter_rows(*rows):\n for each_row in rows:\n if not numpy.nan in each_row:\n yield each_row\n\nfor r in filter_rows(*rows):\n # do something with r.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T22:44:15.617", "Id": "59922", "Score": "0", "body": "I did not spell out the fact that my \"all_rows\" is OP's list \"A\". But it's a vanilla list comprehension. AFAIK it also works in numpy.arrays as well as plain old python lists" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:35:18.750", "Id": "59970", "Score": "0", "body": "would work, but dont you get a shorter list in return? (the index of each point is important, thats why i didnt use a list comprehension like you used)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:40:42.737", "Id": "59971", "Score": "0", "body": "Is the order of the components significant? If not, just filter them out at that level instead of on the list level." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:41:24.627", "Id": "59972", "Score": "0", "body": "yes, each index is linked to a spatial coordinate somewhere else in my code" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T19:41:57.970", "Id": "36535", "ParentId": "36503", "Score": "1" } } ]
{ "AcceptedAnswerId": "36526", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T13:17:51.007", "Id": "36503", "Score": "1", "Tags": [ "python", "numpy" ], "Title": "Elegantly avoid columns containing NaNs?" }
36503
<p>I was given a task:</p> <blockquote> <p><strong>Given any integer</strong> - <strong>write a program, which</strong>:</p> <ol> <li><p>finds all digits of the integer</p></li> <li><p>writes odd and even digits from the integer</p></li> <li><p>finds the biggest even and smallest odd digit</p></li> <li><p>writes the biggest possible number that can be formed by rearranging the odd digits</p></li> <li><p>writes the smallest possible number that can be formed by rearranging the even digits</p></li> </ol> </blockquote> <p>I have written this code, but I am wondering if I can somehow get it written <em>shorter than this</em>:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; using namespace std; int main() { long a,s=0,s1=0; int b,n=0,n1=0,k=0; int d[10],nl[10]; int c=0; int i=0,j=0; for (i=0; i&lt;10; i++) { d[i]=0; nl[i]=0; } cout&lt;&lt;"Write a number: "&lt;&lt;endl; cin&gt;&gt;a; i=0; while(a!=0) { b=a%10; a=a/10; if(b%2!=0) { d[i]=b; i++; } else { nl[k]=b; k++; } } n=i; n1=k; cout&lt;&lt;n1&lt;&lt;" even numbers "&lt;&lt;n&lt;&lt;" odd numbers "&lt;&lt;endl; cout&lt;&lt;" Odd numbers not ranged array"&lt;&lt;endl; for(i=0; i&lt;n; i++) cout&lt;&lt;d[i]&lt;&lt;" "; cout&lt;&lt;endl; cout&lt;&lt;" Even numbers not ranged array"&lt;&lt;endl; for(i=0; i&lt;n1; i++) cout&lt;&lt;nl[i]&lt;&lt;" "; cout&lt;&lt;endl; c=0; for(i=0; i&lt;n; i++) { for(j=0; j&lt;n; j++) { if(d[i]&gt;d[j]) { c=d[i]; d[i]=d[j]; d[j]=c; } } } cout&lt;&lt;" Odd numbers ranged array"&lt;&lt;endl; for(i=0; i&lt;n; i++) cout&lt;&lt;d[i]&lt;&lt;" "; cout&lt;&lt;endl; cout&lt;&lt;"Min odd number "&lt;&lt;d[n-1]&lt;&lt;endl; c=0; for(i=0; i&lt;n1; i++) { for(j=0; j&lt;n1; j++) { if(nl[i]&lt;nl[j]) { c=nl[i]; nl[i]=nl[j]; nl[j]=c; } } } cout&lt;&lt;" Even numbers ranged array"&lt;&lt;endl; for(i=0; i&lt;n1; i++) cout&lt;&lt;nl[i]&lt;&lt;" "; cout&lt;&lt;endl; cout&lt;&lt;"Max even number "&lt;&lt;nl[k-1]&lt;&lt;endl; for(i=0; i&lt;n; i++) { s=s*10+d[i]; } for(i=0; i&lt;n1; i++) s1=s1*10+nl[i]; cout&lt;&lt;"Max odd digits' number "&lt;&lt;s&lt;&lt;endl; cout&lt;&lt;"Min odd digits' number "&lt;&lt;s1&lt;&lt;endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T13:58:09.660", "Id": "59857", "Score": "2", "body": "You mean better, more object-oriented and in line with best practices, or just *shorter*? Right place for the former, http://codegolf.stackexchange.com/ for the latter :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:02:58.237", "Id": "59860", "Score": "1", "body": "I meant everything You mentioned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:07:34.833", "Id": "59861", "Score": "0", "body": "An *algorithm/optimisation review* then! +1 from me" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T23:22:46.917", "Id": "59924", "Score": "0", "body": "Are you avoiding STL on purpose?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T23:58:47.140", "Id": "59926", "Score": "0", "body": "@200_success: Assuming it is homework (which is what it looks like), that could explain that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T00:03:49.093", "Id": "59927", "Score": "2", "body": "You could not have made the program harder to read by naming all your variables a1,a2,a3,a4,a5,a6. Come on write code with meaningful names." } ]
[ { "body": "<p>towards the end of your code you have :</p>\n\n<pre><code>for(i=0; i&lt;n; i++)\n{\n s=s*10+d[i];\n}\nfor(i=0; i&lt;n1; i++)\n s1=s1*10+nl[i];\n</code></pre>\n\n<p>these are two different coding styles that can confuse a programmer in a large set of code, you should have written the second the same as the first, or written them all using the same coding style. I prefer the first myself.</p>\n\n<pre><code>for(i=0; i&lt;n1; i++)\n{\n s1=s1*10+n1[i];\n}\n</code></pre>\n\n<p>this defines when the for loop is over and makes it so that it is more readable, I think.</p>\n\n<hr>\n\n<p>this doesn't make the code shorter, but does make it more readable in my opinion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T00:44:22.627", "Id": "59928", "Score": "1", "body": "It also allows you to easily add more to the body if needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:11:18.357", "Id": "60057", "Score": "2", "body": "It also prevents errors (using the braces). Badlly written macro functions can cause the the loop to be applied only to the first statement in the macro. So this is also a defensive style that prevents errors. I will always use `{}` were there is a nested block statement for exactly this purpose and reject code from code review unless they also follow this convention. After the first time you find a bug caused by this problem you will never leave them out either :-) (because it is a bug that is really hard to find)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:33:35.353", "Id": "36509", "ParentId": "36505", "Score": "4" } }, { "body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try to avoid using <code>using namespace std</code>.</a></p></li>\n<li><p><code>&lt;cmath&gt;</code> is not utilized anywhere, so just remove it unless you end up adding associated code.</p></li>\n<li><p>Avoid giving variables single-letter names (unless they're simple loop counters, which is okay to do). Although it may save some typing, it will instead make them appear meaningless as there is no context. Comments can be added, but they're not a good substitute for actual variable names. If a variable needs a comment, chances are it hasn't been given a good name.</p></li>\n<li><p>To help increase readability and maintainability:</p>\n\n<ul>\n<li><p>Have one variable per line. This also helps in case comments need to be added.</p>\n\n<pre><code>long a;\nlong s=0;\nlong s1=0;\n</code></pre></li>\n<li><p>Separate operators and operands with whitespace so that the two can be identified.</p>\n\n<pre><code>long a;\nlong s = 0;\nlong s1 = 0;\n</code></pre></li>\n<li><p>Separate code lines based on purpose, also so that readers can focus on certain parts.</p>\n\n<pre><code>cout&lt;&lt;\" Odd numbers ranged array\"&lt;&lt;endl;\n\nfor(i=0; i&lt;n; i++)\n cout&lt;&lt;d[i]&lt;&lt;\" \";\n\ncout&lt;&lt;endl;\n</code></pre></li>\n<li><p>Keep variables as close in scope as possible instead of listed together. This could also help determine if a variable is no longer being used.</p>\n\n<pre><code>cout &lt;&lt; \"Write a number: \" &lt;&lt; endl;\nlong a; // move this here\ncin &gt;&gt; a;\n</code></pre></li>\n</ul></li>\n<li><p><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\"><code>std::endl</code></a> also flushes the stream, which is slower. If you want just a newline, use <code>\"\\n\"</code>:</p>\n\n<pre><code>cout &lt;&lt; \"Write a number: \\n\";\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>c=nl[i];\nnl[i]=nl[j];\nnl[j]=c;\n</code></pre>\n\n<p>can be done more concisely with <a href=\"http://en.cppreference.com/w/cpp/algorithm/swap\" rel=\"nofollow noreferrer\"><code>std::swap</code></a>:</p>\n\n<pre><code>std::swap(n1[i], n1[j]);\n</code></pre></li>\n<li><p>Consider making this program more modular (using functions). Keeping everything in <code>main()</code> could make it hard for yourself and others to read and maintain the code. It is also not clear, just from looking at it, that this program is written to fulfill those five tasks. It could just be <em>one</em> task if the reader weren't otherwise aware of them.</p>\n\n<p>This can be done any way you'd like, but the most likely solution could be to have one function for each of those tasks (while giving them appropriate names). They could then be called from <code>main()</code>, and you could also get the user input from <code>main()</code> (this could, for instance, allow you to terminate the program right away if invalid input is given).</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T19:03:45.960", "Id": "36534", "ParentId": "36505", "Score": "9" } }, { "body": "<p>Before you aim for brevity, you should focus on clarity. Your function is obfuscated enough, without trying to shorten it. The code will become somewhat shorter as you extract common snippets into functions. The key is not to aim for the minimum number of characters in the source code, but to limit each function to a reasonable number of lines.</p>\n\n<p>STL vectors are easier to work with than arrays. Since you did not use vectors, I'll assume that you are deliberately avoiding them as a <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged &#39;beginner&#39;\" rel=\"tag\">beginner</a>.</p>\n\n<h3>Correctness</h3>\n\n<ul>\n<li><strong>Handling of zero:</strong> I would consider zero to be a number consisting of one even digit. You treat it as a zero-digit number. Worse, you say that the smallest odd digit is 0 and the largest number that can be formed using the odd digits is also 0.</li>\n<li><strong>Handling of negative integers:</strong> If the input is negative, I think that the digit analysis should act on the absolute value of the number. Instead, your program seems to have a concept of \"negative digits\".</li>\n</ul>\n\n<h3>Maintainability</h3>\n\n<ul>\n<li><strong>Problem decomposition:</strong> You should decompose the problem into functions; otherwise you end up with a god-awful <code>main()</code> function that contains everything. I realize that this problem doesn't naturally lend itself to decomposition due to its eclectic nature, but still, it is possible. I'll discuss this further below.</li>\n<li><strong>Variable naming:</strong> I'll just echo everyone else's complaints.</li>\n<li><strong>Variable declarations:</strong> Declare your variables as close as possible to the point of use. There is no reason to declare all variables at the beginning of the function in C++. (The same goes for C since the C99 standard.)</li>\n<li><strong>Magic number:</strong> Your arrays have size 10, a \"magic number\". At the least, you should explain in a comment that <code>long</code> can be up to 10 digits in your C++ environment. (This assumption is <a href=\"https://stackoverflow.com/q/589575/1157100\"><em>not portable</em></a>!) The correct approach is to use <code>std::numeric_limits&lt;long&gt;::digits10</code> (which is defined in <code>#include &lt;limits&gt;</code>).</li>\n</ul>\n\n<h3>Data Types</h3>\n\n<p>Array indices should be of type <code>size_t</code>.</p>\n\n<p>I suggest treating base-10 digits as <code>unsigned short</code>. Furthermore, <code>typedef unsigned short digit</code> would be handy.</p>\n\n<p>You can templatize the code to handle even larger inputs, such as <code>long long</code>. I'll use <code>template &lt;typename T&gt;</code> below, but you could just continue to use <code>long</code>.</p>\n\n<h3>Decomposition</h3>\n\n<p>The most obvious code that you can immediately extract is your sorting routine. If you used STL <code>std::vector</code> to store the digits, then it would be easiest to call <code>std::sort()</code>. If you use plain arrays, then you could call <code>qsort()</code> (in <code>#include &lt;cstdlib&gt;</code>) with one of the following comparators:</p>\n\n<pre><code>static int ascending_digits(const void *pa, const void *pb) {\n digit const &amp;a = *static_cast&lt;digit const *&gt;(pa);\n digit const &amp;b = *static_cast&lt;digit const *&gt;(pb);\n return (a &lt; b) ? -1 :\n (a &gt; b) ? +1 : 0;\n}\n\nstatic int descending_digits(const void *pa, const void *pb) {\n return -ascending_digits(pa, pb);\n}\n</code></pre>\n\n<p>Other than that, I would recommend that the problem be decomposed into the following functions.</p>\n\n<pre><code>/**\n * Extracts the base-10 digits of number into an array. The caller must\n * provide an array that is large enough for any value of type T, i.e.\n * it should have a size of at least std::numeric_limits&lt;T&gt;::digits10\n * (which is defined in #include &lt;limits&gt;).\n *\n * If number is negative, its absolute value is considered.\n *\n * The digits array will be filled, least-significant digit first.\n * Returns the actual number of digits in the number.\n */\ntemplate &lt;typename T&gt;\nstatic size_t number_to_digits(T number, digit digits[]);\n\n/**\n * Interprets an array of base-10 digits (least-significant digit first)\n * as a number.\n */\ntemplate &lt;typename T&gt;\nstatic T digits_to_number(const digit digits[], size_t ndigits);\n\n/**\n * Given an array of digits, copies just the odd digits (when parity=1)\n * or just the even digits (when parity=0). The size of both the input\n * digits array and the output filtered array is specified by ndigits.\n *\n * Returns the number of digits copied into the filtered array.\n */\nstatic size_t filter_digits(bool parity, const digit digits[], digit filtered[], size_t ndigits);\n\n/**\n * Prints the label, followed by '\\n', followed by n space-delimited digits,\n * followed by std::endl.\n *\n * Returns out for chaining convenience.\n */\nstatic std::ostream &amp;output_digits(std::ostream &amp;out, const char *label, const digit digits[], size_t n);\n\n/**\n * Prints the analysis of the number.\n */ \ntemplate &lt;typename T&gt;\nvoid analyze(T number, std::ostream &amp;out);\n\nint main() {\n long long number;\n std::cout &lt;&lt; \"Enter a number: \" &lt;&lt; std::endl;\n std::cin &gt;&gt; number;\n analyze(number, std::cout);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:05:34.287", "Id": "60054", "Score": "2", "body": "Agree with everything apart from `size_t` and `unsigned` usage. Until very recently I also applied the above rule in my code (because I got it from the behavior of the standard library). But while at \"[Going Native](http://channel9.msdn.com/Events/GoingNative/2013)\" all the big guys in the C++ community said that it was a bad idea. You should use signed types for everything (apart for ints that you are using to hold bit flags). They basically said that the got it wrong when designing the standard library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:06:24.430", "Id": "60055", "Score": "1", "body": "See this [video of the discussion](http://channel9.msdn.com/Events/GoingNative/2013/Interactive-Panel-Ask-Us-Anything). The general discussion on int starts at 41:05 The specific bit about unsigned starts at 42:54 Herb starts his apology at 44:25 and wraps up at 46:00. The basic argument is that mixing signed/unsigned introduces errors. But the two problems it (using unsigned) tries to solve don't really exist. Example: setSize(unsigned int s) Now call it like this: setSize(-1); Works perfectly well but probably does not do what you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:07:01.493", "Id": "60056", "Score": "0", "body": "Sorry: Copy and pasted the comment from another thread (but I think it is important enough to repeat)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T01:43:16.403", "Id": "60118", "Score": "0", "body": "@LokiAstari: [I'll keep that right here](http://codereview.stackexchange.com/questions/33555/review-of-three-constructors-for-a-string-class/33560#33560)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T03:55:57.467", "Id": "36544", "ParentId": "36505", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T13:55:36.103", "Id": "36505", "Score": "5", "Tags": [ "c++", "algorithm" ], "Title": "Finding odd and even digits from an integer" }
36505
<p>I would like your opinion on the following subject. I have to provide icons in different sizes and states. The sizes will be <code>16*16</code>, <code>24*24</code> and <code>32*32</code>.</p> <p>The states bright, dark, disabled and link.</p> <p>Because of browser support we decided for <code>.png</code> instead of <code>.svg</code>. Do you feel this is the best CSS approach for this case? </p> <p>Would you make some changes to improve this styles?</p> <pre><code>&lt;i class="fx-icon fx-icon-home"&gt; .fx-icon { /*standard icon size*/ border: none; display: inline-block; height: 16px; line-height: 16px; margin-right: 3px; vertical-align: top; width: 16px; } .fx-icon.fx-icon-medium { height: 24px; line-height: 24px; width: 24px; } .fx-icon.fx-icon-large { height: 32px; line-height: 32px; width: 32px; } .fx-icon.fx-icon-larger { height: 48px; line-height: 48px; width: 48px; } /*Icon Home*/ .fx-icon-home-bright, .fx-icon-home-dark, .fx-icon-home-disabled, .fx-icon-home-link { background: url(images/icon-home.png) no-repeat; } .fx-icon-home-dark { background-position: -16px 0; } .fx-icon-home-disabled { background-position: -32px 0; } .fx-icon-home-link { background-position: -48px 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:08:48.853", "Id": "59862", "Score": "0", "body": "Is the class `.fx-icon.fx-icon-larger` part of the spec or was it just left out in your introduction?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:24:15.733", "Id": "59866", "Score": "0", "body": "Yes, we also introduced the size 48*48 :)" } ]
[ { "body": "<p>Yes, it's the right approach. You could use a CSS preprocessor to avoid mistakes due to repeating yourselves. Using PNG icons is a good idea because <a href=\"https://developer.apple.com/library/mac/documentation/userexperience/conceptual/applehiguidelines/IconsImages/IconsImages.html#//apple_ref/doc/uid/20000967-SW7\" rel=\"nofollow noreferrer\">smaller icons should be less detailed</a>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/47Qt6.png\" alt=\"iCal icons\"></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:02:07.777", "Id": "60035", "Score": "0", "body": "What's so special about PNGs that make them better suited than any other image format?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:03:39.593", "Id": "60037", "Score": "0", "body": "@cimmanon It's more about vector graphics vs. raster graphics. PNG is simply a nice lossless format." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T09:14:05.983", "Id": "36557", "ParentId": "36507", "Score": "3" } }, { "body": "<p>My recommendation would be to use a tool to generate a sprite sheet + CSS, rather than writing it out manually yourself. I've not used it myself, but the sprite helpers found in Compass (see: <a href=\"http://compass-style.org/reference/compass/helpers/sprites/\" rel=\"nofollow\">http://compass-style.org/reference/compass/helpers/sprites/</a>, but it only works with PNGs) are very popular. If your set of icons expands in the future, you'll be thankful that you don't have to go back and fix everything manually: just run your tool again with the new images and you're good to go.</p>\n\n<hr>\n\n<p>Just because browser support isn't perfect, that doesn't mean you can't have both PNG <em>and</em> SVG. The only browsers that are widely used that do not support SVGs as a background image are IE8 and Android 2.3x.</p>\n\n<p>By taking advantage of the fact that the browsers that do not support SVGs as a background image either do not support the background-size property (IE8) or require a prefix for it (Android 2.3x), you can serve the correct file to the correct browser:</p>\n\n<pre><code>.foo {\n background: url(foo.png) no-repeat; /* IE8 and Android 2.3x */\n background: url(foo.svg) 0 0 / auto auto no-repeat; /* everyone else */\n}\n</code></pre>\n\n<p>In addition to being able to resize gracefully, SVGs have one other little-known advantage: you can use media queries inside them. This is an excellent way of reducing details as the SVG gets smaller or adding details as the SVG gets bigger. When used as a background image, support for media queries inside the SVG is somewhat limited (the demo below appears to only work as expected in IE9+ and Chrome)</p>\n\n<p><a href=\"http://codepen.io/cimmanon/pen/HldKw\" rel=\"nofollow\">http://codepen.io/cimmanon/pen/HldKw</a></p>\n\n<pre><code>&lt;p class=\"one\"&gt;Foo&lt;/p&gt;\n\n&lt;p class=\"two\"&gt;Foo&lt;/p&gt;\n\n&lt;p class=\"three\"&gt;Foo&lt;/p&gt;\n\np {\n display: inline-block;\n}\n\np:before {\n background: url(http://people.opera.com/andreasb/demos/demos_svgopen2009/update/circle.svg) 0 0 / cover no-repeat;\n height: 200px;\n width: 200px;\n display: block;\n content: ' ';\n}\n\n.two:before {\n height: 100px;\n width: 100px;\n}\n\n.three:before {\n height: 50px;\n width: 50px;\n}\n</code></pre>\n\n<p>The SVG:</p>\n\n<pre><code>&lt;svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"400\" height=\"400\"&gt;\n &lt;g&gt;\n &lt;title&gt;Simple SVG + mediaqueries&lt;/title&gt;\n &lt;defs&gt;\n &lt;style type=\"text/css\"&gt;\n #circle {\n fill: #fce57e;\n stroke: #fff;\n stroke-width: 100px;\n stroke-opacity: 0.5;\n fill-opacity: 1;\n }\n @media screen and (max-width: 350px) {\n #circle {\n fill: #879758;\n }\n }\n @media screen and (max-width: 200px) {\n #circle {\n fill: #3b9557;\n }\n }\n @media screen and (max-width: 100px) {\n #circle {\n fill: #d8f935;\n }\n }\n @media screen and (max-width: 50px) {\n #circle {\n fill: #a8c45f;\n }\n }\n @media screen and (max-width: 25px) {\n #circle {\n fill: #2c3c0c;\n }\n }\n &lt;/style&gt;\n &lt;/defs&gt;\n &lt;circle cx=\"200\" cy=\"200\" r=\"150\" id=\"circle\" /&gt;\n &lt;/g&gt;\n&lt;/svg&gt;\n</code></pre>\n\n<p>Learn more: <a href=\"http://blog.cloudfour.com/media-queries-in-svg-images/\" rel=\"nofollow\">http://blog.cloudfour.com/media-queries-in-svg-images/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:39:50.310", "Id": "36586", "ParentId": "36507", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T14:02:07.417", "Id": "36507", "Score": "4", "Tags": [ "css" ], "Title": "Iconography - How would you improve this?" }
36507
<p>There doesn't seem to be anything really wrong with this method. But it has a little smell to me. Does the name make sense (do what you think it would do). Is there some logic I could use to make the enabler a bit more elegant?</p> <pre><code>private void tryEnableCRUD(bool tryEnable = true) { bool enable = false; if (_securityLevel &lt; 3) { enable = tryEnable; } else { enable = tryEnable; } tsbDelete.Enabled = enable; tsbReplace.Enabled = enable; tsbUpload.Enabled = enable; } </code></pre> <h2>UPDATE</h2> <pre><code>private void tryEnableCRUD(bool tryEnable = true) { bool enable = false; if (_securityLevel &lt; 3) { enable = tryEnable; } tsbDelete.Enabled = enable; tsbReplace.Enabled = enable; tsbUpload.Enabled = enable; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:21:33.687", "Id": "59870", "Score": "1", "body": "please show the entire code in addition to the question. leave what you have but add the rest of the code, you don't want to negate the answers already given" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:15:51.223", "Id": "59882", "Score": "0", "body": "Your [Rev 4](http://codereview.stackexchange.com/revisions/36514/4) seems buggy: your `if` and `else` bodies are identical." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:06:22.230", "Id": "59893", "Score": "0", "body": "why are you setting the parameter? I have been baffled by this the entire time, why `bool tryEnable = true' and where is `_securityLevel` coming from. looks like you just want to enable everything when you call this function, why are those things not inside the if statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:08:30.383", "Id": "59894", "Score": "0", "body": "when you update code, add it to the end, don't change what you have." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T20:34:44.440", "Id": "59911", "Score": "1", "body": "Just a note, if this is [tag:wpf], this entire method can be dropped. **It's [tag:winforms], right?** (please update tags accordingly)" } ]
[ { "body": "<p>I would replace the <code>if</code>-<code>else</code>-part:</p>\n\n<pre><code>private void tryEnableCRUD(bool tryEnable = true)\n{\n bool enable = (_securityLevel &lt; 3);\n\n tsbDelete.Enabled = enable;\n tsbReplace.Enabled = enable;\n tsbUpload.Enabled = enable;\n}\n</code></pre>\n\n<p>I would also recommend to make <code>3</code> a constant with a speaking name.</p>\n\n<pre><code>private static int SecurityLevelThreshold = 3;\n\nprivate void tryEnableCRUD(bool tryEnable = true)\n{\n bool enable = (_securityLevel &lt; SecurityLevelThreshold);\n\n tsbDelete.Enabled = enable;\n tsbReplace.Enabled = enable;\n tsbUpload.Enabled = enable;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T16:06:05.690", "Id": "59877", "Score": "2", "body": "You keep forgetting the = sign on you bool enable line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:57:53.650", "Id": "59890", "Score": "0", "body": "@Alex Dresko: Thank you, added the missing `=`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:01:33.287", "Id": "59891", "Score": "0", "body": "\"Threshold\" is a more appropriate term than \"barrier\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T20:23:52.703", "Id": "59910", "Score": "0", "body": "@200_success: You are right, I changed the name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T05:26:51.833", "Id": "59948", "Score": "0", "body": "`SECURITY_LEVEL_THRESHOLD` is C++ naming style. In C# the proper naming is `SecurityLevelThreshold`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:15:30.133", "Id": "36517", "ParentId": "36514", "Score": "5" } }, { "body": "<p>A method like this should do at least two things in addition to MrSmith42's answer:</p>\n\n<ol>\n<li>It should return boolean to indicate whether it succeeded or not (i.e. <code>return enable;</code> at the end)</li>\n<li>if it declares a parameter <code>tryEnable = true</code> then it should either use it, or remove it.</li>\n</ol>\n\n<hr>\n\n<p><strong>EDIT:</strong> after edit and comment from OP.</p>\n\n<p>After your changes I think my point-1 remains valid, but your changes make the 'smell' even worse.... ;-)</p>\n\n<ol>\n<li>You should change the method name to trySetCRUDEnabled(...)</li>\n<li>what if the settings are currently enabled, and the user calls trySetCRUDEnabled(false) ... it makes the logic hard to understand.... in fact, it's broken because now it does not matter what the security-level is ... ;-) (you are changing the code in haste, and making mistakes).</li>\n</ol>\n\n<p>Incorporating MrSmith42's suggestion for simplifying the code, it should read:</p>\n\n<pre><code>bool enable = tryEnable &amp;&amp; _securityLevel &lt; MINSECURITY;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:21:07.277", "Id": "59869", "Score": "0", "body": "i am thinking that this is going to be used in a form or something similar. so it should really only do the last 3 things if it's true. there are probably going to be Drop Down boxes or something that will be enabled if this evaluates to true." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:29:15.267", "Id": "59873", "Score": "0", "body": "@Malachi - how does that change my suggestions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:32:19.507", "Id": "59874", "Score": "0", "body": "@rolfl updated question regarding point #2, code now is my original intention" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:36:06.250", "Id": "59875", "Score": "0", "body": "@rolfl, meaning, instead of returning a value to something, it enables the user to be able to do something on the form/page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:47:14.053", "Id": "59876", "Score": "2", "body": "@TruthOf42 - updated my answer..... your code is now more broken than before ... ;-)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:17:18.927", "Id": "36518", "ParentId": "36514", "Score": "8" } }, { "body": "<p>Based on the code in <a href=\"https://codereview.stackexchange.com/revisions/36514/5\">Rev 5</a> of the question…</p>\n\n<pre><code>private void tryEnableCRUD(bool tryEnable=true)\n{\n tsbDelete.Enabled = tsbReplace.Enabled = tsbUpload.Enabled =\n (_securityLevel &lt; 3) &amp;&amp; tryEnable;\n}\n</code></pre>\n\n<p>The first line emphasizes that all three variables will be assigned the same value. The second line emphasizes that that value will be true only when <code>_securityLevel</code> is less than 3 and <code>tryEnable</code> is true. The fact that the resulting function is compact is a bonus.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T19:49:57.883", "Id": "59908", "Score": "1", "body": "This is rad. I can think of a million different places I could do something like this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T17:55:38.643", "Id": "36529", "ParentId": "36514", "Score": "6" } }, { "body": "<p>This method does not make sense, semantically. I am really surprised no one mentioned that. I would refactor it the following way:</p>\n\n<pre><code>private bool TrySetEnabled(bool value)\n{\n if (value &amp;&amp; _securityLevel &lt; 3) return false;\n tsbDelete.Enabled = tsbReplace.Enabled = tsbUpload.Enabled = value;\n return true;\n}\n</code></pre>\n\n<ol>\n<li>I changed the name of method and parameter to emphasize the fact that this method can both disable and enable controls. </li>\n<li>I changed return type, because it is a common style for methods which start with <code>Try</code> to return the flag which shows if operation succeeded. And it makes sense in this case.</li>\n<li><p>I removed this weird code part, where you set <code>enabled</code> to <code>false</code> if security check failed (even when controls were already enabled). This is a really weird behaviour which adds a non-obvious side effect to your method. If you really need this logic just call</p>\n\n<pre><code> if (!TrySetEnabled(true))\n {\n TrySetEnabled(false);\n } \n</code></pre></li>\n<li><p>As suggested by <strong>MrSmith42</strong> you should probably use constant field instead of <code>3</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:25:27.600", "Id": "60014", "Score": "0", "body": "I like it. I think some people disagree that methods should have multiple exit points, but to me multiple exits are great." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:06:14.093", "Id": "36550", "ParentId": "36514", "Score": "6" } } ]
{ "AcceptedAnswerId": "36550", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:07:39.343", "Id": "36514", "Score": "4", "Tags": [ "c#" ], "Title": "Improving readability of enabling method" }
36514
<p>The <em>weekend challenge</em> problem must be solvable with a relatively short solution that can be posted in anyone's favorite programming language.</p> <p>After the community <a href="http://meta.codereview.stackexchange.com/questions/1201/cr-weekend-challenge">has agreed on a problem for the weekend challenge</a>, entries can be posted anytime.</p> <p>Extended discussion on this topic can be carried out in our <a href="http://chat.stackexchange.com/rooms/8595/the-2nd-monitor">chat room</a>. The current problem / "challenge" will be pinned in the "starred posts" list, which is subscribed to the RSS feed for new questions that use the <a href="/questions/tagged/weekend-challenge" class="post-tag" title="show questions tagged &#39;weekend-challenge&#39;" rel="tag">weekend-challenge</a> tag.</p> <p><em>Questions posted must be fully working solutions, and must include all the code.</em> For more info regarding on-topic questions, consult the <a href="http://chat.stackexchange.com/rooms/8595/the-2nd-monitor">Help Center</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:15:09.280", "Id": "36515", "Score": "0", "Tags": null, "Title": null }
36515
Reviewing code is fun! Every now and then the community decides on a problem to solve; solutions are posted as questions to be peer reviewed. Use this tag to mark your question as a weekend challenge entry.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:15:09.280", "Id": "36516", "Score": "0", "Tags": null, "Title": null }
36516
<p>I initially thought that this was just an architecture issue so I placed it on programmers as <a href="https://softwareengineering.stackexchange.com/questions/219960/thoughts-on-refactoring-a-generic-dao">Thoughts on refactoring a generic DAO</a>. Then I asked on codereview meta <a href="https://codereview.meta.stackexchange.com/questions/1205/is-this-appropriate-for-codereview-se">here</a> and decided to put up the code here. </p> <ul> <li>Here's a <a href="https://github.com/anshbansal/general/tree/173fd357bdc287a5d1e462a43b15a3fb5690fafd/Java/Generic%20DAO" rel="nofollow noreferrer">github link</a> if someone wants to see there.</li> <li>There are four DAOs - DAODelete, DAOUpdate, DAORead, DAOInsert but I am just putting DAORead and its implementation here so that it is easier to review.</li> <li>I have trimmed the code a lot so if something is amiss please tell me and I'll correct it. Otherwise you can see github link as it has complete code(kinda).</li> </ul> <hr> <p>My architecture is like this</p> <ul> <li>Abstraction layer of DAO at top</li> <li>DataBase specific implementation of DAO <strong>BUT</strong> Table-independent</li> <li>Table dependency is passed down to a lower utility layer</li> <li>A <code>Enum</code> is passed down to the lower utility layer by which it gives table specific results</li> <li>Table-specific utility classes for the lower utility layer mentioned in the previous point.</li> <li>There is a <code>Student</code> pojo that I am omitting because well it is just a pojo. <code>private</code> variables and all. Just note that <code>enrollmentDate</code> is of type <code>java.sql.Date</code></li> </ul> <p><strong>My concern</strong></p> <ul> <li>I am satisfied with the upper layer of DAO but I think that at the the lower level specifically at the <code>OracleSpecific.java</code> the things which should have strong coupling have weak coupling. e.g. there are different methods for getting pojo from resultset or getting primary key. Each of these in turn have <code>switch</code> case for calling the functions in lower utility class. </li> <li><strong>Although</strong> the <code>schema-specific</code> methods are tied together in different utility classes the method call themselves in <code>OracleSpecifics.java</code> do not have any coupling.</li> <li>I am thinking whether I should change the enum <code>TableName</code> to contain a <em>specific state</em>. The state I am thinking for the schema-specific lowest level utility classes.</li> <li><p>These <code>specific states</code> contained in enums can be used to change the state of DAO and the DAO can then call the specific functions based on an interface implemented by all such states. Thus depending on the state the behavior can change automatically.</p></li> <li><p>Is this design decision correct or would it be meaningless?</p></li> <li>Any other thing that I might have overlooked? </li> <li>Any thoughts about the design itself?</li> <li>Would I lose type safety introduced by generics due to this change?</li> </ul> <hr> <h2>Enums Used</h2> <p><strong>QueryType.java</strong></p> <pre><code>package aseemEnums; public enum QueryType { READ, DELETE; } </code></pre> <p><strong>Databases.java</strong></p> <pre><code>package aseemEnums; public enum Databases { Oracle; } </code></pre> <p><strong>TableName.java</strong></p> <pre><code>package aseemEnums; public enum TableName { STUDENT_TABLE("STUDENT_TABLE"); private final String tableName; TableName(String tableName) { this.tableName = tableName; } public String toString() { return tableName; } } </code></pre> <hr> <h2>The Abstraction layer</h2> <p><strong>DAOFactory.java</strong></p> <pre><code>package aseemDao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.NamingException; import aseemEnums.Databases; public abstract class DAOFactory { // Abstract Instance methods public abstract DAOInsert getDAOInsert() throws SQLException; public abstract DAORead getDAORead() throws SQLException; public abstract DAODelete getDAODelete(); public abstract DAOUpdate getDAOUpdate(); // Concrete Class Methods public static DAOFactory factoryProducer(Databases db) throws NamingException { switch (db) { case Oracle: return new OracleFactory(); default: return null; } } static void closeAll(PreparedStatement ps, ResultSet rs) { try { rs.close(); } catch (Exception e) { } try { ps.close(); } catch (Exception e) { } } } </code></pre> <p><strong>DAORead.java</strong></p> <pre><code>package aseemDao; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import aseemEnums.TableName; public interface DAORead { public abstract &lt;T&gt; List&lt;T&gt; getAll(Connection con, TableName tableName) throws SQLException; public abstract &lt;T&gt; List&lt;T&gt; getAllForInput(Connection con, TableName tableName, String columnName, String searchValue) throws SQLException; public abstract &lt;T&gt; T getPojoForPrimarKey(Connection con, TableName tableName, String primaryKey) throws SQLException; public abstract &lt;T&gt; boolean alreadyExisting(Connection con, TableName tableName, String primaryKey) throws SQLException; public abstract &lt;T&gt; boolean alreadyExisting(Connection con, TableName tableName, T currentPojo) throws SQLException; } </code></pre> <p><hr></p> <h2>Concrete Implementation of DAO's abstraction</h2> <p><strong>OracleFactory.java</strong></p> <pre><code>package aseemDao; import java.sql.SQLException; public class OracleFactory extends DAOFactory { @Override public DAOInsert getDAOInsert() throws SQLException { return new OracleInsert(this); } @Override public DAORead getDAORead() throws SQLException { return new OracleRead(this); } @Override public DAODelete getDAODelete() { return new OracleDelete(this); } @Override public DAOUpdate getDAOUpdate() { return new OracleUpdate(this); } } </code></pre> <p><strong>OracleRead.java</strong></p> <pre><code>package aseemDao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import aseemEnums.QueryType; import aseemEnums.TableName; public class OracleRead implements DAORead { DAOFactory fac = null; OracleRead(DAOFactory fac) throws SQLException { this.fac = fac; } @SuppressWarnings("unchecked") public &lt;T&gt; List&lt;T&gt; getAll(Connection con, TableName tableName) throws SQLException { List&lt;T&gt; list = new ArrayList&lt;T&gt;(); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("select * from " + tableName); rs = ps.executeQuery(); while (rs.next()) { list.add((T) OracleSpecifics .getPojoFromResultSet(tableName, rs)); } } finally { DAOFactory.closeAll(ps, rs); } return list; } @SuppressWarnings("unchecked") public &lt;T&gt; List&lt;T&gt; getAllForInput(Connection con, TableName tableName, String columnName, String searchValue) throws SQLException { List&lt;T&gt; list = new ArrayList&lt;T&gt;(); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + " LIKE '%" + searchValue + "%'"); rs = ps.executeQuery(); while (rs.next()) { list.add((T) OracleSpecifics .getPojoFromResultSet(tableName, rs)); } } finally { DAOFactory.closeAll(ps, rs); } return list; } @Override public &lt;T&gt; T getPojoForPrimarKey(Connection con, TableName tableName, String primaryKey) throws SQLException { T currentPojo = null; PreparedStatement ps = null; ResultSet rs = null; try { String queryString = OracleSpecifics.queryString(tableName, primaryKey, QueryType.READ); ps = con.prepareStatement(queryString); rs = ps.executeQuery(); if (rs.next()) { currentPojo = OracleSpecifics.getPojoFromResultSet(tableName, rs); } } finally { DAOFactory.closeAll(ps, rs); } return currentPojo; } @Override public &lt;T&gt; boolean alreadyExisting(Connection con, TableName tableName, String primaryKey) throws SQLException { if (getPojoForPrimarKey(con, tableName, primaryKey) != null) { return true; } else { return false; } } @Override public &lt;T&gt; boolean alreadyExisting(Connection con, TableName tableName, T currentPojo) throws SQLException { String primaryKey = OracleSpecifics.&lt;T&gt; getPrimaryKey(tableName, currentPojo); if (alreadyExisting(con, tableName, primaryKey) == false) { return false; } else { return true; } } } </code></pre> <hr> <h2>The lower utility layer in DAO</h2> <p><strong>OracleSpecifics.java</strong></p> <pre><code>package aseemDao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import aseemEnums.QueryType; import aseemEnums.TableName; import aseemPojo.Student; public class OracleSpecifics { // These functions don't call any table-specific functions static String queryString(TableName tableName, String keyValue, QueryType type) { String firstHalf = null; switch (type) { case READ: firstHalf = "select * from " + tableName + " where "; break; case DELETE: firstHalf = "DELETE from " + tableName + " where "; break; default: } switch (tableName) { case STUDENT_TABLE: return firstHalf + "STUDENT_ID='" + keyValue + "'"; default: return null; } } static &lt;T&gt; String getPrimaryKey(TableName tableName, T currentPojo) { switch (tableName) { case STUDENT_TABLE: return ((Student) currentPojo).getStudentId(); default: return null; } } // These functions call table-specific functions @SuppressWarnings("unchecked") static &lt;T&gt; T getPojoFromResultSet(TableName tableName, ResultSet rs) throws SQLException { switch (tableName) { case STUDENT_TABLE: return (T) SpecStudent.getPojo(rs); default: return null; } } } </code></pre> <h2>One of the Table-Specifics utility Classes</h2> <p><strong>SpecStudent.java</strong></p> <pre><code>package aseemDao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import aseemEnums.TableName; import aseemPojo.Student; public class SpecStudent { public static Student getPojo(ResultSet rs) throws SQLException { Student currentStudent = new Student(); currentStudent.setStudentId(rs.getString("Student_Id")); currentStudent.setRollNo(rs.getString("Roll_No")); currentStudent.setStudentName(rs.getString("Student_Name")); currentStudent.setAddress(rs.getString("Address")); currentStudent.setEmail(rs.getString("Email")); currentStudent.setContactNumber(rs.getString("Contact_Number")); currentStudent.setGuardianName(rs.getString("Guardian_Name")); currentStudent.setEnrollmentDate(rs.getDate("Enrollment_Date")); return currentStudent; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T16:44:22.723", "Id": "59880", "Score": "1", "body": "I strongly urge you to check out [Datanucleus](http://www.datanucleus.org/) and [Hibernate](http://www.hibernate.org/) before trying to roll-out your own [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping), for anything remotely serious. Though trying to write an ORM is kind of a rite-of-passage for student programmers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T16:46:37.160", "Id": "59881", "Score": "6", "body": "@abuzittingillifirca I know that such things exist but I want to do this for learning purposes. That's why I included `reinventing-the-wheel` tag." } ]
[ { "body": "<p>I'll leave the actual generic DAO discussions out of this answer for now, and just offer my two cents on coding styles...</p>\n\n<ol>\n<li><p>You can use better method names instead of <code>getPojo</code>... Pojo is well-understood but still quite an informal term, and you'll probably attract equal comments whether to keep it all caps or not - it's an acronym afterall. The Spring framework calls their helper classes RowMappers with a <code>mapRow</code> method, so maybe you want to follow something like that. <a href=\"http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/jdbc/core/RowMapper.html\">http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/jdbc/core/RowMapper.html</a></p></li>\n<li><p>You can inline your conditional checks in the <code>return</code> statements as such:</p>\n\n<pre><code>@Override\npublic &lt;T&gt; boolean alreadyExisting(Connection con, TableName tableName,\n String primaryKey) throws SQLException {\n return getPojoForPrimarKey(con, tableName, primaryKey) != null;\n}\n\n@Override\npublic &lt;T&gt; boolean alreadyExisting(Connection con, TableName tableName,\n T currentPojo) throws SQLException {\n return alreadyExisting(con, tableName, OracleSpecifics.&lt;T&gt; getPrimaryKey(tableName, currentPojo));\n}\n</code></pre></li>\n<li><p>Actually, I'm not that sure whether you really need to map the Pojo in order to determine if a row with the primary key exists or not... Perhaps there's a simpler way?</p></li>\n</ol>\n\n<p>edit: </p>\n\n<ul>\n<li>Your <code>Oracle*</code> classes don't really have anything Oracle-specific now, I'm not sure if that is intended because things are still work-in-progress. Or do you mean you will be creating new classes for other RDBMS software like MySQL, MariaDB etc. with their own dialect? </li>\n<li>DAOs should not need to keep 'states' beyond the current <code>ResultSet</code> object that it is doing the mapping for. You may need to re-consider your implementation of the <code>TableName</code> enum to contain <em>a specific state</em>. More clarification is needed here.</li>\n<li>After another quick reading, you may want to consider the 'generic-ness' of your approach, because it appears that adding new classes (aka entities) to pass to your DAO framework requires a <code>Spec&lt;Table&gt;</code> class (or updating your existing <code>SpecStudent</code>) for the actual implemention (e.g. calling all the getter methods on your <code>Student</code> class), and updating your <code>TableName</code> enum as well. Maybe you can also consider using reflection for the implementation, so that there is less code to update in the long run?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T05:30:20.673", "Id": "59949", "Score": "0", "body": "+1 Nice catch on #3! Change the first method to simply look for the PK without loading the POJO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:20:05.970", "Id": "60018", "Score": "0", "body": "Good point about inlining the return statements. About there being nothing `Oracle Specific`. Yeah totally correct. Currently there isn't anything. I had to deal with Oracle so I made Oracle classes only. But the structure of the DAO itself allows it to be used for others, I think. I kept it separate for extensibility. About `TableName` enum containing specific state I'll update the question. I know that the current implementation is not actually `generic` (plain English intended). The `Oracle Specifics` and the lower classes are a big concern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:23:08.220", "Id": "60019", "Score": "0", "body": "I'll take a look at reflection. I got the same suggestion on programmers also. Currently the whole thing is small but it will become a huge monster, at least `Oracle Specifics` will, in the long run. Your response is much appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:02:25.057", "Id": "60036", "Score": "0", "body": "About mapping the pojo for determining whether a row with the primary key exists, I did that to make the generic-ness of the DAO consistent. Suppose a table had a primary key stored as `Timestamp` then it would need a `Timestamp` object passed. If I added a type parameter for primary key's data type then there will be a huge maintainability problem in case the schema changes i.e. all function calls from other tiers of architecture will have to be changed. Pojo aka DTO was the only thing I placed the restriction on. That's the least denominator that I thought people could maintain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:55:07.860", "Id": "60069", "Score": "0", "body": "@AseemBansal A common approach taken by ORMs is to require a `Serializable` primary key. This handles `Integer`, `Timestamp` and even compound keys such as `VehicleKey { String state, String plate }`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:14:48.670", "Id": "36545", "ParentId": "36519", "Score": "11" } }, { "body": "<p><strong>General</strong></p>\n\n<ul>\n<li><p>Replace <code>if (&lt;expr&gt;) return true; else return false;</code> with <code>return &lt;expr&gt;;</code>.</p></li>\n<li><p>Change all but the first letter of each acronym into lowercase: <code>DaoFactory</code>. While it looks strange at first, they're easier to type, you'll quickly get used to it, and you won't get confused when they're combined as in <code>MySQLJDBCDAO</code>. This simple, consistent rule eliminates a lot of guesswork.</p></li>\n<li><p>Be consistent with your plural vs. singular naming. <code>QueryType</code>, <code>TableName</code> and . . . <code>Databases</code>? Code completion will obviously keep you from getting it wrong, but that will slow you down after a while.</p></li>\n<li><p>Spell check your code. Yes, you have to do it manually, but there's no reason to let <code>getPojoForPrimarKey</code> make it into a public interface. And h.j.k. is right here: switch \"pojo\" out for \"entity\" or something more explanatory.</p></li>\n<li><p>Don't leak exceptions from the specific implementations such as <code>SQLException</code> because you're limiting yourself to SQL databases using checked exceptions. Create <code>DaoException</code> and map them with a utility class a la Hibernate and Spring.</p></li>\n</ul>\n\n<p><strong>Java</strong></p>\n\n<ul>\n<li><p>Java package names are typically all lowercase and form a tree structure: <code>aseem.enums</code>, <code>aseem.dao</code>, and <code>aseem.pojo</code>. They also tend to avoid plurals, so <code>aseem.enum</code> instead of <code>aseem.enums</code>.</p></li>\n<li><p>Use <code>StringBuilder</code> instead of concatenating strings in many steps. Every <code>x + y + ... + z</code> creates a new <code>StringBuilder</code>, appends the strings, and packages the result under the hood. Splitting this across statements results in extra temporary builders and immutable strings which causes churn in the garbage collector.</p></li>\n<li><p>Every method <em>in an interface</em> is by definition public and abstract, so you may remove those modifiers. This is more a personal preference, and in those cases I tend to lean toward laziness wherever practical. Any superfluous information that applies to everything is noise.</p></li>\n<li><p>Don't catch <code>Exception</code> except at very high-levels such as an event loop or thread's <code>run</code> method. <code>DAOFactory.closeAll</code> can catch <code>SQLException</code> to let unrelated problems bubble up. The reason is that you may inadvertently catch an exception (e.g. <code>InvalidStateException</code>) that you aren't prepared to handle. It's safe to ignore a <code>SQLException</code> in <code>closeAll</code>, but not other types of exceptions that may signal real problems. Thus, change both <code>catch</code> clauses to <code>SQLException</code>.</p></li>\n</ul>\n\n<p><strong>DAO Design</strong></p>\n\n<ul>\n<li><p>Does the set of table names really deserve to be decided at compile time? Why not column names, too? I didn't see any place where you're switching on the table [oh, see next item], and if you are that should be moved into a proper class with polymorphic behavior instead. An enumeration should model a truly fixed set of items. <code>QueryType</code> is a great example.</p></li>\n<li><p><code>OracleSpecifics</code> seems like it will become a monster as it grows to deal with a) Oracle and b) every table. Create a proper <code>Table</code> class with either a subclass for each table or read the configuration from a file so that <code>OracleSpecifics</code> can be 100% Oracle-specific and you don't have to repeat it in <code>MySqlSpecifics</code> and <code>SqlServerSpecifics</code>.</p></li>\n<li><p>What does <code>alreadyExisting</code> mean? Does this query for the database to see if the primary key is already there? How about <code>exists</code>? Similarly with <code>getAllForInput</code>; make the name more explicit such as <code>getForColumn</code> to distinguish it from <code>getForColumns</code> that takes a column/value map. I've always been fond of <code>findBy...</code> for query methods that may return no results and <code>getBy...</code> for methods that return a single result or throw an exception.</p></li>\n<li><p>Why does the <code>OracleRead</code> constructor declare that it throws <code>SQLException</code> when it cannot?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:32:51.187", "Id": "60022", "Score": "0", "body": "Just for clarification, I should spell check manually so that inconsistencies in the naming is taken care of? Am I correct or did I miss something in that? `getPojoForPrimaryKey` has to be in public interface so to query a specific record. Or can I get a particular row without that? FYI I am not a experienced person. Having said that what other type of databases there can be? You said don't catch Exception as it can lead to unrelated problems. What kind of problems and then what should I do? Propagate user-defined Exeptions to the calling layer for giving information to caller?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:37:18.367", "Id": "60023", "Score": "0", "body": "I **am really** concerned about DAO design. Specifically how `OracleSpecifics` will grow and less cohesion between related terms in the various `switch` cases. Any suggestions about how to arrange the Table specific things? So far I got things about reflection. Any other thing? Good suggestions about the names and all the other things. I'll take care of them. Much appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:01:52.577", "Id": "60070", "Score": "0", "body": "@AseemBansal Yes, spell checking is (sadly) a manual process for class/variable names. I've clarified the 3rd and 4th bullets under **Java**." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T05:27:19.837", "Id": "36548", "ParentId": "36519", "Score": "8" } } ]
{ "AcceptedAnswerId": "36548", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T15:18:02.870", "Id": "36519", "Score": "21", "Tags": [ "java", "design-patterns", "reinventing-the-wheel" ], "Title": "Generic DAO written in Java" }
36519
<pre><code>open System type Date = System.DateTime type SafeDate = | WorkingDate of Date | InvalidDate of Exception let dateAttempt (x: int, y:int, z:int) = try let returnDate = Date(z,y,x) WorkingDate returnDate with ex -&gt; InvalidDate ex let rnd = System.Random(4) let randomBirthYear() = rnd.Next(1904,1954) let randomBirthMonth() = rnd.Next(1,13) let randomBirthDay() = rnd.Next(1,32) let generateDate() = (randomBirthDay(), randomBirthMonth(), randomBirthYear()) |&gt; dateAttempt let chooseValidDate d = match d with | WorkingDate d -&gt; Some d | _ -&gt; None let sampleDobs = [for i in 1 .. 1000 -&gt; generateDate()] let cleanDates = Seq.choose chooseValidDate sampleDobs </code></pre>
[]
[ { "body": "<p>One way to work around invalid dates is not to generate them in the first place: find the number of days between the boundary dates, generate a random integer from this range and then add that number of days to the start date:</p>\n\n<pre><code>let generateDate (min : Date) max =\n let totalDays = int (max - min).TotalDays\n let generatedDays = rnd.Next(0, totalDays)\n let generatedDate = min.AddDays(float generatedDays)\n generatedDate\n\nlet generateDateByYear minYear maxYear =\n generateDate (Date(minYear, 1, 1)) (Date(maxYear, 1, 1))\n\nlet generateBirthDate() = generateDateByYear 1904 1954\n\nlet sampleDobs = [for i in 1 .. 1000 -&gt; generateBirthDate()]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:18:25.257", "Id": "36530", "ParentId": "36521", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T16:00:49.433", "Id": "36521", "Score": "4", "Tags": [ "random", "f#", "datetime", "functional-programming" ], "Title": "is there a more functionally idiomatic way of generating valid dates in f#?" }
36521
<p>I have been writing the application. I meant to implement a repository pattern with Unit of Work. Is it correctly done? Can you make a code review? I use <code>SQLite</code> wrapper <code>sqlite-net</code>.</p> <h3>IFeedRepository:</h3> <pre><code>internal interface IFeedRepository&lt;T&gt; : IDisposable where T : IBaseFeed { int Count { get; } void Add(T feed); IEnumerable&lt;T&gt; GetAll(); T GetFeedById(int id); T GetFeedByLink(string feedLink); T GetFeedByLink(Uri feedLink); int GetFeedIdByLink(string feedLink); int GetFeedIdByLink(Uri feedLink); void Remove(T feed); void RemoveById(int id); void Update(T feed); void Save(); } </code></pre> <h3>FeedRepository:</h3> <pre><code>internal class FeedRepository&lt;T&gt; : IFeedRepository&lt;T&gt; where T: IBaseFeed, new() { private readonly SQLiteConnection _db; private IList&lt;T&gt; _feeds; private bool _isDisposed = false; public int Count { get { return _feeds.Count; } } public FeedRepository(SQLiteConnection db) { this._db = db; this._feeds = _db.Table&lt;T&gt;().ToList(); this._db.BeginTransaction(); } public void Add(T feed) { this._feeds.Add(feed); this._db.Insert(feed); } public IEnumerable&lt;T&gt; GetAll() { return this._feeds; } public T GetFeedById(int id) { return this._feeds.Where(feed =&gt; int.Equals(feed.Id, id)).Single(); } public T GetFeedByLink(string feedLink) { return this.GetFeedByLink(new Uri(feedLink)); } public T GetFeedByLink(Uri feedLink) { return this._feeds.Where(feed =&gt; Uri.Equals(feed.Link, feedLink)).Single(); } public int GetFeedIdByLink(string feedLink) { return this.GetFeedIdByLink(new Uri(feedLink)); } public int GetFeedIdByLink(Uri feedLink) { return this._feeds.Where(feed =&gt; Uri.Equals(feed.Link, feedLink)).Select(feed =&gt; feed.Id).Single(); } public void Remove(T feed) { this._feeds.Remove(feed); this._db.Delete(feed); } public void RemoveById(int id) { this.Remove(this.GetFeedById(id)); } public void Update(T feed) { int indexOfFeed = this._feeds.IndexOf(this.GetFeedById(feed.Id)); this._feeds[indexOfFeed] = feed; this._db.Update(feed); } public void Save() { this._db.Commit(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { if (!this._isDisposed) { if (isDisposing) { if (this._db != null) { this._db.Dispose(); } } this._isDisposed = true; } } ~FeedRepository() { this.Dispose(false); } } </code></pre> <p>And Unit of Work, that is probably wrong :/</p> <h3>IUnitOfWork:</h3> <pre><code>public interface IUnitOfWork : IDisposable { int Count { get; } void Add(FeedData feedData); IEnumerable&lt;FeedData&gt; GetAll(); FeedData GetFeedDataById(int feedDataId); FeedData GetFeedDataByLink(string feedDataLink); FeedData GetFeedDataByLink(Uri feedDataLink); void Remove(FeedData feedData); void RemoveByFeedDataId(int feedDataId); void Update(FeedData feedData); void Save(); } </code></pre> <h3>UnitOfWork:</h3> <pre><code>public class UnitOfWork : IUnitOfWork { private readonly SQLiteConnection _db; private IList&lt;FeedData&gt; _feedsData; private FeedRepository&lt;FeedData&gt; _feedDataRepository; private FeedRepository&lt;FeedItem&gt; _feedItemRepository; private bool _isDisposed = false; public int Count { get { return _feedsData.Count; } } public UnitOfWork(SQLiteConnection db) { this._db = db; this._feedDataRepository = new FeedRepository&lt;FeedData&gt;(this._db); this._feedItemRepository = new FeedRepository&lt;FeedItem&gt;(this._db); foreach (FeedData feedData in this._feedDataRepository.GetAll()) { feedData.Items = this._feedItemRepository.GetAll().Where(item =&gt; int.Equals(item.FeedDataId, feedData.Id)).ToList(); this._feedsData.Add(feedData); } } public void Add(FeedData feedData) { this._feedsData.Add(feedData); this._db.BeginTransaction(); this._feedDataRepository.Add(feedData); foreach (FeedItem item in feedData.Items) { item.FeedDataId = feedData.Id; this._feedItemRepository.Add(item); } this._db.Commit(); } public IEnumerable&lt;FeedData&gt; GetAll() { return this._feedsData; } public FeedData GetFeedDataById(int feedDataId) { return this._feedsData.Where(feed =&gt; int.Equals(feed.Id, feedDataId)).Single(); } public FeedData GetFeedDataByLink(string feedDataLink) { return this.GetFeedDataByLink(new Uri(feedDataLink)); } public FeedData GetFeedDataByLink(Uri feedDataLink) { return this._feedsData.Where(feed =&gt; Uri.Equals(feed.Link, feedDataLink)).Single(); } public void Remove(FeedData feedData) { this._feedsData.Remove(feedData); this._db.BeginTransaction(); this._feedDataRepository.Remove(feedData); foreach (FeedItem feedItem in feedData.Items) { this._feedItemRepository.Remove(feedItem); } this._db.Commit(); } public void RemoveByFeedDataId(int feedDataId) { FeedData feedData = this._feedDataRepository.GetFeedById(feedDataId); feedData.Items = this._feedItemRepository.GetAll().Where(item =&gt; int.Equals(item.FeedDataId, feedData.Id)).ToList(); this.Remove(feedData); } public void Update(FeedData feedData) { var matches = this._feedsData.Where(feed =&gt; int.Equals(feed.Id, feedData.Id)); int indexOfFeed = this._feedsData.IndexOf(matches.Single()); this._feedsData[indexOfFeed] = feedData; this._db.BeginTransaction(); this._feedDataRepository.Update(feedData); foreach (FeedItem feedItem in feedData.Items) { this._feedItemRepository.Update(feedItem); } this._db.Commit(); } protected virtual void Dispose(bool isDisposing) { if (!this._isDisposed) { if (isDisposing) { if (this._feedDataRepository != null) { this._feedDataRepository.Dispose(); } if (this._feedItemRepository != null) { this._feedItemRepository.Dispose(); } } this._isDisposed = true; } } public void Save() { this._feedDataRepository.Save(); this._feedItemRepository.Save(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~UnitOfWork() { this.Dispose(false); } } </code></pre> <p>Is it clear? Or Shall I specify what I want to achieve?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:47:52.603", "Id": "59900", "Score": "2", "body": "From http://msdn.microsoft.com/en-us/library/b1yfkh5e%28v=vs.110%29.aspx#finalizable_types: `AVOID making types finalizable. Carefully consider any case in which you think a finalizer is needed. There is a real cost associated with instances with finalizers, from both a performance and code complexity standpoint.`" } ]
[ { "body": "<p>Your <code>IUnitOfWork</code> interface has mixed concerns with <code>IFeedRepository</code>; I don't think the <code>GetFeedData</code> methods belong in there. The way I understand UoW, it should be looking something like this:</p>\n\n<pre><code>public interface IUnitOfWork\n{\n void Commit(); // save changes\n void Rollback(); // discard changes\n}\n</code></pre>\n\n<p>..and vice-versa; if <code>IFeedRepository.Save()</code> has the same meaning as <code>IUnitOfWork.Save()</code>, then I don't think <code>IFeedRepository</code> interface should feature it.</p>\n\n<p>An <em>interface</em> is an <em>abstraction</em>. An interface that forces its implementation to implement <code>IDisposable</code> is a <em>leaky abstraction</em>, because you're assuming all implementations of your repository interface will be disposable, which is an <em>assumption</em> waiting to be proven wrong: the <em>implementation</em> is leaking into the abstraction. What if you wanted to implement that repository with an <code>IList&lt;T&gt;</code> instead of a Sqlite backend?</p>\n\n<p>Also I don't think the finalizers are needed; just call the <code>Dispose()</code> method, or wrap your instance in a <code>using</code> block instead.</p>\n\n<hr>\n\n<p>I don't like that your <code>UnitOfWork</code> class constructor has the side-effect of hitting the database, but I do like the connection being owned by the caller and being constructor-injected into the UoW, and as a <em>Unit of Work</em> is actually supposed to encapsulate a <em>transaction</em>, I suggest you move the transaction stuff in there.</p>\n\n<p>I think <code>IFeedRepository&lt;T&gt;</code> can be dropped altogether, since the UoW isn't using it - it's directly instanciating the concrete implementations and encapsulates them as concrete implementations, which leaves your interface unused.</p>\n\n<p>Alternatively, you could have some <code>IRepositoryFactory&lt;T&gt;</code> with some <code>IFeedRepository&lt;T&gt; Create(SQLiteConnection)</code> method, constructor-injected into your UoW - this would decouple your UoW from the repository implementations, and make the interface serve a purpose. I prefer this alternative, because it's <em>coding against an interface, not an implementation</em>.</p>\n\n<p>Now I just noticed this line in your repo constructor:</p>\n\n<pre><code>this._feeds = _db.Table&lt;T&gt;().ToList();\n</code></pre>\n\n<p>If you have 1,000,000 rows in that table, you have a very expensive constructor here. Again, it's a constructor with side-effects; I would only assign the connection reference in there.</p>\n\n<p>In the end, I would try to keep it as simple as possible:</p>\n\n<ul>\n<li><strong>UnitOfWork</strong>:\n<ul>\n<li>Owns (and exposes) repositories (<em>owns</em>, meaning it's its job to also <em>dispose</em> them)</li>\n<li>Encapsulates transaction (commit/rollback)</li>\n</ul></li>\n<li><strong>Repositories</strong>:\n<ul>\n<li>Provide an abstraction layer over the SQLite plumbing</li>\n<li>Expose ways to perform CRUD operations</li>\n</ul></li>\n</ul>\n\n<p><sub>Note: this may be all wrong: I use <a href=\"/questions/tagged/entity-framework\" class=\"post-tag\" title=\"show questions tagged &#39;entity-framework&#39;\" rel=\"tag\">entity-framework</a> and don't bother with UoW/Repository patterns; my view of a UoW is probably biased with <code>DbContext</code>, which I've read some people consider a bad UoW implementation - yet nobody could clearly explain why.</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:43:34.773", "Id": "59899", "Score": "0", "body": "Calling `GC.SuppressFinalize(yhis)` is part of the basic pattern for using `IDisposable` (http://msdn.microsoft.com/en-us/library/b1yfkh5e%28v=vs.110%29.aspx#basic_pattern)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:47:58.860", "Id": "59901", "Score": "1", "body": "@ChrisWue I thought all you had to do was implementing `IDisposable.Dispose()` with a method that calls `Dispose()` on all `IDisposable` resources you're holding.. wouldn't that be enough?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:54:10.380", "Id": "59902", "Score": "0", "body": "The idea is that if `Dispose` was called the resources have been cleaned up and there is not need to run the finalizer which reduces the amount of work the CLR has to do. If you have an unsealed class then someone can derive from it and possibly have a subclass implementing a finalizer. The default pattern will take care of it. In the end it's always good to use a pattern consistently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T19:23:58.073", "Id": "59904", "Score": "0", "body": "Ok, so what should I do with my current UoW?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T19:42:49.913", "Id": "59906", "Score": "0", "body": "@retailcoder, from my knowledge of the `using` statement/block the entity has to have a dispose method or something like that, does that sound about right to you, or am I thinking of a different method it needs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T19:49:47.450", "Id": "59907", "Score": "1", "body": "@Malachi `using (var foo = new bar())` will not compile if `bar` isn't `IDisposable`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T19:55:00.333", "Id": "59909", "Score": "1", "body": "@J.Marciniak edited with more details :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T18:19:27.797", "Id": "36531", "ParentId": "36523", "Score": "6" } } ]
{ "AcceptedAnswerId": "36531", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T16:53:38.663", "Id": "36523", "Score": "8", "Tags": [ "c#", "sqlite", "mvvm" ], "Title": "Unit of Work with Generic Repository Pattern MVVM" }
36523
<p>Is this a <strong>valid</strong> and <strong>safe</strong> use of .NET's <a href="http://msdn.microsoft.com/en-us/library/system.threading.spinlock(v=vs.110).aspx" rel="nofollow"><code>System.Threading.SpinLock</code></a>?</p> <blockquote> <p><strong>Why am I doing this?</strong></p> <p><code>Random</code>'s public methods are not thread-safe. I could be calling from any thread which I do not know until run-time; they are from the Thread Pool, and it could be called fairly frequently (up to a hundred times a second), so I would rather not create a new <code>Random</code> object each time.</p> </blockquote> <pre><code>public static class SingleRandom { private static Random random; private static SpinLock spinLock; static SingleRandom() { random = new Random(); spinLock = new SpinLock(); } public static int Next() { bool gotLock = false; spinLock.Enter(ref gotLock); int rv = random.Next(); if(gotLock) spinLock.Exit(false); // ASSUMPTION not IA64, TODO what if ARM? return rv; } public static int Next(int min, int max) { bool gotLock = false; spinLock.Enter(ref gotLock); int rv = random.Next(min, max); if (gotLock) spinLock.Exit(false); // ASSUMPTION not IA64, TODO what if ARM? return rv; } public static double NextDouble() { bool gotLock = false; spinLock.Enter(ref gotLock); double rv = random.NextDouble(); if (gotLock) spinLock.Exit(false); // ASSUMPTION not IA64, TODO what if ARM? return rv; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T03:08:15.127", "Id": "59933", "Score": "3", "body": "Jon Skeet took care of `Random` and threading issues: http://msmvps.com/blogs/jon_skeet/archive/2009/11/04/revisiting-randomness.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T03:10:25.080", "Id": "59934", "Score": "0", "body": "@JesseC.Slicer Ah-ha! Well now I have a bit of a clue of what I want to be testing!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:00:00.763", "Id": "59939", "Score": "0", "body": "Hmm his creates a Random for every thread, there could be many threads calling few times so I am not sure I would want that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T09:22:23.423", "Id": "59985", "Score": "1", "body": "why not use a thread local Random..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T10:03:01.057", "Id": "59992", "Score": "2", "body": "A hundred times per second is not frequent. I benchmarked a simple `lock` based code, and it ran *forty million* times per second on an uncontended lock. With `ThreadStatic` it gets to *ninety million* per second per core." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T19:20:27.407", "Id": "60090", "Score": "0", "body": "No, I would say, since you don't have any error handling in your methods. If you are to use a SpinLock you should place it in a try catch finally block where you call spinLock.Exit(); in the finally block. Otherwise the key might end up with a faulty state. Apart from that I would say that this solution is overkill I would create a new random on each thread when needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T00:39:32.820", "Id": "60115", "Score": "0", "body": "@CodesInChaos agreed, I am just trying to teach myself lock-free techniques and thought this would be a good example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T00:47:00.023", "Id": "60116", "Score": "0", "body": "@Jocke good points, the Next(min, max) has the possibility of an exception, however the others I don't think that would be necessary." } ]
[ { "body": "<p>I'll be humbly honest, understanding exactly what <em>useMemoryBarrier</em> does is way, <strong>way</strong> beyond my current understanding of C#, multithreading and memory management, so I'll leave that part to other answerers.</p>\n\n<p>I'm not sure this test is valid, but I ran it several times and it always passed - I started with 10, then 100, then 1000, then 10000 (failed a couple times with 10K iterations) - the test starts consistently failing with 100000 iterations, so a couple 100 times/second shouldn't be much of a problem.</p>\n\n<pre><code>// arrange\nvar results = new ConcurrentBag&lt;int&gt;();\nvar iterations = 1000;\n\n// act\nParallel.For(0, iterations, o =&gt;\n{\n results.Add(SingleRandom.Next());\n});\n\n// assert\nAssert.AreEqual(iterations, results.GroupBy(e =&gt; e).Count());\n</code></pre>\n\n<p>I ran the same test with some <code>var rnd = new Random()</code> and 1000 iterations failed very, very often. Bottom line, looks pretty safe <em>to me</em>.</p>\n\n<p><strong>Couple nitpicks:</strong></p>\n\n<pre><code>private static Random random = new Random();\nprivate static SpinLock spinLock = new SpinLock();\n</code></pre>\n\n<p>Statically initializing these <code>static</code> fields eliminates the need for a <code>static</code> constructor, provided that you're going to be using that <code>SingleRandom</code> type at one point.</p>\n\n<pre><code>if (gotLock) spinLock.Exit(false); // ASSUMPTION not IA64, TODO what if ARM?\n</code></pre>\n\n<p>I find this <code>Exit(false)</code> call is better off as a one-liner together with the <code>gotLock</code> condition. The alternative would be this:</p>\n\n<pre><code>if (gotLock)\n{\n spinLock.Exit(false);\n}\n</code></pre>\n\n<p>Building your <code>if</code> block on more than a single line without those <code>{}</code> curly braces isn't a recommended practice - everything that <em>defines a scope</em>, should be enclosed with curly braces; this isn't much more typing either:</p>\n\n<pre><code>if (gotLock) { spinLock.Exit(false); }\n</code></pre>\n\n\n\n<pre><code>var gotLock = false;\nvar rv = random.Next();\n</code></pre>\n\n<p>Implicit typing, IMHO, makes more room for the <em>significant</em> code.</p>\n\n<p>That's about all I can say here - I'll only add that I would have named <code>rv</code> as <code>result</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T03:58:28.947", "Id": "59937", "Score": "0", "body": "I wouldn't expect any errors ever - does ConcurrentBag<int> throw an error if you add value equal to one already in the bag?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:03:03.580", "Id": "59940", "Score": "0", "body": "No, it's essentially a concurrent, unordered collection of `T`. I checked for existing values with the linq `GroupBy` in the assertion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:03:08.980", "Id": "59941", "Score": "0", "body": "No it doesn't of course Random could eventually return the same number it has before - that would be why you assert failed more often the higher the iterations" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:04:16.143", "Id": "59942", "Score": "0", "body": "And the reason it failed when you create new ones is it is seeded with the current time - which will be the same if you create new ones right after one another - so they will return the same sequence" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:05:07.357", "Id": "59943", "Score": "1", "body": "My guts are telling me this test is utter BS - `random != unique` anyway... sorry I can't be more conclusive :/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:09:06.537", "Id": "59944", "Score": "0", "body": "@markmnl does the rest make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T04:18:27.827", "Id": "59945", "Score": "0", "body": "sure, though I dont't agree :) I prefer using a ctor - that way they only instantiated if ever actually used and I prefer to always put if condition blocks on a newline and if it is only one line I prefer not to have braces (but that is all a matter of preference)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:51:01.297", "Id": "59959", "Score": "0", "body": "@retailcoder: Yes your test as it stands is BS :). Lose the `GroupBy`." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T03:08:38.163", "Id": "36543", "ParentId": "36542", "Score": "0" } }, { "body": "<ol>\n<li><code>SingleRandom</code> is a really bad name for your class. <code>Single</code> means <code>float</code> in C# context, so your name implies that its a <code>Random</code> which generates <code>float</code> values, which is not true. <code>ThreadSafeRandom</code> or <code>SynchronizedRandom</code> are the examples of better naming.</li>\n<li><p>Are you sure that using <code>SpinLock</code> in you case improves performance in any way? Somehow i think that a simple <code>lock</code> will be just as fast, while being a lot more readable.</p>\n\n<pre><code>public static int Next()\n{\n lock (random)\n {\n return random.Next();\n }\n}\n</code></pre></li>\n<li><p>I am not sure that making your class static is the best way to go. In my experience in such cases its almost always better to make a non-static class and then to either inject its instance or initialize some <code>static readonly</code> field. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T08:07:23.803", "Id": "59974", "Score": "0", "body": "1. OK, 2. Not yet - and given the lock will mostly be uncontended I think you are right, 3. sounds like more work to me!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T08:40:52.263", "Id": "59978", "Score": "0", "body": "@markmnl, 3. not nessesary, its just one line of extra code, which might save you a headache in a long run. The main disadvantage of static class is that it _forces_ you to use single `Random` instance. Imagine that some other developer (or you yourself) decides to reuse your class in his segment of application. What will happen then? You will have his code slowing down your code, simply because you will share the same instance (and therefore the same `lock`). Non-static class does not have this problem - you will have different instances, unique to your contexts, but not globally." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T09:00:54.607", "Id": "59980", "Score": "0", "body": "in this case I offer nothing beyond Random, they can use their own Random, nor do I intend to additional functionality to my SingleRandom not in Random - it is a singleton after all" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T10:32:31.430", "Id": "59996", "Score": "0", "body": "@markmnl, it is a singleton, true, but only because you designed it that way. It does not _have_ to be. \"They can use their own random\" is not how a developer should think (especisally since it is not \"just Random\", it is a synchronized wrapper). A developer should always identify re-usable logic and write code accordingly. Static class is not reusable, period. Its just my opinion though, you ofcause is free to do as you see fit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T06:53:55.777", "Id": "60135", "Score": "0", "body": "This is going a bit off topic but re-use is not always desired. In this case I would rather have encapsulation and security as I don't want to allow another developer to have their own version purporting to be SingleRandom." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T05:06:59.303", "Id": "36546", "ParentId": "36542", "Score": "6" } }, { "body": "<p>First, to re-iterate a point made in another answer:</p>\n\n<p>Making a helper class which has internal state <code>static</code> is a bad idea. You lose a lot of flexibility, re-usability and increase testing pain and gain nothing from it.</p>\n\n<p>The major problem with a static class is: You can't easily mock it for unit testing. If you want to unit test something which uses random numbers it's very helpful to be able to feed it a known sequence of random numbers but with a static class you start adding code which is just used for testing and your tests become brittle if you forget to reset the global state to a known point. Calling <code>new SingleRandom()</code> is hardly much work - if you consider that a problem then maybe an OO language is the wrong choice.</p>\n\n<p>A static class with a state is effectively a singleton which is an anti-pattern. As such your question should not be \"what are convincing reason to not use it\" but rather \"what are convincing reasons to use it\". </p>\n\n<p>My other major point is:</p>\n\n<p>My very first thought when reading this was: Classic case of premature optimization.</p>\n\n<ul>\n<li>Heave you measured that generating the random numbers is the bottle neck?</li>\n<li>Have you measured that you need a spin lock?</li>\n</ul>\n\n<p>I changed your implementation to use standard .NET locking:</p>\n\n<pre><code>public static class StandardLockSingleRandom\n{\n private static Random random = new Random();\n private static object _lock = new object();\n\n public static int Next()\n {\n lock (_lock)\n {\n return random.Next();\n }\n }\n\n public static int Next(int min, int max)\n {\n lock (_lock)\n {\n return random.Next(min, max);\n }\n }\n\n public static double NextDouble()\n {\n lock (_lock)\n {\n return random.NextDouble();\n }\n }\n}\n</code></pre>\n\n<p>This implementation has 30% less code than yours and the code which is there is considerably less complex. So your spin lock better stack up some nice performance.</p>\n\n<p>Let's write some quick benchmark:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n const int numRandomCalls = 100000;\n const int numTestLoops = 100;\n\n for (int p = 1; p &lt;= 16; p &lt;&lt;= 1)\n {\n Console.WriteLine(\"=========================================================================================================\");\n Console.WriteLine(\"Parallelism = {0}, Count of random numbers per iteration {1}\", p, numRandomCalls);\n var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = p };\n RunAndMeasure(\"Spin Locked\", numTestLoops, () =&gt; { Parallel.For(0, numRandomCalls, parallelOptions, (idx) =&gt; { SingleRandom.Next(); }); });\n RunAndMeasure(\"Standard Locked\", numTestLoops, () =&gt; { Parallel.For(0, numRandomCalls, parallelOptions, (idx) =&gt; { StandardLockSingleRandom.Next(); }); });\n }\n\n }\n\n private static void RunAndMeasure(string name, int numLoops, Action act)\n {\n var stopWatch = new Stopwatch();\n stopWatch.Start();\n for (int i = 0; i &lt; numLoops; ++i)\n {\n act();\n }\n stopWatch.Stop();\n var total = stopWatch.Elapsed.TotalMilliseconds;\n var perIter = total / numLoops;\n Console.WriteLine(\"{0}: # Test Loops = {1}, total time {2:.000}ms, {3:.000}ms per iteration\", name, numLoops, total, perIter);\n }\n}\n</code></pre>\n\n<p>Basically:</p>\n\n<ul>\n<li>Obtain 100,000 random numbers at varying degree of parallelism</li>\n<li>Run each test 100 times and build the average</li>\n</ul>\n\n<p>On my machine which is an i7 with hyperthreading enabled (so going much beyond 8 in parallelism is probably not going to change much) results in this output:</p>\n\n<pre><code>=========================================================================================\nParallelism = 1, Count of random numbers per iteration 100000\nSpin Locked: # Test Loops = 100, total time 996.986ms, 9.970ms per iteration\nStandard Locked: # Test Loops = 100, total time 482.924ms, 4.829ms per iteration\n=========================================================================================\nParallelism = 2, Count of random numbers per iteration 100000\nSpin Locked: # Test Loops = 100, total time 1144.200ms, 11.442ms per iteration\nStandard Locked: # Test Loops = 100, total time 560.377ms, 5.604ms per iteration\n=========================================================================================\nParallelism = 4, Count of random numbers per iteration 100000\nSpin Locked: # Test Loops = 100, total time 1253.103ms, 12.531ms per iteration\nStandard Locked: # Test Loops = 100, total time 601.836ms, 6.018ms per iteration\n=========================================================================================\nParallelism = 8, Count of random numbers per iteration 100000\nSpin Locked: # Test Loops = 100, total time 1592.358ms, 15.924ms per iteration\nStandard Locked: # Test Loops = 100, total time 802.485ms, 8.025ms per iteration\n=========================================================================================\nParallelism = 16, Count of random numbers per iteration 100000\nSpin Locked: # Test Loops = 100, total time 1603.059ms, 16.031ms per iteration\nStandard Locked: # Test Loops = 100, total time 811.937ms, 8.119ms per iteration\n</code></pre>\n\n<p>So your spin lock implementation is considerably more complex and it takes twice the time.</p>\n\n<p>What do we learn: Do not optimize things before you have measured them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T08:58:13.627", "Id": "59979", "Score": "0", "body": "For 1 million iterations the spin lock ran 100ms faster on mine (did you build with optimizations?). Nonetheless I agree it would be better to use lock. However I disagree with your first remark (or rather do not understand it) - it is dead easy to unit test a static class, and I have the added flexibility of calling it from anywhere in app without any initialization.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T09:28:01.517", "Id": "59986", "Score": "0", "body": "@markmnl: I built it in Release mode VS2010. Calling random 1,000,000 times rather than 100,000 times doesn't change anything for me except all tests take about 10x longer. Updated my answer regarding static." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T10:14:28.393", "Id": "75874", "Score": "0", "body": "Perhaps the difference in our tests comes from you do nothing with the results of call to Random so the operation has been fully optimised away?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T18:41:39.410", "Id": "75922", "Score": "0", "body": "@markmnl I seriously doubt that this would be an allowed optimization" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T08:45:41.900", "Id": "36555", "ParentId": "36542", "Score": "4" } }, { "body": "<p>since you want thread safety you can just use a <code>ThreadLocal&lt;Random&gt;</code> </p>\n\n<pre><code>public static class SingleRandom\n{\n private static ThreadLocal&lt;Random&gt; random;\n\n static SingleRandom()\n {\n random = new ThreadLocal&lt;Random&gt;(() =&gt;\n {\n return new Random();\n });\n }\n\n public static int Next()\n {\n int rv = random.Value.Next();\n return rv;\n }\n\n public static int Next(int min, int max)\n {\n int rv = random.Value.Next(min, max);\n return rv;\n }\n\n public static double NextDouble()\n {\n double rv = random.Value.NextDouble();\n return rv;\n }\n}\n</code></pre>\n\n<p>you can also explicitly define the seed for each Random by passing a Func to the ThreadLocal constructor</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T10:14:42.010", "Id": "59994", "Score": "0", "body": "1) You forgot the constructor call, your code will initialize `random.Value` to `null` 2) You could use a field initializer to simplify your code 3) The `[ThreadStatic]` is faster than `ThreadLocal<T>`. (factor 3 in a quick test)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T10:33:14.157", "Id": "59997", "Score": "1", "body": "4) Explicit seeding is essential for this code. Your current code will fail if you spin up multiple threads at the same time (within a few milliseconds). All those threads will emit the same sequence." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:52:27.610", "Id": "60087", "Score": "0", "body": "@CodesInChaos `ThreadStatic` might be faster, but it means you have to deal with initialization yourself. (And it forces your to stay `static`, which other answers argued against.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T09:32:41.200", "Id": "36559", "ParentId": "36542", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T01:41:37.573", "Id": "36542", "Score": "6", "Tags": [ "c#", "thread-safety", "random", "singleton", "lock-free" ], "Title": "Singleton SpinLock: Making Random Thread-Safe" }
36542
<p>I have an array where each element is either one less or one greater than the preceding element \$\{x_i = x_{i-1} \pm 1\}\$. I wish to find an element in it in less than \$O(n)\$ time. I've implemented it like this:</p> <pre><code>public int searchArray(int[] arr, int i, int elem) { if (i &gt; arr.length - 1 || i &lt; 0) { return -1; } if (arr[i] == elem) { return i; } else { int diff = Math.abs(elem - arr[i]); int index = searchArray(arr, i + diff, elem); if (index == -1) { index = searchArray(arr, i - diff, elem); if (index == -1) { return -1; } } return index; } } </code></pre> <p>And calling it like:</p> <pre><code>int[] arr = {2, 1, 2, 3, 4, 3, 2, 3, 4, 5, 6, 5, 4, 3, 4}; int index = searchArray(arr, 0, 3); </code></pre> <p>It is working fine, but can it be improved? Specifically, is there a way to do it iteratively? And is the current algorithm less than \$O(n)\$. I guess it is, but I'm not sure.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:58:38.127", "Id": "59961", "Score": "0", "body": "Does `searchArray({2, 1, 2}, 0, 4)` terminate? `diff` will be `2` which calls again with `i = 2`, then `i = 0`, then `i = 2`, ad infinitum. If that's the case, you'll need to keep track of visited indices to avoid infinite recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:04:20.423", "Id": "59962", "Score": "0", "body": "@DavidHarkness Oh Dear! Never thought of that. Ok, I can keep track of visited indices. Seems like the only workaround." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:06:30.280", "Id": "59963", "Score": "1", "body": "@DavidHarkness To my surprise, it didn't go into infinite recursion with that. In fact, the iterative approach broke. OutOfMemory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:06:51.987", "Id": "59964", "Score": "0", "body": "If you don't care about space (small input arrays), a simple `boolean` array with the same size is sufficient and managing it is constant time (ignoring the O(n) allocation time)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:07:45.867", "Id": "59965", "Score": "2", "body": "That's because the stack outgrew the available memory. If memory had been infinite, the method would never terminate. I don't see how the recursive method could work, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:09:09.760", "Id": "59966", "Score": "0", "body": "@DavidHarkness It is working, and returning `-1` :( I'm trying to trace the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T08:29:35.413", "Id": "59977", "Score": "5", "body": "When you say \"less than O(n)\", do you mean that a worst case O(n) is unacceptable, or that O(n - 1) is fine despite being equivalent to O(n) in complexity because it's less than O(n)? I would assume the former, but it doesn't seem possible to search `{1, 2, 1, 2, ...}` for `3` without comparing all but one element. I can see reducing the *average* running time by splitting up the array into ascending and descending sequences, but that won't get around the worst case for a non-match in an array of alternating elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T12:18:35.773", "Id": "60003", "Score": "0", "body": "@sqykly Actually this is an interview questions. And it was mentioned to do this in less than O(n). May be it actually meant not more than O(n). In that case, I think `O(n)` would do. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:56:40.273", "Id": "60026", "Score": "1", "body": "I'm wondering whether the phrase \"less than O(n)\" even has a well-defined meaning. `O(n)` already implies an upper bound on the resources an algorithm takes. Remember that `O(n/2)` is not less that `O(n)`. If the question asked for an `O(log(n))` algorithm, that would be a meaningful question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:16:33.113", "Id": "60078", "Score": "1", "body": "@LarsH Unfortunately in the *real* world, outside of complexity theorists, people use `O(n/2)` to mean that the algorithm is twice as fast as the obvious `O(n)` solution. We really need a way of talking about the speed of algorithms on more detailed scales(and that everyone would universally understand), so that people meaning well don't have to say nonsense things like `O(n/2)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:26:20.443", "Id": "60098", "Score": "1", "body": "@Cruncher Doing that in a meaningful way is quite hard. You can for example count the exact number of comparisons two sorting algorithm make and compare them based on that. But it's not really clear whether real performance will actually depend on those numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T10:24:17.063", "Id": "60141", "Score": "2", "body": "It seems there is some contention about O(n) vs O(n/2). Back when computers were slow and assembly programmers were cool, the phrase \"never ignore k\" was heard often. That comes to mind as I comment: *complexity != running time*. Run time is k times O for relevantly large n. \"O(n/2)\" is at worst gibberish, at best shorthand for \"O(n) with k = 1/2 of some reference algorithm\". O(n/2) *complexity* is *not* better than O(n). k(n/2) *run-time* *is* better than k(n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T14:47:15.780", "Id": "60168", "Score": "0", "body": "@Cruncher, I think you're right about people's usage, though I reserve judgment about the extent of the \"real\" world. But I would expect interview questions to be held to a bit higher standard. On the other hand, part of being successful on the job is understanding what people mean even if it's not what they said, so maybe the interview question is good in examining that skill." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T10:06:10.453", "Id": "60712", "Score": "0", "body": "@Cruncher: Why would someone who is not a complexity theorist use big-Oh notation? Someone who uses big-Oh notation is practically the *definition* of a complexity theorist. (Either that or a BS-merchant :) )" } ]
[ { "body": "<p>Here's some generic advice first:</p>\n\n<ul>\n<li><p>Avoid single-letter parameter names. For small loops <code>i</code> is fine, but it shouldn't leak into method signatures--especially when <code>index</code> is only four more letters.</p></li>\n<li><p>Be consistent with <code>if-else</code>. You have two <code>if</code> blocks that both <em>return from the method</em>, either use <code>else</code> with both or neither. Otherwise it appears at a quick glance that one doesn't exit.</p>\n\n<pre><code>if (x)\n return foo;\nelse if (y)\n return bar;\nelse\n baz\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (x)\n return foo;\nif (y)\n return bar;\nbaz\n</code></pre></li>\n<li><p><code>if (index == -1) return -1;</code> is redundant since it's immediately followed by <code>return index;</code>.</p></li>\n<li><p><code>Math.abs</code> is unnecessary since you first add and then subtract <code>diff</code>. The order doesn't matter here.</p></li>\n<li><p>I would reverse the <code>i</code> and <code>elem</code> parameters and add an overloaded form that omits <code>i</code> and simply calls the other with <code>i = 0</code>. This provides a nicer API for callers. The three-parameter version could also be private to the class containing both if only the latter form is needed externally.</p></li>\n</ul>\n\n<p>As to your question about the time complexity, my gut says that it is probably possible for the worst case to cause an infinite loop, but I haven't delved too deep in the actual algorithm yet.</p>\n\n<p>To rewrite this iteratively you'll need to use a stack to allow backtracking since you sometimes need to branch both directions. Here's a quick stab at it in psuedocode:</p>\n\n<pre><code>search(int[] arr, int find)\n return search(arr, find, 0)\n\nsearch(int[] arr, int find, int index)\n stack = [-1]\n while (index != -1)\n if (0 &lt;= index &amp;&amp; index &lt; arr.length)\n elem = arr[index]\n if (elem == find)\n return index\n else\n diff = find - elem\n stack.push(index + diff)\n stack.push(index - diff)\n index = stack.pop();\n return -1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:25:04.540", "Id": "59952", "Score": "0", "body": "Hi David. Thanks for those valuable tips. I've done the modification in my original code as per the suggestion. But the iterative approach is not working. It is always returning -1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:27:18.960", "Id": "59953", "Score": "0", "body": "Ok, your code will fail if the diff comes out to be -1. That is what happening currenly. If I search for `3`, and first element is `2`, it breaks. I'm trying to fix it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:29:05.560", "Id": "59954", "Score": "0", "body": "Fixed it. No need to push anything in the stack before loop. And I changed outer while loop to `while (true);`, and removed the return statement after it. Thanks you so much. If you have better way to solve this, except `while (true)`, please do share." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:36:46.340", "Id": "59955", "Score": "0", "body": "@user3011937 The initial `-1` value in the stack is to indicate when we run out of indexes to check and thus the element was not found. You could do the same thing with `stack.isEmpty` checks, but I found using the poison pill value simpler. Note that I used indentation instead of braces since it's psuedocode: the two push calls must happen only in the `else` block with `diff`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:39:44.753", "Id": "59956", "Score": "0", "body": "@DavidHarkness: Your argumentation about the `if-else` is quite weird. If an `else` case doesn't make sense then, well don't use an `else` case. Saying you should use `else` with all if conditions just because you used it for one is not really sensible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:40:09.930", "Id": "59957", "Score": "0", "body": "@David Yes I've done two pushes in else only. The problem is, when I search for `3`, and first index element is `2`, then diff would be `1`, then we push `index + diff = 1`, and `index - diff = -1`. So, outside `else`, the `pop()` will return `-1`, and then the `while` loop exits, and returns `-1`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T06:52:59.917", "Id": "59960", "Score": "1", "body": "@ChrisWue I did a poor job of explaining myself. Hopefully my edit to the second bullet is clearer." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T05:58:23.970", "Id": "36549", "ParentId": "36547", "Score": "13" } }, { "body": "<p>The function should be</p>\n\n<pre><code>public static int searchArray(int[] array, int value) {\n // Call private static int searchArray(int[] array, int index, int value)\n return searchArray(array, 0, value);\n}\n</code></pre>\n\n<p>… because if the caller can pick any starting index, the result could be wrong. (Consider <code>searchArray(arr, 12, 6)</code> in your example.) The functions should be <code>static</code> since they rely on no instance variables.</p>\n\n<p>I believe that the worst case would be at least O(<em>n</em>), as in the following example:</p>\n\n<pre><code>int[] arr = {1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 3};\nint index = searchArray(arr, 0, 3);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:18:20.603", "Id": "59967", "Score": "0", "body": "do you have any better way? So that worst case is less than `O(n)`? What if we start from middle? Or some random location?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:25:19.283", "Id": "59968", "Score": "0", "body": "Starting from the middle would cut the time in half, at best. O(n / 4) is still O(n). Same argument goes for starting anywhere else." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T07:08:34.917", "Id": "36553", "ParentId": "36547", "Score": "5" } }, { "body": "<p>The problem is in \\$O(n)\\$. Consider the case that 200_success describes. </p>\n\n<p>You have a sequence of alternating 1 and 2's where a single 1 is replaced by a 3. </p>\n\n<p>When you are asked to search for a 3 you know, after inspecting the first element, that it will have an even index. But if every odd index holds a 2 then any even index can hold a 3, so you can not guarantee that the 3 is not in the last index you search. This means that you will have to look in \\$O(\\dfrac{n}{2})\\$ places. \\$O(\\dfrac{n}{2})\\$ = \\$O(n)\\$, so the problem is \\$O(n)\\$. </p>\n\n<p>No correct algorithm can have better worst time performance than this.</p>\n\n<p>A more interesting question is what happens if you know that no number occurs more than some fixed upper bound.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:04:35.800", "Id": "60029", "Score": "2", "body": "This should have been the accepted answer, as it's the only one so far that deals correctly with the question of finding a \"less than O(n)\" algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:49:46.480", "Id": "60034", "Score": "3", "body": "@LarsH Well OP also asks how his algorithm can be improved. And from context it's fair to assume that this is the most important part of the question. So I don't feel too bad about which answer was accepted. Esp since this is codereview rather than cstheory." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T10:04:56.850", "Id": "36560", "ParentId": "36547", "Score": "34" } }, { "body": "<p>You never need to look backwards if you start at 0.</p>\n\n<p>Proof by induction over algorithm steps j:</p>\n\n<p>For j = 0, i(j) = 0, you cannot go backwards.</p>\n\n<p>For j > 1, there are two cases: First one, we found our number. Second one, there is a difference <code>diff(j) = abs(elem - array[i(j)])</code>. Then no number in <code>array[i(j),i(j)+diff)</code> can contain elem. By induction hypothesis, no element in <code>array[i(j-1),i(j)=i(j-1)+diff(j-1))</code> contains that number either. So the next possible index for i is <code>i(j)+diff(j) (= i(j+1))</code></p>\n\n<p>But that algorithm really is in O(n) as Taemyr already answered.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T12:40:01.910", "Id": "60008", "Score": "0", "body": "Got it. Very nice. Thank you so much for induction :) Let me clear myself. Just going forward will get me the element if there is. And if there are more, I'll automatically get the very first element right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T23:19:52.903", "Id": "60110", "Score": "0", "body": "@user3011937 Not only that, but because you're always going in one direction you eliminate the possibility of an infinite loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T10:28:57.557", "Id": "36562", "ParentId": "36547", "Score": "15" } }, { "body": "<p>While other answers make good points, I have to wonder why you are using recursion. This is such a simple problem to solve with a <code>for</code> loop.</p>\n\n<p>I assume that you are not supposed to start from any index other than index 0, so consider the following routine:</p>\n\n<pre><code>public int searchArray(int[] arr, int elem) {\n\n for (int i = 0; i &lt; arr.length; ) {\n if (arr[i] == elem) {\n return i;\n }\n i += Math.abs(elem - arr[i]);\n }\n return -1;\n}\n</code></pre>\n\n<p>(If you need to start the search part-way through the array then you can add the <code>offset</code> input parameter again and start <code>i</code> from that).</p>\n\n<p>The bottom line is that recursion is overkill, this system is \\$O(n)\\$, but the cost of each cycle is less than the same thing using recursion.</p>\n\n<p>I am not aware of any way to solve the given problem with a system of better than \\$O(n)\\$ complexity.</p>\n\n<hr>\n\n<p><strong>Discussion on complexity - why this is \\$O(n)\\$</strong></p>\n\n<p>This answer has generated a lot of discussion about complexity, that this method only ever scans, at most, half the members of the input array, and thus it should be complexity \\$O \\left( \\frac{n}{2} \\right )\\$ instead of \\$O(n)\\$. The argument given is something like:</p>\n\n<blockquote>\n <p>Consider the worst-case data <code>1,2,1,2,1,2,1,2,1,2,1,2</code> and the search term <code>3</code>. For this situation the method will start at <code>data[0]</code>, and then skip to <code>data[2]</code>, then <code>data[4]</code>, and so on. It will never inspect <code>data[1]</code>, and other odd-indexed data points. If the search term is even more 'different' than the actual data (e.g. <code>100</code>) then the method will do only one comparison at <code>data[0]</code> and will then return 'not found' <code>-1</code>.</p>\n</blockquote>\n\n<p>This is an interesting observation, that the method only ever needs to scan half the data <strong>at most</strong>. This is especially interesting considering a 'naive' method which just scans the data one-member-at-a-time and returns when it finds the value. That 'naive' method most certainly has \\$ O\\left(n\\right) \\$ 'performance' and complexity, and the 'skip-method' will be more than twice as fast.</p>\n\n<p>The important thing to note though, is how the algorithms scale <strong>relative to the amount of data</strong>, not relative to each other!</p>\n\n<p>So, consider a hypothetical set of worst-case data <code>1,2,1,2,1,2,....</code> and the search-term <code>3</code>. This hypothetical happens to be searched in 4 milliseconds by the skip-method, and in 8 milliseconds by the naive-method. Now we double the amount of data, what happens? The processing time for <strong>both</strong> methods will double!</p>\n\n<p>In both cases, the performance of the algorithms will double for each doubling of the data volume. This is what makes <strong>both</strong> algorithms \\$ O(n) \\$ complexity. <a href=\"http://en.wikipedia.org/wiki/Big_O_notation\" rel=\"noreferrer\">From Wikipedia</a>:</p>\n\n<blockquote>\n <p>In computer science, big O notation is used to classify algorithms by how they respond (e.g., in their processing time or working space requirements) to changes in input size.</p>\n</blockquote>\n\n<p>Reversing the argument, by suggesting the skip-method has \\$O \\left( \\frac{n}{2} \\right) \\$ complexity, I would then expect that, if I double the data, the execution time would only increase by a half, or 50%. This is 'obviously' not true for the skip-method (nor the naive-method).</p>\n\n<p>Both methods have \\$O(n)\\$ complexity because they both scale the same way with increasing volumes of data.</p>\n\n<p>But, just because they scale the same way, does not mean that one method is not better than the other... <strong>obviously</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T12:16:57.577", "Id": "60002", "Score": "0", "body": "When you do `i += Math.abs(elem - arr[i]);`, won't the index only increase and not decrease? While in the problem, the value before the index `i` might also be less than or greater than the one at `i`. It is not certain that the elements in array are in increasing order, which is what your solution seem to consider. Correct me if I'm taking it wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T12:23:08.923", "Id": "60004", "Score": "5", "body": "@user3011937 The solution in my example will always find the **first** matching value **from** the start position (which I have set to 0 but it can be easily changed by adding a parameter). Because of the rules for the data (index[n] = index[n - 1] +/- 1, you can always move forward and never have to move backward. I think you should do some debugging of the various solutions, or work them out on paper.... really, this works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T12:33:59.333", "Id": "60005", "Score": "0", "body": "@rofl. Oh great! I didn't look into that aspect. This is really enlightening. Thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T12:36:02.250", "Id": "60006", "Score": "0", "body": "@user3011937 kutschkem pointed out that you don't need to go backwards...: http://codereview.stackexchange.com/a/36562/31503 ... I just pointed out that the for-loop is much easier than recursion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:57:40.470", "Id": "60016", "Score": "14", "body": "\"A good programmer knows how to use recursion. A great programmer knows when not to.\" --Anonymous" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:58:43.673", "Id": "60027", "Score": "4", "body": "This is a fine algorithm, but what makes anyone think that it takes \"less than O(n)\" time? Sure it doesn't require examining all n elements in the array, but saying it takes less than O(n) time implies that as n grows, the time to complete the algorithm grows more slowly than n. Is there any evidence of that? (Let's say in the average case, let alone the worst case.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:05:31.467", "Id": "60030", "Score": "0", "body": "@LarsH Of course... I removed the 'worst-case' which implied that the complexity was somehow not linnearly related to n." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:07:38.020", "Id": "60031", "Score": "1", "body": "OK... I assumed that since an answer was posted, it claimed to answer the title question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:17:07.877", "Id": "60060", "Score": "0", "body": "You could modify that `if` statement slightly to `if (arr[i] == elem) {\n idxes.add(i++);\n }`\nThis should save all the indexes where the searched value occurs (assuming `idxes` is an `ArrayList`). You would also have to put the `Math.abs` in an `else` clause." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:29:11.300", "Id": "60099", "Score": "0", "body": "“the complexity of each O” That doesn't make much sense to me. Do you mean something like “the constant factor”?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T03:44:41.183", "Id": "60123", "Score": "0", "body": "This answer takes O(n/2) time and will never reach O(n) or above. Consider example worst case: n=10, list={3,4,3,4,3,4,3,4,3,2}, e=2. The index will jump 2 indices until end of list. Skipping 1 index would result to either the next element is 2-unit far or exactly the element being searched." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T03:45:32.913", "Id": "60124", "Score": "4", "body": "@xuwicha - indeed, but *O(n/2)* is still *O(n)*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T03:58:29.420", "Id": "60125", "Score": "0", "body": "@rofl, I think O(n) is not enough to describe the speed of an algorithm. Halving the execution time is a very large improvement. Saying to a normal programmer to write an algorithm with O(n) time would by default mean implementing an algorithm that would check ALL n elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T03:59:43.087", "Id": "60126", "Score": "5", "body": "@xuwicha - actually, if you double the amount of data the algorithm will take twice as long, hence *O(n)* ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T04:17:11.263", "Id": "60127", "Score": "0", "body": "@rofl, So I guess that's what O(f(n)) means. I can't think of any algorithm faster than this answer. But in terms of improving an algorithm, I prefer more specific f(n). It might be there will never be algorithms faster than O(n) time algorithms for this problem. But among those O(n) time algorithms there will be the best and it need to stand-out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:38:10.270", "Id": "60178", "Score": "0", "body": "@xuwicha The advantage of big-O notation is that it is largely independent on architechture and implementation details. This imidiately implies that it doesn't tell us the full story about which implementation is fastest, but it allows a comparison that are consistent. Other comparisons quickly bogs down in details, for example rofl's implementation will be slower in the worst case than a naive implementation. Because the function calls are slow in java. Making twice as many comparisons would be an easy tradeoff. Of course, in the average case the situation would tend to be different." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:28:18.960", "Id": "60191", "Score": "0", "body": "The big-O performance is even worse when the input array is malformed (a.k.a. worserest-case!). For example, searching for 2 in {1,3,1,3,1,3,1,3,1,3,1,3}." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:45:04.690", "Id": "60196", "Score": "1", "body": "@Silveri that would be true, but the 'rules' for this problem stipulate that `data[n] == data[n-1] +/- 1`, so that input data would be 'illegal' ... `I've an array where each element is either one less or one greater than the preceding element`" } ], "meta_data": { "CommentCount": "18", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T11:35:03.350", "Id": "36570", "ParentId": "36547", "Score": "59" } }, { "body": "<p>Is there a restriction that says the array has to (or can't be) in a specific order? If you keep a sorted array you could perform a binary search which would run in O(log(n)). There are both recursive and iterative implementation. Of course the drawback is that the array has to be sorted but the pro is that you can search through millions of records in less than 10 iterations/recursions.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"nofollow\">From Wikipedia's article on the binary search algorithm:</a></p>\n\n<pre><code>int binary_search(int A[], int key, int imin, int imax)\n{\n // test if array is empty\n if (imax &lt; imin)\n // set is empty, so return value showing not found\n return KEY_NOT_FOUND;\n else\n {\n // calculate midpoint to cut set in half\n int imid = midpoint(imin, imax);\n\n // three-way comparison\n if (A[imid] &gt; key)\n // key is in lower subset\n return binary_search(A, key, imin, imid-1);\n else if (A[imid] &lt; key)\n // key is in upper subset\n return binary_search(A, key, imid+1, imax);\n else\n // key has been found\n return imid;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:54:18.250", "Id": "60049", "Score": "0", "body": "Having a pre-ordered array would not help with the OP's problem (in fact it would break it...). The original problem requires the data to be in a predefined (unordered) sequence" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:04:11.077", "Id": "60071", "Score": "0", "body": "@rolfl With the OP's requirement an ordered list is not impossible, but certainly not assumable. This is just addressing that you said an ordered array would break the OP's problem, when it wouldn't necessarily." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:17:00.243", "Id": "60079", "Score": "1", "body": "@Cruncher - of course, and you are right to point out the inconsistency in my statement, but, forcing an order woud certainly break the OP's requirement." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:49:25.830", "Id": "36581", "ParentId": "36547", "Score": "-3" } }, { "body": "<pre><code>public static int search(int[] array, int start, int end, int target)\n{\n\n if(array[start] == target)return start;\n if(array[end] == target)return end;\n if(Math.abs(array[start]-target) + Math.abs(array[end]-target) &gt;= end-start+1)\n return -1;\n\n\n int middle = (start+end) / 2;\n\n int val = search(array, start, middle, target);\n if(val != -1)return val;\n\n val = search(array, middle+1, end, target);\n if(val != -1)return val;\n\n return -1;\n}\n</code></pre>\n\n<p>This is what I came up with. It actually splits the list down the middle. After each split it checks if it's possible for the target to be in this array. <code>Math.abs(array[start]-target) + Math.abs(array[end]-target) &gt;= end-start+1</code> covers that(it uses the fact that you have to get from the first number to target, then back down to the last number in the array). If it is possible, we continue splitting on that until the target is the beginning or end of a range. </p>\n\n<p>For an example of how this cuts, consider an array starting and ending in 1, and it's only length 5. You are asked to find 4 in it. You know this is impossible, since you need to spend 3 slots getting to 4, and then 3 back down to one. This means the length needs to be at least 7. So we can return -1 immediately.</p>\n\n<p>This does actually even help a little bit in the case of 12121212121212.....321212 because you often get sublists of <code>121</code> which can't have a 3. </p>\n\n<p>That being said. It still looks O(n) on worst case to me. Though I wouldn't be surprised if this has a sub-linear average case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:14:51.607", "Id": "60059", "Score": "0", "body": "This is a good suggestion... the OP's question did not specify whether the result had to be the 'first' index. Your solution would give O(log(n)) if the question is whether to get **any** hit.... But, even then, it could, with the right depth-first-approach work well. The best-case for a simple loop is going to be faster, but your worst case would be much better than the simple-loop worst case" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:27:48.653", "Id": "60063", "Score": "0", "body": "Actually, I have worked through your solution, I think the worst case will be slower than the worst-case for the simple-loop option. for the data `1,2,1,2,1,2,1,2,1,2,1,2,1,2,3,2,1` it would do as many, operations as a simple loop, and carries the recursion overhead. Your solution is very similar in performance to the loop, which also 'skips' blocks where the value is impossible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:37:43.617", "Id": "60066", "Score": "0", "body": "@rolfl This solution does actually find the first index. Since I recurse through the first half first. I only look at the second half when the first half returns not found. However, yes it does still have a bad worst case. I just thought I'd present a slightly different way of looking at the problem :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T21:04:20.487", "Id": "60100", "Score": "0", "body": "I have been stewing through this solution of yours, and it has me intrigued. But, in my (almost) final analysis, the iterative solution will always find the **first** matching solution before the recursive solution, and it will always require fewer comparisons. Despite my initial though that your solution has a *log(n)* complexity, I am now, surprisingly, convinced it is also plain `O(n)`. This only holds true if the goal is to return the **first** match." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T21:20:06.253", "Id": "60101", "Score": "0", "body": "@rolfl I'm glad that I've intrigued you xD. It's probably provable actually that `O(n)` is the optimal worst case. I pretty much assumed that from the beginning. What I'm more interested is average case, which I am terrible at analysing(not to mention how difficult this solution is to analyse). Do you think that can hit `log(n)` complexity on average?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T21:46:12.203", "Id": "60105", "Score": "0", "body": "No, never. Unlike things like Binary Search, your algorithm **does not discard** half the data, it just saves it to come back to later. Splitting the data in half only makes it `O(log(n))` if you can save having to process what you threw out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T21:52:13.877", "Id": "60106", "Score": "0", "body": "@rolfl The idea is that there is some probability that I can discard half of the data. It depends on if that probability is high enough that would determine this on average." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T21:53:30.760", "Id": "60107", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11800/discussion-between-cruncher-and-rolfl)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T09:23:44.267", "Id": "60140", "Score": "0", "body": "You can make this a little bit better if you add the difference to start / subtract it from end. As this reduces your problem size, it should get you to the end a little quicker." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T14:10:04.927", "Id": "60161", "Score": "0", "body": "@kutschkem Can you elaborate on this enhancement a little bit? Are you talking about essentially doing just one of the jumps in the iterative solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:57:15.100", "Id": "60200", "Score": "0", "body": "@Cruncher yes just do one of the jumps (forward for start, backward for end). You compute the difference anyways." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T18:01:31.713", "Id": "60201", "Score": "0", "body": "@kutschkem I see what you're saying. That's interesting" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T18:04:17.023", "Id": "60202", "Score": "0", "body": "@kutschkem Right, at the very least I trim off the end points. I guess it was pretty crazy to potentially check the same point several times. This should bring the constant down quite a bit" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:56:07.153", "Id": "36583", "ParentId": "36547", "Score": "6" } }, { "body": "<p>This can be done in O(1) time, if it is ok to use O(n) time to build a lookup-table just once. If the array stays the same, and you're going to search multiple times, this might be a good approach. The following pseudocode assumes you're going to search the whole array (from index 0), and returns the first index where the element is found. It can easily be modified to search from an index > 0, and also tell you all the indices where the element occur.</p>\n\n<p>Say your input array is called arr, the length of arr is n, and arr[0] is k. We know that the values in arr are in the range [k-n+1,k+n-1], in total 2n-1 different values. For each possible integer in the range, we make an entry for it in our lookup table:</p>\n\n<pre><code>// Initialization\nfor i = 0 to 2n-2 \n lookup[i] = -1\n\nk = arr[0]\n\n// Build lookup-table\nfor i = 0 to n-1\n index = arr[i]-k+n-1\n if lookup[index] == -1\n lookup[index] = i // We only store the position in arr of the first occurrence\n\n\n// Search for, say, s (assuming s is in the valid range, no check for it here)\nlookup[s-k+n-1] // A result &gt;= 0 is a hit, giving the (first) position of s in arr\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T08:18:44.640", "Id": "36625", "ParentId": "36547", "Score": "9" } }, { "body": "<p>I'm sure there are algorithms that, on average, are better than \\$O(n)\\$ on average.</p>\n\n<p>For instance, if a search algorithm searches array <code>source</code>, length <code>length</code>, indexing through with variable <code>index</code> searching for <code>target</code>, then if <code>source[index] != target</code>, then the next value for <code>index</code> could be <code>index + abs(source[index]-target)</code>, which might skip many elements, or even run off the end of the array and terminate.</p>\n\n<p>That is, you only need to check a few elements of the array since their values are constrained.</p>\n\n<p>A better mathematician than me will be able to tell you what the upper bound is, but my guess would be \\$O(1)\\$.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T22:05:13.807", "Id": "73590", "Score": "0", "body": "In the worst case, `abs(source[index]-target)` is always less than or equal to 2, and so this algorithm only skips half of the elements, making it O(n/2), which is the same thing as O(n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T11:03:25.647", "Id": "73654", "Score": "0", "body": "@TannerSwett: I'm not convinced that `abs(source[index]-target)` is always less than or equal to 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T01:09:47.610", "Id": "74004", "Score": "1", "body": "I'm not claiming that `abs(source[index]-target)` is always less than or equal to 2. I'm saying that *if* `abs(source[index]-target)` is less than or equal to 2 throughout some array, then no algorithm can successfully search that array faster than O(n)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T09:50:33.230", "Id": "36627", "ParentId": "36547", "Score": "-3" } }, { "body": "<p>Here is a different solution:</p>\n\n<pre><code>public static void radixSort(int[] data) {\n boolean flag = true;\n int divisor = 1;\n Queue [ ] buckets = new Queue[10];\n for (int i = 0; i &lt; 10; i++)\n buckets[i] = new LinkedList();\n\n while (flag) {\n flag = false;\n // first copy the values into buckets\n for (int i = 0; i &lt; data.length; i++) {\n int hashIndex = (data[i] / divisor) % 10;\n if (hashIndex &gt; 0) flag = true;\n buckets[hashIndex].add(data[i]);\n }\n // then copy the values back into vector\n divisor *= 10;\n int i = 0;\n for (int j = 0; j &lt; 10; j++) {\n while (! buckets[j].isEmpty()) {\n Integer ival = (Integer) buckets[j].element();\n buckets[j].remove();\n data[i++] = ival.intValue();\n }\n }\n }\n}\n\npublic static int searchArray(int[] arr,int offset,int elm) {\n radixSort(arr);\n return Arrays.binarySearch(arr, elm);\n}\n</code></pre>\n\n<p>The first part, <code>radixSort</code>, is \\$O(kn)\\$ and the second part, <code>binarySearch</code>, is \\$O(log(n))\\$. Alternatively to writing <code>radixSort</code>, you could have used the standard Java <code>Arrays.sort</code> which has an order of \\$O(n log(n))\\$ because it's an implementation of quick sort.</p>\n\n<p>This was my old solution which as was pointed out is still \\$O(n)\\$:</p>\n\n<p>The solution is fairly simple. You can optimize this down to \\$O(\\frac{n}{2})\\$, simply because when you look at the value of an item, you know what the value of the item before and after that item is.</p>\n\n<p>The simple function would be:</p>\n\n<pre><code>public int searchArray(int[] arr,int offset,int elm) { \n if(arr != null &amp;&amp; arr.length &gt; (offset+1)) {\n for(int i = (offset+1); i &lt; arr.length; i+=2) { \n int absVal = Math.abs(elm - arr[i]);\n if(absVal == 1) {\n int behind = i - 1;\n int infront = i + 1;\n if(arr[behind] == elm) {\n return behind;\n } else if(arr[infront] == elm) {\n return infront;\n }\n } else if(absVal == 0) {\n //we are the value\n return i;\n }\n }\n } else if(arr != null &amp;&amp; arr.length &gt; offset &amp;&amp; arr[offset] == elm) {\n return offset;\n } \n return -1; \n }\n</code></pre>\n\n<p>Here is a complete sample program that will also run a regression test on the entire code example for every element in the array to prove that it works. I also included a counter to show the number of cycles that were actually performed. Since we increment the array counter by 2 in any case, the maximum order of the algorithm will always be lower that \\$O(n)\\$.</p>\n\n<p>Complete code sample:</p>\n\n<pre><code>package cstura;\n\nimport javax.xml.ws.Holder;\n\n/**\n *\n * @author cstura\n */\npublic class Test {\n\n public static void main(String[] args) throws Throwable {\n int[] arr = {2, 1, 2, 3, 4, 3, 2, 3, 4, 5, 6, 5, 4, 3, 4}; \n for(int i = 0; i &lt; arr.length; ++i) {\n Holder&lt;Integer&gt; numItrs = new Holder(0);\n int idx = searchArray(arr,0,arr[i],numItrs);\n System.out.println(String.format(\"first position of %d in the array is: %d total itrs were: %d\",arr[i],idx,numItrs.value));\n }\n }\n\n public static int searchArray(int[] arr,int offset,int elm,Holder&lt;Integer&gt; numItrs) {\n int itrs = 0;\n try { \n if(arr != null &amp;&amp; arr.length &gt; (offset+1)) {\n for(int i = (offset+1); i &lt; arr.length; i+=2) { \n itrs++;\n int absVal = Math.abs(elm - arr[i]);\n if(absVal == 1) {\n //the value if infront or behind us (maybe)\n int behind = i - 1;\n int infront = i + 1;\n if(arr[behind] == elm) {\n return behind;\n } else if(arr[infront] == elm) { //if it's not behind then it must be infront.\n return infront;\n }\n } else if(absVal == 0) {\n //we are the value\n return i;\n }\n }\n } else if(arr != null &amp;&amp; arr.length &gt; offset &amp;&amp; arr[offset] == elm) {\n return offset;\n }\n\n return -1; \n }finally {\n numItrs.value = itrs;\n }\n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T12:50:26.867", "Id": "60151", "Score": "3", "body": "O(n/2) is not lower than O(n), it is exactly the same as O(n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T14:08:30.207", "Id": "60159", "Score": "0", "body": "this statement doesn't make much sense. because n/2 does half as many clock cycles in a worst case scenario as O(n) which means that it is not the same it's faster. the be precise the algorithm is always twice as fast." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T14:16:00.600", "Id": "60165", "Score": "3", "body": "Then you most likely don't understand what the [big O notation](https://en.wikipedia.org/wiki/Big_O_notation) actually means. When comparing algorithms, it's hard to compare “n/2 slow iterations” and “n fast iterations”. So you use the big O notation to say that both are about the same and that the real difference is between, say, O(log n), O(n) and O(n^2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:29:33.260", "Id": "60192", "Score": "0", "body": "Welcome to Code Review. Answers should contain some critique of the original code. If you present your own code, please justify why it is better. (Shorter? Faster? Easier to understand? …)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T10:02:56.917", "Id": "36628", "ParentId": "36547", "Score": "0" } }, { "body": "<p>There are a lot of good answers here, but I felt like taking a stab at the question.</p>\n\n<p>If your task is to search the array with \\$O(n)\\$ or less <em>complexity</em>, I most smugly propose:</p>\n\n<pre><code>int search(int[] data, int value) {\n for (int i = 0 ; i &lt; data.length ; i++) {\n if (data[i] == value) {\n return i;\n }\n }\n return -1;\n}\n</code></pre>\n\n<p>So I doubt that's the case; either the original asker incorrectly used big \\$O\\$ to refer to <em>running time</em>, or you're really over-complicating the search.</p>\n\n<p>Assuming they meant <em>running time</em> \\$R &lt; k*N\\$ my solution below differs from yours in two important respects:</p>\n\n<p>It seems you understand that you can save time by skipping ahead, exploiting the fact that for two values \\$x\\$ and \\$y\\$ at indices \\$i\\$ and \\$j\\$ respectively where \\$i &lt; j\\$, \\$y \\le x + j - i\\$ and \\$y \\ge x + i - j\\$. However, your algorithm goes ahead and searches backward after it skips ahead; this is not necessary. You can skip ahead because the search value <em>can't be in the range you skipped</em>.</p>\n\n<p>Recursion is not recommended because it expands the storage requirements for the algorithm by occupying stack, makes the <em>complexity</em> of the algorithm more difficult to evaluate, and usually increases \\$k\\$. It is perfectly possible to search with a loop that is easily shown to be \\$O(n)\\$ time and \\$O(k)\\$ space <em>complexity</em>.</p>\n\n<pre><code>int searchWeirdlyOrganizedArray(int[] data, int forValue) {\n int i = 0;\n while (i &lt; data.length) {\n if (data[i] == forValue) {\n return i;\n } else {\n i += abs(forValue - data[i]);\n }\n }\n return -1;\n}\n</code></pre>\n\n<p>Final note: I was wrong in my comment that searching \\$\\lbrace1, 2, 1, 2, \\dots\\rbrace\\$ for 3 would require \\$N\\$ comparisons. It requires \\$\\frac{N}{2}\\$ comparisons because all the 2s are skipped over. If the 2s and 1s are reversed (\\$\\lbrace2, 1, 2, 1, \\dots\\rbrace\\$) it takes \\$1 + \\frac{N - 1}{2}\\$ comparisons, as the initial comparison only advances the search by 1, but thereafter every 2 is skipped. However, I was right that it is still \\$O(n)\\$ <em>complexity</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-24T17:11:56.757", "Id": "63280", "Score": "0", "body": "Just a bit confused. I am trying to see whether there is anything significantly different (apart from the while-vs-for loop) between your suggested code and the accepted-answer code. Am I missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-24T23:27:33.600", "Id": "63313", "Score": "0", "body": "@rolfl Code doesn't look different. I don't like the `for` with a modification to `i` in the loop body. Discussion and comparison to the OP's code is a little different. Also, I offer a cheeky solution to the problem as originally stated if interpreted literally. I should probably upvote the accepted answer in agreement, though, eh?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-24T02:06:51.700", "Id": "38004", "ParentId": "36547", "Score": "2" } }, { "body": "<p>I don't think you will find a better worst-case than \\$O(n)\\$. But if you want to do a lot of queries on one array (i.e. check multiple numbers in single array), you can use <a href=\"https://en.wikipedia.org/wiki/Counting_sort\" rel=\"nofollow\">counting sort</a>.</p>\n\n<p>There is one improvement that can be done here that works in \\$O(n)\\$ preprocessing and \\$O(1)\\$ time for each query. That is, you can do \\$t\\$ queries in \\$O(t + n)\\$ time, not in \\$O(nt)\\$, as you would need to do with your current method.</p>\n\n<p>One obvious way is to sort your array in \\$O(nlogn)\\$ and do binary searches in \\$O(logn)\\$. For \\$t\\$ queries, time would be \\$O(tlogn + nlogn)\\$. But that can still be improved.</p>\n\n<p>You can sort your numbers in \\$O(n)\\$ time using counting sort, but there is one trade-off this way. That is, if the biggest number in the array is \\$k\\$, then you need an array of size \\$k\\$ in your RAM, which would cause problems in rare cases.</p>\n\n<p>This code only works for non-negative integers. With a little change, the algorithm would work for negative integers as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-05T06:39:12.800", "Id": "109844", "ParentId": "36547", "Score": "0" } } ]
{ "AcceptedAnswerId": "36570", "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T05:18:49.320", "Id": "36547", "Score": "50", "Tags": [ "java", "algorithm", "interview-questions", "search", "complexity" ], "Title": "Searching in an array in less than O(n) time" }
36547
<p>Continuation of this question: <a href="https://codereview.stackexchange.com/questions/36523/unit-of-work-with-generic-repository-pattern-mvvm">Unit of Work with Generic Repository Pattern MVVM</a></p> <p>I have made some modifications:</p> <ul> <li>Interfaces aren't forced to implement IDisposable</li> <li>Removed the finalizers</li> <li>Rebuilt UoW</li> </ul> <p><strong>FeedRepository:</strong></p> <pre><code>internal class FeedRepository&lt;T&gt; : IFeedRepository&lt;T&gt;, IDisposable where T: IBaseFeed, new() { private readonly SQLiteConnection _db; private IList&lt;T&gt; _feeds; private bool _isDisposed = false; public int Count { get { return _feeds.Count; } } public FeedRepository(SQLiteConnection db) { this._db = db; this._feeds = _db.Table&lt;T&gt;().ToList(); } public void Add(T feed) { this._feeds.Add(feed); this._db.Insert(feed); } public IEnumerable&lt;T&gt; GetAll() { return this._feeds; } public T GetFeedById(int id) { return this._feeds.Where(feed =&gt; int.Equals(feed.Id, id)).Single(); } public T GetFeedByLink(string feedLink) { return this.GetFeedByLink(new Uri(feedLink)); } public T GetFeedByLink(Uri feedLink) { return this._feeds.Where(feed =&gt; Uri.Equals(feed.Link, feedLink)).Single(); } public int GetFeedIdByLink(string feedLink) { return this.GetFeedIdByLink(new Uri(feedLink)); } public int GetFeedIdByLink(Uri feedLink) { return this._feeds.Where(feed =&gt; Uri.Equals(feed.Link, feedLink)).Select(feed =&gt; feed.Id).Single(); } public void Remove(T feed) { this._feeds.Remove(feed); this._db.Delete(feed); } public void RemoveById(int id) { this.Remove(this.GetFeedById(id)); } public void Update(T feed) { int indexOfFeed = this._feeds.IndexOf(this.GetFeedById(feed.Id)); this._feeds[indexOfFeed] = feed; this._db.Update(feed); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { if (!this._isDisposed) { if (isDisposing) { if (this._db != null) { this._db.Dispose(); } } this._isDisposed = true; } } } </code></pre> <p><strong>IUnitOfWork:</strong></p> <pre><code>internal interface IUnitOfWork { void Commit(); void Rollback(); } </code></pre> <p><strong>UnitOfWork:</strong></p> <pre><code>internal class UnitOfWork : IUnitOfWork, IDisposable { private readonly SQLiteConnection _db; private FeedRepository&lt;FeedData&gt; _feedDataRepository; private FeedRepository&lt;FeedItem&gt; _feedItemRepository; private bool _isDisposed = false; public FeedRepository&lt;FeedData&gt; FeedDataRepository { get { return _feedDataRepository; } set { _feedDataRepository = value; } } public FeedRepository&lt;FeedItem&gt; FeedItemRepository { get { return _feedItemRepository; } set { _feedItemRepository = value; } } public UnitOfWork(SQLiteConnection db) { this._db = db; this._feedDataRepository = new FeedRepository&lt;FeedData&gt;(this._db); this._feedItemRepository = new FeedRepository&lt;FeedItem&gt;(this._db); this._db.BeginTransaction(); } public void Commit() { this._db.Commit(); } public void Rollback() { this._db.Rollback(); } protected virtual void Dispose(bool isDisposing) { if (!this._isDisposed) { if (isDisposing) { if (this._db != null) { this._db.Dispose(); } } this._isDisposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } </code></pre> <p>Unfortunately, I still have no idea how to remove <code>this._feeds = _db.Table&lt;T&gt;().ToList();</code> from the repository, because when I delete it, I can't use <code>GetAll()</code>, <code>GetFeedById()</code> and so on.</p> <p><strong><em>Edit</em></strong></p> <p>That's <strong>IBaseFeed:</strong></p> <pre><code>public interface IBaseFeed { int Id { get; set; } string Title { get; set; } DateTime PubDate { get; set; } Uri Link { get; set; } string Misc { get; set; } } </code></pre> <p>If I don't use IBaseFeed I won't take advantage of using:</p> <pre><code> public T GetFeedByLink(Uri feedLink) { return this._feeds.Where(feed =&gt; Uri.Equals(feed.Link, feedLink)).Single(); } </code></pre> <p>due to any of following properties such as 'Id' or 'Link'. That' why I'd rather use <code>IRepository&lt;T&gt; where T : class</code> and <code>IFeedRepository&lt;T&gt; where T : class, IBaseFeed</code>.</p> <p>I have been writing an app for Windows 8.1 and unluckily EF is not available. The only wrapper for SQLite that I found is sqlite-net.</p> <p><code>sqlite-net</code> doesn't contain method <code>LastInsertId</code> so I have no idea how to return <code>T</code> with the database-generated ID?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:50:19.207", "Id": "60225", "Score": "1", "body": "If SQLite-net works like EF, then you don't need a `LastInsertId` method - it should just update your POCO *automagically* :)" } ]
[ { "body": "<p>This new code looks much more cohesive, well done!</p>\n\n<pre><code>this._feeds = _db.Table&lt;T&gt;().ToList();\n</code></pre>\n\n<p>This is <em>eager-loading</em> the table content into your repository class, whenever you instantiate it. What you want is <em>lazy-loading</em>, and that's a different ball game - I mean, I would rely on an <em>object/relational mapper</em> like <a href=\"/questions/tagged/entity-framework\" class=\"post-tag\" title=\"show questions tagged &#39;entity-framework&#39;\" rel=\"tag\">entity-framework</a> to do that gruntwork for me. There must be an EF <em>provider</em> for sqlite, for sure.</p>\n\n<hr>\n\n<p>Something about your repository interface <code>IFeedRepository&lt;T&gt;</code>, is bothering me. Based on your previous post and this updated code, I believe your interface now looks like this:</p>\n\n<pre><code>internal interface IFeedRepository&lt;T&gt; where T : IBaseFeed\n{\n int Count { get; }\n\n void Add(T feed);\n IEnumerable&lt;T&gt; GetAll();\n T GetFeedById(int id);\n T GetFeedByLink(string feedLink);\n T GetFeedByLink(Uri feedLink);\n int GetFeedIdByLink(string feedLink);\n int GetFeedIdByLink(Uri feedLink);\n void Remove(T feed);\n void RemoveById(int id);\n void Update(T feed);\n}\n</code></pre>\n\n<p>I think you're missing an opportunity at a generic repository here:</p>\n\n<pre><code>internal interface IRepository&lt;T&gt; where T : class\n{\n int Count { get; }\n T GetById(int it);\n IEnumerable&lt;T&gt; GetAll();\n void Add(T entity);\n void Remove(T entity);\n void RemoveById(int id);\n void Update(T entity);\n}\n</code></pre>\n\n<p>And then you could have <code>IFeedRepository&lt;T&gt; : IRepository&lt;T&gt; where T : class</code> (I'm not sure what <code>IBaseFeed</code> is, but it looks like a superfluous interface), and you can reuse your <code>IRepository&lt;T&gt;</code> interface for other \"entities\".</p>\n\n<p>Just noticed you have <code>Add(T)</code> returning <code>void</code> - wouldn't it be practical if it returned a <code>T</code> with the database-generated ID?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:49:16.563", "Id": "60048", "Score": "0", "body": "Edited first post ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-09T12:26:04.520", "Id": "65034", "Score": "0", "body": "I hope you remember my problem ;) https://codereview.stackexchange.com/questions/38901/unit-of-work-with-generic-repository-pattern-mvvm-vol-3" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:11:10.960", "Id": "36577", "ParentId": "36561", "Score": "2" } } ]
{ "AcceptedAnswerId": "36577", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T10:07:38.017", "Id": "36561", "Score": "1", "Tags": [ "c#", "sqlite", "mvvm" ], "Title": "Unit of Work with Generic Repository Pattern MVVM, vol. 2" }
36561
<p>I have been building a site using php and would like advice to improve the structure of my site and the best way to lay out my code for SEO. I'm also a little concerned about echoing large chunks of HTML and how SEO will work with my structure.</p> <p>Ok here's my structure...</p> <p>My site contains many pages with only the body content changing for each page. So I have created template functions in PHP for echoing HTML. I use $_GET['page_id'] in a switch statement to determine what page content to load. .</p> <p>my pages look something like this....</p> <pre><code>Header(); //echo header HTML switch ($_GET['page_id']) //Echo body content { default: homePage(); break; case 1: servicesPage(); break; case 2: galleryPage(); break; case 3: contactPage(); break; } Footer(); //Echo footer HTML </code></pre> <p>And my php functions look like this</p> <pre><code> function header() { echo "&lt;div&gt; &lt;h1&gt;Header&lt;/h1&gt; &lt;/div&gt;"; } function footer() { echo "&lt;div&gt; &lt;h1&gt;Header&lt;/h1&gt; &lt;/div&gt;"; } function homePage() { echo "&lt;div&gt; &lt;h1&gt; Home &lt;/h1&gt; &lt;ul&gt; &lt;li&gt; Home1 &lt;/li&gt; &lt;li&gt; Home1 &lt;/li&gt; &lt;/ul&gt; &lt;p&gt;This is home page&lt;/p&gt; &lt;/div&gt;"; } </code></pre> <p>I'm really looking for any pointers to improve my code but my main concerns are...</p> <p>Is it ok to echo large chucks of HTML like that from php? especially with my site growing?</p> <p>Does Google crawler bot still crawl my site ok using $_GET['page_id'] for all my pages?</p> <p>P.S I'm new here, so sorry if any code formatting is a little off!</p>
[]
[ { "body": "<p>I would not recommend using functions and echo-ing large chunks of HTML. You could just require the files. There is no need for functions. Also, use names instead of ID's</p>\n\n<pre><code>if (in_array($_GET['page'],array('home','contact','test')){\n require_once 'pages/'.$_GET['page'].'.php';\n}\n</code></pre>\n\n<p>And in the files themself, just add the HTML content, and if needed PHP variables:</p>\n\n<pre><code> &lt;div&gt; \n &lt;h1&gt;&lt;?php echo $_GET['page']; ?&gt;&lt;/h1&gt;\n &lt;ul&gt; \n &lt;li&gt; Home1 &lt;/li&gt;\n &lt;li&gt; Home1 &lt;/li&gt;\n &lt;/ul&gt;\n &lt;p&gt;This is home page&lt;/p&gt;\n &lt;/div&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:23:27.523", "Id": "60013", "Score": "2", "body": "The `require_once` is a terrible idea! I explain why in my answer, but please, don't just suggest _horribly unsafe_ things, without any form of warning!!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:51:21.313", "Id": "60015", "Score": "0", "body": "I have to agree with @EliasVanOotegem here. That specific security hole has killed both one and two servers for me. Even though there is an `in_array` check there, I would use a different way to check it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:27:30.343", "Id": "60020", "Score": "3", "body": "`<?php echo $_GET['page']; ?>` is also an xss attack waiting to happen. Using files as templates is itself a good suggestion - but because of the simplistic code example this could easily become vulnerable code - for that reason -1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:22:17.660", "Id": "60097", "Score": "0", "body": "+1 for the suggestion on structure. Apart from the security flaw this was helpful." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T11:05:33.750", "Id": "36568", "ParentId": "36563", "Score": "2" } }, { "body": "<p>Looking at your <code>switch</code> statement from an SEO point of view, I'd have to say: it's awful (sorry).<br/>\nOne of the first things to look at, when you're interested in SEO, is <code>mod_rewrite</code>. Search engines don't like urls that say nothing:</p>\n\n<pre><code>http://www.my-site.com/1\nhttp://www.my-site.com/2\nhttp://www.my-site.com/3\nhttp://www.my-site.com/3\n</code></pre>\n\n<p>Doesn't say anything, whereas</p>\n\n<pre><code>http://www.my-site.com/home\nhttp://www.my-site.com/services\nhttp://www.my-site.com/gallery\nhttp://www.my-site.com/contact\n</code></pre>\n\n<p>If anything, contains a sort-of meaningful keyword in the url from the off. Not only to crawlers love that, so do people browsing your site, for that matter.<br/>\nNaturally, you have to keep this up, take the services page for example. I'm assuming that this is the page where you list what you do/offer, then all sub-nav urls should look like:</p>\n\n<pre><code>http://www.my-site.com/services/custom/cms\nhttp://www.my-site.com/services/portfolio\n</code></pre>\n\n<p>And so on...<br/>\nAs to what Topener suggested: <code>require_once 'pages/'.$_GET['page'].'.php';</code> is a <em>terrible</em>, <strong><em>terrible</em></strong> idea. Using data from the network, data the <em>client</em> can change to determine what files should be loaded is a <em>huuuuge</em> security hole!</p>\n\n<p>From a CodeReview viewpoint:<br/>\nA <code>switch</code> is all well and good, but it won't be long untill you find yourself scrolling up and down through your code, because the switch-case has grown so large. You'll have to invent hacky ways of dealing with form validation, and other types of client requests (pagination, ajax, file uploads, ...) in a manageable, safe and maintainable way.<br/>\nA switch can be useful to shorten a lot of <code>if-elseif-elseif-else</code> branches, but not for something as crucial as to determine what page you have to present the client with. Most modern sites would go with a framework that implements the MVC pattern (Symfony2, ZendFW, Yii, ...)<br/>\nAs AD7Six said in his comment: if all you're after is a simple routing solution, there are micro-fw's, too, that might be a better fit for your problem. Even so, most frameworks are more or less modular, and with a dependency manager like composer, you can use the routing module(s) from any framework.</p>\n\n<p>Your functions are also in violation of the PSR standards as defined by PHP-Fig (look for them on github). Classes (objects) start with an upper-case, functions/methods don't. Try to adhere to what little standards/conventions you have</p>\n\n<p>Lastly, this just looks wrong to me:</p>\n\n<pre><code>switch($foo)\n{\n default: homePage(); break;\n case 1: ...\n}\n</code></pre>\n\n<p>The <code>defaut</code> case is the <em>fallback</em> case. To me, logic dictates that the default/fallback procedure is the <em>last resort</em>, and it should therefore be written as the last case label. Maybe that's just me, and my (sometimes over eager) tendency to use case fallthroughs:</p>\n\n<pre><code>switch ($foo)\n{\n case 1:\n case 2:\n bothDoTheSame();\n break;\n case 3:\n threeSpecific();\n case 4:\n threeAndFour();\n break;\n default: defaultCase();//no break required\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:31:57.893", "Id": "60021", "Score": "0", "body": "+1. Pointing out that there are [many](http://www.slimframework.com/) [existing](http://silex.sensiolabs.org/) [micro frameworks](http://limonade-php.github.io/) which already implement simple routing solutions - rather than full stack frameworks (zend, cakephp, symfony) might be useful to future readers since the question as posed is effectively _only_ about routing logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:00:42.830", "Id": "60094", "Score": "0", "body": "Thank you, a great help! am I right in thinking that specific security flaw doesn't affect me as i don't use $_GET['page_id'] in my require_once() function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T10:58:13.420", "Id": "60142", "Score": "0", "body": "@Scott: Not as such... but that doesn't mean there aren't any security issues with your site. But if your code (a switch-case-default) is all there is to it, then you are safe from tinkered urls" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-24T08:44:09.160", "Id": "385219", "Score": "0", "body": "*It is rather arguable*, but I tend to belive that having a single switch for all static routes is a huge win. It depends a lot on site complexity, but when your site is only about several pages I think it is much better to use plain self-documented switch instead of bloated frameworks no one knows about." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:22:20.813", "Id": "36574", "ParentId": "36563", "Score": "6" } } ]
{ "AcceptedAnswerId": "36574", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T10:32:25.227", "Id": "36563", "Score": "2", "Tags": [ "php", "html" ], "Title": "Is this a good structure for my website?" }
36563
<p>I've made a Regex to find any URL on site, which uses PHP:</p> <pre><code>Reg = new System.Text.RegularExpressions.Regex("((http|https)://([a-zA-Z0-9-]{1,}[/]?))?[/]?([a-zA-Z0-9-]{1,}[.](php|html))((/[a-zA-Z0-9-]{1,}){1,}[/]?){0,}([?]([a-zA-Z0-9]{1,}=[a-zA-Z0-9\"&gt;&lt;();/.,]{1,}&amp;?){1,})?"); </code></pre> <p>Is this code optimal, or is there a better solution? </p>
[]
[ { "body": "<p>Using regex to match a URI is never a good solution... as you have discovered, you now have <strong>two</strong> problems (the base problem, and the regex problem).</p>\n\n<p>In this case, you should use the language features to help you.... (<em>bear in mind I am a Java person, so I may have some syntax errors</em>)....</p>\n\n<pre><code>try {\n Uri uri = new Uri(stringvalue);\n // use your favourite C# function to check the localpath of the URI...\n if (uri.LocalPath.EndsWith(\"php\") {\n // it **may** be a php page\n }\n} catch (UriFormatException e) {\n // this is **not** a php page\n}\n</code></pre>\n\n<p>Look!!! No potential regex problems... because <a href=\"https://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url\">using a regex to match a URI is nearly impossible</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:06:47.567", "Id": "60009", "Score": "2", "body": "*\"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems.\"* - Jamie Zawinski" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:10:24.853", "Id": "60010", "Score": "1", "body": "@Max - thanks, I was lazy and did not dig up the reference. FWIW, I love regex, it's like a really nice hammer... but not every problem is a nail." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T12:51:55.430", "Id": "36572", "ParentId": "36571", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T12:39:28.497", "Id": "36571", "Score": "2", "Tags": [ "c#", "regex", "url" ], "Title": "Finding PHP URL" }
36571
<p>I have a method that checks to see if a hash of given items should have discounts applied and if so, determines and returns the discount:</p> <pre><code>def get_discounts @items.each do |name, attr| @specials.each do |special| while name == special.sale_item &amp;&amp; attr[:quantity] &gt;= special.quantity @discounts &lt;&lt; special.discount attr[:quantity] = attr[:quantity] - special.quantity end end end determine_discount end def determine_discount if @discounts.empty? @discounts = 0 else @discounts = @discounts.inject(:+) end end </code></pre> <p>This works perfectly, but is there a more concise way to write it? I'm looking especially at the two <code>each</code> loops. I'm also a bit iffy about the <code>while</code> loop - it was an <code>if</code> statement (<code>if name == special.sale_item</code>) but it felt like too much so I combined it into the <code>while</code> loop.</p>
[]
[ { "body": "<p>I agree with both of your suspected issues:</p>\n\n<ul>\n<li><strong>Pointless iteration through <code>@items</code> hash:</strong> As you suspected, iterating through all entries of a hash defeats the purpose of a hash. That takes O(<em>I</em> * <em>S</em>) time — the number of items times the number of specials. Why not iterate through <code>@specials</code>, then look up the item by name? That's only O(<em>S</em>).</li>\n<li><strong>while loop:</strong> The loop can be replaced with arithmetic.</li>\n</ul>\n\n<p>In addition, I would like to point out some more problems:</p>\n\n<ul>\n<li><strong>Surprising side-effect in getter:</strong> By convention, any method named <code>get_*()</code> is assumed to have no side-effects. However, <code>get_discounts()</code> alters <code>@items</code>, reducing their quantity. If that is intentional, you should rename the method to <code>apply_discounts()</code> or something even more suggestive that there is a side-effect.</li>\n<li><strong>Abuse of instance variable:</strong> <code>@discounts</code> is assumed to be pre-initialized to an empty array before <code>get_discounts()</code> is called. <code>get_discounts()</code> populates the array, then calls <code>determine_discount()</code>, which converts it into a scalar. That indicates that <code>@discounts</code> is not storing the state of the object, so using an instance variable for that purpose is abuse.</li>\n</ul>\n\n<p>Here is a revised version of the code:</p>\n\n<pre><code>def get_discounts\n discount = 0\n @specials.each do |special|\n if item = @items[special.sale_item]\n multiples = (item[:quantity] / special.quantity).floor\n discount += multiples * special.discount\n\n # Suspicious side-effect...\n # item[:quantity] -= multiples * special.quantity\n end\n end\n return discount\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:19:10.837", "Id": "60096", "Score": "0", "body": "great answer, thank you - actually i had remedied the 'side-effect' but thanks for pointing that out. I did `count = info[:quantity]` and then `count = count - special.quantity` but your way is nicer. Cheers, really appreciate the push in the right direction!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:39:16.210", "Id": "36595", "ParentId": "36573", "Score": "6" } } ]
{ "AcceptedAnswerId": "36595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T13:17:05.587", "Id": "36573", "Score": "5", "Tags": [ "ruby", "e-commerce" ], "Title": "Calculating shopping cart discounts" }
36573
<p>The current code solves the issue I had when trying to use property injection.</p> <p><strong>Problem</strong>: Every module must use constructor injection because of a circular reference that occurs when not using constructor injection with my factories and trying to use property injection</p> <p><strong>Reason</strong>: A module requires a client and each client must have its own list of instantiated modules.</p> <p><strong>What I want</strong>: I want every module that derives from <code>BaseModule</code> to be able to not declare a constructor and allow <code>BaseModule</code> to have <code>IIrcClient</code> injected via a property.</p> <p>But I'm not sure how to use Ninject to correctly do this without getting a circular reference. Is there a way so that for each client, a new list of modules are injected into that client (where all modules then have an injected reference of the client they belong to).</p> <p><code>.ToFactory()</code> is an extension method of Ninject which creates a proxy based on an interface that creates an object with a dependency. </p> <pre class="lang-cs prettyprint-override"><code>public class BaseClient : IClient { private readonly IEnumerable&lt;IModule&gt; modules; protected BaseClient(IModuleFactory moduleFactory) { // each client has its own instances of modules set // each module needs a reference to the client this.modules = moduleFactory.Create(this); } } public class BaseModule : IModule { private readonly IIrcClient ircClient; // Factory will inject and create protected BaseModule(IIrcClient ircClient) { this.ircClient = ircClient; } } public class Bot { // Injected factory public Bot(Context context, IrcClientFactory factory) { this.factory = factory; this.context = context; } public void Start() { List&lt;Network&gt; networks = context.Networks.ToList(); foreach (var network in networks) { // create new client...but also // new client gets injected with module factory // module factory then populates modules based on client IIrcClient ircClient = this.ircClientFactory.Create(); ircClient.Connect(network); this.clients.Add(ircClient); } } } public class Program { public void Main() { kernel.Bind&lt;IIrcClient&gt;().To&lt;DefaultIrcClient&gt;(); kernel.Bind&lt;IIrcClientFactory&gt;().ToFactory(); kernel.Bind&lt;IModule&gt;().To&lt;DiceModule&gt;().WithPropertyValue("Name", "Dice Module"); kernel.Bind&lt;IModule&gt;().To&lt;ModuleOne&gt;().WithPropertyValue("Name", "ModuleOne"); kernel.Bind&lt;IModule&gt;().To&lt;RubyModule&gt;().WithPropertyValue("Name", "Ruby Module"); kernel.Bind&lt;IModule&gt;().To&lt;AdminModule&gt;().WithPropertyValue("Name", "Admin Module"); // Module Factory will generate IEnumerable&lt;IModule&gt; kernel.Bind&lt;IModuleFactory&gt;().ToFactory(); var bot = kernel.Get&lt;Bot&gt;(); bot.Start(); } } </code></pre> <p>A possible fix, but I would have to manaually set the property instead of letting Ninject inject the property:</p> <pre><code>public class BaseClient : IClient { private readonly IEnumerable&lt;IModule&gt; modules; protected BaseClient(IModuleFactory moduleFactory) { // let the factory create new modules // but dont pass the instance of the client this.modules = moduleFactory.Create(); foreach(var module in modules) { module.IrcClient = this; // don't want to do this, but I think it would fix it } } } </code></pre> <p>This way, I could create tons of modules without needing to always implement the base constructor and pass in the <code>IClient</code> dependency:</p> <pre><code>public class ChildModule : BaseModule { // client was injected via property // override virtual methods as required. } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T20:41:18.127", "Id": "60663", "Score": "0", "body": "Each DI has its pros and cons. Ninject, although very popular, may not be the best option for your situation. Have you tried any others?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T21:30:47.667", "Id": "60669", "Score": "0", "body": "Thanks for the comment, no i have not, though apparently AutoFac is a good alternative." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T02:28:39.500", "Id": "60686", "Score": "0", "body": "I'm not sure... but I do primarily use AutoFac." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T07:59:47.747", "Id": "65475", "Score": "0", "body": "Have you considered perhaps you could make it Laxy:\nEither with actual Lazy<T>\nhttp://msdn.microsoft.com/en-us/library/dd997286.aspx\nOr by instead of depending on being passed the object, ask to be passed a Process<T> ()=> new T()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T11:05:10.040", "Id": "74039", "Score": "3", "body": "Could you be more explicit about what \"circular reference\" you are getting with your attempted/preferred solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T01:53:04.483", "Id": "74663", "Score": "0", "body": "@PatrickMagee if you have found a solution to your problem, you can share it here and earn an easy 100pts :)" } ]
[ { "body": "<p>Your question isn't crystal-clear about what it is exactly that your code is supposed to be doing. We have to infer the functionality from this block of code:</p>\n\n<pre><code>public void Start()\n{\n List&lt;Network&gt; networks = context.Networks.ToList();\n\n foreach (var network in networks)\n {\n // create new client...but also\n // new client gets injected with module factory\n // module factory then populates modules based on client\n IIrcClient ircClient = this.ircClientFactory.Create();\n ircClient.Connect(network);\n this.clients.Add(ircClient);\n }\n}\n</code></pre>\n\n<p>This code involves [what appears to be] private fields that you haven't included. I'll assume the following:</p>\n\n<pre><code>private readonly Context context;\nprivate readonly IrcClientFactory factory;\n</code></pre>\n\n<p>If I read this correctly, your <code>Bot</code> class is depending on <em>concrete types</em>; they should be <em>abstractions</em>, like <code>IContext</code> and <code>IIrcClientFactory</code> (the latter being an <em>abstract factory</em>).</p>\n\n<blockquote>\n <h3>Naming - Private Fields</h3>\n \n <p>This might be of personal preference, but I like my private fields prefixed with an underscore. Having <code>_context</code> and <code>_factory</code> removes the ambiguity in the constructor and then the <code>this</code> qualifier becomes redundant:</p>\n\n<pre><code>public Bot(Context context, IrcClientFactory factory)\n{\n _factory = factory\n _context = context\n}\n</code></pre>\n</blockquote>\n\n<p>The comment <code>// injected factory</code> is a useless one; prefer XML comments for that purpose:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Creates a new instance of a Bot.\n /// &lt;/summary&gt;\n /// &lt;param name=\"context\"&gt;The data context.&lt;/param&gt;\n /// &lt;param name=\"factory\"&gt;A factory that creates IrcClient instances.&lt;/param&gt;\n public Bot(Context context, IrcClientFactory factory)\n {\n _factory = factory\n _context = context\n }\n</code></pre>\n\n<p>As a bonus, you'll get instant IntelliSense support for your constructor and its parameters.</p>\n\n<p>Back to the <code>foreach</code> loop; the code you have here doesn't seem to be using the fields you've initialized in your constructor:</p>\n\n<blockquote>\n<pre><code>IIrcClient ircClient = this.ircClientFactory.Create();\n</code></pre>\n</blockquote>\n\n<p>I would have expected:</p>\n\n<pre><code>IIrcClient ircClient = this.factory.Create();\n</code></pre>\n\n<p>I would rewrite it like this:</p>\n\n<pre><code>var client = _factory.Create();\n</code></pre>\n\n<blockquote>\n <h3>Implicit Typing</h3>\n \n <p>The <em>abstract factory</em> shouldn't be revealing the implementation of its <em>product</em> to its client; the factory's <code>Create()</code> method should be returning an implementation for <code>IClient</code>, and shouldn't have to even know what possible implementations the factory can spit out. Your code is expecting an <code>IIrcClient</code> which is an abstraction, but from the rest of your code I infer that <code>IIrcClient</code> extends the <code>IClient</code> interface. Bottom line, the code doesn't care what type is returned, and it should be working against all implementations of <code>IClient</code> (assuming <code>Connect(Network)</code> is a member of <code>IClient</code>).</p>\n \n <p>Implicit typing not only makes your code shorter and easier to read, it also emphasize that you don't really care what the actual type is.</p>\n</blockquote>\n\n<p>After creating a <code>client</code>, the loop's body passes the <code>network</code> to the client through its <code>Connect</code> method, and then the <code>client</code> gets added to yet another unmentioned field, assuming:</p>\n\n<pre><code>private readonly _clients = new List&lt;IClient&gt;();`\n</code></pre>\n\n\n\n<pre><code>public void Start()\n{\n var networks = context.Networks.ToList();\n foreach (var network in networks)\n {\n var client = _factory.Create();\n client.Connect(network);\n _clients.Add(client);\n }\n}\n</code></pre>\n\n<p>If the <code>network</code> parameter is passed into a field of the <code>client</code>, and used anywhere other than in the <code>Connect</code> method, it would probably be best to constructor-inject the <code>network</code> into the <code>client</code> inside the factory method. If it's passed into a field of the <code>client</code> but isn't used anywhere other than the <code>Connect</code> method, it would be best to constructor-inject the <code>network</code> into the <code>client</code> inside the factory method; what I'm trying to get to, is that constructor injection should always be prioritized over other forms of injections, whenever possible. In this case, I'd probably call the <code>IClient</code> implementation something like <code>ConnectedClient</code> and inject the <code>network</code> through the <code>Create</code> method, which returns an <code>IClient</code> with a connection, as the <code>ConnectedClient</code> implementing class' name says.</p>\n\n<hr>\n\n<p>Reviewing the rest of this code is very hard, I'm not seeing all the pieces of the puzzle that I'd like to see in order to be confident in anything else I'd have to say.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T23:04:03.373", "Id": "74852", "Score": "0", "body": "Thanks for this answer, to be truthful I've been very busy with other work related things but eventually I'll come round to this since I asked this some time ago. I do appreciate this so give me some time :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T23:05:45.227", "Id": "74854", "Score": "0", "body": "I recall i ended up changing my complete architecture so that its based on a request / response pattern rather than associating and injecting dependencies like i am (from my sketchy memory)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T05:50:38.633", "Id": "43278", "ParentId": "36578", "Score": "10" } } ]
{ "AcceptedAnswerId": "43278", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:19:10.763", "Id": "36578", "Score": "11", "Tags": [ "c#", "dependency-injection", "ninject" ], "Title": "How can I solve my constructor injection code architecture?" }
36578
<p>This looks pretty messy (need to reduce nesting I feel). I need a check an input for a seat, but I can't guarantee it has a value (one may not be chosen for example). If the seats aren't in a certain color it goes to seat basic (1), otherwise seat premium (2).</p> <pre><code> var seat = $("input[id*=" + seatPrefix + "]"); if (seat != 'undefined') { seat = seat[0].value; if (seat != "") { if (seat != "red" &amp;&amp; seat != "blue" &amp;&amp; seat != "silver" &amp;&amp; seat != "gold") { chooseSeat(seat, "2"); } else { chooseSeat(seat, "1"); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T17:20:20.890", "Id": "76810", "Score": "0", "body": "Sorry to ask, but didn't you mean `typeof seat == 'undefined'` instead of `seat == 'undefined'`? `typeof` will check if the variable is undefined, while you do check if it is a string saying \"undefined\" like \"foo\" or \"bar\" or \"apple\"." } ]
[ { "body": "<p>I'm not into <a href=\"/questions/tagged/javascript\" class=\"post-tag\" title=\"show questions tagged &#39;javascript&#39;\" rel=\"tag\">javascript</a>, so I'm not sure this would be legal, but I'd reduce nesting like this, by reverting the conditions and returning immediately:</p>\n\n<pre><code> var seat = $(\"input[id*=\" + seatPrefix + \"]\");\n if (seat == 'undefined') return;\n seat = seat[0].value;\n if (seat == \"\") return;\n if (seat != \"red\" &amp;&amp; seat != \"blue\" &amp;&amp; seat != \"silver\" &amp;&amp; seat != \"gold\") { \n chooseSeat(seat, \"2\"); \n }\n else { \n chooseSeat(seat, \"1\"); \n }\n</code></pre>\n\n<p>Other than that... I would think it depends <em>what color</em> is a <code>seat</code> that's not \"red\" nor \"blue\" nor \"silver\" nor \"gold\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:08:21.763", "Id": "60040", "Score": "0", "body": "the other colors could be almost anything (color related): brown, green, purple, aqua, navy etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:10:13.867", "Id": "60041", "Score": "0", "body": "Ah, I thought it was some *F1 Grand Prix* ticket booth app :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:11:40.940", "Id": "60042", "Score": "0", "body": "haha I wish... yeah if the selection for what wasn't a premium seat was smaller than premium seat I would have used that. good answer so far though!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:03:58.443", "Id": "36585", "ParentId": "36582", "Score": "4" } }, { "body": "<pre><code>var seat = $(\"input[id*=\" + seatPrefix + \"]\");\n if (seat != 'undefined') {\n</code></pre>\n\n<p>First off, an extra level of indentation has crept in here. Let me assume this is just a copy/paste error.</p>\n\n<p>Any chance you could be using classes here instead of prefixed IDs? Best case: a single ID you know in advance. It seems that you assume there's only one match anyways.</p>\n\n<p>jQuery, when it doesn't find anything, returns an empty collection, not <code>undefined</code> (or <code>'undefined'</code>; did you get confused by <code>typeof x !== 'undefined'</code>?). To test if a jQuery collection is empty, you can use <code>seat.length === 0</code> or even <code>! seat.length</code>.</p>\n\n<p>I don't normally use hungarian notation, but I do use it for jQuery objects, especially when I'm dealing with native elements as well: <code>$seat</code>. On a side note, shouldn't the variable name be <code>$seatInput</code> or something, rather than just <code>$seat</code>?</p>\n\n<p>I recommend against the coercing equality operator (<code>==</code>). Use <code>===</code> instead. <code>==</code> can be a bit... unpredictable at times. There are some special cases or case where I find <code>==</code> acceptable (<code>== null</code> for <code>null</code> or <code>undefined</code>) but this is not one of them (if only because <code>undefined != 'undefined'</code>)</p>\n\n<pre><code>seat = seat[0].value;\n</code></pre>\n\n<p>You can use <code>seat.val()</code> here. This has a positive side-effect that <code>val</code> returns <code>undefined</code> if the jQuery object holds no elements. Your code will attempt to dereference <code>undefined</code> in that case.</p>\n\n<p>Also, you are reusing the same variable to mean a jQuery object at one point, then to mean a string in the next line. You should use two separate variables (or inline the first one) here.</p>\n\n<pre><code>if (seat != \"\") {\n</code></pre>\n\n<p>If you use <code>val</code>, you can move it outside its condition block, and merge the condition with this one:</p>\n\n<pre><code>if(seat !== undefined &amp;&amp; seat !== \"\")\n</code></pre>\n\n<p>Since both <code>undefined</code> and the empty string are falsy and all other strings are truthy, this will work as well:</p>\n\n<pre><code>if(seat)\n</code></pre>\n\n<p>Of course, @retailcoder's suggestion to invert the condition and return early still applies.</p>\n\n<pre><code>if (seat != \"red\" &amp;&amp; seat != \"blue\" &amp;&amp; seat != \"silver\" &amp;&amp; seat != \"gold\") {\n</code></pre>\n\n<p>You can use <code>indexOf</code> to shorten that code and make it more readable:</p>\n\n<pre><code>if ([\"red\", \"blue\", \"silver\", \"gold\"].indexOf(seat) == -1)\n</code></pre>\n\n<p>if you like shortcuts,</p>\n\n<pre><code>if (!~[\"red\", \"blue\", \"silver\", \"gold\"].indexOf(seat))\n</code></pre>\n\n<p>At this point, the array definition can (and should) be moved outside the condition. It is marginally nicer to the memory, but more importantly it's easier to find the array in case you want to ever change it if you put it at the beginning of the file.</p>\n\n<pre><code>if(...){\n chooseSeat(seat, \"2\");\n} else {\n chooseSeat(seat, \"1\");\n}\n</code></pre>\n\n<p>Shouldn't this logic be part of the <code>chooseSeat</code> function?</p>\n\n<p>Also, <code>1</code> and <code>2</code> are non-obvious. Since you're passing a string anyways (why?), perhaps <code>chooseSeat</code> should accept <code>\"basic\"</code> and <code>\"premium\"</code> as its arguments?</p>\n\n<hr>\n\n<p>If I couldn't modify the <code>chooseSeat</code> function or your HTML, I would probably refactor your code like this:</p>\n\n<pre><code>var basicColors = [\"red\", \"blue\", \"silver\", \"gold\"];\nvar seat = $(\"input[id*=\" + seatPrefix + \"]\").val();\nif (!seat) return;\n\nif (~basicColors.indexOf(seat)) {\n chooseSeat(seat, \"1\");\n} else {\n chooseSeat(seat, \"2\");\n}\n</code></pre>\n\n<p>or, if <code>return</code> cannot be used (this is not the whole body of the function it is in),</p>\n\n<pre><code>var basicColors = [\"red\", \"blue\", \"silver\", \"gold\"];\nvar seat = $(\"input[id*=\" + seatPrefix + \"]\").val();\n\nif (seat) {\n if (~basicColors.indexOf(seat)) {\n chooseSeat(seat, \"1\");\n } else {\n chooseSeat(seat, \"2\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:48:17.717", "Id": "60046", "Score": "0", "body": "Thanks, you are correct about not being able to modify the chooseSeat function. I am unable to do so.\nGreat answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:41:59.430", "Id": "36587", "ParentId": "36582", "Score": "12" } }, { "body": "<pre><code>var seat = $(\"input[id*=\" + seatPrefix + \"]\");\nif (seat.length == 0) return;\n</code></pre>\n\n<p>jQuery will be the <code>seat</code> object. If that object has a javascript object inside it will be in <code>seat[0]</code>. Thats why you can do <code>seat[0].value</code>. seat.length will be 0 if the element is not found.</p>\n\n<p>Checking for undefined shouldn't have worked for you. Did it?</p>\n\n<pre><code>// if (seat == \"\") return;\n// replace above with\n// if (!seat) return;\n</code></pre>\n\n<p>That will check for all falsy values including undefined, null, and empty string.</p>\n\n<p>A normal pattern when check if an object exist and then if a property has a value will look like:</p>\n\n<pre><code>// without nesting:\nif(!myJsObject || !myJsObject.value) return;\n// or without negations:\nif(myJsObject &amp;&amp; myJsObject.value) { // code here }\n</code></pre>\n\n<p>In jQuery the <code>.val()</code> method will always exist but return <code>undefined</code> if no element was selected. Then the above pattern can be simplified to:</p>\n\n<pre><code>if(!seat.val()) return; // Will work if .val() doesn't return any falsy values.\n</code></pre>\n\n<p>The last if-statement should be reversed to check if <code>seat === \"red || ...</code>. Then it doesn't need to go through all the colors.</p>\n\n<p>Also, I suggest you put all colors in an array and check if the array contains the color. That way you can add and remove colors from the array without affecting the code. </p>\n\n<p>If you do lots of stuff like this I would recommend a library like <a href=\"http://lodash.com/docs\" rel=\"nofollow\">Lo-Dash</a>. You would like the <code>_.contains([\"red\", \"blue\", \"green\"], \"green\")</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:12:25.720", "Id": "60058", "Score": "1", "body": "since the only possible values of `val()` are `undefined` or a string, testing for an arbitrary falsy value is perfectly fine. `if(!seat[0].length || !seat.val())` is absolutely wrong - the first element doesn't always exist and never has a length. Remove the square brackets. Also, you want to use `&&`, not `||` here. Or, you can drop the first half entirely. Also, `&&` stops at the first falsy condition just as `||` stops at truthy ones. No need to reverse the condition and lose readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:29:58.743", "Id": "60065", "Score": "1", "body": "fix these to turn my vote into an upvote. The first few paragraphs are great!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T12:36:48.077", "Id": "60149", "Score": "0", "body": "I think Jan's answer is correctly marked as the solution, so read that instead.\n\nI fixed my suggestion as you pointed out, but I do not fully agree on the change from !true || !true to true && true. The reason to do the first one is to escape early with a return. If I don't escape the code, then I would do the &&-variant.\n\nThank you for the effort in reading through my suggestion Jan, I learnt something new about jQuery from it!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T16:44:28.653", "Id": "36588", "ParentId": "36582", "Score": "6" } }, { "body": "<p>jQuery is designed to make null-checking less onerous. I believe that this is a faithful rewrite of your code:</p>\n\n<pre><code>var seat = $(\"input[id*=\" + seatPrefix + \"]\").val();\nif (seat == \"red\" || seat == \"blue\" || seat == \"silver\" || seat == \"gold\") {\n chooseSeat(seat, \"1\");\n} else if (typeof seat != 'undefined') {\n chooseSeat(seat, \"2\");\n}\n</code></pre>\n\n<p>Note the changes:</p>\n\n<ul>\n<li><p><a href=\"http://api.jquery.com/val/\" rel=\"nofollow\"><code>$.val()</code></a> fetches the first result with null-handling:</p>\n\n<blockquote>\n <p><code>.val()</code></p>\n \n <hr>\n \n <p><strong>Description:</strong> Get the current value of the first element in the set of matched elements.</p>\n</blockquote>\n\n<p>I deduce from the context that your <code>&lt;input&gt;</code> elements are just text fields (not radio buttons or buttons or <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input\" rel=\"nofollow\">other types</a>).</p>\n\n<p>If the jQuery selector matches at least one element, but the first matched element is not filled in, then <code>.val()</code> would return an empty string. If the jQuery selector matches no <code>&lt;input&gt;</code> elements at all, then <code>.val()</code> would return <code>undefined</code>.</p></li>\n<li><p>Reading affirmative conditions is less taxing on the mind than reading negated conditions. I've applied De Morgan's Law to invert the branches of the if-else. Furthermore, we can optimistically defer the checking of <code>typeof seat == 'undefined'</code> and eliminate a level of indentation.</p></li>\n</ul>\n\n<p>Departing from your original code, I further suggest two changes:</p>\n\n<ul>\n<li><p>The fact that your variable is named <code>seatPrefix</code> suggests that you want to use the <a href=\"http://api.jquery.com/attribute-starts-with-selector/\" rel=\"nofollow\">attribute-name-starts-with selector</a> rather than the <a href=\"http://api.jquery.com/attribute-contains-selector/\" rel=\"nofollow\">attribute-name-contains selector</a>. Also, the jQuery documentation suggests that the <code>seatPrefix</code> should be in quotes (though jQuery appears to be lenient in that regard).</p></li>\n<li><p>As mentioned above, <code>seat</code> would be <code>undefined</code> only if the expected form element does not exist at all. Perhaps the <code>else if (typeof seat != 'undefined')</code> could just be a simple <code>else</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T18:15:56.213", "Id": "44284", "ParentId": "36582", "Score": "2" } } ]
{ "AcceptedAnswerId": "36587", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T15:54:09.240", "Id": "36582", "Score": "8", "Tags": [ "javascript", "jquery", "null" ], "Title": "null/undefined checking for checking seats" }
36582
<p>There is a user login, and the requirements are the following:</p> <ul> <li>The login must start with a Latin letter. </li> <li>The login must finish with either a Latin letter or a digit.</li> <li>There may also be digits, dots, and minus signs in the login.</li> <li>Min. login length is 1.</li> <li>Max. login length is 20.</li> </ul> <p>Here is my Java code.</p> <pre><code>boolean checkLogin(String login) { final int maxLength = 20; if (login == null || login.isEmpty() || login.length() &gt; maxLength) { return false; } final Pattern pattern = Pattern.compile("^[a-z][a-z\\d\\.\\-]*[a-z\\d]+$", Pattern.CASE_INSENSITIVE); final Matcher matcher = pattern.matcher(login); return matcher.matches(); } </code></pre> <p>Is everything OK? </p>
[]
[ { "body": "<p>That regex does not meet the requirements of your rules... so ... No, it is not OK.</p>\n\n<p>The missing aspect is that the regex requires at least two characters, but the rules say one char is OK.</p>\n\n<p>Also, I don't like that the last group has the <code>+</code> on it. While it is accurate in the sense that the last characters can be alpha/digit, it implies that the rule is for more than just the last character.</p>\n\n<p>Another problem is that you allow logins of more than 20 characters.</p>\n\n<p>A more meaningful/accurate regex would be:</p>\n\n<pre><code>^[a-z]([a-z\\\\d\\\\.\\\\-]{0,18}[a-z\\\\d])?$\n</code></pre>\n\n<p>Which requires 1 character, and then up to 18 'broad' characters followed by a constrained alpha/digit character.</p>\n\n<p>EDIT:\n2 things:</p>\n\n<ol>\n<li>Aseem has rightly pointed out that the preceding if-condition essentially makes the <code>{0,18}</code> limit redundant. My preference is to keep it there for clarity, but, it does create duplication of logic which may lead to bugs later (How did I miss that the lenght is checked first... hmmm). Your call as to whether you should replace the <code>{0,18}</code> with just <code>{*}</code>.</li>\n<li><p>The Pattern should be made static. There is no reason to re-compile the pattern for every call to the method (Patterns are thread-safe):</p>\n\n<pre><code>private static final Pattern pattern = Pattern.compile(\n \"^[a-z]([a-z\\\\d\\\\.\\\\-]{0,18}[a-z\\\\d])?$\", Pattern.CASE_INSENSITIVE);\n\nprivate static final int maxLength = 20;\n\nboolean checkLogin(String login) {\n\n if (login == null || login.isEmpty() || login.length() &gt; maxLength) {\n return false;\n }\n\n return pattern.matcher(login).matches();\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:04:17.840", "Id": "60072", "Score": "0", "body": "How does it allow logins of more than 20 characters? Isn't that checked in the `if`? Your approach is better but.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:07:00.230", "Id": "60073", "Score": "0", "body": "@AseemBansal - yes, the preceding if condition makes the `{0,18}` redundant... hmmm. The {0,18} can be replaced with `*` but there is a **very** slight performance benefit for the exactly-20 char login if you constrain to 18.... so slight it's not worth considering...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:09:21.227", "Id": "60074", "Score": "0", "body": "@rolfl, Why do use a group in your reply? It could look like this **^[a-z][a-z\\d\\.\\-]{0,18}[a-z\\d]$** I guess that the group makes it work faster" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:09:59.343", "Id": "60075", "Score": "1", "body": "@MaksimDmitriev That makes it minimum 2 characters" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:12:30.693", "Id": "60076", "Score": "0", "body": "@AseemBansal, thanks! **^[a-z][a-z]$** means that there must be at least two characters" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:14:42.887", "Id": "60077", "Score": "1", "body": "@AseemBansal I have edited to add a couple more suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:18:41.817", "Id": "60080", "Score": "0", "body": "It's Aseem with a single **s**. The option to precompile it is good but the reusablity is lost in case same rules are applied but the minimum and maximum length are different. So having the `if` can actually be a good thing. The `Pattern` will be precompiled and you get the option of different bounds on length. Currently the edited code has redundancy for checking length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:18:49.350", "Id": "60081", "Score": "0", "body": "@rolfl, I edited my code. I agree that there is no reason to recompile `Pattern` every time, and `{0,18}` is better than my `if` because it really keeps logic at one place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:20:55.550", "Id": "60082", "Score": "0", "body": "@AseemBansal, the min/max length won't be different; therefore, I can use `{0,18}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:23:51.907", "Id": "60084", "Score": "0", "body": "@MaksimDmitriev It's better to have reusable code. Later if you extended it then making changes later can introduce subtle bugs which can make your life hell. If you leave reuseability out of the picture then your life will be spent debugging code instead of writing code. But it's your code and you know it better than me. I may just be thinking too much :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:26:23.813", "Id": "60085", "Score": "0", "body": "@AseemBansal - to make this code reusable, I would still leave it as a private-stat-final, but make it a call to a method like: `Pattern pattern = MyUtilities.passwordpattern(maxPassLength);` or something." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:55:50.073", "Id": "36593", "ParentId": "36591", "Score": "4" } }, { "body": "<p>A good naming convention for predicates (functions that return a boolean and that have no side-effects) is <code>isBlah()</code>. I would rename the method to <code>isValidLogin()</code>.</p>\n\n<p>If you would like to use a regular expression, then let the regular expression do the hard work. You can even limit the length using the regex. The only thing the regular expression matcher can't handle is a null string.</p>\n\n<p>Compile the pattern just once as a class constant.</p>\n\n<p>Your regex is wrong. Within a character class (i.e., between <code>[…]</code>), the language is different: <code>.</code> is a literal dot. The hyphen is also literal if it comes at the end of the character class. Therefore, no backslashes are necessary. Also, your regex requires at least two characters, though your rules require just one.</p>\n\n<p>Here is how I would write it:</p>\n\n<pre><code>private static final LOGIN_PATTERN =\n Pattern.compile(\"^[a-z](?:[a-z0-9.-]{0,18}[a-z0-9])?$\", Pattern.CASE_INSENSITIVE);\n\nboolean isValidLogin(String login) {\n return (login != null) &amp;&amp; LOGIN_PATTERN.matcher(login).matches();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T19:11:55.840", "Id": "36597", "ParentId": "36591", "Score": "4" } }, { "body": "<p>The regexes</p>\n\n<pre><code>\"^[a-z][a-z\\\\d\\\\.\\\\-]*[a-z\\\\d]+$\"\n</code></pre>\n\n<p></p>\n\n<pre><code>\"^[a-z][a-z0-9.-]*[a-z0-9]$\"\n</code></pre>\n\n<p>are basically the same. True story.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T13:49:33.507", "Id": "36696", "ParentId": "36591", "Score": "0" } } ]
{ "AcceptedAnswerId": "36593", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:35:10.727", "Id": "36591", "Score": "7", "Tags": [ "java", "regex" ], "Title": "A regex in Java. Latin letters, digits, dots, and minus signs" }
36591
<p>I'm rather new to jQuery but managed to get some social links to open in a new controlled window instead of new tab. I have a few functions that do the same thing, and this works, but there is always a better method.</p> <p>I did review the question and answer <a href="https://codereview.stackexchange.com/questions/22976/jquery-two-click-functions-doing-the-same-thing-only-difference-is-the-selecto">here</a> and couldn't figure out which would apply to this case.</p> <pre><code>jQuery(document).ready(function ($) { $("#ssba_facebook_share").attr('title','opens in a new pop-up'); $("#ssba_facebook_share").click(function(){ w = parseInt((screen.width - 600)/2); h = parseInt((screen.height - 400)/2); cwin = window.open($(this).attr('href'), 'closewin', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,height=400,width=600'); cwin.moveTo(w,h); return false; }); $("#ssba_twitter_share").attr('title','opens in a new pop-up'); $("#ssba_twitter_share").click(function(){ w = parseInt((screen.width - 600)/2); h = parseInt((screen.height - 400)/2); cwin = window.open($(this).attr('href'), 'closewin', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,height=400,width=600'); cwin.moveTo(w,h); return false; }); $("#ssba_google_share").attr('title','opens in a new pop-up'); $("#ssba_google_share").click(function(){ w = parseInt((screen.width - 600)/2); h = parseInt((screen.height - 400)/2); cwin = window.open($(this).attr('href'), 'closewin', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,height=400,width=600'); cwin.moveTo(w,h); return false; }); }); </code></pre> <p>Now, I've attempted a few things to no avail, and one method was this:</p> <pre><code>jQuery(document).ready(function ($) { $("#ssba_facebook_share","#ssba_twitter_share","#ssba_google_share").attr('title','opens in a new pop-up'); $(this).click(function(){ w = parseInt((screen.width - 600)/2); h = parseInt((screen.height - 400)/2); cwin = window.open($(this).attr('href'), 'closewin', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,height=400,width=600'); cwin.moveTo(w,h); return false; }); }); </code></pre> <p>Does anyone have any pointers in this, if possible, with a description of where I went wrong? Or even post a link to a question that goes over this in laymen terms? (I've been looking around and found similar posts, which is how I arrived at where I am now, but still having trouble making complete sense of it.)</p>
[]
[ { "body": "<p>First of all, make sure you declare your variables using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var?redirectlocale=en-US&amp;redirectslug=JavaScript/Reference/Statements/var\" rel=\"nofollow\">var</a>:</p>\n\n<blockquote>\n <p>assigning a value to an undeclared variable implicitly declares it as\n a global variable (it is now a property of the global object)</p>\n</blockquote>\n\n<p>Personally, I'd probably add a class to the links in question like <code>shareLink</code> then you could simply do:</p>\n\n<p><code>$(\".shareLink\")</code> to select all three links</p>\n\n<p>Alternately, you could try selecting by id ending in <code>_share</code> assuming that quality is unique to these three links:</p>\n\n<p><code>$(\"[id$='_share']\")</code></p>\n\n<p>I'd also suggest chaining so that your whole code would be something like this:</p>\n\n<pre><code>$(\"[id$='_share']\").click(function(){\n var w = parseInt((screen.width - 600)/2)\n , h = parseInt((screen.height - 400)/2)\n , cwin = window.open($(this).attr('href'), 'closewin',\n 'status=0,toolbar=0,location=0,menubar=0,directories=0,\n resizable=0,scrollbars=0,height=400,width=600');\n cwin.moveTo(w,h);\n return false;\n }).attr('title','opens in a new pop-up');\n</code></pre>\n\n<p>Finally, I'd review the documentation on <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window.open?redirectlocale=en-US&amp;redirectslug=DOM/window.open#Position_and_size_features\" rel=\"nofollow\">Window.open</a> to be sure you don't want to provide <code>left</code> or <code>top</code> parameters, instead of immediately moving the window, or even a different solution. Make sure you at least read the section on <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window.open?redirectlocale=en-US&amp;redirectslug=DOM/window.open#Usability_issues\" rel=\"nofollow\">Usability issues</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T00:28:19.417", "Id": "60114", "Score": "0", "body": "Ah, I wasn't aware I could use attribute selectors like in css (which I'm much more familiar with). so I could have gone with either `id^=ssba_`, `id$=_share`, or `id*=ssba_` / `id*=_share`. The links are generated from a plugin in wordpress, to prevent breaking anything should the plugin update I don't want to edit the actual plugin source files (e.g. no classes). So in this case both \"ssba_\" and \"_share\" are unique to the links generated. I'll definitely read up on 'window.open' and eventually do away with the plugin and build a modal in it's place. But great post, thanks for the insight!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T13:38:56.537", "Id": "60156", "Score": "0", "body": "@darcher Yes, I believe all of those would work. Jquery provides all sorts of [selectors](http://api.jquery.com/category/selectors/) which is part of why it's so popular." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T21:44:57.663", "Id": "36604", "ParentId": "36596", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T18:49:54.717", "Id": "36596", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Opening social media links in a new window" }
36596
<p>I just learned the quicksort algorithm and tried to implement it, but it feels dirty:</p> <pre><code>#include &lt;iostream&gt; void quicksort(int list[], int low, int high) { if(low &gt;= high) return; else { int pivot = low, i = low, j = high; while(i &lt; j) { while(list[i] &lt;= list[pivot] &amp;&amp; i &lt; high) { i++; } while(list[j] &gt; list[pivot] &amp;&amp; j &gt; low) { j--; } if(i &gt; j) break; int temp = list[i]; list[i] = list[j]; list[j] = temp; } int temp = list[pivot]; list[pivot] = list[j]; list[j] = temp; quicksort(list, low, j-1); quicksort(list, j+1, high); } } int main() { int arr[10] = { 12, 2, 24, 32, 5, 1203, 7, 123, 2354, 2 }; quicksort(arr, 0, 9); for(int i = 0; i &lt; 10; i++) { std::cout &lt;&lt; arr[i] &lt;&lt; " "; } } </code></pre> <p>The <code>break</code> condition in the while loop feels really cheap; as if I did something wrong and needed to put it there...</p> <p>What can I improve?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T19:18:08.937", "Id": "60088", "Score": "0", "body": "Is this just C++? The only C here are some of the libraries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T19:19:47.680", "Id": "60089", "Score": "0", "body": "@Jamal Yea, sorry, I had used the C libs to sleep for debugging purposes." } ]
[ { "body": "<p>There are three things I can see which can improve (but this is a far from complete answer... there may be more)..</p>\n\n<ol>\n<li>You can start <code>i</code> at <code>low + 1</code>, which will save you a comparison on each pivot.</li>\n<li>Your <code>i</code> loop should be terminated at <code>i &lt; j</code> and not <code>i &lt; high</code>.</li>\n<li>Your <code>j</code> loop should be terminated at <code>j &gt; i</code> and not <code>j &gt; low</code>.</li>\n</ol>\n\n<p>This should save a bunch of comparisons.....</p>\n\n<p>if the <code>break;</code> looks wrong to you, then you should just reverse the logic:</p>\n\n<pre><code> if(j &gt; i) {\n std::swap(list[i], list[j]);\n }\n</code></pre>\n\n<p>There, much neater!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:12:27.233", "Id": "60095", "Score": "1", "body": "`std::swap(list[i], list[j]);` would make it even neater." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:09:42.650", "Id": "36600", "ParentId": "36598", "Score": "3" } }, { "body": "<ul>\n<li><p>Prefer <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow\"><code>std::size_t</code></a> for the loop. This is especially helpful if an <code>int</code> is not large enough.</p></li>\n<li><p>Prefer to let the compiler determine the array size. It'll also prevent errors if you add/remove elements without changing the size.</p>\n\n<pre><code>int arr[] = { 12, 2, 24, 32, 5, 1203, 7, 123, 2354, 2 };\n</code></pre>\n\n<p>Similar issue here:</p>\n\n<pre><code>quicksort(arr, 0, 9);\n</code></pre>\n\n<p>If you modify your array size without updating the third parameter, you'll run into problems.</p>\n\n<p>If you don't want to bother with this, I'd recommend an STL container such as <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow\"><code>std::vector</code></a>. With that, you can do this:</p>\n\n<pre><code>std::vector&lt;int&gt; origVec = { 12, 2, 24, 32, 5, 1203, 7, 123, 2354, 2 };\n\nstd::vector&lt;int&gt; sortedVec = quicksort(origVec);\n\n// parameters in definition\nstd::vector&lt;int&gt; quicksort(std::vector&lt;int&gt; const&amp; origVec) { }\n</code></pre>\n\n<p>In your function, <code>vec.front()</code> would be your <code>low</code> and <code>vec.back()</code> would be your <code>high</code>. These return values adjust to your vector contents, so you won't have to keep track of size.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:29:16.253", "Id": "36602", "ParentId": "36598", "Score": "2" } }, { "body": "<p>I don't like seeing arrays passed as parameters.</p>\n\n<pre><code>void quicksort(int list[], int low, int high)\n// ^^^^^\n</code></pre>\n\n<p>Inside the function all similarity to an array has disappeared. It has decayed into a pointer. By using the array like syntax you might catch people out that want to treat it as an array (which is a real maintenance issue).</p>\n\n<p>If this code is C then just pass as a pointer.<br>\nIf this code is C++ then pass as a reference to an array, or use a container type and pass by reference (I prefer the container option as you can template it).</p>\n\n<p>In quick pre-condition checks at the head of a function like this.<br>\nThere is no need for the <code>else</code> part.</p>\n\n<pre><code>if(low &gt;= high)\n return;\nelse\n</code></pre>\n\n<p>It looks neater and saves you a level of indentation. </p>\n\n<p>One variable per line.<br>\nAlso give the variables more meaningful names.</p>\n\n<pre><code> int pivot = low, i = low, j = high;\n</code></pre>\n\n<p>Also I would say that pivot is really the value you are pivoting around. Not the location of the value you are pivoting around.</p>\n\n<pre><code> int pivot = list[&lt;location Of Pivot Value&gt;]; // See below for more.\n</code></pre>\n\n<p>Pretty sure there is a bug here <code>i &lt; high</code> is not correct.</p>\n\n<pre><code> while(list[i] &lt;= list[pivot] &amp;&amp; i &lt; high)\n</code></pre>\n\n<p>Same thing here. Pretty sure there is a bug here <code>j &gt; low</code> is not correct.</p>\n\n<pre><code> while(list[j] &gt; list[pivot] &amp;&amp; j &gt; low)\n</code></pre>\n\n<p>Yep. You are correct the break is ugly here.</p>\n\n<pre><code> if(i &lt; j)\n { std::swap(list[i], list[j]);\n }\n</code></pre>\n\n<p>You are only doing this (below) to prevent your self choosing the same pivot point each time. So you should choose a different technique to choose the pivot point. Why not the element in the middle of the list?</p>\n\n<pre><code> int temp = list[pivot];\n list[pivot] = list[j];\n list[j] = temp;\n</code></pre>\n\n<p>You pass the location of the first and last element in the array.</p>\n\n<pre><code> quicksort(list, low, j-1);\n quicksort(list, j+1, high);\n</code></pre>\n\n<p>It is more C++ like to use first and one past the point you consider end. It also makes the code look neater try it and see.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T03:07:50.033", "Id": "60122", "Score": "0", "body": "Why is `i < high` and `j > low` not correct? (This implementation works)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T04:42:45.487", "Id": "60129", "Score": "0", "body": "If its not the first time through the outer loop. Then i could blow past j all the way to high. Even if works it does not make logical sense." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T22:18:16.550", "Id": "36607", "ParentId": "36598", "Score": "5" } } ]
{ "AcceptedAnswerId": "36607", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T19:16:14.637", "Id": "36598", "Score": "3", "Tags": [ "c++", "optimization", "algorithm", "quick-sort" ], "Title": "I feel as if my quicksort can be made more efficient, but what?" }
36598
<p>I'm looking for any and all feedback on quality, style and efficacy of the code. If there's a simple way to get the header put in, I'd love to hear that.</p> <p>The code is used to take zip codes from a csv file and and spit back out the city and state where available.</p> <pre><code>import sys import os import csv from bs4 import BeautifulSoup import requests def main(): pass def getCityState(zipCode): # given zip code, return city and state if available zipCode = str(zipCode) url = "http://www.city-data.com/zips/" + zipCode + ".html" r = requests.get(url) data = r.text soup = BeautifulSoup(data) if soup.findAll(text="City:") ==[]: cityNeeded = soup.findAll(text="Cities:") for t in cityNeeded: return t.find_next('a').string else: cityNeeded = soup.findAll(text="City:") for t in cityNeeded: return t.find_next('a').string def getTableFromCSV(fileName, settings): with open(fileName, settings) as fp: reader = csv.DictReader(fp, skipinitialspace=True) table = [row for row in reader] header = reader.fieldnames return header,table # header and table are lists of dicts def printTable(header, table): # print table in console print"begin printTable" for row in table: print row print"end printTable" def addToList(theList, position, newItem): theList.insert(position, newItem) return theList def addToDict(theDict, newKey, newItem): theDict[newKey] = newItem return theDict def checkZips(table): # check zips and insert the city and town if there is a good zip for row in table: stringNeed = row['zip'] if not stringNeed.isdigit(): # check to see if it's a number row["cityState"] = "zip not number" pass else: if not len(stringNeed) == 5: #check to see if it's 5 digits long row["cityState"] = "zip not 5 digits" else: cityState = getCityState(stringNeed) row["cityState"] = cityState # print row return table if __name__ == '__main__': print"begin main" # get table from csv file header, table = getTableFromCSV("propertyOutputTest.csv","rUbw") # add city, state to header header.insert(0,"cityState") #check zips and insert city and state whree available checkZips(table) # write table to a csv file that replaces the old csv file with open("propertyOutputTest.csv","wb") as fp: writer = csv.DictWriter(fp, header) for row in table: writer.writerow(row) print"end main" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T01:51:03.673", "Id": "60119", "Score": "0", "body": "Just curious from someone in the beginning stages of python, but why pass in your main method but instead put everything inline?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T02:14:05.607", "Id": "60120", "Score": "0", "body": "i'm a n00b too. That was just in the textmate template. No idea why." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T08:35:26.237", "Id": "60138", "Score": "0", "body": "@Phix explained that in my answer." } ]
[ { "body": "<p>First, a few general comments about the 'main function' in Python. The <code>__name__ == '__main__'</code> idiom is a way to distinguish between simply importing a module and launching one. You may want to simply import the module you just wrote to reuse the <code>checkZips</code> function elsewhere, but you don't want the main function to run when doing that.</p>\n\n<p>Some people simply write:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>to run a function called <code>main()</code> when running this module (eg. with <code>python mymodule.py</code>). This is only a convention, the function could be called whatever you want it to be, or you could simply put all the code in the conditional, as you've done here. TextMate provided you with a <code>main()</code> function with a <code>pass</code> statement to specify that it does nothing and avoid a syntax error. Long story short: <strong>remove that main function</strong>!</p>\n\n<pre><code>import sys\nimport os\nimport csv\nfrom bs4 import BeautifulSoup\nimport requests\n</code></pre>\n\n<p>Your module lacks a docstring. It could contain the explanation you gave us. Read more about Python code conventions in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> and docstring conventions <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">PEP 257</a>.</p>\n\n<pre><code>def main():\n pass\n</code></pre>\n\n<p>Remove that, as said earlier.</p>\n\n<pre><code>def getCityState(zipCode):\n# given zip code, return city and state if available\n</code></pre>\n\n<p>This should be a docstring.</p>\n\n<pre><code> zipCode = str(zipCode)\n</code></pre>\n\n<p>Your zip code is already a string, you don't need to convert it first.</p>\n\n<pre><code> url = \"http://www.city-data.com/zips/\" + zipCode + \".html\"\n r = requests.get(url)\n data = r.text\n soup = BeautifulSoup(data)\n</code></pre>\n\n<p>You may not need all those variables, but that's up to you (eg. you could simply write <code>BeautifulSoup(r.text)</code>).</p>\n\n<pre><code> if soup.findAll(text=\"City:\") ==[]:\n</code></pre>\n\n<p>Be careful about indentation and follow PEP8 closely (eg. using a PEP 8 checker). Here you need a space after the <code>==</code>, it makes the whole code easier to read and allows everyone to focus on the important matters.</p>\n\n<pre><code> cityNeeded = soup.findAll(text=\"Cities:\")\n for t in cityNeeded:\n return t.find_next('a').string\n\n else:\n cityNeeded = soup.findAll(text=\"City:\")\n for t in cityNeeded:\n return t.find_next('a').string\n</code></pre>\n\n<p>First, you might want to know about list comprehensions, this can be written as <code>return [t.find_next('a').string for t in cityNeeded]</code>. Second, <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Don't repeat yourself!</a> Having duplicated code increases the likelihood of errors, eg. when you only fix one part. It is easy here, you can simply move the loop out of the conditional. You can also use a regular expression to remove the conditional entirely (untested):</p>\n\n<pre><code>cityNeeded = soup.findAll(text=re.compile(\"City:|Cities:\"))\n</code></pre>\n\n<p>Make sure to <code>import re</code>.</p>\n\n<pre><code>def getTableFromCSV(fileName, settings):\n with open(fileName, settings) as fp:\n reader = csv.DictReader(fp, skipinitialspace=True)\n table = [row for row in reader]\n header = reader.fieldnames\n return header,table # header and table are lists of dicts\n</code></pre>\n\n<p>Nothing much to say here, so I will talk about coding style. :) PEP 8 says that you should write <code>get_table_from_csv</code>. If you don't like it, you don't have to, it's just how most Python coders write code. Second, <code>header,table</code> should be <code>header, table</code>. Third, PEP 8 says you need a double space before inline comments (<code>return header, table # ...</code>). Fourth, this isn't really a comment, and would be a better fit in the docstring. Fifth, about indentation: don't mix tabs and spaces, and no trailing spaces after your lines. (You didn't have any trailing spaces in this function though).</p>\n\n<pre><code>def printTable(header, table):\n# print table in console\n print\"begin printTable\"\n for row in table:\n print row\n print\"end printTable\"\n</code></pre>\n\n<p><code>print</code> is statement in Python 2, but a function in Python 3. I'd advise you to switch to Python 3 since Python 2 will soon be the past of Python, and at least write things such as <code>print(\"end printTable\")</code> to prepare yourself to write Python 3. There are a few major differences and many small differences between the two version, so the earlier you switch, the easier it will be to get acustomed to Python 3.</p>\n\n<p>Also, remove debug prints when you don't need them anymore.</p>\n\n<pre><code>def addToList(theList, position, newItem):\n theList.insert(position, newItem)\n return theList\n\ndef addToDict(theDict, newKey, newItem):\n theDict[newKey] = newItem\n return theDict\n</code></pre>\n\n<p>Come on, you don't need a function for those!</p>\n\n<p>Overall, don't be overwhelmed by my comments. The code is nice, but there a lots of little things to improve. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T13:27:04.570", "Id": "60155", "Score": "0", "body": "To use `print()` in Python 2 is dubious advice: consider for example the output of `print \"a\", \"b\"` vs. `print(\"a\", \"b\")`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T13:48:52.940", "Id": "60157", "Score": "0", "body": "I'd answer `from __future__ import print_function`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T08:35:13.140", "Id": "36626", "ParentId": "36601", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T20:20:54.733", "Id": "36601", "Score": "2", "Tags": [ "python", "csv" ], "Title": "get city and state using zip code, scrape in Python" }
36601
<p>I've just created a winform that exports a datagrid to Excel. Originally the file was never shown, but I was asked to give the option. So I put in a checkbox and modified the code.</p> <p>Is my if/else statement at the end enough or should I go about it a different way?</p> <pre><code>private void buttonExport_Click(object sender, EventArgs e) { try { //copy contents of grid into clipboard, open new instance of excel, a new workbook and sheet, //paste clipboard contents into new sheet. copyGrid(); Microsoft.Office.Interop.Excel.Application xlexcel; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlexcel = new Microsoft.Office.Interop.Excel.Application(); xlexcel.Visible = false; xlWorkBook = xlexcel.Workbooks.Add(misValue); xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1]; CR.Select(); xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true); xlWorkBook.SaveAs("C:\\Temp\\ItemUpdate.xls", Excel.XlFileFormat.xlExcel5); MessageBox.Show("File Save Successfull", "Information", MessageBoxButtons.OK); //If box is checked, show the exported file. Otherwise quit Excel. if (checkBox1.Checked == true) { xlexcel.Visible = true; } else { xlexcel.Quit(); } } catch (SystemException ex) { MessageBox.Show(ex.ToString()); } //set the Selection Mode back to Cell Select to avoid conflict with sorting mode dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect; </code></pre>
[]
[ { "body": "<p>Yes, I'd say the <code>if..else</code> is enough, but it's a little wordy. <code>Button.Checked</code> is already a <code>Boolean</code> value, so comparing it to <code>true</code> is superfluous. There's also a lot of shortening of code you can do with the judicious use of <code>using</code> directives. Also, I had to do some fancy dancing to make sure Excel itself is truly shut down when it needs to be. Give this a look-see and let me know what you think:</p>\n\n<pre><code>namespace WindowsFormsApplication1\n{\n using System;\n using System.IO;\n using System.Reflection;\n using System.Runtime.InteropServices;\n using System.Windows.Forms;\n\n using Microsoft.Office.Interop.Excel;\n\n using Application = Microsoft.Office.Interop.Excel.Application;\n\n public partial class Form1 : Form\n {\n private Application xlExcel;\n\n private Workbook xlWorkBook;\n\n public Form1()\n {\n this.InitializeComponent();\n }\n\n private void btnExport_Click(object sender, EventArgs e)\n {\n try\n {\n this.QuitExcel();\n this.xlExcel = new Application { Visible = false };\n this.xlWorkBook = this.xlExcel.Workbooks.Add(Missing.Value);\n\n // Copy contents of grid into clipboard, open new instance of excel, a new workbook and sheet,\n // paste clipboard contents into new sheet.\n this.CopyGrid();\n\n var xlWorkSheet = (Worksheet)this.xlWorkBook.Worksheets.Item[1];\n\n try\n {\n var cr = (Range)xlWorkSheet.Cells[1, 1];\n\n try\n {\n cr.Select();\n xlWorkSheet.PasteSpecial(cr, NoHTMLFormatting: true);\n }\n finally\n {\n Marshal.ReleaseComObject(cr);\n }\n\n this.xlWorkBook.SaveAs(Path.Combine(Path.GetTempPath(), \"ItemUpdate.xls\"), XlFileFormat.xlExcel5);\n }\n finally\n {\n Marshal.ReleaseComObject(xlWorkSheet);\n }\n\n MessageBox.Show(\"File Save Successful\", \"Information\", MessageBoxButtons.OK);\n\n // If box is checked, show the exported file. Otherwise quit Excel.\n if (this.checkBox1.Checked)\n {\n this.xlExcel.Visible = true;\n }\n else\n {\n this.QuitExcel();\n }\n }\n catch (SystemException ex)\n {\n MessageBox.Show(ex.ToString());\n }\n\n // Set the Selection Mode back to Cell Select to avoid conflict with sorting mode.\n this.dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;\n }\n\n private void Form1_FormClosed(object sender, FormClosedEventArgs e)\n {\n this.QuitExcel();\n }\n\n private void QuitExcel()\n {\n if (this.xlWorkBook != null)\n {\n try\n {\n this.xlWorkBook.Close();\n Marshal.ReleaseComObject(this.xlWorkBook);\n }\n catch (COMException)\n {\n }\n\n this.xlWorkBook = null;\n }\n\n if (this.xlExcel != null)\n {\n try\n {\n this.xlExcel.Quit();\n Marshal.ReleaseComObject(this.xlExcel);\n }\n catch (COMException)\n {\n }\n\n this.xlExcel = null;\n }\n }\n\n private void CopyGrid()\n {\n // I'm making this up...\n this.dataGridView1.SelectAll();\n\n var data = this.dataGridView1.GetClipboardContent();\n\n if (data != null)\n {\n Clipboard.SetDataObject(data, true);\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T14:44:57.387", "Id": "60166", "Score": "0", "body": "thank you VERY much! This is what I was looking for. I'm still fairly new to programming and self-taught. While I can make a lot of things \"work\", I'm trying to become more efficient and \"clean\" in my coding." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T23:20:20.467", "Id": "36609", "ParentId": "36605", "Score": "3" } }, { "body": "<p>You may want to consider writing to a CSV instead. It's a lot simpler and doesn't rely on the MS office interop. On the other hand you don't get an XLS file and you can't do formatting... Here is a standard chunk of code I wrote for DataTable to CSV conversion. Hope it helps!</p>\n\n<pre><code>public static void SaveToCSV(string filePath, DataTable table)\n{\n StringBuilder builderFile = new StringBuilder();\n StringBuilder builderRow = new StringBuilder();\n\n //First build the column headers\n for (int colIndex = 0; colIndex &lt; table.Columns.Count; colIndex++)\n {\n builderRow.Append(string.Format(\"\\\"{0}\\\"\", table.Columns[colIndex].ColumnName.Replace(\"\\\"\", \"\\\"\\\"\")));\n\n //Add a comma delimiter if it is not the last column\n if (colIndex &lt; table.Columns.Count - 1)\n builderRow.Append(\",\");\n }\n\n //Append the column headers to the main file\n builderFile.AppendLine(builderRow.ToString());\n\n for (int rowIndex = 0; rowIndex &lt; table.Rows.Count; rowIndex++)\n {\n builderRow.Clear();\n\n //Add all the items of the row\n for (int colIndex = 0; colIndex &lt; table.Columns.Count; colIndex++)\n {\n builderRow.Append(string.Format(\"\\\"{0}\\\"\", table.Rows[rowIndex][colIndex].ToString().Replace(\"\\\"\", \"\\\"\\\"\")));\n\n //Add a comma delimiter if it is not the last column\n if (colIndex &lt; table.Columns.Count - 1)\n builderRow.Append(\",\");\n }\n\n //Append this row to the main file\n builderFile.AppendLine(builderRow.ToString());\n }\n\n //Write the file\n File.WriteAllText(filePath, builderFile.ToString());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T14:46:40.360", "Id": "60167", "Score": "0", "body": "Thanks for your help. Unfortunately I have to use Excel as the exported sheet later is used in an import procedure to our accounting software. But it is a good example that may come in handy for other applications!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T07:14:32.653", "Id": "36624", "ParentId": "36605", "Score": "0" } } ]
{ "AcceptedAnswerId": "36609", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T22:06:23.247", "Id": "36605", "Score": "5", "Tags": [ "c#", "winforms", "excel" ], "Title": "Winform that exports a datagrid to Excel" }
36605
<p>I've written a code snippet that will get a (max.) 14 character string from the user input, and while the user is typing, simultaneously echo it out to the screen.</p> <p>It seems a bit long and ugly, so I was wondering if any of you would happen to have ideas on how to shorten, and generally optimize this.</p> <pre><code>for(int i = 0; i &lt; 15; i++) { char npt = _getch(); // Get input if(i == 14) // Last character (user has to press \r or \b) { if(npt == '\r') // enter, break loop break; else if(npt == '\b') // backspace, re-loop { if(!name.empty()) name.erase(std::prev(name.end())); if(i &gt;= 1) i -= 2; else i--; } else // other input, meaning re-loop i--; SetConsoleCursorPosition(hOut, cDraw); printf(" "); // clear string area SetConsoleCursorPosition(hOut, cDraw); std::cout &lt;&lt; name; // echo string continue; } else { if(npt == '\r') break; else if(npt == '\b') { if(!name.empty()) name.erase(std::prev(name.end())); if(i &gt;= 1) i -= 2; else i--; } else name += npt; // add input to string SetConsoleCursorPosition(hOut, cDraw); printf(" "); SetConsoleCursorPosition(hOut, cDraw); std::cout &lt;&lt; name; } } </code></pre>
[]
[ { "body": "<p>c++ isn't really my language, but I believe this would be an identical loop:</p>\n\n<pre><code>for(int i = 0; i &lt; 15; i++)\n{\n char npt = _getch(); // Get input\n\n if(npt == '\\r')\n break;\n else if(npt == '\\b')\n {\n if(!name.empty())\n name.erase(std::prev(name.end()));\n if(i &gt;= 1)\n i -= 2;\n else\n i--;\n }\n else if(i == 14)\n i--;\n else \n name += npt; // add input to string\n\n SetConsoleCursorPosition(hOut, cDraw);\n printf(\" \");\n SetConsoleCursorPosition(hOut, cDraw);\n std::cout &lt;&lt; name;\n}\n</code></pre>\n\n<p>The only difference between your first <code>if</code> and the <code>else</code> is the final <code>else</code> line, so I moved the conditional to the end to avoid repeating the same logic.</p>\n\n<p>Additionally, I assume there's some way you could pad <code>name</code> with blank spaces so that you only have to call <code>SetConsoleCursorPosition</code> and print once per iteration.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:11:47.280", "Id": "60258", "Score": "0", "body": "Hey, that's a really good answer! I'll accept it in a minute. Meanwhile, would you have an idea on how to efficiently do the `name` padding?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T00:23:25.323", "Id": "60265", "Score": "0", "body": "I don't know. But [this page](http://www.cplusplus.com/forum/general/15952/) seems to provide a possible method. You might ask on StackOverflow if you're unable to find a way after searching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T00:32:32.653", "Id": "60267", "Score": "0", "body": "Ok, I'll search around for an answer. Thanks, man." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T14:51:38.777", "Id": "36641", "ParentId": "36606", "Score": "1" } } ]
{ "AcceptedAnswerId": "36641", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T22:14:49.757", "Id": "36606", "Score": "1", "Tags": [ "c++", "strings", "windows", "console" ], "Title": "Getting limited user input, with echo" }
36606
<p>This is probably horribly sloppy, but here it is! This is a section from a large (imo) GUI program I am making. The below code is what triggers when a specific button is pressed. </p> <pre><code> def calc_platenumber(self): customer_firstname = str(self.customer2_entry.get()) customer_lastname = str(self.customer3_entry.get()) infile = open('license_numbers.txt', 'r') license_numbers = infile.readlines() infile.close() self.platenmb = random.choice(license_numbers) self.platenumber.set(self.platenmb) license_numbers.remove(self.platenmb) outfile = open('license_numbers.txt', 'w') for item in license_numbers: outfile.write(item) outfile.close() infile = open('used_license_numbers.txt', 'r') used_license_numbers = infile.readlines() infile.close() used_license_numbers.append(self.platenmb) used_license_numbers.append(customer_firstname) used_license_numbers.append(customer_lastname) outfile = open('used_license_numbers.txt', 'w') for item in used_license_numbers: outfile.write(item) outfile.close() </code></pre> <p>So, I have a GUI that asks for the first name and last name of the person. There is a generate button below that. The generate button will take a random license number from a large list of available numbers, remove it from that list, and then add it to a list of "used" license numbers. That is the function you see here. When it adds it to this second list, I want it to also take their name and add it as well. I have made it do that.</p> <p>Problem is, whenever it adds it, it looks sloppy. No spaces or anything. I would rather it add on like...</p> <pre><code>Tim Bob C565213 </code></pre> <p>And then whenever the next person uses the program, the file is updated to say...</p> <pre><code>Tim Bob C565213 Jim Bean 1234F324 </code></pre> <p>...And so on. Currently it just looks sloppy, and even if sloppy won't matter (this is just a school project), it is going to bother me. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T23:15:22.760", "Id": "60109", "Score": "1", "body": "Clean code is good just for the habit of writing clean code." } ]
[ { "body": "<p>You're opening the files more than once like:</p>\n\n<pre><code>infile = open('used_license_numbers.txt', 'r')\nused_license_numbers = infile.readlines()\ninfile.close()\n</code></pre>\n\n<p>Instead write it like this:</p>\n\n<pre><code>with open('used_license_numbers.txt', 'r') as infile:\n used_license_numbers = infile.readlines()\n</code></pre>\n\n<p><em>(python 2.6 +)</em></p>\n\n<p>Also you're opening the same file twice, once for reading and once for writing. Could you open it for both reading and writing? </p>\n\n<pre><code>open('used_license_numbers.txt', 'r+')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T23:27:52.573", "Id": "36610", "ParentId": "36608", "Score": "4" } }, { "body": "<p>You could do a better job describing the task; the task description should be a docstring. I would also rename the function to <code>select_platenumber()</code>, since it's not really calculating anything.</p>\n\n<p>If you're using plain text files as a database, watch out for race conditions. Unless you implement some kind of locking mechanism, you could easily end up with corrupted files.</p>\n\n<p>As @JamesKhoury says, you should only have to open each file once, using a <code>with</code> block. Use the appropriate mode: you only need to append to the output file. For the input file, you can truncate and overwrite it.</p>\n\n<p>For efficiency, I prefer to select a random array index rather than a random array element. Selecting a random element is more readable, but to remove that element involves a linear search through the list.</p>\n\n<p>I think it would be safer to write the <code>used_license_numbers.txt</code> entry before overwriting <code>license_numbers.txt</code>, in case of an I/O error. (You could have inconsistent data, but at least you would be less likely to <em>lose</em> data.)</p>\n\n<p>Having similarly variables <code>self.platenmb</code> and <code>self.platenumber</code> is confusing.</p>\n\n<pre><code>def select_platenumber(self):\n \"\"\"Selects and removes a random line from license_numbers.txt as the\n license plate, and appends a line to used_license_numbers.txt\n recording the license plate and customer name.\n \"\"\"\n firstname = str(self.customer2_entry.get())\n lastname = str(self.customer3_entry.get())\n\n with open('license_numbers.txt', 'r+') as in_file, \\\n open('used_license_numbers.txt', 'a') as out_file:\n plates = in_file.readlines()\n self.platenmb = plates.pop(random.randrange(len(plates))).rstrip()\n self.platenumber.set(self.platenmb)\n\n out_file.write('%-19s %s %s\\n' % (plate, firstname, lastname))\n\n in_file.truncate(0)\n in_file.writelines(plates)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T01:16:40.587", "Id": "60271", "Score": "0", "body": "If you don't want to use the format strings, you can also use the string functions ljust, rjust and center to pad you coluns in the output http://docs.python.org/2/library/string.html" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T00:42:30.877", "Id": "36613", "ParentId": "36608", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T22:42:45.700", "Id": "36608", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Copying data to a .txt, but making it look nice?" }
36608
<p>One of my colleagues told me that you can use <code>streambuffer</code> for <code>std::string</code>, and instead of using <code>string id</code> in the <code>for</code> loop, you can declare it outside.</p> <p>I am not sure whether this will make any difference or not.</p> <pre><code>void getRecord(uint64_t currentTime, const std::vector&lt;uint32_t&gt; &amp;shards) { try { currentTime = (currentTime / 1000) * 1000; uint64_t start = (currentTime / (60 * 60 * 1000 * 24)) % 3; string query; Cassandra::Result result; std::string base(boost::lexical_cast&lt;std::string&gt;(currentTime) + "."); for (std::vector&lt;uint32_t&gt;::const_iterator it = shards.begin() ; it != shards.end(); ++it) { string id = base + boost::lexical_cast&lt;std::string&gt;(*it); // use stream buffer query = "select name, value from keyspace.hour_"+boost::lexical_cast&lt;std::string&gt;(start)+" where id ='"+id+"';"; result = Cassandra::execute_query(query); } } } </code></pre> <p>I am coming from a Java background, so I'm not sure which one will be more efficient compared to the other, as C++ is all about memory allocation. Is there any way to optimize the above code, even slightly?</p> <p>For me what I am trying to optimize is the other part leaving Cassandra query part as it is. I know there might be few minimal optimization that I am supposed to make but if it is worth doing it, then I might do it now then later figuring it out.</p> <p>Below is my full code. Again, I am mainly worried about my other string manipulation instead of Cassandra query part - I have removed some extra code which was not needed.</p> <pre><code>void getData(uint64_t currentTime, const std::vector&lt;uint32_t&gt; &amp;shards) { uint16_t id; uint64_t lmd; uint32_t length; const char* binary_value; string column_key; string bt; uint64_t user_id; string colo; bool flag = false; try { currentTime = (currentTime / 1000) * 1000; uint64_t start = (currentTime / (60 * 60 * 1000 * 24)) % 3; string query; Cassandra::Result result; std::string base(boost::lexical_cast&lt;std::string&gt;(currentTime) + "."); for (std::vector&lt;uint32_t&gt;::const_iterator it = shards.begin() ; it != shards.end(); ++it) { string id = base + boost::lexical_cast&lt;std::string&gt;(*it); // use stream buffer query = "select name, value from keyspace.hour_"+boost::lexical_cast&lt;std::string&gt;(start)+" where id ='"+id+"';"; result = Cassandra::execute_query(query); while (result &amp;&amp; result.value()-&gt;next()) { char* key = 0; for (size_t i = 0; i &lt; result.value()-&gt;column_count(); ++i) { cql::cql_byte_t* data = NULL; cql::cql_int_t size = 0; result.value()-&gt;get_data(i, &amp;data, size); if (!flag) { key = reinterpret_cast&lt;char*&gt;(data); flag = true; } else { int index=0; id = Mgr::get_uint16((&amp;data[index])); index += 2; lmd = Mgr::get_uint64((&amp;data[index])); index += 8; length = Mgr::get_uint32((&amp;data[index])); index += 4; binary_value = reinterpret_cast&lt;const char *&gt;(&amp;data[index]); flag = false; } } if(key) { vector&lt;string&gt; res; char* p; char* totken = strtok_r(key, ".", &amp;p); while(totken != NULL) { res.push_back(totken); totken = strtok_r(NULL, ".", &amp;p); } column_key= res[0]; bt= res[1]; user_id= atoi(res[2].c_str()); colo = res[3]; } } } } catch (const std::exception&amp; ex) { } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T05:14:03.587", "Id": "60132", "Score": "1", "body": "I would not care about optimizing the string code (write it in the most easy way to read and thus maintain). Be far the slowest part of that code is the line: `Cassandra::execute_query(query);` by many orders of magnitude." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T08:39:08.720", "Id": "60139", "Score": "0", "body": "I'd be more worried about sql injection (granted you fully control what can go in here but this is a bad sign for other parts of the code), does Cassandra have parameterized queries?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:09:38.193", "Id": "60217", "Score": "0", "body": "For me what I am trying to optimize is the other part leaving Cassandra query part as it is.. \nI know there might be few minimal optimization that I am supposed to make but if it is worth doing it, then I might do it now then later figuring it out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:14:30.490", "Id": "60219", "Score": "0", "body": "In that case, you really need to update your question to show what it's really doing. Right now your method **does nothing** (it does a lot of work and **it throws it all away**) and the entire method can be removed...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:24:27.627", "Id": "60220", "Score": "0", "body": "Updated the question with details.." } ]
[ { "body": "<p>This looks like incomplete code to me.... what do you do with <code>result</code> once you have it?</p>\n\n<p>Still, I look at what your code does, and can't help but think your priorities are wrong in this instance.....</p>\n\n<p>sure, <code>streambuffer</code> may hypothetically be faster than your String manipulation, but, really, <strong>who cares?</strong> (<strong>Note:</strong> I say 'who cares' from the context of the work you are doing).</p>\n\n<p>Running any database query is going to take much, much longer than the string concatenation operations you are doing.....</p>\n\n<p>When Cassandra gets your query, it is going to strip it down to components, analyze them for validity, relate them to database structures, optimize the query to use the best possible access plans, and then execute the query....</p>\n\n<p>I would guess that the work you are doing in <strong>your</strong> method is probably 'orders of magnitude' less than what Cassandra is going to do...</p>\n\n<p>In this instance, for your code specifically, I would recommend that you use the most readable and maintainable mechanisms. If you want to use <code>streambuffer</code>s then do it, but whatever you do the motivation should not, in this case, be because of performance.</p>\n\n<p>Read up on <a href=\"http://en.wikipedia.org/wiki/Amdahl%27s_law\">Amdahl's Law</a> ... ;-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:10:57.747", "Id": "60218", "Score": "0", "body": "For me what I am trying to optimize is the other part leaving Cassandra query part as it is.. I know there might be few minimal optimization that I am supposed to make but if it is worth doing it, then I might do it now then later figuring it out such as the way I am doing for string manipulation and other minor things if any.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T20:40:15.263", "Id": "60222", "Score": "0", "body": "I have updated the question with more details..!!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T03:30:11.767", "Id": "36618", "ParentId": "36614", "Score": "6" } } ]
{ "AcceptedAnswerId": "36618", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T00:47:58.650", "Id": "36614", "Score": "4", "Tags": [ "c++", "optimization", "strings" ], "Title": "Streambuffer and string manipulation" }
36614
<p>I am developing a WPF application that requires me to get an Access Token from <a href="https://developers.facebook.com/docs/reference/dialogs/oauth/" rel="nofollow" title="Facebook Login Dialog">Facebook using oAuth</a>. After much searching online, I came to the following conclusions:</p> <ol> <li>OAuth must be done in a browser</li> <li>I need to watch the URL posts in that browser, therefore it would have to be inside a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser%28v=vs.110%29.aspx" rel="nofollow" title="MSDN : WebBrowser">WebBrowser</a> WPF control</li> </ol> <p>I decided to create a Modal Dialog for doing the Facebook authentication, and I can just take the Access Token and ignore the rest. I wanted to keep to the MVVM model but it was more difficult than I anticipated. <em>Any ideas on how to do that would be very helpful</em></p> <p>Here are some features that I implemented</p> <ul> <li><strong>Cookie deletion</strong> so I could have another user authenticate without needing to log the current user out</li> <li><strong>Disable new account creation</strong> since it led to a weird UI experience</li> <li><strong>Listening to the cancel button</strong> from the javascript generated by Facebook</li> </ul> <p><strong>The WPF Window</strong></p> <p>The WPF is very simple. In essence it is just a WebBrowser control with the Navigated and Navigating events hooked up.</p> <pre class="lang-xml prettyprint-override"><code>&lt;Window x:Class="FacebookAuthenticator.FacebookAuthenticationWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Authenticate Facebook" Height="600" Width="600" ResizeMode="NoResize" WindowStyle="ToolWindow"&gt; &lt;Grid&gt; &lt;WebBrowser Name="webBrowser" Navigated="webBrowser_Navigated" Navigating="webBrowser_Navigating" /&gt; &lt;/Grid&gt; </code></pre> <p></p> <hr> <pre class="lang-java prettyprint-override"><code>//The Application ID from Facebook public string AppID {get; set; } //The access token retrieved from facebook's authentication public string AccessToken {get; set; } public FacebookAuthenticationWindow() { InitializeComponent(); this.Loaded += (object sender, RoutedEventArgs e) =&gt; { //Add the message hook in the code behind since I got a weird bug when trying to do it in the XAML webBrowser.MessageHook += webBrowser_MessageHook; //Delete the cookies since the last authentication DeleteFacebookCookie(); //Create the destination URL var destinationURL = String.Format("https://www.facebook.com/dialog/oauth?client_id={0}&amp;scope={1}&amp;display=popup&amp;redirect_uri=http://www.facebook.com/connect/login_success.html&amp;response_type=token", AppID, //client_id "email,user_birthday" //scope ); webBrowser.Navigate(destinationURL); }; } </code></pre> <p><strong>Getting the Access Token</strong></p> <p>I forgot exactly where I got this code (if someone can remind me so that I could give proper credit I would be grateful).</p> <pre class="lang-java prettyprint-override"><code>private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { //If the URL has an access_token, grab it and walk away... var url = e.Uri.Fragment; if (url.Contains("access_token") &amp;&amp; url.Contains("#")) { url = (new System.Text.RegularExpressions.Regex("#")).Replace(url, "?", 1); AccessToken = System.Web.HttpUtility.ParseQueryString(url).Get("access_token"); DialogResult = true; this.Close(); } } </code></pre> <p><strong>Deleting Cookies</strong></p> <p>I realized that after someone logged in, there status stayed that way and would not allow someone else to log in. I decided to remove the cookies in the beginning of each authentication in order to prevent this.</p> <pre class="lang-java prettyprint-override"><code>private void DeleteFacebookCookie() { //Set the current user cookie to have expired yesterday string cookie = String.Format("c_user=; expires={0:R}; path=/; domain=.facebook.com", DateTime.UtcNow.AddDays(-1).ToString("R")); Application.SetCookie(new Uri("https://www.facebook.com"), cookie); } </code></pre> <p><strong>No New Accounts</strong></p> <p>Allowing the user to create a new account led to a weird UI experience. For my use cases, the user should already have an exsiting account. I disabled this by checking if the user was redirected to "r.php/" which is what Facebook uses to create a new account.</p> <pre class="lang-java prettyprint-override"><code>private void webBrowser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e) { if (e.Uri.LocalPath == "/r.php") { MessageBox.Show("To create a new account go to www.facebook.com", "Could Not Create Account", MessageBoxButton.OK, MessageBoxImage.Error); e.Cancel = true; } } </code></pre> <p><strong>Handling <code>window.close()</code></strong></p> <p>The cancel button in Facebook's dialog shows the ability to close the window. I needed to catch this and make sure to close the window. I had no idea how but I saw that in the MessageHook I was able to see that the last message to be sent (int msg) each time was 130, so I just listened for 130. It's sloppy, but it works.</p> <pre class="lang-java prettyprint-override"><code>IntPtr webBrowser_MessageHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { //msg = 130 is the last call for when the window gets closed on a window.close() in javascript if (msg == 130) { this.Close(); } return IntPtr.Zero; } </code></pre> <p><strong>Summary</strong></p> <p>Using the code is pretty simple:</p> <pre class="lang-java prettyprint-override"><code>FacebookAuthenticationWindow dialog = new FacebookAuthenticationWindow() { AppID = "YOURAPPID" }; if(dialog.ShowDialog() == true) { string accessToken = dialog.AccessToken; //The world is your oyster } </code></pre>
[]
[ { "body": "<p>I don't know much about Facebook or OAuth, so I'm not going to comment on that.</p>\n\n<ol>\n<li><pre><code>this.Loaded += (object sender, RoutedEventArgs e) =&gt;\n</code></pre>\n\n<p>When you have a lambda that's this long, it's usually better to write it as a normal method. And when you do that, then you could also wire the event from XAML.</p></li>\n<li><pre><code>System.Windows.Navigation.NavigationEventArgs\nSystem.Text.RegularExpressions.Regex\nSystem.Web.HttpUtility.ParseQueryString\n</code></pre>\n\n<p>Add those namespaces as <code>using</code>s at the top of your file, so that you don't have to repeat them.</p></li>\n<li><pre><code>var url = e.Uri.Fragment;\nif (url.Contains(\"access_token\") &amp;&amp; url.Contains(\"#\"))\n{\n url = (new System.Text.RegularExpressions.Regex(\"#\")).Replace(url, \"?\", 1);\n AccessToken = System.Web.HttpUtility.ParseQueryString(url).Get(\"access_token\");\n</code></pre>\n\n<p>This code is confusing (the variable <code>url</code> doesn't actually contain the whole url) and, if I understand it correctly, overcomplicated. First, <code>ParseQueryString()</code> doesn't require the leading <code>?</code>. Second, if <code>Fragment</code> is not empty, it will always start with <code>#</code>. Together, this means you could just use <code>Remove(0, 1)</code>, no need for <code>Replace()</code> and certainly no need to use regular expressions:</p>\n\n<pre><code>var urlFragment = e.Uri.Fragment;\nif (urlFragment.Contains(\"access_token\"))\n{\n var queryString = urlFragment.Remove(0, 1); // remove leading #\n AccessToken = HttpUtility.ParseQueryString(queryString).Get(\"access_token\");\n</code></pre></li>\n<li><blockquote>\n <p>I was able to see that the last message to be sent (int msg) each time was 130</p>\n</blockquote>\n\n<p>That seems to be the code for <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms632636\" rel=\"nofollow\"><code>WM_NCDESTROY</code></a>.</p></li>\n<li><pre><code>new FacebookAuthenticationWindow() { AppID = \"YOURAPPID\" }\n</code></pre>\n\n<p>Since <code>AppID</code> is required, it should be a constructor parameter.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T14:11:55.623", "Id": "60162", "Score": "0", "body": "WM_NCDESTROY - AWESOME!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T13:41:26.240", "Id": "36639", "ParentId": "36623", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T07:02:30.093", "Id": "36623", "Score": "2", "Tags": [ "c#", "wpf", "facebook", "oauth" ], "Title": "Facebook OAuth in WPF" }
36623
<p>I would like to develop a kind of template or canonical implementation for a concurrent subclass of <code>NSOperation</code>.</p> <p><strong>Edit:</strong> there is a related request which implements the <a href="https://codereview.stackexchange.com/questions/107659/canonical-implementation-for-a-concurrent-subclass-of-nsoperation-in-swift-2">NSOperation subclass in Swift</a>.</p> <h3>Requirements:</h3> <ul> <li>Thread safe API.</li> <li><code>start</code> shall only start the task once, otherwise it has no effect.</li> <li>The NSOperation object shall be immortal while the task is executing.</li> </ul> <h3>References:</h3> <p><a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html" rel="noreferrer">https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html</a></p> <hr /> <h3>Solution</h3> <p>So far, I came up with this solution:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; /** Canonical, Concurrent Subclass of NSOperation */ typedef void (^completion_block_t)(id result); @interface MyOperation : NSOperation // Designated Initializer // For the sake of testing, parameter count equals the duration in 1/10 seconds until the task is fininshed. - (id)initWithCount:(int)count completion:(completion_block_t)completioHandler; @property (nonatomic, readonly) id result; @property (nonatomic, copy) completion_block_t completionHandler; @end @implementation MyOperation { BOOL _isExecuting; BOOL _isFinished; dispatch_queue_t _syncQueue; int _count; id _result; completion_block_t _completionHandler; id _self; // immortality } - (id)initWithCount:(int)count completion:(completion_block_t)completionHandler { self = [super init]; if (self) { _count = count; _syncQueue = dispatch_queue_create(&quot;op.sync_queue&quot;, NULL); _completionHandler = [completionHandler copy]; } return self; } - (id) result { __block id result; dispatch_sync(_syncQueue, ^{ result = _result; }); return result; } - (void) start { dispatch_async(_syncQueue, ^{ if (!self.isCancelled &amp;&amp; !_isFinished &amp;&amp; !_isExecuting) { self.isExecuting = YES; _self = self; // make self immortal for the duration of the task dispatch_async(dispatch_get_global_queue(0, 0), ^{ // Simulated work load: int count = _count; while (count &gt; 0) { if (self.isCancelled) { break; } printf(&quot;.&quot;); usleep(100*1000); --count; } // Set result and terminate dispatch_async(_syncQueue, ^{ if (_result == nil &amp;&amp; count == 0) { _result = @&quot;OK&quot;; } [self terminate]; }); }); } }); } - (void) terminate { self.isExecuting = NO; self.isFinished = YES; completion_block_t completionHandler = _completionHandler; _completionHandler = nil; id result = _result; _self = nil; if (completionHandler) { dispatch_async(dispatch_get_global_queue(0, 0), ^{ completionHandler(result); }); } } - (BOOL) isConcurrent { return YES; } - (BOOL) isExecuting { return _isExecuting; } - (void) setIsExecuting:(BOOL)isExecuting { if (_isExecuting != isExecuting) { [self willChangeValueForKey:@&quot;isExecuting&quot;]; _isExecuting = isExecuting; [self didChangeValueForKey:@&quot;isExecuting&quot;]; } } - (BOOL) isFinished { return _isFinished; } - (void) setIsFinished:(BOOL)isFinished { if (_isFinished != isFinished) { [self willChangeValueForKey:@&quot;isFinished&quot;]; _isFinished = isFinished; [self didChangeValueForKey:@&quot;isFinished&quot;]; } } - (void) cancel { dispatch_async(_syncQueue, ^{ if (_result == nil) { NSLog(@&quot;Operation cancelled&quot;); [super cancel]; _result = [[NSError alloc] initWithDomain:@&quot;MyOperation&quot; code:-1000 userInfo:@{NSLocalizedDescriptionKey: @&quot;cancelled&quot;}]; } }); } @end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T12:23:20.880", "Id": "60146", "Score": "0", "body": "Are you satisfied that your code is working? Are there problems you need to resolve or is the code ready for a review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T12:36:12.640", "Id": "60148", "Score": "0", "body": "I'm quite confident that there are no obvious errors. But thread-safity is tricky. So I would appreciate it if you or anybody else can take a look and possibly spot potential issues. ;) E.g.: dead locks, due to dispatch lib, circular references, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T21:28:53.230", "Id": "64476", "Score": "1", "body": "Why aren't you dispatching on to `_syncQueue` for `terminate` and the setters & getters for `isExecuting` and `isFinished`? I guess it doesn't matter for `terminate`, since only you access that, but `isExecuting` and `isFinished` could be accessed by a developer from any thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T11:03:57.003", "Id": "64692", "Score": "0", "body": "@AaronBrager It's guaranteed by the implementation that `terminate` will be executed on the `_syncQueue`. For properties `isExecuting` and `isFinished`, IMHO synchronization and memory barriers are not required: both are boolean values which are initially set to zero. Any access might return either zero or a non-zero value - which is the value of the corresponding memory location (no register). When a `NO` is returned, its value MUST be treated immediately stale, anyway. It's also guaranteed that the value of the memory location will be eventually set and never changes subsequently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T15:34:24.597", "Id": "64710", "Score": "0", "body": "@CouchDeveloper That makes sense. I can find no issues with your implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T06:45:46.137", "Id": "84440", "Score": "0", "body": "@CouchDeveloper Shouldn't the `cancel` method set `_isFinished` to `YES` and `_isExecuting ` to `NO` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-25T06:51:35.683", "Id": "84441", "Score": "0", "body": "Specifically, you must change the value returned by isFinished to YES and the value returned by isExecuting to NO. You must make these changes even if the operation was cancelled before it started executing.\n\nhttps://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T11:08:38.320", "Id": "98992", "Score": "0", "body": "@Jonas Quite late - but yes you are right. I changed the example implementation such that `terminate` will be called even when the operation has been cancelled before it has been started. This ensures that the completion handler will be called in any case, and the operation has proper states." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T13:40:45.183", "Id": "99003", "Score": "2", "body": "@CouchDeveloper: Please read: [What you can and cannot do after receiving answers](http://meta.codereview.stackexchange.com/a/1765) to understand what edits can make sense when there are answers to your questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-16T14:15:29.730", "Id": "102111", "Score": "0", "body": "Whether or not this is a problem depends on the semantics you've defined for your NSOperation implementation, but your `executing` and `finished` properties can be in an inconsistent state with respect to each other. In other words, you aren't setting `finished` to YES and `executing` to NO atomically." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-09T21:00:46.997", "Id": "131949", "Score": "0", "body": "Another latecomer. But why this requirement? \"start shall only start the task once, otherwise it has no effect.\". NSOperation documentation specifically states that they are one-shot so calling start twice on an NSOperation instance is a programmer error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-09T21:07:49.280", "Id": "131952", "Score": "0", "body": "@JeremyWiebe If it's a programmer error, how should the implementation deal with this? Perhaps with an `assert`, or throwing an exception or doing nothing? Of course, this is debatable. IMHO, the implementation should check for preconditions if possible. In this special case an assertion would be fine, too. However, it would have required some means to check whether this method has bee invoked already - even in Debug configuration - and possibly in a thread-safe manner." } ]
[ { "body": "<pre><code>- (id)initWithCount:(int)count completion:(completion_block_t)completioHandler;\n</code></pre>\n\n<p>There's a typo here, a missing \"n\" in the last argument.</p>\n\n<hr>\n\n<pre><code>- (id)initWithCount:(int)count completion:(completion_block_t)completionHandler\n{\n\n- (id) result {\n\n- (void) start\n{\n</code></pre>\n\n<p>This inconsistency is really bothersome to me. The opening bracket should either be on the same line or the next line, but do it consistently. Personally, I prefer the opening bracket on the same line as it looks better when the methods are collapsed in Xcode.</p>\n\n<hr>\n\n<pre><code>if (!self.isCancelled &amp;&amp; !_isFinished &amp;&amp; !_isExecuting) {\n self.isExecuting = YES;\n</code></pre>\n\n<p>This inconsistency also bothers me, and it's not immediately clear why it's done. In fact, even as a season Objective-C programmer, I'm confused as to what would actually happen here when you do <code>self.isExecuting = YES;</code></p>\n\n<p>Normally, you'd do <code>self.isExecuting = YES;</code> because you've defined <code>isExecuting</code> as a property, and what is actually done is more akin to this:</p>\n\n<pre><code>[self setIsExecuting:YES];\n</code></pre>\n\n<p>But you've not defined <code>isExecuting</code> as a full property, but rather you've defined <code>_isExecuting</code> as an instance variable and created <code>setIsExecuting:(BOOL)isExecuting</code> as a method.</p>\n\n<p>I don't rightly know without just running the code what would or should happen here.</p>\n\n<p>So the solution is to either define <code>isExecuting</code> as a property so it's more clear what <code>self.isExecuting = YES;</code> would actually do, or to change your <code>self.isExecuting = YES;</code> to either <code>_isExecuting = YES;</code> or <code>[self setIsExecuting:YES];</code> depending on the intent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T11:05:34.373", "Id": "98991", "Score": "0", "body": "The property declarations were indeed missing. Thanks for pointing this to us. Just for information: the dot syntax would still work - but I too prefer to have proper declarations ;) Then, the invocation of the property setter in the implementation for `isExecuting` and `isFinished` is required in order to fire the KVO notification messages." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T02:01:12.593", "Id": "56245", "ParentId": "36632", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T11:32:45.890", "Id": "36632", "Score": "10", "Tags": [ "objective-c", "ios", "osx" ], "Title": "Canonical Implementation of a Subclass of NSOperation" }
36632
<p>How can I shorten and optimize this code which displays then hides a <code>DIV</code>?</p> <pre><code>setTimeout(function () { $('.updateNotification').show().addClass('heightener'); callback(); },2000) function callback() { setTimeout(function() { $( '.updateNotification' ).fadeOut(); }, 10000 ); }; </code></pre> <p>My first thought was to combine the functions. However, I would like them to remain separate because at a later date I will additionally incorporate a button which will trigger <code>callback()</code> in addition to the timer.</p>
[]
[ { "body": "<p>I'm not sure how you would shorten this code. However I think that <code>callback</code> is a <em>terrible</em> name for a function that fades a CSS class. Remember that a function signature should represent what a function does and with that said I would rename it to something like <code>fadeUpdateNotification()</code>.</p>\n\n<p>And in the fashion of fading you could replace <code>.show()</code> with <code>.fadeIn()</code> to have the div fade in and out - I dunno how your styling/website looks like but that might look nice...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:33:27.933", "Id": "36644", "ParentId": "36642", "Score": "6" } }, { "body": "<p>There's not much here to optimize mostly because there's very little here. A few things you could do:</p>\n\n<p>Store your selection to a variable outside both functions (bad idea if you may have multiple notificationDivs).</p>\n\n<pre><code>var notificationDiv = $( '.updateNotification' )\n</code></pre>\n\n<p>You could save 1 character by adding the callback to the <code>show</code> animation (not really an improvement):</p>\n\n<pre><code>notificationDiv.show(0,callback)\n</code></pre>\n\n<p>I'm more confused about why you're doing the <code>setTimeout</code>s the way you are. Why do you need a 2 second delay to show the div? Also if you plan to call <code>callback</code> later, I think it'd confuse most people if the div takes 10 seconds to start to disappear.</p>\n\n<p>Here's a <a href=\"http://jsfiddle.net/PSLeQ/\" rel=\"nofollow\">fiddle</a> I used while tinkering.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:41:23.697", "Id": "36645", "ParentId": "36642", "Score": "3" } }, { "body": "<p>if you want to combine them you can just do it like this </p>\n\n<pre><code>$('.updateNotification').delay(2000).show(0).addClass('heightener').delay(10000).fadeOut(); \n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/4XYg8/\" rel=\"nofollow\">http://jsfiddle.net/4XYg8/</a></p>\n\n<p>or to keep the callback function something like this </p>\n\n<pre><code>var notifications= $('.updateNotification'); //store the selection like Daniel Cook said\nsetTimeout(function () {\n //if you use the no-arguments form of .show()\n //you can just add display:block on the class .heightener\n notifications.addClass('heightener');\n callback();\n},2000);\n\nfunction callback() {\n notifications.delay(10000).fadeOut();//if you only want to fadeOut you can use delay\n}; \n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/4XYg8/1/\" rel=\"nofollow\">http://jsfiddle.net/4XYg8/1/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T00:24:24.407", "Id": "60266", "Score": "0", "body": "I knew someone would know the \"correct\" way to combine it. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T22:57:52.773", "Id": "36668", "ParentId": "36642", "Score": "3" } } ]
{ "AcceptedAnswerId": "36644", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T15:11:15.913", "Id": "36642", "Score": "3", "Tags": [ "javascript", "performance", "jquery" ], "Title": "jQuery function that modifies a DIV" }
36642