body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p><strong>Summary:</strong> a bunch of algorithms to find if particular substring exists in the string. Meanwhile there's a lot to learn and I am looking forward to implementing more complex ones, I suppose there's some crucial insight regarding style, syntax, or design, which I might be missing. I have also managed to implement the auxiliary functions which potentially would assist me in the future.</p> <p><strong>Note:</strong> the question I have is how to avoid the boilerplate part in the main function. There should have been a some kind of "framework", which would accept the vector of functions and perform the tests. However, for me it's not quite clear how the architecture should be designed.</p> <pre><code>#include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;random&gt; #include &lt;string_view&gt; #include &lt;utility&gt; #include &lt;vector&gt; template &lt;typename T&gt; std::ostream &amp;operator&lt;&lt;(std::ostream &amp;o, std::vector&lt;T&gt; const &amp;vector) { for (auto const &amp;element: vector) o &lt;&lt; element &lt;&lt; " "; return o; } namespace string_generator_utility { std::string generate_string(std::string::size_type length, std::vector&lt;char&gt;&amp;&amp; alphabet = {'a', 'b', 'c', 'd'}) { std::string result; static std::random_device rd; static std::mt19937_64 mersenne_twister_generator {rd ()}; const auto supremum = alphabet.size() - 1; std::uniform_int_distribution&lt;std::size_t&gt; range {0, supremum}; for (std::size_t index = 0; index &lt; length; ++index) { const auto letter = range(mersenne_twister_generator); result += alphabet[letter]; } return result; } std::vector&lt;std::string&gt; generate_n_strings(std::size_t vector_size, std::size_t string_length, std::vector&lt;char&gt;&amp;&amp; alphabet = {'a', 'b', 'c', 'd'}) { std::vector&lt;std::string&gt; generated; generated.reserve(vector_size); std::generate_n(std::back_inserter(generated), vector_size, [&amp;]() { return generate_string(string_length, std::move(alphabet)); }); return generated; } } // namespace string_generator_utility namespace algo { std::vector&lt;std::int64_t&gt; naive_substring(std::string_view haystack, std::string_view needle) { const auto haystack_size = haystack.size(); const auto needle_size = needle.size(); assert(haystack_size &gt;= needle_size); std::vector&lt;std::int64_t&gt; result; for (std::size_t index = 0; index &lt; haystack_size - needle_size + 1; ++index) { std::size_t offset = 0; for (; offset &lt; needle_size; ++offset) { if (haystack[index + offset] != needle[offset]) break; } if (offset == needle_size) result.push_back(index); } return result; } std::vector&lt;std::int64_t&gt; rabin_karp_hash(std::string_view haystack, std::string_view needle) { const auto haystack_size = haystack.size(); const auto needle_size = needle.size(); assert(haystack_size &gt;= needle_size); std::vector&lt;std::int64_t&gt; matches; static const auto hash_function = [](std::string_view::iterator begin, std::string_view::iterator end) { std::int64_t hash = 5381; for (; begin != end; ++begin) hash = ((hash &lt;&lt; 5) + hash) + *begin; return hash; }; const auto needle_hashed = hash_function(std::begin(needle), std::end(needle)); for (std::size_t index = 0; index &lt; haystack_size - needle_size + 1; ++index) { const auto substring_hash = hash_function ( std::begin(haystack) + index, std::begin(haystack) + index + needle_size ); if (substring_hash == needle_hashed) matches.push_back(index); } return matches; } } // namespace algo int main() { auto vector = string_generator_utility::generate_n_strings(25, 50); std::cout &lt;&lt; "naive substring:\n"; for (std::size_t index = 0; index &lt; vector.size(); ++index) { std::cout &lt;&lt; vector[index] &lt;&lt; ": "; auto shift = algo::naive_substring(vector[index], "ab"); std::cout &lt;&lt; shift &lt;&lt; "\n"; } std::cout &lt;&lt; "rabin-karp-substring:\n"; for (std::size_t index = 0; index &lt; vector.size(); ++index) { std::cout &lt;&lt; vector[index] &lt;&lt; ": "; auto shift = algo::rabin_karp_hash(vector[index], "ab"); std::cout &lt;&lt; shift &lt;&lt; "\n"; } return 0; } </code></pre>
[]
[ { "body": "<ol>\n<li><p>I think the assertion in the <code>rabin_karp_hash</code> is redundant. There is nothing wrong with trying to find a substring with a size exceeding that of a text (although the result is self-evident), besides you can just return an empty vector there.</p></li>\n<li><p>I'd replace </p>\n\n<pre><code>for (; offset &lt; needle_size; ++offset) {\n if (haystack[index + offset] != needle[offset])\n break;\n}\n</code></pre>\n\n<p>with something like</p>\n\n<pre><code>while (offset &lt; needle_size &amp;&amp; haystack[index + offset] == needle[offset])\n ++offset;\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:13:05.720", "Id": "213053", "ParentId": "213023", "Score": "1" } }, { "body": "<p>From a readability viewpoint, your <code>operator&lt;&lt;</code> for <code>std::vector</code> declared at the top of your file should be spread out onto multiple lines so that it is easier to read and understand.</p>\n\n<p>Also, the calculation of <code>((hash &lt;&lt; 5) + hash)</code> should be rewritten as the simpler <code>hash * 33</code>. The compiler will know the best way to multiply a number by 33. This could be a multiply, a shift-and-add like you've coded, or some sequence involving the address calculation instructions.</p>\n\n<p>Rather than using an <code>assert</code> to verify that the needle is not longer than the haystack (which will only <a href=\"https://en.cppreference.com/w/cpp/error/assert\" rel=\"nofollow noreferrer\">check the condition</a> if the <code>NDEBUG</code> macro is not defined), just check the condition and return an empty collection.</p>\n\n<p>In <code>rabin_karp_hash</code> you assume that two strings match if their hash values are the same. This is not necessarily the case. It is possible, however unlikely, that two different strings will have the same hash value. This is a <em>hash collision</em>. To ensure that your potential match are identical strings, you still need to compare both strings when the hashes match.</p>\n\n<p>To simplify the code in <code>main</code> and eliminate the duplication, you can create a class with a virtual <code>compare</code> member. Then derive two classes from it, one for the naive comparison, the other for the Rabin-Karp one. Put your loop into another function, and pass instances of the appropriate derived class to use the specific comparison you want to test.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-04T17:43:32.340", "Id": "415206", "Score": "0", "body": "Thank you. I'll set this answer as bounty-worthy if nobody comes around. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-01T20:23:48.213", "Id": "214568", "ParentId": "213023", "Score": "3" } } ]
{ "AcceptedAnswerId": "214568", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T10:16:14.490", "Id": "213023", "Score": "6", "Tags": [ "c++", "algorithm", "c++17" ], "Title": "Basic substring algorithms + auxiliary string-generating functions" }
213023
<p>I'm setting up a python mqtt client that is supposed to receive messages of specific topics, process the messages when all incoming messages from the clients are complete, output the new calculated data via http request, request new data via mqtt and start from the beginning.</p> <p>Are there any issues regarding receiving multiple messages at the same time?</p> <p>What happens if the control function is executed and the client receives a new message? </p> <p>How can I implement a timeout that the control function waits for maximum X seconds?</p> <pre><code>#!/usr/bin/env python import paho.mqtt.client as mqtt import time import socket import json import requests import array from configparser import SafeConfigParser def on_connect(client, userdata, flags, rc): print("CONNECTED") print("Connected with result code: ", str(rc)) print("subscribing to topics:") print(*mqtt_sub_topics) client.subscribe(mqtt_sub_topics) def on_message(client, userdata, message): print("MESSAGE") print("message received " ,str(message.payload.decode("utf-8"))) print("message topic=",message.topic) print("message qos=",message.qos) print("message retain flag=",message.retain) received=message.payload.decode("utf-8","ignore") received=json.loads(received) #JSON data to python object # UPDATING print("Updating...") index = mqtt_sub_topics.index((message.topic,0)) #search for index of message topic for i in range(len(keys)): data[index][i] = float(received[keys[i]]) data[index][7] = 1 print("Update von Wallbox ",index," =&gt; ",data[index]) def main(): print("WAIT for max: ",control_timeout, "seconds") while True: # CHECK IF UPDATE OF ALL CLIENTS COMPLETE bUpdate = True for i in range(NbrClients): if data[i][7] == 0: # If data not updated bUpdate = False #print("Wallbox ",i," not updated") break if bUpdate == True: print("Update of all Clients complete") control() def control(): print("CONTROL") # Get properties NbrActive=NbrMin=NbrLimit=NbrOutdated = 0 print("Updating Properties") for i in range(NbrClients): print("Updating properties of client: ",i) if data[i][0] != 3 and data[i][7] == 1: NbrActive += 1 if data[i][6] &gt; data[i][1]: data[i][4] = 1 NbrLimit += 1 if sum(data[i][1:3]) &lt; MinCurrent: data[i][5] = 1 NbrMin += 1 elif data[i][7] == 0: NbrOutdated += 1 data[i][1] = 32 data[i][2] = 32 data[i][3] = 32 print("Number active: ",NbrActive) print("Number limited: ",NbrLimit) print("Number minimum: ",NbrMin) print("Number outdated", NbrOutdated) ##################################### #Calculate currents of the 3 phases p1,p2,p3 = 0,0,0 for i in range(NbrClients): p1 += data[i][1] p2 += data[i][2] p3 += data[i][3] print("Strom auf den Phasen: ",p1,", ",p2,", ",p3) diff1 = p1 - MaxCurrent diff2 = p2 - MaxCurrent diff3 = p3 - MaxCurrent diff = max(diff1,diff2,diff3) if diff &lt; 0: bIncrease = True print("Current potential available: ",diff," A") elif diff == 0: bIncrease = True print("Current limit reached") else: bIncrease = False print("Current limit exceeded: ",diff," =&gt; Decreasing") #Calculate Number of stations for current distribution if bIncrease == False and data[0][0] != 3: # WB 0 Active div = NbrActive - 1 - NbrMin elif bIncrease == False and data[0][0] == 3: # WB 0 Inactive div = NbrActive - NbrMin elif bIncrease == True and data[0][0] != 3: # WB 0 Active div = NbrActive - 1 - NbrLimit elif bIncrease == True and data[0][0] == 3: # WB 0 Inactive div = NbrActive - NbrLimit if div &gt; 0: diff = diff / div for i in range(NbrClients): if data[i][0] == 3: data[i][6] == 0 elif bIncrease == True and data[i][4] == 0: data[i][6] = data[i][1] - diff elif bIncrease == True and data[i][4] == 1: data[i][6] = data[i][1] elif bIncrease == False and data[i][5] == 0: data[i][6] = data[i][1] - diff elif bIncrease == False and data[i][5] == 1: data[i][6] = data[i][1] else: # no changes possible print("Control not active =&gt; No changes possible") for i in range(NbrClients): payload={'current': data[i][6]} print("Current target for client: ",i," ",payload) #r = requests.get(url_client[i], params=payload) #print(r.url) data[i][4] = 0 # Reset limit flag data[i][5] = 0 # Reset min current flag data[i][7] = 0 # Reset update flag ############################################################## print("Requesting new data: "+mqtt_pub_topic) client.publish(mqtt_pub_topic,"request") #Request new data from clients print("INIT") global url_client, keys, MaxCurrent, data, MinCurrent global control_timeout, NbrClients global mqtt_pub_topic, mqtt_sub_topics, client parser = SafeConfigParser() parser.read('control.ini') # Creates an array containing data of X(NbrClients) clients w, NbrClients = 8, int(parser.get('CLIENT', 'NbrClients')) data = [[0 for x in range(w)] for y in range(NbrClients)] for i in range(NbrClients): data[i][0] = 3 #Init lademodus to stop print(data) url_client = json.loads(parser.get('CLIENT',"url")) MinCurrent = int(parser.get('CLIENT','MinCurrent')) MaxCurrent = int(parser.get('CLIENT','MaxCurrent')) mqtt_broker = parser.get('MQTT', 'mqtt_broker') mqtt_port = int(parser.get('MQTT','mqtt_port')) mqtt_client = parser.get('MQTT','mqtt_client') mqtt_pub_topic = parser.get('MQTT','mqtt_pub_topic') sub_topics = json.loads(parser.get('MQTT','mqtt_sub_topics')) mqtt_sub_topics = [(sub_topics[0],0),] # create list with qos = 0 for i in range(NbrClients-1): # Add subtopics to list mqtt_sub_topics = mqtt_sub_topics + [(sub_topics[i+1],0),] control_timeout = float(parser.get('CONTROL','control_timeout')) #Relevant keys of MQTT messages keys=['mode','p1','p2','p3'] ####################################################### client = mqtt.Client() #create new instance client.on_connect = on_connect #attach function to callback client.on_message = on_message #attach function to callback print("Connecting to broker") client.connect(mqtt_broker,mqtt_port) #connect to broker client.loop_start() #start the loop main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T11:27:12.323", "Id": "412057", "Score": "0", "body": "Thanks for your advise. I published the complete code" } ]
[ { "body": "<p><strong>Logging</strong></p>\n\n<p>You have plenty of statements like this</p>\n\n<blockquote>\n<pre><code>print(\"CONNECTED\")\nprint(\"Connected with result code: \", str(rc))\nprint(\"subscribing to topics:\")\n</code></pre>\n</blockquote>\n\n<p>Instead use the logging module,</p>\n\n<pre><code>import logging\nlogging.basicConfig(filename='example.log',level=logging.DEBUG)\n\n...\n\nlogging.debug('Connected with result code: {}\".format(rc))\n</code></pre>\n\n<p>You should use <code>'str {0}'.format()</code> or even <code>f\"{str}\"</code> (Python3.6+) to concatenate strings for readability</p>\n\n<p><strong>Magic numbers</strong></p>\n\n<p>I see many instances of so call magic numbers,</p>\n\n<blockquote>\n<pre><code>for i in range(NbrClients):\n print(\"Updating properties of client: \",i)\n if data[i][0] != 3 and data[i][7] == 1:\n NbrActive += 1\n if data[i][6] &gt; data[i][1]: \n data[i][4] = 1 \n NbrLimit += 1\n if sum(data[i][1:3]) &lt; MinCurrent:\n data[i][5] = 1 \n NbrMin += 1\n elif data[i][7] == 0:\n NbrOutdated += 1\n data[i][1] = 32 \n data[i][2] = 32\n data[i][3] = 32\n</code></pre>\n</blockquote>\n\n<p>What is the 7th index? or the 3th?</p>\n\n<p>Why <code>32</code> in those data[i][x] = 32</p>\n\n<p>Since numbers don't have meaning, you could consider changing them to constant variables -> <code>SOME_VAR = 32</code>\nor at least document those in a nice docstring</p>\n\n<p><strong>Globals</strong></p>\n\n<blockquote>\n<pre><code> global url_client, keys, MaxCurrent, data, MinCurrent\n global control_timeout, NbrClients\n global mqtt_pub_topic, mqtt_sub_topics, client\n</code></pre>\n</blockquote>\n\n<p>Globals are considered bad style, because you lose track of where each variable is called</p>\n\n<p>If you have a lot of functions that require global variables, consider making it a class.</p>\n\n<p><em>There is more to be improved, but I don't have much time. Hope this helps :)</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T12:08:55.633", "Id": "213033", "ParentId": "213024", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T10:33:53.087", "Id": "213024", "Score": "0", "Tags": [ "python", "multithreading" ], "Title": "MQTT Client that send, receive and process mqtt messages" }
213024
<p>Consider the array:</p> <pre><code>original_array1[17] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17} </code></pre> <p>I want to sort it in such a way that:</p> <ol> <li>Sum of adjacent numbers should be a perfect square</li> <li>You cannot reuse a number</li> </ol> <p>So a possible solution is:</p> <pre><code>16 9 7 2 14 11 5 4 12 13 3 6 10 15 1 8 17 </code></pre> <p>I write a C++ program to get this done using a recursive function and it works.</p> <p>I was wondering how can I improve the program to:</p> <ol> <li>Make it more readable and easy to understand (variable names, better handling or elimination of boundary conditions, comments etc.)</li> <li>Use better library functions or C++ language features to make the code compact.</li> <li>Is there a better algorithm/strategy that I can use instead of using recursive functions.</li> </ol> <p>The motivation for this came from a daily problem posted on brilliant.org, I thought I would solve it by writing a program. But now I want to ask the community for pointers on how to become better at coding in general.</p> <p>Here is the code have:</p> <pre><code>//Compile using g++ -std=c++11 arrange.cpp #include &lt;iostream&gt; #include &lt;cstdint&gt; #include &lt;cmath&gt; using namespace std; int original_array1[17] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17}; bool isSumPerfectSquare(int x, int y) { long double sr = sqrt((long double)x + (long double)y); return ((sr - floor(sr)) == 0); } int * ArrangeNumbers(int * done, int * remaining, int size_done, int size_remaining) { static int ctr = 0; // cout&lt;&lt;"ArrangeNumbers() "&lt;&lt; (ctr++) &lt;&lt; endl&lt;&lt;" "; // if(done != nullptr) { // for(int jj = 0; jj&lt;size_done;jj++) { // cout&lt;&lt;done[jj]&lt;&lt;" "; // } // } // cout&lt;&lt;" | "; // if(remaining != nullptr) { // for(int jj = 0; jj&lt;size_remaining;jj++) { // cout&lt;&lt;remaining[jj]&lt;&lt;" "; // } // } // cout&lt;&lt;endl; if(size_remaining == 1) { // Border Case 1: Last number remaining, lets check if pairs up with the last number in sorted array if(isSumPerfectSquare(done[size_done-1],remaining[0])) { int * finally_done = (int *) calloc(size_done+1,sizeof(int)); for(int jj = 0; jj&lt;size_done;jj++) { finally_done[jj] = done[jj]; } finally_done[size_done] = remaining[0]; return finally_done; } else { return nullptr; } } else if(size_done == 0) { // Border Case 2: Come back and choose the first number again int * done1 = (int *) calloc(size_done+1,sizeof(int)); int * remaining1 = (int *) calloc(size_remaining-1,sizeof(int)); for(int kk = 0; kk&lt;size_remaining;kk++) { done1[0] = remaining[kk]; for(int ll = 0; ll&lt;kk;ll++) { remaining1[ll] = remaining[ll]; } for(int ll = kk+1; ll&lt;size_remaining;ll++) { remaining1[ll-1] = remaining[ll]; } int * sr_arr = ArrangeNumbers(done1, remaining1, size_done+1, size_remaining-1); if(sr_arr != nullptr) { free(done1); free(remaining1); return sr_arr; } } free(done1); free(remaining1); return nullptr; } else { int * done1 = (int *) calloc(size_done+1,sizeof(int)); int * remaining1 = (int *) calloc(size_remaining-1,sizeof(int)); // Copy array till now if(done != nullptr) { for(int jj = 0; jj&lt;size_done;jj++) { done1[jj] = done[jj]; } } // Choose next number and respawn for(int kk = 0; kk&lt;size_remaining;kk++) { if(isSumPerfectSquare(done1[size_done-1],remaining[kk])) { done1[size_done] = remaining[kk]; for(int ll = 0; ll&lt;kk;ll++) { remaining1[ll] = remaining[ll]; } for(int ll = kk+1; ll&lt;size_remaining;ll++) { remaining1[ll-1] = remaining[ll]; } int * sr_arr = ArrangeNumbers(done1, remaining1, size_done+1, size_remaining-1); if(sr_arr != nullptr) { free(done1); free(remaining1); return sr_arr; } } } free(done1); free(remaining1); return nullptr; } } int main() { int * sorted_array = ArrangeNumbers(nullptr, original_array1, 0, 17); cout&lt;&lt;"Original Array :"; for(int i = 0; i&lt;17;i++) { cout&lt;&lt;" "&lt;&lt;original_array1[i]; } cout&lt;&lt;endl&lt;&lt;"Sorted Array :"; if(sorted_array != nullptr) { for(int i = 0; i&lt;17;i++) { cout&lt;&lt;" "&lt;&lt;sorted_array[i]; } free(sorted_array); } cout&lt;&lt;endl; return 0; } </code></pre>
[]
[ { "body": "<h1>Compilation options</h1>\n\n<p>Use more warnings, e.g. <code>g++ -std=c++11 -Wall -Wextra</code>. This will identify the unused variable <code>ctr</code>, for instance.</p>\n\n<h1>Avoid <code>using namespace std</code></h1>\n\n<p>Bringing all names in from a namespace is problematic; <code>namespace std</code> particularly so. See <a href=\"//stackoverflow.com/q/1452721\">Why is “using namespace std” considered bad practice?</a>.</p>\n\n<h1>Choice of type</h1>\n\n<p>If all the numbers are guaranteed to be positive, consider using an unsigned type for the array elements.</p>\n\n<p>Prefer using <code>std::array</code> over raw (C-style) arrays.</p>\n\n<h1>Checking for perfect square</h1>\n\n<p>It's good that we have a self-contained function for checking whether a number is a perfect square. However, it has accuracy problems when values reach the limit of a <code>double</code>'s mantissa. It's also relatively slow, due to the use of <code>std::sqrt()</code>. One thing we could do instead is to create a <code>std::set</code> (or <code>std::unordered_set</code>) of the possible square numbers, and then simply test for membership of that set.</p>\n\n<p>That looks something like this:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;unordered_set&gt;\n\nunsigned original_array1[17] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};\n\nbool isSumPerfectSquare(unsigned x) {\n static auto const squares =\n []{\n std::unordered_set&lt;unsigned&gt; s;\n auto max = *std::max_element(std::begin(original_array1), std::end(original_array1));\n for (auto value = 1u, diff = 1u; value &lt; max * 2; value += (diff += 2))\n s.insert(value);\n return s;\n }();\n\n return squares.find(x) != squares.end();\n}\n</code></pre>\n\n<h1>Prefer <code>new[]</code> and <code>delete[]</code></h1>\n\n<p>When writing C++, prefer the <code>new</code> and <code>delete</code> operators and their array counterparts rather than C-style <code>std::malloc()</code>, <code>std::calloc()</code>, <code>std::realloc()</code> and <code>std::free()</code>. Prefer smart pointers and collections to bare pointers.</p>\n\n<p>However, this algorithm shouldn't need any allocations at all, if we modify the input in place.</p>\n\n<p>Here's how I'd do that, using <code>std::swap</code> to move each candidate in turn to the front of the array:</p>\n\n<pre><code>// shuffle [a..b), given preceding number\nbool arrange_numbers(unsigned prev, unsigned *a, unsigned *b)\n{\n if (a == b) {\n // no more numbers; we've done it!\n return true;\n }\n\n for (unsigned *p = a; p != b; ++p) {\n if (is_perfect_square(prev + *p)) {\n std::swap(*a, *p);\n if (arrange_numbers(*a, a+1, b)) {\n // found a match\n return true;\n }\n // reinstate the order, for our caller\n std::swap(*a, *p);\n }\n }\n\n // no satisfactory solution\n return false;\n}\n\n\nbool arrange_numbers(std::array&lt;unsigned,17&gt;&amp; array)\n{\n unsigned *a = array.begin();\n unsigned *b = array.end();\n\n for (unsigned *p = a; p != b; ++p) {\n std::swap(*a, *p);\n if (arrange_numbers(*a, a+1, b)) {\n // found a match\n return true;\n }\n }\n\n // no matches\n return false;\n}\n</code></pre>\n\n<hr>\n\n<h1>Full modified code</h1>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;array&gt;\n#include &lt;iostream&gt;\n#include &lt;unordered_set&gt;\n#include &lt;utility&gt;\n\n\nstd::array&lt;unsigned,17&gt; numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};\n\nbool is_perfect_square(unsigned x) {\n static auto const squares =\n []{\n std::unordered_set&lt;unsigned&gt; s;\n auto max = *std::max_element(numbers.begin(), numbers.end());\n for (auto value = 1u, diff = 1u; value &lt; max * 2; value += (diff += 2))\n s.insert(value);\n return s;\n }();\n\n return squares.find(x) != squares.end();\n}\n\n\n// shuffle [a..b), given preceding number\nbool arrange_numbers(unsigned prev, unsigned *a, unsigned *b)\n{\n if (a == b) {\n // no more numbers; we've done it!\n return true;\n }\n\n for (unsigned *p = a; p != b; ++p) {\n if (is_perfect_square(prev + *p)) {\n std::swap(*a, *p);\n if (arrange_numbers(*a, a+1, b)) {\n // found a match\n return true;\n }\n // reinstate the order, for our caller\n std::swap(*a, *p);\n }\n }\n\n // no satisfactory solution\n return false;\n}\n\n\nbool arrange_numbers(std::array&lt;unsigned,17&gt;&amp; array)\n{\n unsigned *a = array.begin();\n unsigned *b = array.end();\n\n for (unsigned *p = a; p != b; ++p) {\n std::swap(*a, *p);\n if (arrange_numbers(*a, a+1, b)) {\n // found a match\n return true;\n }\n }\n\n // no matches\n return false;\n}\n\n\nint main()\n{\n std::cout &lt;&lt; \"Original array:\";\n for (auto i: numbers) {\n std::cout &lt;&lt; \" \" &lt;&lt; i;\n }\n std::cout &lt;&lt; '\\n';\n\n if (arrange_numbers(numbers)) {\n std::cout &lt;&lt; \"Sorted array:\";\n for (auto i: numbers) {\n std::cout &lt;&lt; \" \" &lt;&lt; i;\n }\n std::cout &lt;&lt; '\\n';\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T13:13:14.187", "Id": "213036", "ParentId": "213025", "Score": "6" } }, { "body": "<p><strong>Better strategy</strong> at the first glance does not exist. Consider a graph formed by the numbers an array, with the edges connecting vertices which add up to a perfect square. The problem then is reduced to finding a <a href=\"https://en.wikipedia.org/wiki/Hamiltonian_path_problem\" rel=\"nofollow noreferrer\">Hamiltonian path</a>. The problem is known to be NP-complete. There is an algorithm solving it in <span class=\"math-container\">\\$O(n^2 2^n)\\$</span> time; in general case it is better than brute force, but still exponential.</p>\n\n<p>Your case <em>could</em> have a better asymptotic, because the graph has a very particular structure. For starters, for path to exist the should be no more than 2 vertices of the degree 1 (if the array had 18, there would be 3 such vertices). Also your graph is very sparsely connected, and has quite a few vertices of degree 2. This suggests a heuristic similar to the <a href=\"https://en.wikipedia.org/wiki/Knight%27s_tour#Warnsdorf&#39;s_rule\" rel=\"nofollow noreferrer\">Warnsdorf's rule</a>: start with a vertex of the least degree, and always inspect the neighbors in the ascending order of degrees (smallest first).</p>\n\n<p>For example in your array, starting with <code>16</code> (degree 1) forces the resulting sequence with not a single branch point.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T19:29:40.507", "Id": "412288", "Score": "0", "body": "Even if you can reduce a problem to an NPC problem, it does not mean the original problem is necessarily hard." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T17:57:17.253", "Id": "213057", "ParentId": "213025", "Score": "4" } } ]
{ "AcceptedAnswerId": "213036", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T10:57:56.240", "Id": "213025", "Score": "7", "Tags": [ "c++", "algorithm", "c++11", "sorting" ], "Title": "Rearrage sequence so that adjacent numbers add to perfect squares" }
213025
<p>This is a <a href="http://www.rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks" rel="nofollow noreferrer"><em>Find unimplemented tasks</em></a> task from Rosetta Code: </p> <blockquote> <p>Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.</p> </blockquote> <p>There is already a <a href="http://www.rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks#Python" rel="nofollow noreferrer">solution</a> that uses urllib, but I decided to add another one using <a href="http://docs.python-requests.org" rel="nofollow noreferrer">Requests</a>. I've never worked with this library before and would like my code to get reviewed. Any comments are welcome.</p> <pre><code>""" Given the name of a language on Rosetta Code, finds all tasks which are not implemented in that language. """ from functools import partial from operator import itemgetter from typing import (Dict, Iterator, Union) import requests URL = 'http://www.rosettacode.org/mw/api.php' REQUEST_PARAMETERS = dict(action='query', list='categorymembers', cmlimit=500, rawcontinue=True, format='json') def unimplemented_tasks(language: str, *, url: str, request_params: Dict[str, Union[str, int, bool]] ) -&gt; Iterator[str]: """Yields all unimplemented tasks for a specified language""" with requests.Session() as session: tasks = partial(tasks_titles, session=session, url=url, **request_params) all_tasks = tasks(cmtitle='Category:Programming_Tasks') language_tasks = set(tasks(cmtitle=f'Category:{language}')) for task in all_tasks: if task not in language_tasks: yield task def tasks_titles(*, session: requests.Session, url: str, **params: Union[str, int, bool]) -&gt; Iterator[str]: """Yields tasks names for a specified category""" while True: request = session.get(url, params=params) data = request.json() yield from map(itemgetter('title'), data['query']['categorymembers']) query_continue = data.get('query-continue') if query_continue is None: return params.update(query_continue['categorymembers']) if __name__ == '__main__': tasks = unimplemented_tasks('Python', url=URL, request_params=REQUEST_PARAMETERS) print(*tasks, sep='\n') </code></pre> <p>Current output for Python:</p> <pre class="lang-none prettyprint-override"><code>Calendar - for "REAL" programmers Catmull–Clark subdivision surface Checkpoint synchronization Colour pinstripe/Printer Compile-time calculation Constrained genericity Create an object at a given address Deconvolution/2D+ Factorial base numbers indexing permutations of a collection Fixed length records Four is the number of letters in the ... Function prototype Hilbert curve Parametric polymorphism Pattern matching Peano curve Pinstripe/Printer Rendezvous Rosetta Code/Find bare lang tags Start from a main routine Suffixation of decimal numbers Video display modes Zeckendorf arithmetic </code></pre>
[]
[ { "body": "<p>LGTM. Ship it!</p>\n\n<p>There were two minor nits that seemed slightly off:</p>\n\n<ol>\n<li>The use of <code>*</code> in the signature to force kw args is maybe overused, as it covers args that are pretty mandatory.</li>\n<li>The <code>print(*tasks, sep='\\n')</code> would more naturally be handled by this idiom, which is reusable outside of print(): <code>print('\\n'.join(tasks))</code> </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:18:30.597", "Id": "455517", "Score": "0", "body": "Thanks for the review! Yes, keyword-only arguments is still something that I don't have a clear idea about. See my related question: [What is the safe way of using keyword-only arguments?](https://softwareengineering.stackexchange.com/q/384523/292449) I'm accepting the answer but if somebody has something else to propose, feel free to post it. BTW, after I posted this question I came up with a more elegant way to solve the task using mwclient library: [link](http://www.rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks#Library:_mwclient)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T20:42:12.527", "Id": "455606", "Score": "0", "body": "Well, if you have a function that uses *args and you're adding args, then they _will_ be kw args, and you'll need a `*` before them. A function with a tediously large number of ordinary args (say four or more) may benefit from `*`, if you're concerned the caller might confuse the order switching 3rd & 4th with no possibility of an exception alerting him to the trouble. I really like the @Jerry101 answer you accepted, especially the \"dangerous\" aspect of this example: `def delete(base, *, recursive)`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T01:52:56.743", "Id": "233097", "ParentId": "213026", "Score": "1" } } ]
{ "AcceptedAnswerId": "233097", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T11:02:54.720", "Id": "213026", "Score": "8", "Tags": [ "python", "python-3.x", "programming-challenge", "json" ], "Title": "Finding unimplemented tasks on Rosetta Code using Requests" }
213026
<p>can you review the this code for the <a href="https://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow noreferrer">Monty Hall</a> simulation, mainly on the aspects of <strong>OOP</strong> and <strong>CleanCode</strong></p> <pre><code>public static void main(String[] args) { final int iterations = 10000; System.out.println("chance with change = " + getChanceForPlay(iterations, true)); System.out.println("chance without change = " + getChanceForPlay(iterations, false)); } private static double getChanceForPlay(int iterations, boolean doChange) { double win = 0; for (int i = 0; i &lt; iterations; i++) { List&lt;Price&gt; doors = createDoors(); int selectedDoor = random.nextInt(3); //the player selects one of three doors //let's remove one goat (but not the selected door) for (int currentDoor = 0; currentDoor &lt; 3; currentDoor++) { if (currentDoor != selectedDoor &amp;&amp; doors.get(currentDoor) == Price.GOAT) { doors.remove(currentDoor); //re-Index, if required selectedDoor = currentDoor &lt; selectedDoor? selectedDoor-1:selectedDoor; break; } } //player changes door if (doChange) { selectedDoor = selectedDoor == 0 ? 1 : 0; } if (doors.get(selectedDoor) == Price.CAR) { win++; } } return win / iterations; } private static List&lt;Price&gt; createDoors() { List&lt;Price&gt; doors = new ArrayList&lt;&gt;(); doors.add(Price.GOAT); doors.add(Price.GOAT); doors.add(Price.CAR); Collections.shuffle(doors); return doors; } private enum Price { GOAT, CAR } </code></pre> <p>I know many other people made the same thing. It's more of an academical question...</p> <p>some thoughs upon it done by myself:</p> <ul> <li>should i break up the code more? maybe one method for removing one door by the showmaster?</li> <li>usage of integer for doors - i think that's not so fancy...</li> <li>overusage of brackets</li> <li>too much comments (tell don't ask)</li> <li>too complicated (brain overload)</li> </ul> <h2>Edit:</h2> <p>there exists an <a href="https://codereview.stackexchange.com/questions/213236/follow-up-implementation-on-monty-hall-simulation?noredirect=1#comment412469_213236">follow up question</a> on how to do it better</p>
[]
[ { "body": "<blockquote>\n <p>.. review .. mainly on the aspects of <em>OOP</em> and <em>CleanCode</em></p>\n</blockquote>\n\n<h2>To Some of Your Thoughts</h2>\n\n<blockquote>\n <p>usage of integer for doors - i think that's not so fancy...</p>\n</blockquote>\n\n<p>Additional to a <code>Door</code> class we could add classes for <code>Player</code>, <code>ShowMaster</code>, and <code>MontyHall</code> too.</p>\n\n<blockquote>\n <p>should I break up the code more? maybe one method for removing one door by the showmaster?</p>\n</blockquote>\n\n<p>This job is be done when we split up the code with classes into different logical units.</p>\n\n<blockquote>\n <p>too much comments (tell don't ask)</p>\n</blockquote>\n\n<p>Comments are add all not bad but when you group your code in a method you all ready see semi-independent logic. In Robert C. Martins words: <a href=\"https://www.goodreads.com/author/quotes/45372.Robert_C_Martin?page=2\" rel=\"nofollow noreferrer\">“Don’t Use a Comment When You Can Use a Function or a Variable”</a></p>\n\n<h1>Review</h1>\n\n<p>Bad news first.. I see no oop at all in your code.. An indicator for non-oop code is the heavy use off <code>static</code> and no own data-types. With other words: You write a huge procedural algorithm. </p>\n\n<h2>Find Objects</h2>\n\n<p>My first step would be to wrap this method into a class called <code>MontyHall</code> and give it a public method <code>caluclateChance</code>. I would avoid the <code>get</code>-prefix because it is not a getter.</p>\n\n<p>After that, we can search for cohesion and abstractions. Your comments helps us very well!</p>\n\n<p>The comment <code>//the player selects one of three doors</code> shows us that we could create a <code>Player</code>. After that the <code>ShowMaster</code> wants <code>//.. remove one goat (but not the selected door)</code>. Than our <code>//player changes door</code> if he wants to. </p>\n\n<p>We should think again about a <code>Door</code>. Currently, the <code>doors</code> are represented as a list of integers. But in the domain of Monty Hill, a door is something that hides a price and has a number. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Door {\n private int number;\n private Price price;\n\n // all-args constructor..\n\n // hashcode and equals-method..\n}\n\n</code></pre>\n\n<h2>Code Smell</h2>\n\n<h3>Magic Number</h3>\n\n<p>The <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">magic number</a> <code>3</code> appears two times in your code:</p>\n\n<ul>\n<li><code>random.nextInt(3)</code></li>\n<li><code>if (..., currentDoor &lt; 3; ..)</code></li>\n</ul>\n\n<p>The <code>3</code> represents the number of doors and can be replaced by <code>int NUMBER_OF_DOORS = doors.size()</code>, or you can hide it in an object, which would be the preferred way. </p>\n\n<h3><a href=\"https://www.martinfowler.com/bliki/FlagArgument.html\" rel=\"nofollow noreferrer\">Flag Argument</a></h3>\n\n<p>The method <code>getChanceForPlay</code> takes as second argument a Boolean value, which creates uses <code>if (doChange) { /*...*/}</code> to create a branch in your method. The downside of this flag is that we need to test each branch when writing a unit test (but ok.. in this we have only on possible branch). </p>\n\n<p>This flag has a logical cohesion to a <code>Player</code>. Let's say a <code>Player</code> is an abstract data type and there are two possible types of players: <code>StraightPlayer</code> and <code>ChangePlayer</code>. With polymorphism we can pass both players and call <code>player.chooseDoor</code>. While the <code>StraightPlayer</code> chooses the same door as before and <code>ChangePlayer</code> changes his/her selection.</p>\n\n<h1>Code</h1>\n\n<p><code>// will follow</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T18:00:29.257", "Id": "412281", "Score": "1", "body": "I have a feeling that using a class for `StraightPlayer`, `ChangePlayer` and `ShowMaster` will be a bit overkill but it will be interesting to see what you come up with there. You have some other very good points here though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T10:43:55.657", "Id": "412329", "Score": "2", "body": "Not sure if it's worth bringing up but the simulation has a flaw in my eyes - an *entirely new* set of doors is created every time. That's not a code problem but a logic problem because it doesn't accurately reflect changing the choice. Given how it works right now, it seems better if it ran over the same door combinations first by changing choices, second without changing choices. Then you would get a more precise win percentage. Although both cases should be fairly close in what they report." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T05:23:40.310", "Id": "412443", "Score": "0", "body": "@SimonForsberg that missing OO-Concept was my very reason to delete that question. After i postet my code i saw all these missing concepts, but i'm still glad you encouraged me to keep the question online." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T21:25:10.447", "Id": "412959", "Score": "0", "body": "Just out of curiousity, will that code still follow?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T15:18:36.623", "Id": "213100", "ParentId": "213027", "Score": "6" } } ]
{ "AcceptedAnswerId": "213100", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T11:07:16.623", "Id": "213027", "Score": "3", "Tags": [ "java", "object-oriented" ], "Title": "Clean Code / OOP on Monty Hall Simulation Implementation" }
213027
<p>Please critique my codebase <a href="https://github.com/davidbyng/acme-simple-servlet-extension" rel="nofollow noreferrer">https://github.com/davidbyng/acme-simple-servlet-extension</a></p> <pre><code>package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Enforce JSON HTTP content type. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface AsJson {} package com.acme.annotations; import com.acme.authentication.LocalAuthentication; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Enforce authentication. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface Authenticated { /** * Authentication class to use. * * @return Authentication class. */ Class value() default LocalAuthentication.class; } package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Enforce HTTP caching. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface Cache {} package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Enforce HTTP content type. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface ContentType { /** * Content type to enforce. * * @return Content type. */ String value() default "text/hml"; } package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Default handler for route class. */ @Documented @Target(ElementType.METHOD) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface DefaultRoute {} package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Enforce HTTP GET method. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface Get {} package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Disable HTTP caching. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface NoCache {} package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Enforce HTTP POST method. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface Post {} package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Disable authentication. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface Public {} package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Add request token to output, * aids in preventing CSRF. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface RequestToken {} package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Bind method to path. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface Route { /** * Servlet path to bind to. * * @return Servlet path. */ String value() default ""; } package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Global filter to applicable to all routes. */ @Documented @Target(ElementType.METHOD) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface RouteFilter {} package com.acme.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Enforce token validation, * aids in preventing CSRF. */ @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface ValidateToken {} package com.acme.authentication; import com.acme.authentication.types.AuthType; public class AuthClass { private final AuthType authType; private final Object authObject; public AuthClass(AuthType authType, Object authObject) { this.authType = authType; this.authObject = authObject; } /** * Returns authentication URL to recirect to. * * @param context Context path of servlet. * * @return Authentication URL. */ public String getAuthUrl(String context) { return authType == authType.LOCAL ? ((LocalAuthentication) authObject).getAuthUrl(context) : ((AzureAuthentication) authObject).getAuthUrl(); } } package com.acme.authentication; import java.io.InputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class AzureAuthentication { private final Logger logger = LoggerFactory.getLogger(AzureAuthentication.class); private final Marker fatal = MarkerFactory.getMarker("FATAL"); private Properties azureProperties; /** * Instantiate a new instance of Azure authentication. */ public AzureAuthentication() { try { String configFile = "META-INF/authentication/azure.config"; InputStream propsFiles = getClass().getClassLoader().getResourceAsStream(configFile); if (logger.isWarnEnabled() &amp;&amp; propsFiles == null) { logger.warn("Can't load Azure config (" + configFile + ")"); } else if (propsFiles != null) { azureProperties = new Properties(); azureProperties.load(propsFiles); if (logger.isDebugEnabled()) { logger.debug("Azure authentication engine initalised"); } } } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(fatal, "Can't initalise authentication engine", e); } } } /** * Get the authentication URL to redirect to. * * @return Authentication URL. */ public String getAuthUrl() { return null; } } package com.acme.authentication; import java.io.InputStream; import java.security.SecureRandom; import java.security.spec.KeySpec; import java.util.Arrays; import java.util.Locale; import java.util.Properties; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.xml.bind.DatatypeConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class LocalAuthentication { private final Logger logger = LoggerFactory.getLogger(LocalAuthentication.class); private final Marker fatal = MarkerFactory.getMarker("FATAL"); private static final String algorithm = "PBKDF2WithHmacSHA1"; private static final int derivedKeyLength = 160; private static final int iterations = 20000; private SecretKeyFactory encryptEngine = null; private SecureRandom randomByteGenerator = null; private Properties userList = null; /** * Instantiate a new instance of local authentication. */ public LocalAuthentication() { try { String usersFile = "META-INF/authentication/users.db"; InputStream propsFile = getClass().getClassLoader().getResourceAsStream(usersFile); if (logger.isWarnEnabled() &amp;&amp; propsFile == null) { logger.warn("Can't load user list (" + usersFile + ")"); } else if (propsFile != null) { userList = new Properties(); userList.load(propsFile); if (logger.isDebugEnabled()) { logger.debug("Users list loaded (" + usersFile + ")"); } } randomByteGenerator = SecureRandom.getInstance("SHA1PRNG"); encryptEngine = SecretKeyFactory.getInstance(algorithm); if (logger.isDebugEnabled()) { logger.debug("Local authentication engine initalised"); } } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(fatal, "Can't initalise local authentication engine", e); } } } public String getAuthUrl(String context) { return context != null ? context + "/auth" : "/auth"; } /** * Perform authentication against user credentials. * * @param username User name credential * @param password Password credential * @return True when credentials match. */ public boolean login(String username, String password) { boolean valid = false; if (userList != null) { String userPassword = userList.getProperty(username.toLowerCase(Locale.ENGLISH)); if (userPassword != null) { if (logger.isDebugEnabled()) { logger.debug("User " + username + " found"); } String[] parts = userPassword.split(":"); if (parts != null &amp;&amp; parts.length == 2) { byte[] salt = DatatypeConverter.parseBase64Binary(parts[0]); byte[] encryptedPassword = DatatypeConverter.parseBase64Binary(parts[1]); if (Arrays.equals(encryptPassword(password, salt), encryptedPassword)) { if (logger.isDebugEnabled()) { logger.debug("Credentials validated"); } valid = true; } else if (logger.isInfoEnabled()) { logger.info("Invalid credentials"); } } } else if (logger.isInfoEnabled()) { logger.info("User " + username + " not found"); } } else if (logger.isErrorEnabled()) { logger.error(fatal, "User list not loaded"); } return valid; } /** * Encrypt password credential. * * @param password Password credential. * * @return Encrypted password credential as base64. */ public String encryptPassword(String password) { byte[] salt = generateSalt(); return DatatypeConverter.printBase64Binary(salt) + ":" + DatatypeConverter.printBase64Binary(encryptPassword("pass", salt)); } private byte[] encryptPassword(String password, byte[] salt) { byte[] encryptedPassword = null; try { KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength); encryptedPassword = encryptEngine.generateSecret(spec).getEncoded(); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(fatal, "Can't encrypt password", e); } } return encryptedPassword; } private byte[] generateSalt() { byte[] salt = null; try { salt = new byte[8]; randomByteGenerator.nextBytes(salt); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(fatal, "Can't generate salt", e); } } return salt; } } package com.acme.authentication.types; public enum AuthType { LOCAL, AZURE; } package com.acme.dictionary; public enum Language { INVALID, ENGLISH, FRENCH, GERMAN, SPANISH; } package com.acme.dictionary; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class LanguageDictionary { private final Logger logger = LoggerFactory.getLogger(LanguageDictionary.class); private final Marker fatal = MarkerFactory.getMarker("FATAL"); private final Map&lt;Language, Properties&gt; languages = new HashMap&lt;Language, Properties&gt;(); private Language defaultLanguage = Language.ENGLISH; private final List&lt;String&gt; allLanguages = new ArrayList&lt;String&gt;(); /** * Instatiate a new language dictionary object. */ public LanguageDictionary() { try { String configFile = "META-INF/dictionary/language.config"; InputStream propsFile = getClass().getClassLoader().getResourceAsStream(configFile); if (logger.isWarnEnabled() &amp;&amp; propsFile == null) { logger.warn("Can't load dictionary configuration (" + configFile + ")"); } else if (propsFile != null) { Properties config = new Properties(); config.load(propsFile); String configLanguage = config.getProperty("defaultLanguage"); if (configLanguage != null) { this.defaultLanguage = Language.valueOf(configLanguage.toUpperCase(Locale.ENGLISH)); if (logger.isDebugEnabled()) { logger.debug( "Default language: " + StringUtils.capitalize(configLanguage.toLowerCase(Locale.ENGLISH))); } } if (logger.isDebugEnabled()) { logger.debug("Dictionary configuration loaded (" + configFile + ")"); } } for (Language language : Language.values()) { String langName = language.toString().toLowerCase(Locale.ENGLISH); String niceName = StringUtils.capitalize(langName); String dictName = "META-INF/dictionary/" + langName + ".lang"; InputStream propsFiles = getClass().getClassLoader().getResourceAsStream(dictName); if (propsFiles == null) { if (logger.isWarnEnabled()) { logger.warn("Can't load " + niceName + " language dictionary (" + dictName + ")"); } continue; } Properties dictionary = new Properties(); dictionary.load(new InputStreamReader(propsFiles, Charset.forName("UTF-8"))); languages.put(language, dictionary); if (logger.isDebugEnabled()) { logger.debug("Loaded " + niceName + " language dictionary (" + dictName + ")"); } allLanguages.add(niceName); } if (logger.isDebugEnabled()) { logger.debug("Language dictionary initalised"); } } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(fatal, "Can't initalise language dictionary", e); } } } /** * Retrieve language constant from dictionary. * * @param langConstant Language constant to lookup. * @param language Language dictionary to check. * @param defaultValue Default value when not found. * @return Constant in desrired language. */ public String getConstant(String langConstant, Language language, String defaultValue) { String result = defaultValue; if (language == null) { language = defaultLanguage; } String niceName = StringUtils.capitalize(language.toString().toLowerCase(Locale.ENGLISH)); Properties dictionary = languages.get(language); if (dictionary != null) { String found = dictionary.getProperty(langConstant); if (found != null) { if (logger.isDebugEnabled()) { logger.debug("Constant " + langConstant + " found in " + niceName + " dictionary"); } result = found; } else if (logger.isWarnEnabled()) { logger.warn("Can't find constant " + langConstant + " in " + niceName + " dictionary"); } } else if (logger.isWarnEnabled()) { logger.warn("Dictionary " + niceName + " not loaded"); } return result; } public Language getDefaultLanguage() { return defaultLanguage; } public List&lt;String&gt; getLanguages() { return allLanguages; } } package com.acme.dictionary; public class TemplateDictionary { private final LanguageDictionary languageDictionary; private final Language language; public TemplateDictionary(LanguageDictionary languageDictionary, Language language) { this.language = language; this.languageDictionary = languageDictionary; } public String get(String constantName, String defaultValue) { return languageDictionary.getConstant(constantName, language, defaultValue); } } package com.acme.encryption; import com.acme.dictionary.Language; import com.acme.http.Session; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import java.io.InputStream; import java.security.Key; import java.util.Date; import java.util.Locale; import java.util.Properties; import java.util.concurrent.TimeUnit; import javax.xml.bind.DatatypeConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class Jwt { private final Logger logger = LoggerFactory.getLogger(Jwt.class); private final Marker fatal = MarkerFactory.getMarker("FATAL"); private Key jwtKey = null; /** * Instantiate a new instance of Jwt. */ public Jwt() { try { String configFile = "META-INF/encryption/jwt.config"; InputStream propsFile = getClass().getClassLoader().getResourceAsStream(configFile); if (logger.isWarnEnabled() &amp;&amp; propsFile == null) { logger.warn("Can't load JWT config (" + configFile + ")"); } else if (propsFile != null) { Properties properties = new Properties(); properties.load(propsFile); jwtKey = Keys.hmacShaKeyFor(DatatypeConverter.parseBase64Binary(properties.getProperty("key"))); if (logger.isDebugEnabled()) { logger.debug("JWT engine initalised"); } } } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(fatal, "Can't initalise JWT engine", e); } } } /** * Sign session cookie. * * @param session HTTP session object. * @return Signed session. */ public String signSession(Session session) { if (logger.isDebugEnabled()) { logger.debug("Signing session cookie"); } return Jwts.builder() .claim("sessionId", session.getId()) .claim("created", session.getCreated()) .claim("updated", session.getUpdated()) .claim("requestToken", session.getRequestToken()) .claim("authToken", session.getAuthToken()) .claim("language", session.getLanguage()) .claim("returnUrl", session.getReturnUrl()) .signWith(jwtKey) .compact(); } /** * Decrypt session cookie. * * @param signedCookie Encrypted session cookie. * @return Users session. * @see Session */ public Session getSession(String signedCookie) { Session session = null; try { Claims claims = Jwts.parser().setSigningKey(jwtKey).parseClaimsJws(signedCookie).getBody(); if (claims != null &amp;&amp; claims.get("sessionId") != null) { if (logger.isDebugEnabled()) { logger.debug("Decrypted signed session cookie"); } Date created = new Date(TimeUnit.SECONDS.toMillis((Long) claims.get("created"))); Date updated = new Date(TimeUnit.SECONDS.toMillis((Long) claims.get("updated"))); session = new Session((String) claims.get("sessionId"), created, updated); if (claims.get("language") != null) { String language = (String) claims.get("language"); if (logger.isDebugEnabled()) { logger.debug("Language: " + language); } session.setLanguage(Language.valueOf(language.toUpperCase(Locale.ENGLISH))); } if (claims.get("requestToken") != null) { if (logger.isDebugEnabled()) { logger.debug("Got request token"); } session.setRequestToken((String) claims.get("requestToken")); } if (claims.get("authToken") != null) { if (logger.isDebugEnabled()) { logger.debug("Got authentication token"); } session.setAuthToken((String) claims.get("authToken")); } if (claims.get("returnUrl") != null) { if (logger.isDebugEnabled()) { logger.debug("Got return URL"); } session.setReturnUrl((String) claims.get("returnUrl")); } } else if (logger.isWarnEnabled()) { logger.warn("Can't decrypt signed session cookie"); } } catch (JwtException e) { if (logger.isErrorEnabled()) { logger.error(fatal, "Can't decrypt session cookie", e); } session = null; } return session; } } package com.acme.format; import com.google.gson.Gson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Json { private final Logger logger = LoggerFactory.getLogger(Json.class); private final Gson gson = new Gson(); public Json() { logger.debug("Gson JSON format engine initalised"); } public String toJson(Object object) { return gson.toJson(object); } } package com.acme.http; import com.acme.http.types.RequestType; import com.acme.http.types.ResponseType; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Event implements Serializable { private static final long serialVersionUID = 1L; private Object content; private String contentType = null; private Session session; private final Routes httpRoutes; private final RequestType requestType; private final HttpServletRequest request; private final HttpServletResponse response; private ResponseType responseType; private Map&lt;String, String&gt; routeParams = new LinkedHashMap&lt;String, String&gt;(); /** * Instatiate new HTTP event object. * * @param requestType HTTP request type. * @param httpRoutes Route parsing object. * @param request HTTP request object. * @param response HTTP response object. * @param session HTTP session object. */ public Event( RequestType requestType, Routes httpRoutes, HttpServletRequest request, HttpServletResponse response, Session session) { this.requestType = requestType; this.session = session; this.request = request; this.response = response; this.httpRoutes = httpRoutes; } public void setRoute(String base, String route) { routeParams = httpRoutes.getRouteParams(base, route, request.getServletPath()); } public RequestType getType() { return requestType; } public HttpServletRequest getRequest() { return request; } public HttpServletResponse getResponse() { return response; } public Map&lt;String, String&gt; getRouteParams() { return routeParams; } public String getRouteParam(String name) { return routeParams.containsKey(name) ? routeParams.get(name) : null; } public void setContent(Object content) { this.content = content; } public Object getContent() { return content; } public void setContentType(String contentType) { this.contentType = contentType; } public String getContentType() { return contentType; } public void setSession(Session session) { this.session = session; } public Session getSession() { return session; } public void setResponseType(ResponseType responseType) { this.responseType = responseType; } public ResponseType getResponseType() { return responseType; } @Override public String toString() { return getContent() != null ? getContent().toString() : null; } } package com.acme.http; import com.acme.http.types.ResponseType; import java.io.Serializable; public class Response implements Serializable { private static final long serialVersionUID = 1L; private final ResponseType responseType; private final Event event; /** * Instatiate new HTTP response object. * * @param responseType HTTP response status code. * @param event HTTP event object. */ public Response(ResponseType responseType, Event event) { this.responseType = responseType; event.setResponseType(responseType); this.event = event; } public ResponseType getType() { return responseType; } public Event getEvent() { return event; } public Object getContent() { return event.getContent(); } @Override public String toString() { return getContent() != null ? getContent().toString() : null; } } package com.acme.http; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Routes { private final Logger logger = LoggerFactory.getLogger(Routes.class); private static final Pattern findRouteParams = Pattern.compile("([^/]+)"); private static final Pattern findParamsDef = Pattern.compile(":([^/]+)"); /** * Instantiate a new instance of route parser. */ public Routes() { if (logger.isDebugEnabled()) { logger.debug("HTTP route parser engine initalised"); } } /** * Get REST parameters from HTTP request. * * @param baseRoute Context path of servlet * @param routeDef Route path definition * @param requestPath HTTP request path * @return Map of found parameters */ public Map&lt;String, String&gt; getRouteParams(String baseRoute, String routeDef, String requestPath) { if (baseRoute != null) { routeDef = baseRoute + routeDef; } Map&lt;String, String&gt; routeParams = new LinkedHashMap&lt;String, String&gt;(); Matcher defFound = findParamsDef.matcher(routeDef); while (defFound.find()) { routeParams.put(defFound.group(1), null); routeDef = routeDef.replaceAll(Pattern.quote("/:" + defFound.group(1)), ""); } requestPath = requestPath.replaceAll(Pattern.quote(routeDef), ""); Matcher paramsFound = findRouteParams.matcher(requestPath); for (String key : routeParams.keySet()) { paramsFound.find(); if (logger.isDebugEnabled()) { logger.debug("Found route param: " + key + " value: " + paramsFound.group()); } routeParams.put(key, paramsFound.group()); } return routeParams; } /** * Matches HTTP request path against route definition. * * @param baseRoute Context path of servlet * @param routeDef Route path definition * @param requestPath HTTP request path * @return True if matched. */ public boolean routeMatched(String baseRoute, String routeDef, String requestPath) { if (baseRoute != null) { routeDef = baseRoute + routeDef; } if (routeDef.equals(requestPath)) { if (logger.isDebugEnabled()) { logger.debug("Request path: " + requestPath + " matches route: " + routeDef); } return true; } String requestPathTemp = requestPath; String routeDefTemp = routeDef; Matcher defFound = findParamsDef.matcher(routeDef); ArrayList&lt;String&gt; routeParams = new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; requestParams = new ArrayList&lt;String&gt;(); while (defFound.find()) { routeParams.add(defFound.group(1)); if (logger.isDebugEnabled()) { logger.debug("Found route param definition: " + defFound.group(1)); } routeDefTemp = routeDefTemp.replaceAll(Pattern.quote("/:" + defFound.group(1)), ""); } if (routeDef.contains(":") &amp;&amp; requestPath.startsWith(routeDefTemp)) { requestPathTemp = requestPathTemp.replaceAll(Pattern.quote(routeDefTemp), ""); Matcher paramsFound = findRouteParams.matcher(requestPathTemp); Iterator iterator = routeParams.iterator(); while (iterator.hasNext()) { iterator.next(); if (paramsFound.find()) { requestParams.add(paramsFound.group()); } } if (!routeParams.isEmpty() &amp;&amp; routeParams.size() == requestParams.size()) { if (logger.isDebugEnabled()) { logger.debug("Request path: " + requestPath + " matches route: " + routeDef); } return true; } } if (logger.isDebugEnabled()) { logger.debug("Request path: " + requestPath + " doesn't match route: " + routeDef); } return false; } } package com.acme.http; import com.acme.dictionary.Language; import java.io.Serializable; import java.util.Date; import java.util.Locale; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Session implements Serializable { private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(Session.class); private final String id; private Date created; private Date updated; private String returnUrl; private Language language; private String authToken = null; private String requestToken = null; public Session(String id) { this(id, new Date(), new Date()); } public Session(String id, Date created) { this(id, created, new Date()); } /** * Instantiate a new instance of HTTP session. * * @param id Session identifier. * @param created Date &amp;amp; time of creation. * @param updated Date &amp;amp; time of last update. */ public Session(String id, Date created, Date updated) { this.id = id; this.created = created; this.updated = updated; this.language = Language.ENGLISH; if (logger.isDebugEnabled()) { logger.debug( "Default language: " + StringUtils.capitalize(language.toString().toLowerCase(Locale.ENGLISH))); logger.debug("New sesison created"); } } public String getId() { return id; } public Date getCreated() { return created; } /** * Set the request token. * * @param requestToken Request token. */ public void setRequestToken(String requestToken) { this.requestToken = requestToken; if (logger.isDebugEnabled()) { logger.debug("Request token added"); } update(); } public String getRequestToken() { return requestToken; } /** * Set the authorisation token. * * @param authToken Authorisation token. */ public void setAuthToken(String authToken) { this.authToken = authToken; if (logger.isDebugEnabled()) { logger.debug("Auth token added"); } update(); } public String getAuthToken() { return authToken; } /** * Set the last updated date &amp;amp; time. * * @param updated Date &amp;amp; time. */ public void setUpdated(Date updated) { this.updated = updated; if (logger.isDebugEnabled()) { logger.debug("Session updated"); } } public Date getUpdated() { return updated; } /** * Set the last updated date &amp;amp; time. */ public void update() { setUpdated(new Date()); } /** * Set the users language. * * @param language Language to set. */ public void setLanguage(Language language) { if (logger.isDebugEnabled()) { logger.debug( "Language: " + StringUtils.capitalize(language.toString().toLowerCase(Locale.ENGLISH))); } this.language = language; update(); } /** * Set the return URL after authenticating. * * @param returnUrl URL to return to. */ public void setReturnUrl(String returnUrl) { if (logger.isDebugEnabled()) { logger.debug("URL to return to after login: " + returnUrl); } this.returnUrl = returnUrl; update(); } public String getReturnUrl() { return returnUrl; } public Language getLanguage() { return language; } } </code></pre> <p>I would appreciate feedback on security, code-smells and performance of this application.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:42:41.200", "Id": "412113", "Score": "1", "body": "\"feedback on security\" What is your threat model?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:45:34.627", "Id": "412114", "Score": "1", "body": "This question is incomplete. What are the file names? Why did you write what you did? If the code is too large (that's quite an achievement by the way, our limit is more than twice that of Stack Overflow), it may simply be too big to be reviewed. Don't cut out the description to save on characters. We need context, part of that is a description of the how and why (unless it's absolutely clear from the code itself, which can't be said with this much code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:48:49.890", "Id": "412116", "Score": "0", "body": "This is 32 individual classes not 1 class, It would be MUCH simpler to just clone the github repository (but this seems to be against the rules) as the tests are also included in addition to original filenames." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T17:00:56.217", "Id": "412119", "Score": "0", "body": "You should decide on a subset of your project to have reviewed. Reviewing a whole application with 32 classes is a very large undertaking in the first place. In addition to that a lot of review concerns will usually duplicate across classes. A \"cross section\" of your application is often enough to give you a lot of insight into the state of your current code base. Please do include additional information about what your code does and supplemental information that can help reviewers to answer any specific questions you might have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T17:06:56.223", "Id": "412121", "Score": "0", "body": "TBH I don't think I am going to get the help I need here :( I have now integrated PMD, spotbugs, checkstyle, jacoco & sonarcloud.io review into my workflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T17:10:20.910", "Id": "412124", "Score": "0", "body": "From a quick scroll through the code I can already see a few minor issues that could be improved ... I hope to be able to help you once the questions is a little clearer and better scoped. While static analysis is great, it can't help terribly much with design problems and naming issues (not that the quick skim I did helps there either)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T17:12:04.580", "Id": "412125", "Score": "0", "body": "A first thing that should help greatly reduce the size of code you present here would be removing the files from `com.acme.annotations`. None of them seem particularly reviewable :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:41:37.547", "Id": "412232", "Score": "0", "body": "This is my report from sonarcloud, still some refactoring to work on https://sonarcloud.io/dashboard?id=davidbyng_acme-simple-servlet-extension" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T12:20:13.317", "Id": "213034", "Score": "1", "Tags": [ "java" ], "Title": "Please check my HTTPServlet route parsing extension for quality" }
213034
<p>I'm developing a simple Snake game in Java using Swing. So far I made the snake animation which is troubling me: when the snakes moves it seems like it starts to lag for no reason, but when I move it around with the arrow keys it goes smooth.</p> <p>How could I make it move smooth also when it goes on a straight line?</p> <p><strong>GameFrame</strong></p> <pre><code>public class GameFrame extends JFrame { private GamePanel gamePanel; private JLabel scoreLabel; public GameFrame() throws HeadlessException { this.setTitle("Snake"); this.setBounds(100, 100, 400, 400); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setResizable(false); getContentPane().setLayout(null); getContentPane().setBackground(Color.BLACK); scoreLabel = new JLabel("0000"); scoreLabel.setBounds(0, 0, 70, 20); scoreLabel.setForeground(Color.WHITE); getContentPane().add(scoreLabel); gamePanel = new GamePanel(); gamePanel.setBounds(20, 20, 360, 350); this.add(gamePanel); this.setVisible(true); } } </code></pre> <p><strong>GamePanel</strong></p> <pre><code>public class GamePanel extends JPanel implements KeyListener, ActionListener { private GameManager gameManager; private Timer timer; private final int DELAY = 150; GamePanel() { this.setOpaque(true); this.setBackground(new Color(51, 51, 51)); this.addKeyListener(this); this.setFocusable(true); this.requestFocus(); gameManager = new GameManager(this); timer = new Timer(DELAY, this); timer.start(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); gameManager.renderSnake(g); } @Override public void actionPerformed(ActionEvent e) { gameManager.gameLoop(); } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: gameManager.moveSnakeUp(); break; case KeyEvent.VK_DOWN: gameManager.moveSnakeDown(); break; case KeyEvent.VK_RIGHT: gameManager.moveSnakeRight(); break; case KeyEvent.VK_LEFT: gameManager.moveSnakeLeft(); break; } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } } </code></pre> <p><strong>GameManager</strong></p> <pre><code>public class GameManager { private Color snakeColor; private Snake snake; private GamePanel gamePanel; private boolean running; public GameManager(GamePanel gamePanel) { this.gamePanel = gamePanel; snakeColor = Color.GREEN; snake = new Snake(); running = true; } public void gameLoop() { update(); draw(); } public void renderSnake(Graphics graphics) { Graphics2D graphics2D = (Graphics2D) graphics; graphics2D.setColor(snakeColor); for (Rectangle tile : snake.getBody()) graphics2D.fillRect(tile.x, tile.y, tile.width, tile.height); } public void update() { snake.move(); } public boolean isRunning() { return running; } public void draw() { gamePanel.repaint(); } public void moveSnakeUp() { snake.setUpDirection(); } public void moveSnakeDown() { snake.setDownDirection(); } public void moveSnakeRight() { snake.setRightDirection(); } public void moveSnakeLeft() { snake.setLeftDirection(); } } </code></pre> <p><strong>Snake</strong></p> <pre><code>public class Snake { private final int SNAKE_SPEED = 10; private final int BODY_WIDTH = 10; private LinkedList&lt;Rectangle&gt; body; private Directions direction; public Snake() { direction = Directions.RIGHT; body = new LinkedList&lt;&gt;(); body.add(new Rectangle(50, 20, BODY_WIDTH, BODY_WIDTH)); body.add(new Rectangle(40, 20, BODY_WIDTH, BODY_WIDTH)); body.add(new Rectangle(30, 20, BODY_WIDTH, BODY_WIDTH)); body.add(new Rectangle(20, 20, BODY_WIDTH, BODY_WIDTH)); body.add(new Rectangle(10, 20, BODY_WIDTH, BODY_WIDTH)); } public LinkedList&lt;Rectangle&gt; getBody() { return body; } public void setUpDirection() { if (direction != Directions.UP) direction = Directions.UP; } public void setDownDirection() { if (direction != Directions.DOWN) direction = Directions.DOWN; } public void setRightDirection() { if (direction != Directions.RIGHT) direction = Directions.RIGHT; } public void setLeftDirection() { if (direction != Directions.LEFT) direction = Directions.LEFT; } public void move() { Rectangle newHead = body.removeLast(); newHead.x = body.peek().x; newHead.y = body.peek().y; switch (direction) { case UP: newHead.y -= SNAKE_SPEED; break; case DOWN: newHead.y += SNAKE_SPEED; break; case RIGHT: newHead.x += SNAKE_SPEED; break; case LEFT: newHead.x -= SNAKE_SPEED; break; } body.addFirst(newHead); } } </code></pre> <p>I have tried using <code>Thread</code>, and different values for delay time but no avail. How could this be improved?</p> <p><strong>EDIT</strong></p> <p>I found a solution using <code>BufferedImage</code> which really makes a lot of difference, simple but effective:</p> <pre><code>@Override protected void paintComponent(Graphics g) { super.paintComponent(g); BufferedImage bufferedImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics bufferedGraphics = bufferedImage.getGraphics(); gameManager.renderSnake(bufferedGraphics); gameManager.renderFruit(bufferedGraphics); g.drawImage(bufferedImage, 0, 0, this); } </code></pre> <p>I also managed to have a decent animation even without using <code>Timer</code> from <code>java.Swing</code>, but using <code>Thread</code> instead. It works well for me.</p> <p>For those interested here is the <a href="https://github.com/LeonardoChirivi/snake" rel="nofollow noreferrer">code</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T05:50:07.900", "Id": "412176", "Score": "0", "body": "can you share your game loop with us (`while(running){...}`) ?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T13:58:08.453", "Id": "213039", "Score": "1", "Tags": [ "java", "performance", "swing", "animation", "snake-game" ], "Title": "Snake animation in Swing" }
213039
<p>I have been studying Python for a few months and just recently decided to stop avoiding OOP and reworked a Pong game to a more object oriented style. Please tell me how I should improve my code.</p> <p>Some of the code is an adaptation from this <a href="//stackoverflow.com/q/14700889/">Stack Overflow question about menu state</a>.</p> <p>There is a known problem with the <code>MenuScene.handle_events()</code> function, such that I need to press the space or return key multiple times to it catch the event, but I don't consider it to be a significant bug.</p> <h2>main.py</h2> <pre><code>from __future__ import absolute_import import pygame from core.config import Colors, Globals from core.scene import GameScene, SceneManager def main(): screen = pygame.display.set_mode((Globals.win_width,Globals.win_height)) pygame.display.set_caption("Pong") clock = pygame.time.Clock() manager = SceneManager() running= True pygame.init() while running: clock.tick(120) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill(Colors.black) manager.scene.render(screen) manager.scene.handle_events(pygame.event.get()) manager.scene.update() pygame.display.flip() pygame.quit() if __name__ == "__main__": main() </code></pre> <h2>scene.py</h2> <pre><code>from .actors import Player,Enemy,Ball from .config import Colors, Globals import pygame class SceneManager(object): def __init__(self): self.go_to(MenuScene()) def go_to(self, scene): self.scene = scene self.scene.manager = self class Scene(object): def __init__(self): pass def render(self, screen): raise NotImplementedError def update(self): raise NotImplementedError def handle_events(self, events): raise NotImplementedError class MenuScene(Scene): def __init__(self): super(MenuScene,self).__init__() pygame.font.init() self.font = pygame.font.SysFont('Arial', 56) self.sfont = pygame.font.SysFont('Arial', 32) pass def render(self, screen): screen.fill(Colors.green) text1 = self.font.render('Pong Rework', True, (255, 255, 255)) text2 = self.sfont.render('&gt; press SPACE to start &lt;', True, (255, 255, 255)) screen.blit(text1, (200, 50)) screen.blit(text2, (200, 350)) def update(self): pass def handle_events(self,events): for e in events: if e.type == pygame.KEYDOWN and (e.key == pygame.K_SPACE or e.key == pygame.K_RETURN): self.manager.go_to(GameScene()) class GameScene(Scene): def __init__(self): super(GameScene, self).__init__() pygame.font.init() self.font = pygame.font.SysFont("Comic Sans MS", 30) self.player = Player() self.enemy = Enemy() self.points ={"player": 0, "enemy": 0} self.player_score=self.font.render("{}".format(self.points["player"]),1,Colors.white) self.enemy_score=self.font.render("{}".format(self.points["enemy"]),1, Colors.white) self.ball = Ball() def render(self,screen): screen.blit(self.player_score,(150,100)) screen.blit(self.enemy_score,(630,100)) pygame.draw.rect(screen,Colors.white,self.player) pygame.draw.rect(screen,Colors.white,self.enemy) pygame.draw.rect(screen,Colors.white,self.ball) def update(self): pressed = pygame.key.get_pressed() up,down = [pressed[key] for key in (pygame.K_UP, pygame.K_DOWN)] self.handle_point() self.player.update(up,down) self.enemy.update(self.ball.y) self.ball.update(self.player,self.enemy) return def handle_events(self, events): for event in events: if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: pass def handle_point(self): def update_points(key) : self.points[key] +=1 self.player_score=self.font.render("{}".format(self.points["player"]),1,Colors.white) self.enemy_score=self.font.render("{}".format(self.points["enemy"]),1, Colors.white) if self.ball.x &lt;= self.ball.width: update_points("enemy") self.ball.reset() if self.ball.x &gt;= (Globals.win_width + self.ball.width): update_points("player") self.ball.reset() self.ball.dir_x *= -1 </code></pre> <h2>actors.py</h2> <pre><code>import pygame from .config import Globals, Colors from math import cos,sin,radians,pi class Player(pygame.Rect): def __init__(self): super(Player,self).__init__(20,225,20,150) self.velocity = 5 print("player class initated") def update(self,up,down): if up and self.y &gt;= 10: self.y -= self.velocity if down and self.y &lt;= Globals.win_height - (self.height +10): self.y += self.velocity pass class Enemy(pygame.Rect): def __init__(self): super(Enemy,self).__init__(760,225,20,150) self.velocity = 3 print("enemy class initated") def update(self,ballYpos): middle = self.y + self.height /2 if ballYpos != middle: if ballYpos &gt; middle and self.y &lt;= Globals.win_height- (self.height+self.velocity): self.y += self.velocity if ballYpos &lt; middle and self.y &gt;= self.velocity*2: self.y -= self.velocity class Ball(pygame.Rect): def __init__(self): super(Ball,self).__init__(400,300,20,20) self.velocity = 5 self.angle = radians(0) self.dir_x = cos(self.angle) self.dir_y = -sin(self.angle) print("Ball class instancieted") def reset(self): self.x =400 self.y = 300 self.angle = radians(0) self.dir_x = cos(self.angle) self.dir_y = -sin(self.angle) def update(self,player,enemy): self.x += self.dir_x * self.velocity self.y += self.dir_y * self.velocity self.handle_bound_collision() self.handle_paddle_collision(player,enemy) def handle_bound_collision(self): if self.y &lt;= 0 or self.y&gt;= Globals.win_height - 10: self.dir_y*= -1.05 def handle_paddle_collision(self,player,enemy): intersectY = self.y if self.colliderect(player): relativeIntersectY = (player.y + (player.height / 2) ) - intersectY normalizedRelativeIntersectY = relativeIntersectY / (player.height/2) self.angle = radians(normalizedRelativeIntersectY * 60) self.dir_x = cos(self.angle) self.dir_y = -sin(self.angle) if self.colliderect(enemy): relativeIntersectY = (enemy.y + (enemy.height/2)) - intersectY normalizedRelativeIntersectY = relativeIntersectY / (enemy.height/2) self.angle = radians(normalizedRelativeIntersectY * 60) self.dir_x = -cos(self.angle) self.dir_y = sin(self.angle) </code></pre> <h2>config.py</h2> <pre><code>class Globals: win_width = 800 win_height = 600 class Colors: white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (0,255,0) blue = (0,0,255) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T14:04:10.750", "Id": "412081", "Score": "0", "body": "If there is a significant known bug, then you should fix it before asking for a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T14:07:34.833", "Id": "412082", "Score": "0", "body": "Sorry, the bug was not significant in my point of view as this is only a study case of oop, i shouldnt have mentioned it" } ]
[ { "body": "<p><strong>Gameplay:</strong> </p>\n\n<p>By placing the paddle in a specific position I managed to break the game (see the image). I think you should add a random starting angle when the game restarts. </p>\n\n<p>Also, as <a href=\"https://en.wikipedia.org/wiki/Pong#Gameplay\" rel=\"noreferrer\">Wikipedia</a> says the game should be finished once someone reaches eleven points.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tpk6Um.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/tpk6Um.png\" alt=\"I_broke_the_game.jpg\"></a></p>\n\n<p><strong>Code:</strong> </p>\n\n<p>You violate some of the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> style recommendations, namely:</p>\n\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"noreferrer\">order of imports</a></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"noreferrer\">blank lines</a></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"noreferrer\">maximum line length</a></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">variable names</a> (e.g. <code>normalizedRelativeIntersectY</code> should be <code>normalized_relative_intersect_y</code>)</li>\n</ul>\n\n<hr>\n\n<p>In some methods like <code>GameScene.update</code> or <code>Player.update</code> you have empty <code>return</code> or <code>pass</code> statements after code blocks. They are redundant and should be removed.</p>\n\n<hr>\n\n<p>Consider changing the class <code>Globals</code> that consists of only width and height of the screen to a <a href=\"https://docs.python.org/library/collections.html#collections.namedtuple\" rel=\"noreferrer\"><code>namedtuple</code></a>:</p>\n\n<pre><code>import namedtuple\n\nSize = namedtuple('Size', ['width', 'height'])\nWINDOW_SIZE = Size(width=800, height=600)\n</code></pre>\n\n<p>So, you could use it in two different ways. As a tuple in <code>main</code>:</p>\n\n<pre><code>screen = pygame.display.set_mode(WINDOW_SIZE)\n</code></pre>\n\n<p>and as a class with <code>width</code> and <code>height</code> attributes, for example in <code>Player.update</code>:</p>\n\n<pre><code>if down and self.y &lt;= WINDOW_SIZE.height - (self.height + 10):\n</code></pre>\n\n<hr>\n\n<p>In the <em>config.py</em> you have a class with colors, but pygame has a special class for that already: <a href=\"https://www.pygame.org/docs/ref/color.html\" rel=\"noreferrer\"><code>pygame.Color</code></a>.\nFor example, in <code>main</code> you would simply write:</p>\n\n<pre><code>screen.fill(pygame.Color('black'))\n</code></pre>\n\n<p>I think it would make sense to move lots of hardcoded values as fonts and dimensions of objects to the <em>config.py</em> file though. Also, be careful, some of your hardcoded values depend on each other, as in the <code>Player</code> class where you check if the paddle is going over the border. That <code>10</code> in <code>if up and self.y &gt;= 10:</code> should be tied with the paddle's dimensions <code>super(Player,self).__init__(20,225,20,150)</code>. </p>\n\n<p>By the way, the last piece should be rewritten as <code>super().__init__(20, 225, 20, 150)</code>. It's been like this since Python 3.0: <a href=\"https://www.python.org/dev/peps/pep-3135/\" rel=\"noreferrer\">PEP 3135 -- New Super</a>.</p>\n\n<hr>\n\n<p>In some places you convert integers to strings using <code>format</code>:</p>\n\n<pre><code>self.player_score=self.font.render(\"{}\".format(self.points[\"player\"]),1,Colors.white)\n</code></pre>\n\n<p>but it can be done by using <code>str</code> function:</p>\n\n<pre><code>self.player_score = self.font.render(str(self.points[\"player\"]), 1, pygame.Color('white'))\n</code></pre>\n\n<hr>\n\n<p>Finally, don't print things like <code>print(\"player class initated\")</code>. As these things are for debugging purposes, consider using <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"noreferrer\"><code>logging</code></a> module.</p>\n\n<hr>\n\n<p>On overall, well done! I'm not a fan of OOP but it was easy to read and understand your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T15:31:45.130", "Id": "213103", "ParentId": "213040", "Score": "6" } } ]
{ "AcceptedAnswerId": "213103", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T14:00:02.210", "Id": "213040", "Score": "6", "Tags": [ "python", "beginner", "object-oriented", "pygame", "pong" ], "Title": "First OOP in Python 3: Pygame Pong" }
213040
A classic arcade game in which two players control paddles to bounce a ball back to their opponent (like air hockey)
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T14:25:14.420", "Id": "213043", "Score": "0", "Tags": null, "Title": null }
213043
<p>My intention is to have a component that serves as a textbox wrapper and able to set the error state, error message, and allow the parent to pass a function that sets its local error as I did not see a way to read from the child component's state.</p> <p>Current known limitations:</p> <ul> <li>Can only pass a single value to the validation function which will be the event target value</li> <li>Will only return 1 error at a time, attempting to format helper text with jsx would only show [object]</li> </ul> <p><strong>Component</strong>:</p> <pre><code>import * as React from 'react'; import * as _ from 'lodash' import { IValidationItem } from '../../../Interfaces/IValidationItem' import TextField, { TextFieldProps } from "@material-ui/core/TextField"; interface IValidatedTextFieldProps { validate?: IValidationItem[], validateon?: 'onBlur' | 'onChange', validationerror?: (hasError?: boolean) =&gt; void } interface IValidatedTextFieldState { validationErrorMessage: string, validationError: boolean } type ValidatedTextFieldAllProps = IValidatedTextFieldProps &amp; TextFieldProps class ValidatedTextField extends React.Component&lt;ValidatedTextFieldAllProps, IValidatedTextFieldState&gt; { public constructor(props: ValidatedTextFieldAllProps) { super(props); this.state = { validationErrorMessage: "", validationError: false } } public validationWrapper = (event: any) =&gt; { const { validate, } = this.props; return !validate ? "" : _.forEach(validate, (validationItem: IValidationItem) =&gt; { const result = !validationItem.func(event.target.value) if (result) { this.setState({ validationErrorMessage: validationItem.validationMessage }); this.setState({ validationError: result }) this.callParentValidationErrorMethod(result) return false; } else { this.setState({ validationErrorMessage: "" }); this.setState({ validationError: result }) this.callParentValidationErrorMethod(result) return; } }); }; public onBlurValidation = (event: any) =&gt; { const { onBlur, validateon, validate } = this.props; if (_.isFunction(onBlur)) { onBlur(event); } if (validateon === "onBlur" &amp;&amp; !!validate) { this.validationWrapper(event); } public onChangeValidation = (event: any) =&gt; { const { onChange, validateon, validate } = this.props; if (_.isFunction(onChange)) { onChange(event); } if (validateon === "onChange" &amp;&amp; !!validate) { this.validationWrapper(event); }; } public callParentValidationErrorMethod = (hasError: boolean) =&gt; { if(_.isFunction(this.props.validationerror)) { this.props.validationerror(hasError); } } public render() { const { validationErrorMessage, validationError } = this.state const {validationerror,validate,validateon, ...textFieldProps } = this.props; return (&lt;TextField {...textFieldProps} onBlur={(event: any) =&gt; { this.onBlurValidation(event); }} onChange={(event: any) =&gt; { this.onChangeValidation(event); } } error={validationError} helperText={validationErrorMessage} /&gt;) } } export default ValidatedTextField; </code></pre> <p><strong>ValidationItem Interface</strong></p> <pre><code>export interface IValidationItem { func: (eventValue?: string) =&gt; boolean, validationMessage: string } </code></pre> <p><strong>ValidationItem implementation</strong></p> <pre><code>import { IValidationItem } from '../../Interfaces/IValidationItem'; export class ValidationItem implements IValidationItem { public func: (eventValue?: string) =&gt; boolean public validationMessage: string constructor(func: (eventValue?: string) =&gt; boolean, validationMessage: string) { this.func = func; this.validationMessage = validationMessage; } } </code></pre> <p><strong>Validations List Class</strong></p> <pre><code>import {ValidationItem} from './ValidationItem'; export class Validations { public static required = new ValidationItem((eventValue: string) =&gt; !!eventValue , "This Field is Required"); public static allowedNameCharacters = new ValidationItem((eventValue: string) =&gt; { const regularExpression = RegExp('^[a-zA-Z0-9\&amp;\-]+$'); return regularExpression.test(eventValue)} , "Input may only contain alphanumeric, &amp;, or - characters"); public static alphanumericCharactersOnly = new ValidationItem((eventValue: string) =&gt; { const regularExpression = RegExp('^[a-zA-Z0-9]+$'); return regularExpression.test(eventValue)} , "Input may only contain alphanumeric characters"); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T14:39:50.560", "Id": "213044", "Score": "2", "Tags": [ "validation", "form", "react.js", "jsx" ], "Title": "Textbox validation component" }
213044
<p>I'm creating a website about an auto show that the user is going to. I'm collecting input from them via textboxes, check boxes, radio buttons, etc. I'm presenting them with a confirmation that the information they entered is correct. Is the way I'm doing this the most efficient, injecting the HTML into the website via JavaScript?</p> <p><strong>online_form.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Online Form - BA&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="external/style.css"&gt; &lt;script src="external/script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- NAV START --&gt; &lt;hr&gt; &lt;a href="index.html"&gt;Main Page&lt;/a&gt; - &lt;a href="online_form.html"&gt;Online Form&lt;/a&gt; - &lt;a href="special.html"&gt;Specialty Car&lt;/a&gt; &lt;hr&gt; &lt;!-- NAV END --&gt; &lt;h2&gt;Complete this online form to get into the Ann Arbor Auto Show for &lt;i&gt;FREE&lt;/i&gt;&lt;/h2&gt; &lt;form action="" method="post"&gt; &lt;fieldset&gt; &lt;label&gt;Name:&lt;/label&gt; &lt;input type="text" id="name"&gt;&lt;br&gt; &lt;label&gt;Age:&lt;/label&gt; &lt;input type="text" id="age"&gt;&lt;br&gt; &lt;label&gt;Email:&lt;/label&gt; &lt;input type="text" id="email"&gt;&lt;br&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;h3&gt;What is your reason for attending the Ann Arbor Auto Show?&lt;/h3&gt; &lt;input type="radio" name="reason" value="cars"&gt;I like cars&lt;br&gt; &lt;input type="radio" name="reason" value="been_before"&gt;I've been here before&lt;br&gt; &lt;input type="radio" name="reason" value="friend"&gt;A friend told me&lt;br&gt; &lt;input type="radio" name="reason" value="other"&gt;Other&lt;br&gt; &lt;p&gt;If other, please explain:&lt;/p&gt; &lt;textarea rows="2" cols="20"&gt;&lt;/textarea&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;h3&gt;What color cars do you like?&lt;/h3&gt; &lt;input type="checkbox" name="color" value="red"&gt;Red&lt;br&gt; &lt;input type="checkbox" name="color" value="blue"&gt;Blue&lt;br&gt; &lt;input type="checkbox" name="color" value="green"&gt;Green&lt;br&gt; &lt;input type="checkbox" name="color" value="orange"&gt;Orange&lt;br&gt; &lt;input type="checkbox" name="color" value="yellow"&gt;Yellow&lt;br&gt; &lt;input type="checkbox" name="color" value="purple"&gt;Purple&lt;br&gt; &lt;input type="checkbox" name="color" value="black"&gt;Black&lt;br&gt; &lt;input type="checkbox" name="color" value="white"&gt;White&lt;br&gt; &lt;/fieldset&gt; &lt;button type="button" onclick="checkInformation()"&gt;Submit&lt;/button&gt; &lt;button type="reset"&gt;Reset&lt;/button&gt; &lt;div id="conformation"&gt;&lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>script.js</strong></p> <pre><code>function Form() { this._name = document.getElementById('name').value; this.age = document.getElementById('age').value; this.email = document.getElementById('email').value; this.conformation = document.getElementById('conformation'); /* * Reset this.conformation if user clicks `no` button */ this.conformation.innerHTML = ""; this.response = '&lt;h3&gt;Is this information correct?&lt;/h3&gt;\n'; this.response += '&lt;p&gt;Name: ' + this._name + '&lt;/p&gt;\n'; this.response += '&lt;p&gt;Age: ' + this.age + '&lt;/p&gt;\n'; this.response += '&lt;p&gt;Email: ' + this.email + '&lt;/p&gt;\n'; this.response += '&lt;button type="button" onclick="yes()"&gt;Yes&lt;/button&gt;'; this.response += '&lt;button type="reset" onclick="no()"&gt;No&lt;/button&gt;'; this.send_conformation = function() { this.conformation.style.display = "block"; this.conformation.innerHTML = this.response; } } var form; function checkInformation() { form = new Form(); form.send_conformation(); } function yes() { /* To be implemented */} function no() { var conf = document.getElementById('conformation'); conf.style.display = "none"; } </code></pre>
[]
[ { "body": "<p>Replace <code>document.getElementById</code>s with a <code>forEach</code> and the <code>this.response</code> lines with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">template literals</a> to keep the code <a href=\"https://dzone.com/articles/is-your-code-dry-or-wet\" rel=\"nofollow noreferrer\">DRY</a> :</p>\n\n<pre><code>function Form () {\n\n [\"_name\", \"age\", \"email\", \"confirmation\"].forEach(key =&gt; {\n const id = key.replace(/^_/, ''); // removes the _ in the beginning\n this[key] = document.getElementById(id).value;\n });\n\n /*\n * Reset this.conformation if user clicks `no` button\n */\n\n this.conformation.innerHTML = \"\";\n\n this.response = `\n &lt;h3&gt;Is this information correct?&lt;/h3&gt;\\n\n &lt;p&gt;Name: ${this._name}&lt;/p&gt;\\n\n &lt;p&gt;Age: ${this.age}&lt;/p&gt;\\n\n &lt;p&gt;Email: ${this.email}&lt;/p&gt;\\n\n &lt;button type=\"button\" onclick=\"yes()\"&gt;Yes&lt;/button&gt;\n &lt;button type=\"reset\" onclick=\"no()\"&gt;No&lt;/button&gt;`;\n\n this.send_conformation = function() {\n this.conformation.style.display = \"block\";\n this.conformation.innerHTML = this.response;\n }\n}\n\nvar form;\n\nfunction checkInformation () {\n form = new Form();\n form.send_conformation();\n}\n\nfunction yes { /* To be implemented */}\n\nfunction no {\n document.getElementById('conformation').style.display = \"none\"; \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:13:10.573", "Id": "213054", "ParentId": "213045", "Score": "3" } } ]
{ "AcceptedAnswerId": "213054", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T14:45:54.670", "Id": "213045", "Score": "2", "Tags": [ "javascript", "html", "form", "dom" ], "Title": "HTML form with confirmation before submission" }
213045
<p>There were multiple times in different applications that I needed to accomplish the following behavior with C# <code>Task</code> and I did it in a certain way, and would like to receive an insight whether it's the best way to achieve the desired effect, or there are other better ways.</p> <p>The issue is that in certain circumstances I would like a specific <code>Task</code> to exist only in one instance. For example, if someone requests, let's say a list of products by executed a method like <code>Task GetProductsAsync()</code>, and someone else tries to request the same thing, it wouldn't fire another task, but rather return already existing task. When the <code>GetProductsAsync</code> finishes, all of those callers who had previously requested the result will receive the same result. So, there should ever be only one <code>GetProductsAsync</code> execution at a given point of time.</p> <p>After failed trials to find something similar and well known design pattern to solve this issue, I came up with my own implementation:</p> <pre><code>public class TaskManager : ITaskManager { private readonly object _taskLocker = new object(); private readonly Dictionary&lt;string, Task&gt; _tasks = new Dictionary&lt;string, Task&gt;(); private readonly Dictionary&lt;string, Task&gt; _continuations = new Dictionary&lt;string, Task&gt;(); public Task&lt;T&gt; ExecuteOnceAsync&lt;T&gt;(string taskId, Func&lt;Task&lt;T&gt;&gt; taskFactory) { lock(_taskLocker) { if(_tasks.TryGetValue(taskId, out Task task)) { if(!(task is Task&lt;T&gt; concreteTask)) { throw new TaskManagerException($"Task with id {taskId} already exists but it has a different type {task.GetType()}. {typeof(Task&lt;T&gt;)} was expected"); } else { return concreteTask; } } else { Task&lt;T&gt; concreteTask = taskFactory(); _tasks.Add(taskId, concreteTask); _continuations.Add(taskId, concreteTask.ContinueWith(_ =&gt; RemoveTask(taskId))); return concreteTask; } } } private void RemoveTask(string taskId) { lock(_taskLocker) { if(_tasks.ContainsKey(taskId)) { _tasks.Remove(taskId); } if(_continuations.ContainsKey(taskId)) { _continuations.Remove(taskId); } } } } </code></pre> <p>The idea is that we will have a single instance of <code>TaskManager</code> throughout the application lifetime. Any async Task request that should be executed only once at a given point in time, will call <code>ExecuteOnceAsync</code> providing the factory method to create the Task itself, and desired application wide unique ID. Any other task that will come in with the same ID, the Task manager with reply with the same instance of Task created before. Only if there are no other Tasks with that ID, the manager will call the factory method and will start the task. I have added locks around code task creation and removal, to ensure thread safety. Also, in order to remove the task from the stored dictionary after Task has been completed, I've added a continuation task using <code>ContinueWith</code> method. So, after a task has been completed, both the task itself, and its continuation will be removed.</p> <p>From my side this seems to be a pretty common scenario. I would assume there is a well established design pattern, or perhaps C# API that accomplishes this exact same thing. So, any insights or suggestions will be very appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T15:54:30.693", "Id": "412099", "Score": "0", "body": "I'm not sure it's such a good idea... what if one method that requested a list of something and another one too and the first one modifies it so it will also be modified for the second method... this would get nasty pretty quickly. Usually we protect resources from being accessed at the same time, not returning the same result to multiple callers... unless the results are immutable I wouldn't want to use this manager or look for bugs it causes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T07:47:18.367", "Id": "412186", "Score": "0", "body": "@t3chb0t Thanks for the reply. In our case we do need to return the same result if asked multiple times at the same time, instead of just protecting the resource from getting accessed simultaneously. So, I do need this type of behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T07:48:22.350", "Id": "412187", "Score": "0", "body": "Well, this looks much more like you need a cache..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T07:50:16.253", "Id": "412188", "Score": "0", "body": "Good point, I thought about that, but then I realized it's not cache either. Cause when all requests are completed, if someone tries to do the same request, it should be re-executed, instead of being fetched from cache." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T07:51:50.657", "Id": "412189", "Score": "0", "body": "Could you reveal your real use case scenario? I think this way you would get much better feedback if we knew what we are actually solving here." } ]
[ { "body": "<p>What's the point of <code>_continuations</code>? I can see three options which use a single dictionary:</p>\n\n<ol>\n<li>Just store and return <code>concreteTask</code>. If this fails because the continuation is GC'd, document this for the benefit of maintainers.</li>\n<li>Just store and return the continuation. If this fails because the continuation is executed multiple times, document it.</li>\n<li>Store the task and return the continuation, so the first caller has the hard reference. I can't think how this could fail unless the caller actively discards the task.</li>\n</ol>\n\n<p>TL;DR: if there are obvious ways of simplifying the code which break for non-obvious reasons, document the reasons so that the maintainer doesn't break it.</p>\n\n<hr>\n\n<p>A further advantage of using a single dictionary would be that you could use <code>ConcurrentDictionary</code> instead of the manual locking. (In fact you could do this even if you do need both copies of the task, using <code>ConcurrentDictionary&lt;string, Tuple&lt;Task, Task&gt;&gt;</code>). The code might be as simple as</p>\n\n<pre><code> public class TaskManager : ITaskManager\n {\n private readonly ConcurrentDictionary&lt;string, Task&gt; _tasks = new ConcurrentDictionary&lt;string, Task&gt;();\n\n public Task&lt;T&gt; ExecuteOnceAsync&lt;T&gt;(string taskId, Func&lt;Task&lt;T&gt;&gt; taskFactory)\n {\n var task = _tasks.GetOrAdd(\n taskId,\n id =&gt; taskFactory().ContinueWith(_ =&gt; _tasks.TryRemove(taskId, out var _)));\n return (task as Task&lt;T&gt;) ??\n throw new Exception($\"Task with id {taskId} already exists but it has a different type {task.GetType()}. {typeof(Task&lt;T&gt;)} was expected\");\n }\n }\n</code></pre>\n\n<hr>\n\n<p>I would like to add: I like the level of detail in the exception message. That should be very helpful in tracking down bugs if it is thrown and logged.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:51:06.727", "Id": "213087", "ParentId": "213048", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T15:07:03.883", "Id": "213048", "Score": "0", "Tags": [ "c#", "async-await" ], "Title": "Enforcing C# Task to exist only once at any given point of time for a given ID" }
213048
<p><strong>Edit</strong>: Following answers, I modified my code, and wrote <a href="https://codereview.stackexchange.com/questions/213106/switch-case-pattern-for-non-constant-types-part-2">an other question</a>.</p> <hr> <h1>History</h1> <p>Recently, I (stupidly) tried to make a switch on <code>myObj.GetType()</code>. Of course, it didn't work. Then I made an ugly (this is subjective) <code>if ... else if ... else if ... else ...</code> list.<br> I ask myself if I couldn't make something to keep the <code>switch-case</code> architecture, and then I started experienced things.</p> <h1>Expected</h1> <p>To keep the structure of a <em>real</em> <code>switch-case</code>, I want to use it in this way:</p> <pre><code>Switch(myInt) .Case(1, EqualsOneMethod) .Case(2, EqualsTwoMethod) .CaseWhen(i =&gt; i &lt;= 0, NullOrNegativeMethod) .Default(DefaultMethod); </code></pre> <hr> <pre><code>static void EqualsOneMethod() { ... } static void EqualsTwoMethod() { ... } static void NullOrNegativeMethod() { ... } static void DefaultMethod() { ... } </code></pre> <h1>Code</h1> <p>Everything starts with this interface:</p> <pre><code>public interface ISwitchCase&lt;T&gt; { ISwitchCase&lt;T&gt; Case(T value, Action action); ISwitchCase&lt;T&gt; Case(T value, IEqualityComparer&lt;T&gt; comparer, Action action); ISwitchCase&lt;T&gt; CaseWhen(Predicate&lt;T&gt; predicate, Action action); void Default(Action action); } </code></pre> <hr> <p>The <em>normal</em> implementation is this one:</p> <pre><code>internal class SwitchCase&lt;T&gt; : ISwitchCase&lt;T&gt; { private T Value { get; } public SwitchCase(T value) { Value = value; } public ISwitchCase&lt;T&gt; Case(T value, Action action) { if (Value is IEquatable&lt;T&gt;) return CaseWhen(t =&gt; ((IEquatable&lt;T&gt;)t).Equals(value), action); if (value is IEquatable&lt;T&gt;) return CaseWhen(t =&gt; ((IEquatable&lt;T&gt;)value).Equals(t), action); return Case(value, EqualityComparer&lt;T&gt;.Default, action); } public ISwitchCase&lt;T&gt; Case(T value, IEqualityComparer&lt;T&gt; comparer, Action action) { return CaseWhen(t =&gt; comparer.Equals(Value, value), action); } public ISwitchCase&lt;T&gt; CaseWhen(Predicate&lt;T&gt; predicate, Action action) { if (predicate(Value)) { action(); return EmptySwitchCase&lt;T&gt;.Instance; } return this; } public void Default(Action action) =&gt; action(); } </code></pre> <hr> <p>Whenever a case fullfils its predicate, it returns an <code>EmptySwitchCase</code>, which is the following:</p> <pre><code>internal class EmptySwitchCase&lt;T&gt; : ISwitchCase&lt;T&gt; { public static EmptySwitchCase&lt;T&gt; Instance { get; } static EmptySwitchCase() { Instance = new EmptySwitchCase&lt;T&gt;(); } private EmptySwitchCase() { } public ISwitchCase&lt;T&gt; Case(T value, Action action) =&gt; this; public ISwitchCase&lt;T&gt; Case(T value, IEqualityComparer&lt;T&gt; comparer, Action action) =&gt; this; public ISwitchCase&lt;T&gt; CaseWhen(Predicate&lt;T&gt; predicate, Action action) =&gt; this; public void Default(Action action) { } } </code></pre> <p>Thanks to this <code>EmptySwitchCase</code>, once a <code>case</code> is <em>executed</em>, no other <code>case</code> / <code>default</code> will be triggered.</p> <hr> <p>Finally, as all these classes are <code>internal</code>, a simple <code>static class</code> is used as a facade:</p> <pre><code>public static class Bar // couldn't find a correct name... { public static ISwitchCase&lt;T&gt; Switch&lt;T&gt;(T value) =&gt; new SwitchCase&lt;T&gt;(value); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T15:48:43.370", "Id": "412098", "Score": "0", "body": "Could you please add all code and replace the `...` in `EqualsOneMethod` etc. with actual implementations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:13:19.587", "Id": "412103", "Score": "2", "body": "@t3chb0t: To what end? OP's question focuses on the structure used to get to those methods, regardless of what each method body entails." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:14:33.157", "Id": "412104", "Score": "0", "body": "Switching on type is possible nowadays with [pattern matching](https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:28:44.637", "Id": "412108", "Score": "1", "body": "Minor nitpick: you are not posting buildable code, as `.CaseWhen(i <= 0, NullOrNegativeMethod)` is not syntactically valid (the first parameter passed in a boolean whereas `CaseWhen` expects a `Predicate`). Also, your `Switch` class doesn't actually have a `CaseWhen` method, so there are several issues at play here. This code does not work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T18:43:57.917", "Id": "412137", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Consider posting a follow-up question instead, after waiting at least 24h. More answers may be incoming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:11:03.710", "Id": "412208", "Score": "3", "body": "@Mast: Checking the revision history, the only changes OP made are changes that fix the code to make it buildable. That's not the same as updating the answer based on the given review; OP was simply fixing the code that still needs to be reviewed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T14:27:29.613", "Id": "412249", "Score": "1", "body": "@Flater Since the changes appear to be based on your answer, we can't accept the edits even partly invalidating said answer. If the code was bugged beyond review without the edit, it shouldn't have been answered *before* the edit. In this case, I highly recommend leaving this question be and let OP and interested reviewers put their effort in the next question. Just leave this one be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T14:44:23.803", "Id": "412255", "Score": "0", "body": "@Mast: The changes are based on my comment, not on my answer. I'll remove the first mention from my answer because it was indeed a typo on OP's part, but blocking the question edit here is counterproductive. I fully agree with the rule you're pointing to but it simply does not apply to the changes OP made." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T15:12:28.267", "Id": "412259", "Score": "1", "body": "@Flater This potentially increases the mess since in the meantime another answer has been posted. However, I don't know whether this actually happened, so while I completely disagree with your actions, I won't follow up on it." } ]
[ { "body": "<pre><code>.Case(2, EqualsTwoMethod)\n.CaseWhen(i &lt;= 0, NullOrNegativeMethod)\n</code></pre>\n\n<p>For consistency's sake, I'd suggest to always keep using the predicate:</p>\n\n<pre><code>.CaseWhen(i =&gt; i == 2, EqualsTwoMethod)\n.CaseWhen(i =&gt; i &lt;= 0, NullOrNegativeMethod)\n</code></pre>\n\n<p>It seems a bit counterintuitive that you'd create a custom method for equality checks, but then use a much broader predicate that handles basically any other boolean evaluation.</p>\n\n<hr>\n\n<p>The biggest issue I have here is that you're not leveraging OOP. Your current usage suggests that you rebuild a new <code>Switch</code> every time you wish to use it for execution. But since the entire switch is built using constant or hardcoded expressions, it makes no sense to have to rebuild it every time.</p>\n\n<p>While I do understand that you're trying to mimic the syntax of an actual <code>switch</code> as closely as possible, this is going to cause performance issues in iterative loops. Simply put:</p>\n\n<pre><code>for(int i = 0; i &lt; 10; i++)\n{\n Switch(i)\n .Case(1, EqualsOneMethod)\n .Case(2, EqualsTwoMethod)\n .CaseWhen(i &lt;= 0, NullOrNegativeMethod)\n .Default(DefaultMethod);\n}\n</code></pre>\n\n<p>You will have instantiated 10 <code>Switch</code> objects.</p>\n\n<p>Instead, how about you create your <code>Switch</code> case once and then reuse it? The only difference is that you then have to pass <code>myInt</code> <em>after</em> you've created the switch:</p>\n\n<pre><code>var mySwitch = (new Switch&lt;int&gt;())\n .CaseWhen(i =&gt; i == 1, EqualsOneMethod)\n .CaseWhen(i =&gt; i == 2, EqualsTwoMethod)\n .CaseWhen(i =&gt; i &lt;= 0, NullOrNegativeMethod)\n .Default(DefaultMethod);\n\nfor(int i = 0; i &lt; 10; i++)\n{\n mySwitch.EvaluateFor(i);\n}\n</code></pre>\n\n<p>This means that you first build your switch (once), and then reuse it as many times as you need. This leverages OOP much better because you are not consuming and releasing switch objects for every single check you want to do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:12:47.177", "Id": "412209", "Score": "0", "body": "I do not like the _only predicate_ choice, because this is what I want to avoid with the `if ... else if ... else ...` method. I do not want to manually write `.CaseWhen(type => type == typeof(MyClass))`, which is the same thing that (maybe _worse than_) `if (myType == typeof(MyClass))`. I want to use it in this way: `Switch(myType) .Case(typeof(String),StringMethod) .Case(typeof(int),IntMethod) .Default(DefaultMethod)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:16:32.670", "Id": "412210", "Score": "0", "body": "Else, I understand your point and totally agree with it, thank you for your answer! I do not accept it for now but it will probably be in a near future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:17:43.750", "Id": "412222", "Score": "0", "body": "@MaximeRecuerda: Fair enough about not wanting to always use the predicate, but I would expect to see more than just equality checks then. You didn't actually develop a type matching case in your example, so my review cannot be based on its (non)existence. Also, I would suggest doing `Case<string>(StringMethod)` to create a slightly cleaner syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T14:57:42.253", "Id": "412256", "Score": "0", "body": "I might be misunderstood, I do not want it to work _only_ with `Type`, so your suggestion doesn't work. I almost finished re-building the whole thing, (I hope that) I'll make my question more precise about what I really want." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:34:20.010", "Id": "213055", "ParentId": "213049", "Score": "2" } }, { "body": "<p>The co-occurrence of <code>Value</code> and <code>value</code> in the same methods is irritating and likely to lead to bugs: I would rename <code>value</code> to <code>query</code> or something like that (and shall call <code>value</code> by <code>query</code> for the rest of this answer in the interests of not making any mistakes myself).</p>\n\n<hr />\n\n<p>I was initially dubious of Flater's suggestion that creating the <code>SwitchCase</code> objects would be a problem given all the predicates flying around, so I looked at the memory characteristics of his example loop (only with a few more zeros on the end), and saw that I was completely wrong:</p>\n\n<p><a href=\"https://i.stack.imgur.com/gjlDt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gjlDt.png\" alt=\"enter image description here\"></a></p>\n\n<p>Note all the predicates and boxed <code>int</code>s (always a bad sign). All those predicates are not the ones the caller wrote: those are predicates created by the <code>Case(T, ...)</code> methods, and all the <code>Int32</code>s are integers being boxed so they can be cast as <code>IEquatable&lt;int&gt;</code>. If you change Flater's code to one which only uses the <code>Case(Predicate&lt;T&gt;, ...)</code> overload, everything disappears with the exception of the <code>SwitchCase</code>s (the caller's predicates are reused), and as Flater says, you can remove those too by caching and improve the method memory characteristics dramatically.</p>\n\n<hr />\n\n<p>Now to diverge from the code itself... there may be little point in your <code>if (Value is IEquatable&lt;T&gt;)</code> condition, since the <code>EqualityComparer</code> will do that for you. The only thing it gives you, is that it will use <code>T</code>'s implementation of <code>IEquatable&lt;T&gt;</code> by default rather than <code>query</code>'s: this sort of thing needs to carefully documented, because it could cause someone down the line no-end of confusion when they try to 'override' the comparison by implementing <code>IEquatable&lt;T&gt;</code> in a super-class of <code>T</code>, only to have it ignored. This feels the wrong way round to me; however, personally I wouldn't do the check for either, and would solely depend on the <code>EqualityComparer</code> (and maybe a comparer passed to the constructor). If I did want to use <code>query</code>'s implementation, then I probably ought to know either that it has an implementation to use (and when it will be used), in which case the caller can decide if they want to use it or not. I'd rather provide a performant version with statically determinable behaviour:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>public ISwitchCase&lt;T&gt; Case&lt;S&gt;(S query, Action action) where S : IEquatable&lt;T&gt;\n{\n if (query.Equals(Value))\n {\n action();\n return EmptySwitchCase&lt;T&gt;.Instance;\n }\n\n return this;\n}\n</code></pre>\n\n<p>Such a method also has the advantage of being efficient when handling <code>structs</code>, as it doesn't involve any boxing. I've also in-lined the conditional logic, because it avoids the allocation of the <code>Predicate&lt;T&gt;</code> and its body (which can't be reused).</p>\n\n<p>This doesn't solve the boxing <code>int</code> problem in Flater's example, because the <code>Case(T, etc.)</code> overloads are better, but if you replace those with these, you can prevent any repetitive allocations occurring when these methods are called.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// &lt;summary&gt;\n/// Compares the query and internal value using the DefaultEqualityComparer, and invokes the given action if they match\n/// &lt;/summary&gt;\npublic ISwitchCase&lt;T&gt; Case(T query, Action action)\n{\n return Case(query, EqualityComparer&lt;T&gt;.Default, action);\n}\n\n/// &lt;summary&gt;\n/// Compares the query and internal value using the given comparer, and invokes the given action if they match\n/// &lt;/summary&gt;\npublic ISwitchCase&lt;T&gt; Case(T query, IEqualityComparer&lt;T&gt; comparer, Action action)\n{\n if (comparer.Equals(Value, query))\n {\n action();\n return EmptySwitchCase&lt;T&gt;.Instance;\n }\n\n return this;\n}\n</code></pre>\n\n<p>Obviously it's your decision what your API does, and it is important to stress that the behaviour is different like this, but that the behaviour was unclear before. With the added inline documentation, the new behaviour is clear and completely transparent at compile time. The difference is that that a value which provides an alternative implementation of <code>IEquatable&lt;T&gt;</code> will only be compared using this implementation if it is not a <code>T</code> and it can be determined at compile time that it is <code>IEquatable&lt;T&gt;</code>. I'd make a case for this behaviour being more 'intuitive', because it become equivalent to using a predicate of the form <code>v =&gt; query.Equals(v)</code> when <code>query</code> is not of type <code>T</code>. Without a <code>: T</code> constraint, this means that stuff which is comparable to <code>T</code> without necessarily being a <code>T</code> can also be used, which may or may nor be desirable.</p>\n\n<hr />\n\n<p>Naturally, it is not nice having many methods implementing the <code>if (predicate(Value))</code> logic, so I'd be inclined to put this login in a simple <code>private ISwitchCase&lt;T&gt; Case(bool condition, Action action)</code>, essentially replacing your current <code>Case(Predicate&lt;T&gt;, etc.)</code> in this role. If you want to keep the dynamic <code>IEquatable&lt;T&gt;</code> behaviour, then you can still rid yourself of all the anonymous methods by using such a method instead of deferring everything to <code>Case(Predicate&lt;T&gt;, etc.)</code>. For example:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// &lt;summary&gt;\n/// Compares the query with the internal value, first trying to use implementation of `IEquatable&amp;lt;t&amp;gt;` provided by the internal value, then that provided by the query, falling back to the DefaultComparer otherwise\n/// &lt;/summary&gt;\npublic ISwitchCase&lt;T&gt; Case(T query, Action action)\n{\n if (Value is IEquatable&lt;T&gt;)\n return Case(((IEquatable&lt;T&gt;)Value).Equals(query), action);\n\n if (query is IEquatable&lt;T&gt;)\n return Case(((IEquatable&lt;T&gt;)query).Equals(Value), action);\n\n return Case(query, EqualityComparer&lt;T&gt;.Default, action);\n}\n\n/// &lt;summary&gt;\n/// Compares the query and internal value using the given comparer, and calls the given action if they match\n/// &lt;/summary&gt;\npublic ISwitchCase&lt;T&gt; Case(T query, IEqualityComparer&lt;T&gt; comparer, Action action)\n{\n return Case(comparer.Equals(Value, query), action);\n}\n\n/// &lt;summary&gt;\n/// Invokes the given action if the condition is true\n/// &lt;/summary&gt;\nprivate ISwitchCase&lt;T&gt; Case(bool condition, Action action)\n{\n if (condition)\n {\n action();\n return EmptySwitchCase&lt;T&gt;.Instance;\n }\n\n return this;\n}\n</code></pre>\n\n<p>Or, more tidily (using pattern matching):</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// &lt;summary&gt;\n/// Compares the query with the internal value, first trying to use implementation of `IEquatable&amp;lt;t&amp;gt;` provided by the internal value, then that provided by the query, falling back to the DefaultComparer otherwise\n/// &lt;/summary&gt;\npublic ISwitchCase&lt;T&gt; Case(T query, Action action)\n{\n if (Value is IEquatable&lt;T&gt; v)\n return Case(v.Equals(query), action);\n\n if (query is IEquatable&lt;T&gt; q)\n return Case(q.Equals(Value), action);\n\n return Case(query, EqualityComparer&lt;T&gt;.Default, action);\n}\n</code></pre>\n\n<p>Note the inline documentation, which should appear on the <code>interface</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T20:53:15.693", "Id": "412291", "Score": "0", "body": "I know I should avoid only thanking people, but as I can only validate one answer, I \"only\" up voted yours, so I want to thank you for your analysis. I understood your point about documentation and my equality checks. I disabled this in my second version. Also, about your `Case(bool, Action)` idea, I didn't manage to build it in my second version, mostly because of @Flater recommandation to build switch before any evaluation. As the switch now can have multiple values, your solution is (to my eyes at least) impossible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T20:54:32.800", "Id": "412292", "Score": "0", "body": "Excuse my ignorance, but what did you use to get this diagram? How can I understand it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T11:24:05.757", "Id": "412332", "Score": "2", "body": "@MaximeRecuerda [ClrProfiler](https://www.microsoft.com/en-us/download/details.aspx?id=16273) in 'allocations' mode (diagram is the Allocation Graph). It's a bit finicky, but very useful for finding memory leaks and excess allocations. The Allocation Graph shows a call-tree, with the roots being types of object, indicating which methods created which objects. In-lining and other optimisations can make them misleading/difficult to interpret sometimes, but that's true with any tool." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:52:37.997", "Id": "213094", "ParentId": "213049", "Score": "4" } } ]
{ "AcceptedAnswerId": "213055", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T15:31:02.993", "Id": "213049", "Score": "0", "Tags": [ "c#" ], "Title": "Switch-Case pattern for non-constant types" }
213049
<p>Here is my voxel engine. I want some review for performance on the renderer. What can be improved? What must change?</p> <p>Also I'm not sure it is efficient to use vkWaitQueueIdle for syncing. The end goal would be to reproduce a cube world like game.</p> <p>Code :</p> <h2>Application.h</h2> <pre><code>#pragma once #include &lt;memory&gt; #include &lt;chrono&gt; #include "Window.h" #include "Renderer.h" #include "ChunkManager.h" #include "Player.h" class Application { public: Application(); ~Application(); void run(); private: void update(); void input(); std::unique_ptr&lt;Config&gt; m_config; std::unique_ptr&lt;Window&gt; m_window; std::shared_ptr&lt;Renderer&gt; m_pRenderer; std::unique_ptr&lt;ChunkManager&gt; m_pChunkManager; std::shared_ptr&lt;Player&gt; m_pPlayer; Pipeline base_pipeline; Camera m_camera; std::chrono::steady_clock::time_point m_last_time = std::chrono::high_resolution_clock::now(); }; </code></pre> <h2>Application.cpp</h2> <pre><code>#include "Application.h" //#include "Math.h" #include &lt;thread&gt; Application::Application() { m_pPlayer = std::make_shared&lt;Player&gt;(); m_config = std::make_unique&lt;Config&gt;(); m_window = std::make_unique&lt;Window&gt;(m_config, m_pPlayer-&gt;getCamera()); m_pRenderer = std::make_shared&lt;Renderer&gt;(m_window-&gt;getHandle(), m_config-&gt;width, m_config-&gt;height); m_pChunkManager = std::make_unique&lt;ChunkManager&gt;(m_pRenderer, m_pPlayer); m_pRenderer-&gt;createNewPipeline(base_pipeline); m_pRenderer-&gt;createDepthResources(); m_pRenderer-&gt;createFramebuffer(); m_pRenderer-&gt;createTextureImage(); m_pRenderer-&gt;createTextureImageView(); m_pRenderer-&gt;createTextureSampler(); m_pRenderer-&gt;createDescriptorPool(); m_pChunkManager-&gt;createChunks(); m_pChunkManager-&gt;loadChunks(); m_pRenderer-&gt;createUBO(); m_pRenderer-&gt;allocateCommandBuffers(); m_pRenderer-&gt;createDescriptorSet(); } Application::~Application() { m_pChunkManager.reset(); m_pRenderer-&gt;cleanSwapchain(std::make_shared&lt;Pipeline&gt;(base_pipeline)); m_pRenderer-&gt;destroyTextures(); m_pRenderer-&gt;destroyDescriptors(); m_pRenderer-&gt;destroyUniformBuffer(); m_pRenderer.reset(); m_window.reset(); m_config.reset(); } void Application::run() { while (!glfwWindowShouldClose(&amp;m_window-&gt;getHandle())) { glfwPollEvents(); input(); update(); if (m_pRenderer-&gt;draw(base_pipeline) != 0) { m_pChunkManager-&gt;setRebuild(true); } } vkDeviceWaitIdle(m_pRenderer-&gt;getDevice()); } void Application::update() { m_pChunkManager-&gt;update(); if (m_pChunkManager-&gt;needRebuild()) { for (uint16_t i = 0; i &lt; m_pRenderer-&gt;getGraphic().command_buffers.size(); i++) { m_pRenderer-&gt;beginRecordCommandBuffers(m_pRenderer-&gt;getGraphic().command_buffers[i], m_pRenderer-&gt;getGraphic().framebuffers[i], base_pipeline); m_pChunkManager-&gt;renderChunks(m_pRenderer-&gt;getGraphic().command_buffers[i], base_pipeline); m_pRenderer-&gt;endRecordCommandBuffers(m_pRenderer-&gt;getGraphic().command_buffers[i]); } m_pChunkManager-&gt;setRebuild(false); } m_pPlayer-&gt;updateUBO(static_cast&lt;float&gt;(m_config-&gt;width), static_cast&lt;float&gt;(m_config-&gt;height)); void* data; vkMapMemory(m_pRenderer-&gt;getDevice(), m_pRenderer-&gt;getGraphic().uniform_memory, 0, sizeof(m_pPlayer-&gt;getUBO()), 0, &amp;data); memcpy(data, &amp;m_pPlayer-&gt;getUBO(), sizeof(m_pPlayer-&gt;getUBO())); vkUnmapMemory(m_pRenderer-&gt;getDevice(), m_pRenderer-&gt;getGraphic().uniform_memory); //std::this_thread::sleep_for(std::chrono::nanoseconds(500));//delete when not streaming } void Application::input() { std::chrono::steady_clock::time_point currentTime = std::chrono::high_resolution_clock::now(); float delta_time = std::chrono::duration&lt;float, std::chrono::seconds::period&gt;(currentTime - m_last_time).count(); m_pPlayer-&gt;update(delta_time); m_last_time = currentTime; } </code></pre> <h2>Renderer.h</h2> <pre><code>#ifndef _RENDERER_H #define _RENDERER_H #ifndef _GLFW3_ #define _GLFW3_ #define GLFW_INCLUDE_VULKAN #include &lt;GLFW\glfw3.h&gt; #endif // !_GLFW3_ #include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;algorithm&gt; #include "Voxel.h" #include "VulkanInstance.h" #include "VulkanDevice.h" #include "VulkanSwapchain.h" #include "VulkanRenderPass.h" #include "VulkanDescriptor.h" #include "VulkanCommandPool.h" #include "VulkanPipeline.h" #include "VulkanBuffer.h" #include "Graphics.h" #include "Logger.h" constexpr unsigned int MAX_FRAMES_IN_FLIGHT = 2; class Renderer { public: Renderer(GLFWwindow&amp; window, uint32_t width, uint32_t height); ~Renderer(); int32_t draw(Pipeline&amp; pipeline); void setupInstance(GLFWwindow&amp; window); void setupDevice(); void setupSwapchain(); void setupRenderPass(); void setupDescriptorSetLayout(); void setupCommandPool(); void createNewPipeline(Pipeline&amp; pipeline); void recordCommandBuffers(Pipeline&amp; pipeline, size_t indices, Buffer&amp; buffer); VkDevice&amp; getDevice(); Graphics&amp; getGraphic();//need to seperate object needed outside the class //rendering void createVerticesBuffer(std::shared_ptr&lt;std::vector&lt;Voxel::Block&gt;&gt; vertices, Buffer&amp; buffer); void createIndicesBuffer(std::shared_ptr&lt;std::vector&lt;uint16_t&gt;&gt; indices, Buffer&amp; buffer); void createUBO(); void allocateCommandBuffers(); void beginRecordCommandBuffers(VkCommandBuffer&amp; commandBuffer, VkFramebuffer&amp; frameBuffer, Pipeline&amp; pipeline); void recordDrawCommands(VkCommandBuffer&amp; commandBuffer, Pipeline&amp; pipeline, Buffer&amp; buffer, size_t indices); void endRecordCommandBuffers(VkCommandBuffer&amp; commandBuffer); //!rendering void setupCallback(); void createSurface(GLFWwindow&amp; window); void createFramebuffer(); void createCommandPool(); void createSyncObject(); void createDescriptorLayout(); void createDescriptorPool(); void createDescriptorSet(); void createTextureImage(); void createTextureImageView(); void createTextureSampler(); void createDepthResources(); //cleaning void destroyTextures(); void destroyDescriptors(); void destroyUniformBuffer(); void destroyBuffers(Buffer&amp; buffers); void cleanSwapchain(std::shared_ptr&lt;Pipeline&gt; pPipeline); private: //init fonctions void recreateSwapchain(Pipeline&amp; pipeline); //helper fonctions bool checkDeviceExtensionSupport(VkPhysicalDevice device); bool checkDeviceSuitability(VkPhysicalDevice device); bool checkValidationLayerSupport(); VkImageView createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags); void createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage&amp; image, VkDeviceMemory&amp; imageMemory); uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties); void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); void copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height); VkFormat findSupportedFormat(const std::vector&lt;VkFormat&gt;&amp; candidates, VkImageTiling tiling, VkFormatFeatureFlags features); VkFormat findDepthFormat(); bool hasStencilComponent(VkFormat format); VkCommandBuffer beginCommands(); void endCommands(VkCommandBuffer commandBuffer); void transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector&lt;VkSurfaceFormatKHR&gt;&amp; availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector&lt;VkPresentModeKHR&gt; availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR&amp; capabilities); SwapchainDetails querySwapChainSupport(VkPhysicalDevice device); QueueFamilyIndices findQueueFamily(VkPhysicalDevice device); std::vector&lt;const char*&gt; getRequiredExtensions(); //static fonctions static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj, size_t location, int32_t code, const char* layerPrefix, const char* msg, void* userData); //proxy fonctions VkResult CreateDebugReportCallbackEXT(VkInstance&amp; instance, const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback); void DestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator); //attributes VkDebugReportCallbackEXT callback; Graphics m_graphic; std::unique_ptr&lt;uint32_t&gt; WIDTH; std::unique_ptr&lt;uint32_t&gt; HEIGHT; std::unique_ptr&lt;VulkanInstance&gt; m_instance; std::unique_ptr&lt;VulkanDevice&gt; m_device; std::unique_ptr&lt;VulkanSwapchain&gt; m_swapchain; std::unique_ptr&lt;VulkanRenderPass&gt; m_pRenderpass; std::unique_ptr&lt;VulkanDescriptor&gt; m_descriptor; std::unique_ptr&lt;VulkanCommandPool&gt; m_commandPool; std::unique_ptr&lt;VulkanPipeline&gt; m_pPipelineFactory; std::unique_ptr&lt;VulkanBuffer&gt; m_pBufferFactory; size_t m_frame_index = 0; }; #endif _RENDERER_H </code></pre> <h2>Renderer.cpp</h2> <pre><code>#include "Renderer.h" #include &lt;set&gt; #ifndef STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #include &lt;stb_image.h&gt; #endif // !STB_IMAGE_IMPLEMENTATION //review createBuffer func Renderer::Renderer(GLFWwindow&amp; window, uint32_t width, uint32_t height) { WIDTH = std::make_unique&lt;uint32_t&gt;(width); HEIGHT = std::make_unique&lt;uint32_t&gt;(height); m_pPipelineFactory = std::make_unique&lt;VulkanPipeline&gt;(m_graphic); m_pBufferFactory = std::make_unique&lt;VulkanBuffer&gt;(m_graphic); setupInstance(window); setupDevice(); setupSwapchain(); setupRenderPass(); setupDescriptorSetLayout(); setupCommandPool(); } Renderer::~Renderer() { for (size_t i = 0; i &lt; MAX_FRAMES_IN_FLIGHT; i++) { vkDestroySemaphore(m_graphic.device, m_graphic.semaphores_image_available[i], nullptr); vkDestroySemaphore(m_graphic.device, m_graphic.semaphores_render_finished[i], nullptr); vkDestroyFence(m_graphic.device, m_graphic.fences_in_flight[i], nullptr); } vkDestroyCommandPool(m_graphic.device, m_graphic.command_pool, nullptr); vkDestroyDevice(m_graphic.device, nullptr); if (m_graphic.validation_layer_enable) { DestroyDebugReportCallbackEXT(m_graphic.instance, callback, nullptr); } vkDestroySurfaceKHR(m_graphic.instance, m_graphic.surface, nullptr); vkDestroyInstance(m_graphic.instance, nullptr); } int32_t Renderer::draw(Pipeline&amp; pipeline) { vkWaitForFences(m_graphic.device, 1, &amp;m_graphic.fences_in_flight[m_frame_index], VK_TRUE, std::numeric_limits&lt;uint64_t&gt;::max()); vkResetFences(m_graphic.device, 1, &amp;m_graphic.fences_in_flight[m_frame_index]); VkResult result; if (m_graphic.validation_layer_enable) { vkQueueWaitIdle(m_graphic.present_queue); } uint32_t image_index = 0; result = vkAcquireNextImageKHR(m_graphic.device, m_graphic.swapchain, std::numeric_limits&lt;uint64_t&gt;::max(), m_graphic.semaphores_image_available[m_frame_index], VK_NULL_HANDLE, &amp;image_index); if (result == VK_ERROR_OUT_OF_DATE_KHR) { recreateSwapchain(pipeline); return 1; } else if (result != VK_SUCCESS &amp;&amp; result != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("failed to acquire swap chain image!"); } VkSubmitInfo submit_info = {}; submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = { m_graphic.semaphores_image_available[m_frame_index] }; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submit_info.waitSemaphoreCount = 1; submit_info.pWaitSemaphores = waitSemaphores; submit_info.pWaitDstStageMask = waitStages; submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &amp;m_graphic.command_buffers[image_index]; VkSemaphore signalSemaphores[] = { m_graphic.semaphores_render_finished[m_frame_index] }; submit_info.signalSemaphoreCount = 1; submit_info.pSignalSemaphores = signalSemaphores; result = vkQueueSubmit(m_graphic.graphics_queue, 1, &amp;submit_info, m_graphic.fences_in_flight[m_frame_index]); if (result != VK_SUCCESS) { std::cerr &lt;&lt; result; throw std::runtime_error("failed to submit draw command buffer!"); } VkPresentInfoKHR present_info = {}; present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present_info.waitSemaphoreCount = 1; present_info.pWaitSemaphores = signalSemaphores; VkSwapchainKHR swapchains[] = { m_graphic.swapchain }; present_info.swapchainCount = 1; present_info.pSwapchains = swapchains; present_info.pImageIndices = &amp;image_index; present_info.pResults = nullptr; result = vkQueuePresentKHR(m_graphic.present_queue, &amp;present_info); if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { recreateSwapchain(pipeline); return 1; } else if (result != VK_SUCCESS) { throw std::runtime_error("failed to present swap chain image!"); } m_frame_index = (m_frame_index + 1) % MAX_FRAMES_IN_FLIGHT; return 0; } void Renderer::setupInstance(GLFWwindow&amp; window) { m_instance = std::make_unique&lt;VulkanInstance&gt;(m_graphic); setupCallback(); createSurface(window); } void Renderer::setupDevice() { m_device = std::make_unique&lt;VulkanDevice&gt;(m_graphic); createSyncObject(); } void Renderer::setupSwapchain() { m_swapchain = std::make_unique&lt;VulkanSwapchain&gt;(m_graphic, *WIDTH.get(), *HEIGHT.get()); } void Renderer::setupRenderPass() { VkFormat format = findSupportedFormat( { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT }, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT); m_pRenderpass = std::make_unique&lt;VulkanRenderPass&gt;(m_graphic, format); } void Renderer::setupDescriptorSetLayout() { m_descriptor = std::make_unique&lt;VulkanDescriptor&gt;(m_graphic); m_descriptor-&gt;createDescriptorSetLayout(); } void Renderer::setupCommandPool() { m_commandPool = std::make_unique&lt;VulkanCommandPool&gt;(m_graphic); } void Renderer::createNewPipeline(Pipeline&amp; pipeline) { m_pPipelineFactory-&gt;createPipeline(pipeline); } VkDevice&amp; Renderer::getDevice() { return m_graphic.device; } Graphics &amp; Renderer::getGraphic() { return m_graphic; } void Renderer::destroyBuffers(Buffer &amp; buffer) { vkQueueWaitIdle(m_graphic.graphics_queue); for (uint32_t i = 0; i &lt; m_graphic.command_buffers.size(); i++) { vkResetCommandBuffer(m_graphic.command_buffers[i], VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT); } vkDestroyBuffer(m_graphic.device, buffer.index, nullptr); vkFreeMemory(m_graphic.device, buffer.index_memory, nullptr); vkDestroyBuffer(m_graphic.device, buffer.vertex, nullptr); vkFreeMemory(m_graphic.device, buffer.vertex_memory, nullptr); } void Renderer::createVerticesBuffer(std::shared_ptr&lt;std::vector&lt;Voxel::Block&gt;&gt; vertices, Buffer&amp; buffer) { VkDeviceSize buffer_size = sizeof(vertices-&gt;at(0)) * vertices-&gt;size(); VkBuffer staging_buffer; VkDeviceMemory staging_buffer_memory; m_pBufferFactory-&gt;createBuffer(staging_buffer, staging_buffer_memory, buffer_size, VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); void* data; vkMapMemory(m_graphic.device, staging_buffer_memory, 0, buffer_size, 0, &amp;data); memcpy(data, vertices-&gt;data(), (size_t)buffer_size); vkUnmapMemory(m_graphic.device, staging_buffer_memory); m_pBufferFactory-&gt;createBuffer(buffer.vertex, buffer.vertex_memory, buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); copyBuffer(staging_buffer, buffer.vertex, buffer_size); vkDestroyBuffer(m_graphic.device, staging_buffer, nullptr); vkFreeMemory(m_graphic.device, staging_buffer_memory, nullptr); } void Renderer::createIndicesBuffer(std::shared_ptr&lt;std::vector&lt;uint16_t&gt;&gt; indices, Buffer&amp; buffer) { VkDeviceSize buffer_size = sizeof(indices-&gt;at(0)) * indices-&gt;size(); VkBuffer staging_buffer; VkDeviceMemory staging_buffer_mem; m_pBufferFactory-&gt;createBuffer(staging_buffer, staging_buffer_mem, buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); void* data; vkMapMemory(m_graphic.device, staging_buffer_mem, 0, buffer_size, 0, &amp;data); memcpy(data, indices-&gt;data(), (size_t)buffer_size); vkUnmapMemory(m_graphic.device, staging_buffer_mem); m_pBufferFactory-&gt;createBuffer(buffer.index, buffer.index_memory, buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); copyBuffer(staging_buffer, buffer.index, buffer_size); vkDestroyBuffer(m_graphic.device, staging_buffer, nullptr); vkFreeMemory(m_graphic.device, staging_buffer_mem, nullptr); } void Renderer::createUBO() { VkDeviceSize buffer_size = sizeof(UniformBufferObject); m_pBufferFactory-&gt;createBuffer(m_graphic.uniform_buffer, m_graphic.uniform_memory, buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); } void Renderer::allocateCommandBuffers() { m_graphic.command_buffers.resize(m_graphic.framebuffers.size()); VkCommandBufferAllocateInfo alloc_buffers_info = {}; alloc_buffers_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; alloc_buffers_info.commandPool = m_graphic.command_pool; alloc_buffers_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; alloc_buffers_info.commandBufferCount = static_cast&lt;uint32_t&gt;(m_graphic.command_buffers.size()); if (vkAllocateCommandBuffers(m_graphic.device, &amp;alloc_buffers_info, m_graphic.command_buffers.data()) != VK_SUCCESS) { throw std::runtime_error("failed to allocate command buffers!"); } } void Renderer::beginRecordCommandBuffers(VkCommandBuffer &amp; commandBuffer, VkFramebuffer&amp; frameBuffer, Pipeline &amp; pipeline) { std::array&lt;VkClearValue, 2&gt; clear_values = {}; clear_values[0].color = { 0.0f, 0.0f, 0.0f, 1.0f }; clear_values[1].depthStencil = { 1.0f, 0 }; VkCommandBufferBeginInfo begin_buffer_info = {}; begin_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin_buffer_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; begin_buffer_info.pInheritanceInfo = nullptr; if (vkBeginCommandBuffer(commandBuffer, &amp;begin_buffer_info) != VK_SUCCESS) { throw std::runtime_error("failed to begin recording command buffer!"); } VkRenderPassBeginInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = m_graphic.render_pass; renderPassInfo.framebuffer = frameBuffer; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = m_graphic.swapchain_details.extent; renderPassInfo.clearValueCount = static_cast&lt;uint32_t&gt;(clear_values.size()); renderPassInfo.pClearValues = clear_values.data(); m_pRenderpass-&gt;beginRenderPass(commandBuffer, renderPassInfo); m_pPipelineFactory-&gt;bindPipeline(commandBuffer, pipeline); } void Renderer::recordDrawCommands(VkCommandBuffer &amp; commandBuffer, Pipeline&amp; pipeline, Buffer &amp; buffer, size_t indices) { VkBuffer vertexBuffers[] = { buffer.vertex }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(commandBuffer, buffer.index, 0, VK_INDEX_TYPE_UINT16); m_descriptor-&gt;bindDescriptorSet(commandBuffer, pipeline.layout, m_graphic.descriptor_set); vkCmdDrawIndexed(commandBuffer, static_cast&lt;uint32_t&gt;(indices), 1, 0, 0, 0); } void Renderer::endRecordCommandBuffers(VkCommandBuffer &amp; commandBuffer) { m_pRenderpass-&gt;endRenderPass(commandBuffer); if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) { throw std::runtime_error("failed to record command buffer!"); } } void Renderer::setupCallback() { if (!m_graphic.validation_layer_enable) { return; } VkDebugReportCallbackCreateInfoEXT create_info = {}; create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; create_info.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; create_info.pfnCallback = debugCallback; if (CreateDebugReportCallbackEXT(m_graphic.instance, &amp;create_info, nullptr, &amp;callback) != VK_SUCCESS) { throw std::runtime_error("Failed to setup callback"); } } void Renderer::createSurface(GLFWwindow&amp; window) { if (glfwCreateWindowSurface(m_graphic.instance, &amp;window, nullptr, &amp;m_graphic.surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create window surface!"); } } void Renderer::createFramebuffer() { m_graphic.framebuffers.resize(m_graphic.images_view.size()); for (size_t i = 0; i &lt; m_graphic.images_view.size(); i++) { std::array&lt;VkImageView, 2&gt; attachments = { m_graphic.images_view[i], m_graphic.depth_view }; VkFramebufferCreateInfo framebufferInfo = {}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = m_graphic.render_pass; framebufferInfo.attachmentCount = static_cast&lt;uint32_t&gt;(attachments.size()); framebufferInfo.pAttachments = attachments.data(); framebufferInfo.width = m_graphic.swapchain_details.extent.width; framebufferInfo.height = m_graphic.swapchain_details.extent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(m_graphic.device, &amp;framebufferInfo, nullptr, &amp;m_graphic.framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("failed to create framebuffer!"); } } } void Renderer::createCommandPool() { VkCommandPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; pool_info.pNext = nullptr; pool_info.queueFamilyIndex = m_graphic.queue_indices.graphic_family; pool_info.flags = 0; if (vkCreateCommandPool(m_graphic.device, &amp;pool_info, nullptr, &amp;m_graphic.command_pool) != VK_SUCCESS) { throw std::runtime_error("failed to create command pool!"); } } void Renderer::createSyncObject() { m_graphic.semaphores_image_available.resize(MAX_FRAMES_IN_FLIGHT); m_graphic.semaphores_render_finished.resize(MAX_FRAMES_IN_FLIGHT); m_graphic.fences_in_flight.resize(MAX_FRAMES_IN_FLIGHT); VkSemaphoreCreateInfo semaphore_info = {}; semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; semaphore_info.pNext = nullptr; semaphore_info.flags = 0; VkFenceCreateInfo fence_info = {}; fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence_info.pNext = nullptr; fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i &lt; MAX_FRAMES_IN_FLIGHT; i++) { if (vkCreateSemaphore(m_graphic.device, &amp;semaphore_info, nullptr, &amp;m_graphic.semaphores_image_available[i]) != VK_SUCCESS || vkCreateSemaphore(m_graphic.device, &amp;semaphore_info, nullptr, &amp;m_graphic.semaphores_render_finished[i]) != VK_SUCCESS || vkCreateFence(m_graphic.device, &amp;fence_info, nullptr, &amp;m_graphic.fences_in_flight[i]) != VK_SUCCESS) { Logger::registerError("failed to create semaphores for a frame!"); throw std::runtime_error("failed to create semaphores for a frame!"); } } } void Renderer::createDescriptorLayout() { VkDescriptorSetLayoutBinding uboLayoutBinding = {}; uboLayoutBinding.binding = 0; uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uboLayoutBinding.descriptorCount = 1; uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; uboLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutBinding samplerLayoutBinding = {}; samplerLayoutBinding.binding = 1; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.pImmutableSamplers = nullptr; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; std::array&lt;VkDescriptorSetLayoutBinding, 2&gt; bindings = { uboLayoutBinding, samplerLayoutBinding }; VkDescriptorSetLayoutCreateInfo layoutInfo = {}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = static_cast&lt;uint32_t&gt;(bindings.size());; layoutInfo.pBindings = bindings.data(); if (vkCreateDescriptorSetLayout(m_graphic.device, &amp;layoutInfo, nullptr, &amp;m_graphic.descriptor_set_layout) != VK_SUCCESS) { throw std::runtime_error("failed to create descriptor set layout!"); } } void Renderer::createDescriptorPool() { std::array&lt;VkDescriptorPoolSize, 2&gt; poolSizes = {}; poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSizes[0].descriptorCount = 1; poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[1].descriptorCount = 1; VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast&lt;uint32_t&gt;(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); poolInfo.maxSets = 1; if (vkCreateDescriptorPool(m_graphic.device, &amp;poolInfo, nullptr, &amp;m_graphic.descriptor_pool) != VK_SUCCESS) { throw std::runtime_error("failed to create descriptor pool!"); } } void Renderer::createDescriptorSet() { VkDescriptorSetLayout layouts[] = { m_graphic.descriptor_set_layout }; VkDescriptorSetAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = m_graphic.descriptor_pool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = layouts; if (vkAllocateDescriptorSets(m_graphic.device, &amp;allocInfo, &amp;m_graphic.descriptor_set) != VK_SUCCESS) { throw std::runtime_error("failed to allocate descriptor set!"); } VkDescriptorBufferInfo bufferInfo = {}; bufferInfo.buffer = m_graphic.uniform_buffer; bufferInfo.offset = 0; bufferInfo.range = sizeof(UniformBufferObject); VkDescriptorImageInfo imageInfo = {}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = m_graphic.texture_view; imageInfo.sampler = m_graphic.texture_sampler; std::array&lt;VkWriteDescriptorSet, 2&gt; descriptorWrites = {}; descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[0].dstSet = m_graphic.descriptor_set; descriptorWrites[0].dstBinding = 0; descriptorWrites[0].dstArrayElement = 0; descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrites[0].descriptorCount = 1; descriptorWrites[0].pBufferInfo = &amp;bufferInfo; descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[1].dstSet = m_graphic.descriptor_set; descriptorWrites[1].dstBinding = 1; descriptorWrites[1].dstArrayElement = 0; descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrites[1].descriptorCount = 1; descriptorWrites[1].pImageInfo = &amp;imageInfo; vkUpdateDescriptorSets(m_graphic.device, static_cast&lt;uint32_t&gt;(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::createTextureImage() { int tex_width, tex_height, tex_channel; stbi_uc* pixels = stbi_load("textures/texture.jpg", &amp;tex_width, &amp;tex_height, &amp;tex_channel, STBI_rgb_alpha); VkDeviceSize imageSize = tex_width * tex_height * 4; if (!pixels) { throw std::runtime_error("failed to load texture image!"); } VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; m_pBufferFactory-&gt;createBuffer(stagingBuffer, stagingBufferMemory, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); void* data; vkMapMemory(m_graphic.device, stagingBufferMemory, 0, imageSize, 0, &amp;data); memcpy(data, pixels, static_cast&lt;size_t&gt;(imageSize)); vkUnmapMemory(m_graphic.device, stagingBufferMemory); stbi_image_free(pixels); createImage(tex_width, tex_height, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, m_graphic.texture_image, m_graphic.texture_memory); transitionImageLayout(m_graphic.texture_image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); copyBufferToImage(stagingBuffer, m_graphic.texture_image, static_cast&lt;uint32_t&gt;(tex_width), static_cast&lt;uint32_t&gt;(tex_height)); transitionImageLayout(m_graphic.texture_image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); vkDestroyBuffer(m_graphic.device, stagingBuffer, nullptr); vkFreeMemory(m_graphic.device, stagingBufferMemory, nullptr); } void Renderer::createTextureImageView() { m_graphic.texture_view = createImageView(m_graphic.texture_image, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT); } void Renderer::createTextureSampler() { VkSamplerCreateInfo samplerInfo = {}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.mipLodBias = 0.0f; samplerInfo.minLod = 0.0f; samplerInfo.maxLod = 0.0f; if (vkCreateSampler(m_graphic.device, &amp;samplerInfo, nullptr, &amp;m_graphic.texture_sampler) != VK_SUCCESS) { throw std::runtime_error("failed to create texture sampler!"); } } void Renderer::createDepthResources() { VkFormat depthFormat = findDepthFormat(); createImage(m_graphic.swapchain_details.extent.width, m_graphic.swapchain_details.extent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, m_graphic.depth_image, m_graphic.depth_memory); m_graphic.depth_view = createImageView(m_graphic.depth_image, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT); transitionImageLayout(m_graphic.depth_image, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); } void Renderer::destroyTextures() { vkDestroySampler(m_graphic.device, m_graphic.texture_sampler, nullptr); vkDestroyImageView(m_graphic.device, m_graphic.texture_view, nullptr); vkDestroyImage(m_graphic.device, m_graphic.texture_image, nullptr); vkFreeMemory(m_graphic.device, m_graphic.texture_memory, nullptr); } void Renderer::destroyDescriptors() { vkDestroyDescriptorPool(m_graphic.device, m_graphic.descriptor_pool, nullptr); vkDestroyDescriptorSetLayout(m_graphic.device, m_graphic.descriptor_set_layout, nullptr); } void Renderer::destroyUniformBuffer() { vkDestroyBuffer(m_graphic.device, m_graphic.uniform_buffer, nullptr); vkFreeMemory(m_graphic.device, m_graphic.uniform_memory, nullptr); } VkImageView Renderer::createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags) { VkImageView imageView; VkImageViewCreateInfo viewInfo = {}; viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; viewInfo.image = image; viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; viewInfo.format = format; viewInfo.subresourceRange.aspectMask = aspectFlags; viewInfo.subresourceRange.baseMipLevel = 0; viewInfo.subresourceRange.levelCount = 1; viewInfo.subresourceRange.baseArrayLayer = 0; viewInfo.subresourceRange.layerCount = 1; if (vkCreateImageView(m_graphic.device, &amp;viewInfo, nullptr, &amp;imageView) != VK_SUCCESS) { throw std::runtime_error("failed to create texture image view!"); } return imageView; } void Renderer::createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage &amp; image, VkDeviceMemory &amp; imageMemory) { VkImageCreateInfo imageInfo = {}; imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageInfo.imageType = VK_IMAGE_TYPE_2D; imageInfo.extent.width = static_cast&lt;uint32_t&gt;(width); imageInfo.extent.height = static_cast&lt;uint32_t&gt;(height); imageInfo.extent.depth = 1; imageInfo.mipLevels = 1; imageInfo.arrayLayers = 1; imageInfo.format = format; imageInfo.tiling = tiling; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.usage = usage; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageInfo.flags = 0; if (vkCreateImage(m_graphic.device, &amp;imageInfo, nullptr, &amp;image) != VK_SUCCESS) { throw std::runtime_error("failed to create image!"); } VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements(m_graphic.device, image, &amp;memRequirements); VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); if (vkAllocateMemory(m_graphic.device, &amp;allocInfo, nullptr, &amp;imageMemory) != VK_SUCCESS) { throw std::runtime_error("failed to allocate image memory!"); } vkBindImageMemory(m_graphic.device, image, imageMemory, 0); } void Renderer::recordCommandBuffers(Pipeline&amp; pipeline, size_t indices, Buffer&amp; buffer) { std::array&lt;VkClearValue, 2&gt; clear_values = {}; clear_values[0].color = { 0.0f, 0.0f, 0.0f, 1.0f }; clear_values[1].depthStencil = { 1.0f, 0 }; m_graphic.command_buffers.resize(m_graphic.framebuffers.size()); VkCommandBufferAllocateInfo alloc_buffers_info = {}; alloc_buffers_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; alloc_buffers_info.commandPool = m_graphic.command_pool; alloc_buffers_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; alloc_buffers_info.commandBufferCount = static_cast&lt;uint32_t&gt;(m_graphic.command_buffers.size()); if (vkAllocateCommandBuffers(m_graphic.device, &amp;alloc_buffers_info, m_graphic.command_buffers.data()) != VK_SUCCESS) { throw std::runtime_error("failed to allocate command buffers!"); } for (size_t i = 0; i &lt; m_graphic.command_buffers.size(); i++) { VkCommandBufferBeginInfo begin_buffer_info = {}; begin_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin_buffer_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; begin_buffer_info.pInheritanceInfo = nullptr; // Optional if (vkBeginCommandBuffer(m_graphic.command_buffers[i], &amp;begin_buffer_info) != VK_SUCCESS) { throw std::runtime_error("failed to begin recording command buffer!"); } VkRenderPassBeginInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = m_graphic.render_pass; renderPassInfo.framebuffer = m_graphic.framebuffers[i]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = m_graphic.swapchain_details.extent; renderPassInfo.clearValueCount = static_cast&lt;uint32_t&gt;(clear_values.size()); renderPassInfo.pClearValues = clear_values.data(); //vkCmdBeginRenderPass(m_graphic.command_buffers[i], &amp;renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); m_pRenderpass-&gt;beginRenderPass(m_graphic.command_buffers[i], renderPassInfo); //vkCmdBindPipeline(m_graphic.command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.handle);//to change m_pPipelineFactory-&gt;bindPipeline(m_graphic.command_buffers[i], pipeline); VkBuffer vertexBuffers[] = { buffer.vertex }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(m_graphic.command_buffers[i], 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(m_graphic.command_buffers[i], buffer.index, 0, VK_INDEX_TYPE_UINT16); //vkCmdBindDescriptorSets(m_graphic.command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS,pipeline.layout, 0, 1, &amp;m_graphic.descriptor_set, 0, nullptr); m_descriptor-&gt;bindDescriptorSet(m_graphic.command_buffers[i], pipeline.layout, m_graphic.descriptor_set); vkCmdDrawIndexed(m_graphic.command_buffers[i], static_cast&lt;uint32_t&gt;(indices), 1, 0, 0, 0); //vkCmdEndRenderPass(m_graphic.command_buffers[i]); m_pRenderpass-&gt;endRenderPass(m_graphic.command_buffers[i]); if (vkEndCommandBuffer(m_graphic.command_buffers[i]) != VK_SUCCESS) { throw std::runtime_error("failed to record command buffer!"); } } } void Renderer::recreateSwapchain(Pipeline&amp; pipeline) { vkDeviceWaitIdle(m_graphic.device); cleanSwapchain(std::make_shared&lt;Pipeline&gt;(pipeline)); m_swapchain-&gt;createSwapchain(); VkFormat format = findSupportedFormat({ VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT }, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT); m_pRenderpass-&gt;createRenderPass(format); createNewPipeline(pipeline); createDepthResources(); createFramebuffer(); allocateCommandBuffers(); } void Renderer::cleanSwapchain(std::shared_ptr&lt;Pipeline&gt; pPipeline) { vkDestroyImageView(m_graphic.device, m_graphic.depth_view, nullptr); vkDestroyImage(m_graphic.device, m_graphic.depth_image, nullptr); vkFreeMemory(m_graphic.device, m_graphic.depth_memory, nullptr); for (size_t i = 0; i &lt; m_graphic.framebuffers.size(); i++) { vkDestroyFramebuffer(m_graphic.device, m_graphic.framebuffers[i], nullptr); } vkFreeCommandBuffers(m_graphic.device, m_graphic.command_pool, static_cast&lt;uint32_t&gt;(m_graphic.command_buffers.size()), m_graphic.command_buffers.data()); vkDestroyPipeline(m_graphic.device, pPipeline-&gt;handle, nullptr); vkDestroyPipelineLayout(m_graphic.device, pPipeline-&gt;layout, nullptr); vkDestroyRenderPass(m_graphic.device, m_graphic.render_pass, nullptr); for (auto imageView : m_graphic.images_view) { vkDestroyImageView(m_graphic.device, imageView, nullptr); } vkDestroySwapchainKHR(m_graphic.device, m_graphic.swapchain, nullptr); } bool Renderer::checkDeviceExtensionSupport(VkPhysicalDevice device) { uint32_t extension_count; vkEnumerateDeviceExtensionProperties(device, nullptr, &amp;extension_count, nullptr); std::vector&lt;VkExtensionProperties&gt; availableExtensions(extension_count); vkEnumerateDeviceExtensionProperties(device, nullptr, &amp;extension_count, availableExtensions.data()); std::set&lt;std::string&gt; requiredExtensions(m_graphic.extensions.device_extensions.begin(), m_graphic.extensions.device_extensions.end()); for (const auto&amp; extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } return requiredExtensions.empty(); } bool Renderer::checkDeviceSuitability(VkPhysicalDevice device) { bool swapChainAdequate = false; VkPhysicalDeviceProperties deviceProperties; VkPhysicalDeviceFeatures deviceFeatures; vkGetPhysicalDeviceProperties(device, &amp;deviceProperties); vkGetPhysicalDeviceFeatures(device, &amp;deviceFeatures); if (!(deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU &amp;&amp; deviceFeatures.geometryShader)) { return false; } QueueFamilyIndices indices = findQueueFamily(device); bool extensionsSupported = checkDeviceExtensionSupport(device); if (extensionsSupported) { SwapchainDetails swapChainSupport = querySwapChainSupport(device); swapChainAdequate = !swapChainSupport.formats.empty() &amp;&amp; !swapChainSupport.presentModes.empty(); } VkPhysicalDeviceFeatures supportedFeatures; vkGetPhysicalDeviceFeatures(device, &amp;supportedFeatures); return indices.isComplete() &amp;&amp; extensionsSupported &amp;&amp; swapChainAdequate &amp;&amp; supportedFeatures.samplerAnisotropy; } bool Renderer::checkValidationLayerSupport() { uint32_t layer_count = 0; vkEnumerateInstanceLayerProperties(&amp;layer_count, nullptr); std::vector&lt;VkLayerProperties&gt; available_layers(layer_count); vkEnumerateInstanceLayerProperties(&amp;layer_count, available_layers.data()); /*std::cout &lt;&lt; "available layer:" &lt;&lt; std::endl; for (const auto&amp; extension : available_layers) { std::cout &lt;&lt; "\t" &lt;&lt; extension.layerName &lt;&lt; std::endl; }*/ for (const char* layerName : m_graphic.extensions.validationLayers) { bool layerFound = false; for (const auto&amp; layerProperties : available_layers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { return false; } } return true; } uint32_t Renderer::findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(m_graphic.physical_device, &amp;memProperties); for (uint32_t i = 0; i &lt; memProperties.memoryTypeCount; i++) { if (typeFilter &amp; (1 &lt;&lt; i) &amp;&amp; (memProperties.memoryTypes[i].propertyFlags &amp; properties) == properties) { return i; } } throw std::runtime_error("failed to find suitable memory type!"); } void Renderer::copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBuffer commandBuffer = beginCommands(); VkBufferCopy copyRegion = {}; copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &amp;copyRegion); endCommands(commandBuffer); } void Renderer::copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height) { VkCommandBuffer commandBuffer = beginCommands(); VkBufferImageCopy region = {}; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset = { 0, 0, 0 }; region.imageExtent = { width, height, 1 }; vkCmdCopyBufferToImage(commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &amp;region); endCommands(commandBuffer); } VkFormat Renderer::findSupportedFormat(const std::vector&lt;VkFormat&gt;&amp; candidates, VkImageTiling tiling, VkFormatFeatureFlags features) { for (VkFormat format : candidates) { VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(m_graphic.physical_device, format, &amp;props); if (tiling == VK_IMAGE_TILING_LINEAR &amp;&amp; (props.linearTilingFeatures &amp; features) == features) { return format; } else if (tiling == VK_IMAGE_TILING_OPTIMAL &amp;&amp; (props.optimalTilingFeatures &amp; features) == features) { return format; } } throw std::runtime_error("failed to find supported format!"); } VkFormat Renderer::findDepthFormat() { return findSupportedFormat( { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT }, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT); } bool Renderer::hasStencilComponent(VkFormat format) { return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT; } VkCommandBuffer Renderer::beginCommands() { VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = m_graphic.command_pool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(m_graphic.device, &amp;allocInfo, &amp;commandBuffer); VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &amp;beginInfo); return commandBuffer; } void Renderer::endCommands(VkCommandBuffer commandBuffer) { vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &amp;commandBuffer; vkQueueSubmit(m_graphic.graphics_queue, 1, &amp;submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(m_graphic.graphics_queue); vkFreeCommandBuffers(m_graphic.device, m_graphic.command_pool, 1, &amp;commandBuffer); } void Renderer::transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout) { VkCommandBuffer commandBuffer = beginCommands(); VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = oldLayout; barrier.newLayout = newLayout; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = image; if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; if (hasStencilComponent(format)) { barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; } } else { barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; } barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = 1; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; VkPipelineStageFlags sourceStage; VkPipelineStageFlags destinationStage; if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &amp;&amp; newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT; } else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL &amp;&amp; newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT; destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &amp;&amp; newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; } else { throw std::invalid_argument("unsupported layout transition!"); } vkCmdPipelineBarrier(commandBuffer, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &amp;barrier); endCommands(commandBuffer); } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector&lt;VkSurfaceFormatKHR&gt;&amp; availableFormats) { if (availableFormats.size() == 1 &amp;&amp; availableFormats[0].format == VK_FORMAT_UNDEFINED) { return { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }; } for (const auto&amp; availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM &amp;&amp; availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector&lt;VkPresentModeKHR&gt; availablePresentModes) { VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR; for (const auto&amp; availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) { bestMode = availablePresentMode; } } return bestMode; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR &amp; capabilities) { if (capabilities.currentExtent.width != std::numeric_limits&lt;uint32_t&gt;::max()) { return capabilities.currentExtent; } else { VkExtent2D actualExtent = { *WIDTH.get(), *HEIGHT.get() }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } SwapchainDetails Renderer::querySwapChainSupport(VkPhysicalDevice device) { SwapchainDetails details; vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, m_graphic.surface, &amp;details.capabilities); uint32_t format_count = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(device, m_graphic.surface, &amp;format_count, nullptr); if (format_count != 0) { details.formats.resize(format_count); vkGetPhysicalDeviceSurfaceFormatsKHR(device, m_graphic.surface, &amp;format_count, details.formats.data()); } uint32_t present_mode_count; vkGetPhysicalDeviceSurfacePresentModesKHR(device, m_graphic.surface, &amp;present_mode_count, nullptr); if (present_mode_count != 0) { details.presentModes.resize(present_mode_count); vkGetPhysicalDeviceSurfacePresentModesKHR(device, m_graphic.surface, &amp;present_mode_count, details.presentModes.data()); } return details; } QueueFamilyIndices Renderer::findQueueFamily(VkPhysicalDevice device) { QueueFamilyIndices indices; uint32_t queue_family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(device, &amp;queue_family_count, nullptr); std::vector&lt;VkQueueFamilyProperties&gt; queue_families(queue_family_count); vkGetPhysicalDeviceQueueFamilyProperties(device, &amp;queue_family_count, queue_families.data()); int i = 0; for (const auto&amp; queueFamily : queue_families) { if (queueFamily.queueCount &gt; 0 &amp;&amp; queueFamily.queueFlags &amp; VK_QUEUE_GRAPHICS_BIT) { indices.graphic_family = i; } VkBool32 present_support = false; vkGetPhysicalDeviceSurfaceSupportKHR(device, i, m_graphic.surface, &amp;present_support); if (queueFamily.queueCount &gt; 0 &amp;&amp; present_support) { indices.present_family = i; } if (indices.isComplete()) { break; } i++; } return indices; } std::vector&lt;const char*&gt; Renderer::getRequiredExtensions() { uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&amp;glfwExtensionCount); std::vector&lt;const char*&gt; extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); if (m_graphic.validation_layer_enable) { extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } return extensions; } VKAPI_ATTR VkBool32 VKAPI_CALL Renderer::debugCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj, size_t location, int32_t code, const char* layerPrefix, const char* msg,void* userData) { std::cerr &lt;&lt; "\nvalidation layer: " &lt;&lt; msg &lt;&lt; std::endl; Logger::registerError("\nvalidation layer: " + std::string(msg)); return VK_FALSE; } VkResult Renderer::CreateDebugReportCallbackEXT(VkInstance&amp; instance, const VkDebugReportCallbackCreateInfoEXT * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkDebugReportCallbackEXT * pCallback) { auto func = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); if (func != nullptr) { return func(instance, pCreateInfo, pAllocator, pCallback); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void Renderer::DestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks * pAllocator) { auto func = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); if (func != nullptr) { func(instance, callback, pAllocator); } } </code></pre> <h2>Graphics.h</h2> <pre><code>#ifndef _GRAPHICS_H #define _GRAPHICS_H #include "vulkan\vulkan.h" #include &lt;vector&gt; struct Extensions { const std::vector&lt;const char*&gt; validationLayers = { "VK_LAYER_LUNARG_standard_validation", "VK_LAYER_LUNARG_monitor" }; const std::vector&lt;const char*&gt; device_extensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; }; struct QueueFamilyIndices { int32_t graphic_family = -1; int32_t present_family = -1; bool isComplete() { return graphic_family &gt;= 0 &amp;&amp; present_family &gt;= 0; } }; struct SwapchainDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector&lt;VkSurfaceFormatKHR&gt; formats; std::vector&lt;VkPresentModeKHR&gt; presentModes; }; struct SwapchainImage { VkFormat format; VkExtent2D extent; }; struct Graphics { #ifdef NDEBUG const bool validation_layer_enable = false; #else const bool validation_layer_enable = true; #endif VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physical_device = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface = VK_NULL_HANDLE; Extensions extensions; QueueFamilyIndices queue_indices; VkQueue graphics_queue = VK_NULL_HANDLE; VkQueue present_queue = VK_NULL_HANDLE; SwapchainImage swapchain_details; VkSwapchainKHR swapchain = VK_NULL_HANDLE; std::vector&lt;VkImage&gt; swapchain_images; std::vector&lt;VkImageView&gt; images_view; std::vector&lt;VkFramebuffer&gt; framebuffers; VkCommandPool command_pool; std::vector&lt;VkCommandBuffer&gt; command_buffers;//replace VkCommandBuffer with CommandBuffer std::vector&lt;VkSemaphore&gt; semaphores_render_finished; std::vector&lt;VkSemaphore&gt; semaphores_image_available; std::vector&lt;VkFence&gt; fences_in_flight; VkRenderPass render_pass; VkBuffer uniform_buffer; VkDeviceMemory uniform_memory; VkDescriptorSetLayout descriptor_set_layout = VK_NULL_HANDLE; VkDescriptorPool descriptor_pool = VK_NULL_HANDLE; VkDescriptorSet descriptor_set = VK_NULL_HANDLE; VkImage texture_image; VkImageView texture_view; VkSampler texture_sampler; VkDeviceMemory texture_memory; VkImage depth_image; VkDeviceMemory depth_memory; VkImageView depth_view; }; struct Pipeline { VkPipeline handle = VK_NULL_HANDLE; VkPipelineLayout layout = VK_NULL_HANDLE; }; struct Buffer { VkBuffer vertex = VK_NULL_HANDLE; VkDeviceMemory vertex_memory = VK_NULL_HANDLE; VkBuffer index = VK_NULL_HANDLE; VkDeviceMemory index_memory = VK_NULL_HANDLE; }; struct CommandBuffers { bool needUpdate = true;//base state VkCommandBuffer handle = VK_NULL_HANDLE; }; #endif // !_GRAPHICS_H </code></pre> <h2>Camera.h</h2> <pre><code>#ifndef _CAMERA_H #define _CAMERA_H #include &lt;GLFW/glfw3.h&gt; #include &lt;glm/glm.hpp&gt; #include &lt;glm/gtc/quaternion.hpp&gt; #include &lt;glm/gtc/matrix_transform.hpp&gt; #include &lt;memory&gt; #include &lt;bitset&gt; #include &lt;iostream&gt; class Camera { public: Camera(); ~Camera(); void setInput(int32_t key, int32_t scancode, int32_t mods, int32_t action); void mouse(double xpos, double ypos); void updatePos(); glm::vec3 getPosition(); glm::vec3 getRotation(); float&amp; getPitch(); float&amp; getYaw(); void setDeltaTime(float dt); private: std::bitset&lt;348&gt; m_keyboard_press; glm::vec3 m_position; glm::vec3 m_rotation; float m_yaw; float m_pitch; glm::vec2 last_mouse_pos; float delta_time; }; #endif // !_CAMERA_H </code></pre> <h2>Camera.cpp</h2> <pre><code>#include "Camera.h" Camera::Camera() { m_yaw = 0; m_pitch = 0; last_mouse_pos = glm::vec2(0, 0); delta_time = 0; m_keyboard_press = { false }; m_position = { 0.0f, 0.0f, 0.0f }; m_rotation = { 1.0f, 1.0f, 0.0f }; } Camera::~Camera() { } void Camera::setInput(int32_t key, int32_t scancode, int32_t mods, int32_t action) { if (action == GLFW_PRESS) { m_keyboard_press.set(key, true); } else if(action == GLFW_RELEASE) { m_keyboard_press.set(key, false); } } void Camera::mouse(double xpos, double ypos) { float sensibility = 0.005f; glm::vec2 mouse_delta = glm::vec2(xpos, ypos); m_yaw = mouse_delta.x * sensibility; m_pitch = mouse_delta.y * sensibility; } void Camera::updatePos() { glm::vec3 change = { 0.0f, 0.0f, 0.0f }; float speed = 10.0f; if (m_keyboard_press[GLFW_KEY_W] == true) { change.x -= -glm::cos(glm::radians(m_yaw)) * speed;//rotation still not working change.z -= -glm::sin(glm::radians(m_yaw)) * speed; } if (m_keyboard_press[GLFW_KEY_S] == true) { change.x += -glm::cos(glm::radians(m_rotation.y)) * speed; change.z += -glm::sin(glm::radians(m_rotation.y)) * speed; } if (m_keyboard_press[GLFW_KEY_D] == true) { change.x += -glm::cos(glm::radians(m_rotation.y + 90)) * speed; change.z += -glm::sin(glm::radians(m_rotation.y + 90)) * speed; } if (m_keyboard_press[GLFW_KEY_A] == true) { change.x -= -glm::cos(glm::radians(m_rotation.y + 90)) * speed; change.z -= -glm::sin(glm::radians(m_rotation.y + 90)) * speed; } if (m_keyboard_press[GLFW_KEY_LEFT_SHIFT] == true) { change.y += 1.0f * speed; } if (m_keyboard_press[GLFW_KEY_LEFT_CONTROL] == true) { change.y -= 1.0f * speed; } m_position += change * delta_time; } glm::vec3 Camera::getPosition() { return m_position; } glm::vec3 Camera::getRotation() { return m_rotation; } float &amp; Camera::getPitch() { return m_pitch; } float &amp; Camera::getYaw() { return m_yaw; } void Camera::setDeltaTime(float dt) { delta_time = dt; } </code></pre> <h2>VulkanBuffer.h</h2> <pre><code>#ifndef _VULKANBUFFER_H #define _VULKANBUFFER_H #include &lt;memory&gt; #include "Graphics.h" #include "Voxel.h" class VulkanBuffer { public: VulkanBuffer(Graphics &amp; graphic); ~VulkanBuffer(); void createBuffer(VkBuffer &amp; buffer, VkDeviceMemory &amp; bufferMemory, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties); private: uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties); Graphics &amp; m_graphic; }; #endif // !_VULKANBUFFER_H </code></pre> <h2>VulkanBuffer.cpp</h2> <pre><code>#include "VulkanBuffer.h" VulkanBuffer::VulkanBuffer(Graphics&amp; graphic) : m_graphic(graphic) { } VulkanBuffer::~VulkanBuffer() { } void VulkanBuffer::createBuffer(VkBuffer &amp; buffer, VkDeviceMemory &amp; bufferMemory, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties) { VkResult result; VkBufferCreateInfo bufferInfo = {}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; result = vkCreateBuffer(m_graphic.device, &amp;bufferInfo, nullptr, &amp;buffer); switch (result) { case VK_SUCCESS: break; case VK_ERROR_OUT_OF_HOST_MEMORY: throw std::runtime_error("Failed to create buffer!"); break; case VK_ERROR_OUT_OF_DEVICE_MEMORY: throw std::runtime_error("Failed to create buffer!"); break; default: throw std::runtime_error("Failed to create buffer!"); break; } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(m_graphic.device, buffer, &amp;memRequirements); VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties); result = vkAllocateMemory(m_graphic.device, &amp;allocInfo, nullptr, &amp;bufferMemory); switch (result) { case VK_SUCCESS: break; case VK_ERROR_OUT_OF_HOST_MEMORY: throw std::runtime_error("Failed to allocate buffer memory!"); break; case VK_ERROR_OUT_OF_DEVICE_MEMORY: throw std::runtime_error("Failed to allocate buffer memory!"); break; case VK_ERROR_TOO_MANY_OBJECTS: throw std::runtime_error("Failed to allocate buffer memory!"); break; case VK_ERROR_INVALID_EXTERNAL_HANDLE: throw std::runtime_error("Failed to allocate buffer memory!"); break; default: throw std::runtime_error("Failed to allocate buffer memory!"); break; } result = vkBindBufferMemory(m_graphic.device, buffer, bufferMemory, 0); switch (result) { case VK_SUCCESS: break; case VK_ERROR_OUT_OF_HOST_MEMORY: throw std::runtime_error("Failed to bind buffer!"); break; case VK_ERROR_OUT_OF_DEVICE_MEMORY: throw std::runtime_error("Failed to bind buffer!"); break; default: throw std::runtime_error("Failed to bind buffer!"); break; } } uint32_t VulkanBuffer::findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(m_graphic.physical_device, &amp;memProperties); for (uint32_t i = 0; i &lt; memProperties.memoryTypeCount; i++) { if (typeFilter &amp; (1 &lt;&lt; i) &amp;&amp; (memProperties.memoryTypes[i].propertyFlags &amp; properties) == properties) { return i; } } throw std::runtime_error("failed to find suitable memory type!"); } </code></pre> <h2>Window.h</h2> <pre><code>#pragma once #ifndef _GLFW3_ #define _GLFW3_ #define GLFW_INCLUDE_VULKAN #include &lt;GLFW\glfw3.h&gt; #endif // !_GLFW3_ #include &lt;memory&gt; #include "Camera.h" #include "Config.h" class Window { public: Window(std::unique_ptr&lt;Config&gt;&amp; config, Camera&amp; camera); ~Window(); static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); static void mouse_callback(GLFWwindow* window, double xpos, double ypos); GLFWwindow&amp; getHandle(); //Camera&amp; getCamera(); private: GLFWwindow * m_handle; }; </code></pre> <h2>Window.cpp</h2> <pre><code>#include "Window.h" Window::Window(std::unique_ptr&lt;Config&gt;&amp; config, Camera&amp; camera) { glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); m_handle = glfwCreateWindow(config-&gt;width, config-&gt;height, "Vulkan", nullptr, nullptr); glfwSetInputMode(m_handle, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetWindowUserPointer(m_handle, &amp;camera); glfwSetKeyCallback(m_handle, key_callback); glfwSetCursorPosCallback(m_handle, mouse_callback); } Window::~Window() { glfwDestroyWindow(m_handle); glfwTerminate(); } void Window::key_callback(GLFWwindow * window, int key, int scancode, int action, int mods) { Camera* pCamera = static_cast&lt;Camera*&gt;(glfwGetWindowUserPointer(window)); pCamera-&gt;setInput(static_cast&lt;int32_t&gt;(key), static_cast&lt;int32_t&gt;(scancode), static_cast&lt;int32_t&gt;(mods), static_cast&lt;int32_t&gt;(action)); if (key == GLFW_KEY_ESCAPE &amp;&amp; action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GLFW_TRUE); } } void Window::mouse_callback(GLFWwindow * window, double xpos, double ypos) { Camera* pCamera = static_cast&lt;Camera*&gt;(glfwGetWindowUserPointer(window)); pCamera-&gt;mouse(xpos, ypos); } GLFWwindow &amp; Window::getHandle() { return *m_handle; } </code></pre> <p>If you need anything else, please ask.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:09:45.710", "Id": "412101", "Score": "0", "body": "Code to be reviewed must be in the body of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:12:21.207", "Id": "412102", "Score": "0", "body": "@TobySpeight So I post the code full engine in the body?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:21:02.843", "Id": "412105", "Score": "3", "body": "@MrScriptX at least the complete, **working** part you want to get reviewed. After all, your code in your GitHub repository may change at any time. Due to StackExchange Q&A style, any answer should be valid throughout the question's life, and the question+answer should be self contained. A link to a repository unfortunately defeats both purposes: your code may change (and invalidate reviews), and visitors to this site cannot benefit from the review, as the code is missing. Keep in mind that this will put your code under CC-BY-SA, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T17:55:33.583", "Id": "412127", "Score": "0", "body": "@Incomputable Hm. The headers are missing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T17:59:01.907", "Id": "412129", "Score": "0", "body": "@Zeta, would be great to implement some sort of tool that would automatically generate the post given a repository. I guess it is possible with boost.asio and std.filesystem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T08:41:46.963", "Id": "412197", "Score": "0", "body": "@Incomputable Nah. That's a shell script's job, e.g. `find . -not -path \"*.git*\" -not -path \"*/build/*\" -type f \\( -name \"*.c*\" -or -name \"*.h\" -or -name \"*.hpp\" \\) -printf \"\\n\\n## File: %P\\n\\n\" -exec sed 's#^# #' {} \\;` (that should be four spaces in the `sed` command, but comment markdown fails me). After all, OP has the repository on their disk. Keep in mind that only *they* are allowed to post their code, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T09:04:34.123", "Id": "412198", "Score": "0", "body": "@Zeta, sure, I fully respect their property. I just thought that it is not always funny to do that manually, thought about some cross platform solution, something that would require little to no setup involved. I guess one could write such a tool in a language question is written in, and suggest it if needed. I guess that will be a good code review question, I'll try it out later this week." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:05:52.890", "Id": "412207", "Score": "0", "body": "@Incomputable we should probably discuss this somewhere else, but [feel free to try this](https://codereview.stackexchange.com/questions/213084/easy-to-use-code-preparation-script-for-codereview-questions)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T15:51:30.590", "Id": "213051", "Score": "1", "Tags": [ "c++", "performance", "graphics" ], "Title": "Voxel Engine with Vulkan" }
213051
<p>This might appear to be a trivial task, but I think it's not the case. My code originally looked like this:</p> <pre><code>class DataSetToPdf { static byte [] F1 = Util.GetFile( "C:\PdfFiles\FreeSans.ttf" ); public static void Go( Data.DataSet ds, int ix, System.IO.Stream output ) { // Code which uses F1 } } </code></pre> <p>Util.GetFile simply reads the file and returns an array of bytes. For completeness, here it is:</p> <pre><code>class Util { public static byte[] GetFile( String path ) { IO.MemoryStream ms = new IO.MemoryStream(); using( IO.FileStream f = IO.File.OpenRead( path) ) { f.CopyTo( ms ); } return ms.ToArray(); } } </code></pre> <p>However, when using DataSetToPdf in a multi-threaded environment (IIS), I was sometimes ( but not always ) getting mysterious null reference exceptions, which I could not easily debug. However, what I believe what was happening is that the static method could be called before the initialisation is complete. Instead what appears to be is necessary is this:</p> <pre><code>class DataSetToPdf { static System.Object Locker = new System.Object(); static byte [] F1; public static void Go( Data.DataSet ds, int ix, System.IO.Stream output ) { lock( Locker ) { if ( F1 == null ) { F1 = Util.GetFile( "C:\PdfFiles\FreeSans.ttf" ); } } // Code which uses F1 } } </code></pre> <p>Please review my updated code, was it wrong before, is it right now?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T18:38:33.310", "Id": "412134", "Score": "3", "body": "`MemoryStream` is also an `IDisposable`-implementing class (it descends from `Stream`) and should be wrapped in a `using` construct just like `FileStream` is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T18:52:28.633", "Id": "412139", "Score": "1", "body": "What was the null reference exception? `F1` could never be null, because `MemoryStream.ToArray() ` never returns null. Ideally, `F1` should be `readonly`, so I guess it's *possible* something else is setting it to null. My guess is the exception is unrelated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T19:00:51.720", "Id": "412143", "Score": "3", "body": "Also, `File.ReadAllBytes()` should be able to do what you want without the intermediate copy to memory stream." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T19:04:21.400", "Id": "412145", "Score": "0", "body": "@BradM F1 was null because it hadn't YET been initialised. C# doesn't guarantee that initialisation of static members completes before members are called in a multi-threaded environment ( which caught me out ). I believe it can only happen when the initialisation is delayed by blocking, in this case an IO operation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T19:15:55.760", "Id": "412146", "Score": "1", "body": "@GeorgeBarwood Thats not true to my knowledge. Static fields are guaranteed to be initalized before first usage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T19:42:35.263", "Id": "412148", "Score": "0", "body": "This link describes how a static constructor does result in locking, but initialisers are I think different. I think I could use a static constructor, and that would be safe.\nhttps://docs.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T10:03:01.347", "Id": "412368", "Score": "0", "body": "There are a couple of proven [singleton initilization patterns](http://csharpindepth.com/Articles/General/Singleton.aspx) that I find you should use or `Lazy<T>` rather than trying to come up with your own solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:37:33.187", "Id": "412384", "Score": "0", "body": "Note the file paths need to either have the backslashes escaped as \\\\, or be defined as a verbatim string, e.g. `@\"C:\\PdfFiles\\FreeSans.ttf\"`" } ]
[ { "body": "<p>I would avoid doing this kind of thing in a static constructor or static initializer. Error handling in this situation can get tricky: errors thrown will result in a <code>TypeInitializationException</code> and the static constructor will not get executed again even if this is handled. You also don't have much control about where this will get thrown in your code: it would be very easy to refactor your code and end up with the first reference to the type appearing in a completely different place.</p>\n\n<p>Loading from a file is also going to cause issues when you write tests: a reference to the type will trigger the static initialization and therefore depend on the presence of the file, which you will need to ensure is present in all the relevant test assemblies (and this kind of thing becomes a headache if you are using things like ReSharper's shadow copying behavior).</p>\n\n<p>I would consider avoiding the use of static methods: define an interface and pass the relevant data in through the class constructor, e.g.</p>\n\n<pre><code>public interface IDataSetToPdf\n{\n void Process();\n} \n\npublic class DataSetToPdf : IDataSetToPdf\n{\n private readonly byte[] fontData;\n\n public DataSetToPdf(byte[] fontData)\n {\n this.fontData = fontData ?? throw new ArgumentNullException(nameof(fontData));\n }\n\n public void Process()\n {\n // do stuff with fontData\n }\n}\n</code></pre>\n\n<p>There are several advantages of doing this: firstly, if the data is in a static field, it it will last as long as the application does, whereas using an instance field allows the memory to be reclaimed by the garbage collector when no further references to it remains.</p>\n\n<p>Another advantage is that it makes it easier to unit test: provided you write your code against the interface <code>IDataSetToPdf</code> rather than the concrete class <code>DataSetToPdf</code>, you would be able to provide a mock implementation of the interface for your tests, which would allow you to focus your tests on the calling code rather than the combination of the calling code with <code>DataSetToPdf</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:35:43.560", "Id": "213182", "ParentId": "213058", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T17:58:03.243", "Id": "213058", "Score": "2", "Tags": [ "c#" ], "Title": "Safely Initialising a static variable to a file" }
213058
<p>I've developed a toy example to investigate how <code>async</code> works in C#. Though I've learned a lot this week, I'm still unsure of the finer details, as this is my first C# program.</p> <p>Compilation was done with .Net Core 2.2.</p> <h3>Usage</h3> <ul> <li>The program runs in an infinite loop. Press any key to stop the program.</li> </ul> <h3>Goal</h3> <ul> <li>Process stream data such that: <ul> <li>The stream is never blocked.</li> <li>Data from the stream is bucketed into separate processing tasks based on an Id.</li> <li>This bucketing allows processing tasks to be done in parallel.</li> <li>This bucketing also ensures that data are processed in order.</li> <li>Processed data from all buckets is then fed to a mutual IO operation.</li> </ul></li> </ul> <h3>Implementation</h3> <ul> <li>Data streams from set of Machines.</li> <li>This data is accessible from a single producer -- here a <code>while(true)</code> loop.</li> <li>The data consists of ordered records containing fields {machineId, sensorId, sensorValue}. <ul> <li>A single machine may have multiple sensors.</li> </ul></li> <li>To maintain order and introduce parallelism, records are processed in a separate <code>BlockingCollection</code> for each Id.</li> <li>After raw data processing, a new aggregate value is created and then passed to a common IO <code>BlockingCollection</code>.</li> </ul> <h3>Issues</h3> <ol> <li>Is it reasonable to start multiple <code>BlockingCollection.​getConsumingEnumerable()</code> loops with <code>Task.Run</code> in preparation for data ingestion?</li> <li>Is passing data between <code>BlockingCollection</code>s the way I do it reasonable?</li> <li>Are there any performance issues with passing data between multiple <code>BlockingCollection</code>s?</li> <li>Am I using <code>Task.Run</code> and <code>await</code> properly?</li> <li>Am I using <code>CancellationToken</code>s properly?</li> </ol> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; public struct SensorReading { public int machineId; public int sensorId; public int value; public SensorReading(int machineId, int sensorId, int value) { this.machineId = machineId; this.sensorId = sensorId; this.value = value; } } public struct MachineAggregateReading { public int machineId { get; set; } public int aggregateSum { get; set; } public MachineAggregateReading(int machineId, int aggregateSum) { this.machineId = machineId; this.aggregateSum = aggregateSum; } } public class IOQueue { private BlockingCollection&lt;MachineAggregateReading&gt; collection; private CancellationToken token; public IOQueue(CancellationToken token) { collection = new BlockingCollection&lt;MachineAggregateReading&gt;( new ConcurrentQueue&lt;MachineAggregateReading&gt;()); this.token = token; } public void addToQueue(MachineAggregateReading m) { if (!collection.IsAddingCompleted) { collection.Add(m); } } // Return `Task` for an async method that performs an operation but returns no value. public async Task processQueue() { foreach (var s in collection.GetConsumingEnumerable()) { Console.WriteLine("IO: machineId: {0}. aggregateSum {1}. queue count: {2}", s.machineId, s.aggregateSum, collection.Count); await Task.Delay(20 * 5, token); } } public void completeAdding() { collection.CompleteAdding(); } } public class MachineSensorReadingCollector { private int machineId; private IOQueue ioQueue; private CancellationToken token; private BlockingCollection&lt;SensorReading&gt; collection; private Dictionary&lt;int, int&gt; aggregateSensorReadings; public MachineSensorReadingCollector( int machineId, IOQueue ioQueue, CancellationToken token) { this.machineId = machineId; this.ioQueue = ioQueue; this.token = token; this.collection = new BlockingCollection&lt;SensorReading&gt;( new ConcurrentQueue&lt;SensorReading&gt;()); aggregateSensorReadings = new Dictionary&lt;int, int&gt;(); } public void addToQueue(SensorReading s) { if (!collection.IsAddingCompleted) { collection.Add(s); } } // Return `Task` for an async method that performs an operation // but returns no value. public async Task processQueue() { int aggregateSum; foreach (var s in collection.GetConsumingEnumerable()) { // Add to aggregate sensor readings if (!aggregateSensorReadings.ContainsKey(s.sensorId)) { aggregateSensorReadings[s.sensorId] = 0; } aggregateSensorReadings[s.sensorId] += s.value; Console.WriteLine("Consuming: machineId: {0}. sensorId: {1}. value: {2}. aggregate: {3}. queue count: {4}", machineId, s.sensorId, s.value, aggregateSensorReadings[s.sensorId], collection.Count); await Task.Delay(10 * 5, token); aggregateSum = 0; foreach ((_, int value) in aggregateSensorReadings) { aggregateSum += value; } ioQueue.addToQueue( new MachineAggregateReading(machineId, aggregateSum)); } } public void completeAdding() { collection.CompleteAdding(); } } public class Client { private Random random; private CancellationTokenSource tokenSource { get; set; } private CancellationToken token { get; set; } private int[] machineIdArray; private List&lt;Task&gt; machineTasksList; private IOQueue ioQueue; private Dictionary&lt;int, MachineSensorReadingCollector&gt; machineCollectorDict; public Client(int[] machineIdArray) { random = new Random(); tokenSource = new CancellationTokenSource(); this.token = tokenSource.Token; ioQueue = new IOQueue(this.token); this.machineIdArray = machineIdArray; machineTasksList = new List&lt;Task&gt;(); machineCollectorDict = new Dictionary&lt;int, MachineSensorReadingCollector&gt;(); foreach (var machineId in machineIdArray) { machineCollectorDict[machineId] = new MachineSensorReadingCollector( machineId: machineId, ioQueue: ioQueue, token: token); } } public async Task Start() { // Start IO Queue // `Task.Run` must be used here rather than `await`. // // Possible: // var ioQueueProcessor = Task.Run(() =&gt; ioQueue.processQueue()); // // Not possible: // await ioQueue.processQueue(); // // If `await ioQueue.processQueue();` is used the executing thread // will get stuck inside the GetConsumingEnumerable method. var ioQueueProcessor = Task.Run(() =&gt; ioQueue.processQueue()); // Start Machine Collectors foreach (var (_, machineCollector) in machineCollectorDict) { // Again, `Task.Run` must be used here rather than `await` for // the same reason given above. var machineCollectorProcessor = Task.Run(() =&gt; machineCollector.processQueue()); machineTasksList.Add(machineCollectorProcessor); } Console.WriteLine("Press any key to send cancellation token."); while (true) { if (Console.KeyAvailable) { tokenSource.Cancel(); Console.WriteLine("Key pressed. Cancellation token activated."); break; } var s = new SensorReading( machineId: machineIdArray[random.Next(machineIdArray.Length)], sensorId: random.Next(1, 4), value: random.Next(-2, 2)); Console.WriteLine("Producing: machineId {0}. sensorId {1}. value {2}", s.machineId, s.sensorId, s.value); machineCollectorDict[s.machineId].addToQueue(s); await Task.Delay(30, token); } } public static void Main(string[] args) { int[] machineIdArray = new int[] { 1, 3, 5 }; var c = new Client(machineIdArray); try { c.Start().Wait(); } catch (AggregateException agg) { foreach (var ex in agg.InnerExceptions) { if (ex is TaskCanceledException) { Console.WriteLine("Task successfully canceled."); } else { Console.WriteLine(ex); } } } Console.WriteLine("All actions completed."); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T23:57:34.357", "Id": "412161", "Score": "0", "body": "Your `Main()` method can be `async Task` instead of `void`. This way you can `await` the `Start()` task instead of `Wait()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T02:12:59.847", "Id": "412167", "Score": "0", "body": "Thanks @brad-m. Any other feedback would be much appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T07:46:30.367", "Id": "412185", "Score": "1", "body": "We cannot currently review your code because it contains bugs that make your solution not working properly. We'll be happy to take a look a it when you've fixed them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T14:01:51.250", "Id": "412247", "Score": "1", "body": "@t3chb0t I've edited the code. Thanks for reaching out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T11:47:28.417", "Id": "412333", "Score": "0", "body": "Writing code like this line `while (true) if (!token.IsCancellationRequested)` is a very bad style and error-prone - also in many other places where you use a `foreach` followed by an `if` without any `{}` - this is difficult to refactor and can very quickly go sideways." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T13:40:25.337", "Id": "412334", "Score": "0", "body": "@t3chb0t cheers. I've removed those forech / while if statements and added a break in the main while loop. Much cleaner." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T18:24:41.840", "Id": "213061", "Score": "1", "Tags": [ "c#", "beginner", ".net", "asynchronous", "async-await" ], "Title": "Aggregate sensor readings from multiple sources" }
213061
<p>I have to weekly upload a csv file to sqlserver, and I do the job using python 3. The problem is that it takes too long for the file to be uploaded (around 30 minutes), and the table has 49000 rows and 80 columns.</p> <p>Here is a piece of the code, where I have to transform the date format and replace quotes as well. I have already tried it with pandas, but took longer than that.</p> <pre><code>import csv import os import pyodbc import time srv='server_name' db='database' tb='table' conn=pyodbc.connect('Trusted_Connection=yes',DRIVER='{SQL Server}',SERVER=srv,DATABASE=db) c=conn.cursor() csvfile='file.csv' with open(csvfile,'r') as csvfile: reader = csv.reader(csvfile, delimiter=';') cnt=0 for row in reader: if cnt&gt;0: for r in range(0,len(row)): #this is the part where I transform the date format from dd/mm/yyyy to yyyy-mm-dd if (len(row[r])==10 or len(row[r])==19) and row[r][2]=='/' and row[r][5]=='/': row[r]=row[r][6:10]+'-'+row[r][3:5]+'-'+row[r][0:2] #here I replace the quote to nothing, since it is not important for the report if row[r].find("'")&gt;0: row[r]=row[r].replace("'","") #at this part I query the index to increment by 1 on the table qcnt="select count(1) from "+tb resq=c.execute(qcnt) rq=c.fetchone() rq=str(rq[0]) #here I insert each row into the table that already exists insrt=("insert into "+tb+" values("+rq+",'"+("', '".join(row))+"')") if cnt&gt;0: res=c.execute(insrt) conn.commit() cnt+=1 conn.close() </code></pre> <p>Any help will be appreciated. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T21:57:19.850", "Id": "412154", "Score": "2", "body": "What is `reader`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T13:23:39.057", "Id": "412242", "Score": "0", "body": "sorry, copied from my code but forgot to insert it here. It comes at this part: 'with open(csvfile,'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=';')'. Just edited it now." } ]
[ { "body": "<p>First of all, when in doubt, profile.</p>\n\n<p>Now a not-so-wild guess. Most of the time is wasted in</p>\n\n<pre><code> qcnt=\"select count(1) from \"+tb\n resq=c.execute(qcnt)\n rq=c.fetchone()\n rq=str(rq[0])\n</code></pre>\n\n<p>In fact, the <code>rq</code> is incremented by each successful <code>insert</code>. Better fetch it once, and increment it locally:</p>\n\n<pre><code> qcnt=\"select count(1) from \"+tb\n resq=c.execute(qcnt)\n rq=c.fetchone()\n\n for row in csvfile:\n ....\n insert = ....\n c.execute(insert)\n rq += 1\n ....\n</code></pre>\n\n<p>Another guess is that committing each insert separately also does not help with performance. Do it once, after the loop. In any case, you must check the success of each commit.</p>\n\n<hr>\n\n<p>Notice that if there is more than one client updating the table simultaneously, there is a data race (clients fetching the same <code>rq</code>), both with the original design, and with my suggestion. Moving <code>rq</code> into a column of its own may help; I don't know your DB design and requirements.</p>\n\n<p>Consider a single <code>insert values</code>, wrapped into a transaction, instead of multiple independent <code>insert</code>s.</p>\n\n<hr>\n\n<p>Testing for <code>cnt &gt; 0</code> is also wasteful. Read and discard the first line; then loop for the remaining rows.</p>\n\n<hr>\n\n<p>Figuring out whether a field represents a date seems strange. You shall know that in advance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T17:17:32.387", "Id": "412272", "Score": "0", "body": "Thanks man, made two modifications, and elapsed time was reduced by half the time (mainly on the increment part). Awesome!!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T22:16:43.037", "Id": "213070", "ParentId": "213063", "Score": "2" } } ]
{ "AcceptedAnswerId": "213070", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T18:46:26.420", "Id": "213063", "Score": "1", "Tags": [ "python", "sql-server", "csv" ], "Title": "Upload csv file to sqlserver with python" }
213063
<p>I mostly develop AddIns for Office. In the example of MS Word, I have an AddIn which allows to review drafting style, another AddIn which allows to monitor cross-references, another Addin which allows to import graphics from the web, etc. What the AddIns do is irrelevant here, but you should now they all work independently from each other.</p> <p>I now would like to centralise all these AddIn 'Extensions' into one executable, so that the end users only deal with only one setup for Word, instead of 3. Due to some internal restriction rules, some users may not be allowed to use some AddIn extensions. Hence the need for some verifications at runTime.</p> <p>At the moment I came up with the following arquitecture, but I am not 100% satisfied. I set below a listing of strenghts and weaknesses. Feel free to suggest aditionnal weaknesses, and/or fixes.</p> <h2>Strengths</h2> <ol> <li>The flow between the UI (button callbacks) and the execution is centralized and standardized.</li> <li>The feature availability validation is centralised and easy to update if needs be.</li> <li>Dealing with an new AddIn Extension is "easy": build a new <code>class</code> which <code>inherits AddInExtension</code>, populate the <code>AddInExtensions Collection</code>, populate the newly built <code>Class</code> with relevant callback names in the <code>Overrides Sub FinallyExecute()</code>, and add their corresponding features (Subs, Classes) into the same <code>Class</code>.</li> <li>Encapsulation is total and there is no risk for interference between two extensions.</li> </ol> <h2>Weaknesses</h2> <ol start="5"> <li>I am worried I will have to include the entire code of an AddIn Extension into a single .vb file (the AddInExtensionABCServices <code>Class</code>).</li> <li>I am also worried I will have to nest all AddIn Extension Sub-Classes into the Main-Class. I feel this can get messy.</li> <li>Architecture is not 100% Hard Typed, in the sens that the callback <code>Sub</code> uses text strings twice to run the relevant Sub, whilst I would have loved to be able to do something like <code>MyExtensions.ABCServices.GetChocolate</code>.</li> </ol> <p>Re point 7, my intuition tells me this could be fixed through (i) <code>Shared Class</code> or (ii) a combination of <code>Module</code> and <code>Namespace</code>. But (i) a <code>MustInherit Class</code> cannot be <code>Shared</code>, and (ii) Modules are hard to keep <code>Private</code> (default is <code>Public</code>, hence prone to errors).</p> <hr> <pre><code>Module Module1 Private AddInExtensions As New Collections.Hashtable() Sub Main() AddInExtensions.Add("OnlineServices", New AddInExtensionOnlineServices) AddInExtensions.Add("LocalServices", New AddInExtensionLocalServices) AddInExtensions.Add("SpaceServices", New AddInExtensionSpaceServices) '... rest of initialization code End Sub 'Example of a CallBack Sub MyCallBackButtonClicked() Dim MyExtension As IAddInExtension = AddInExtensions("LocalServices") MyExtension.TryExecute("GetTea") End Sub End Module '# Interface required for Intelisense when calling AddInExtensions As Collections.Hashtable() Interface IAddInExtension Sub TryExecute(ByVal ActionName As String) End Interface '# Base Class from which will derive each AddIn Extension class Friend MustInherit Class AddInExtension Implements IAddInExtension Protected Property Name As String Protected Property StatusIsOk As Boolean 'This sub verifies the services are available Public Sub TryExecute(ByVal ActionName As String) Implements IAddInExtension.TryExecute If StatusIsOk Then Me.FinallyExecute(ActionName) Else MsgBox("Sorry, you cannot use this service. Please contact your IT department.", vbOKOnly) End If End Sub 'The overriden version of this Sub will contain all the features related to a given Extension Protected MustOverride Sub FinallyExecute(ByVal ActionName As String) End Class '# AddIn Extension Class for ONLINE SERVICES Friend Class AddInExtensionOnlineServices Inherits AddInExtension Public Sub New() MyBase.Name = "OnlineServices" MyBase.StatusIsOk = True 'Let's say this AddIn Extension is PERMITED (typically would run a function here) End Sub 'Actions available through the Button Callback for this AddIn Extension Protected Overrides Sub FinallyExecute(ActionName As String) Select Case ActionName Case "GetTime" Call Me.GetTime() Case "GetWeather" Call Me.GetWeather() End Select End Sub Private Sub GetTime() '... End Sub Private Sub GetWeather() '... End Sub End Class '# AddIn Extension Class for LOCAL SERVICES Friend Class AddInExtensionLocalServices Inherits AddInExtension Public Sub New() MyBase.Name = "LocalServices" MyBase.StatusIsOk = True 'Let's say this AddIn Extension is PERMITED (typically would run a function here) End Sub 'Actions available through the Button Callback for this AddIn Extension Protected Overrides Sub FinallyExecute(ActionName As String) Select Case ActionName Case "GetCoffee" Call Me.GetCoffee() Case "GetTea" Call Me.GetTea() End Select End Sub Private Sub GetCoffee() '... End Sub Private Sub GetTea() '... End Sub End Class '# AddIn Extension Class for SPACE SERVICES Friend Class AddInExtensionSpaceServices Inherits AddInExtension Public Sub New() MyBase.Name = "SpaceServices" MyBase.StatusIsOk = False 'Let's say this AddIn Extension is FORBIDDEN (typically would run a function here) End Sub 'Actions available through the Button Callback for this AddIn Extension Protected Overrides Sub FinallyExecute(ActionName As String) Select Case ActionName Case "GetOxygen" Call Me.GetOxygen() Case "GetSun" Call Me.GetSun() End Select End Sub Private Sub GetOxygen() '... End Sub Private Sub GetSun() '... End Sub End Class </code></pre> <hr> <p>Also one question aside: I would like to change</p> <pre><code>Dim MyExtension As IAddInExtension = AddInExtensions("LocalServices") MyExtension.Execute("GetTea") </code></pre> <p>by</p> <pre><code>AddInExtensions("LocalServices").Execute("GetTea") </code></pre> <p>but Intelisense does not pick up the type so <code>.Execute</code> does not show in the dropwodn list. Other than minorly inconvenient, would that cause any problem?</p> <p>I was thinking of typing the Hashtable with something in the like of <code>Private AddInExtensions As New Collections.Hashtable(Of IAddInExtension)</code> but the compiler does not like it.</p>
[]
[ { "body": "<p><strong>Use generics</strong></p>\n\n<pre><code>Private AddInExtensions As New Generic.Dictionary(Of String, IAddInExtension)\n</code></pre>\n\n<p>Later you can do</p>\n\n<pre><code>AddInExtensions(\"LocalServices\").TryExecute(\"GetTea\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T18:51:10.160", "Id": "215521", "ParentId": "213073", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T22:45:48.690", "Id": "213073", "Score": "0", "Tags": [ "vb.net" ], "Title": "Efficiently centralise and manage Groups of Features (aka \"lines of services\")" }
213073
<p>I am trying to model the proof of Immerman–Szelepcsényi Theorem with Haskell since it heavily uses non-determinism. An explanation of what the point of this is can be found <a href="https://brilliant.org/discussions/thread/a-haskell-aware-explanation-of/" rel="nofollow noreferrer">here</a>.</p> <pre><code>{-# LANGUAGE FlexibleContexts #-} import Control.Monad import Control.Monad.State type NonDet a = [a] type NonDetState s a = StateT s [] a type Vertex = Int -- represent the graph as an adjacency list -- or equivalently, a nondeterministic computation -- that returns the next vertex given the current getNextVertex :: Vertex -&gt; NonDet Vertex getNextVertex = undefined -- is there a path from `source` to `target` in `bound` steps guessPath :: Int -&gt; Vertex -&gt; Vertex -&gt; NonDetState Vertex () guessPath bound source target = do put source nonDeterministicWalk bound where nonDeterministicWalk bound = do guard (bound &gt;= 0) v &lt;- get if v == target then return () else do w &lt;- lift $ getNextVertex v put w nonDeterministicWalk (bound - 1) -- if you knew the number of vertices reachable from the source -- use that to certify that target is not reachable certifyUnreachAux :: [Vertex] -&gt; Int -&gt; Vertex -&gt; Vertex -&gt; NonDetState Int () certifyUnreachAux vertices c source target = do put 0 forM_ vertices $ \v -&gt; do -- guess whether the vertex v is reachable or not guess &lt;- lift [True, False] if (not guess || v == target) -- if the vertex v is not reachable or is the target -- then just move on to the next one then return () else do -- otherwise verify that the vertex is indeed reachable guessPath (length vertices) source v counter &lt;- get put (counter + 1) counter &lt;- get guard (counter == c) return () -- figure out the number of vertices reachable from source -- in `steps` steps countReachable :: [Vertex] -&gt; Int -&gt; Vertex -&gt; NonDet Int countReachable vertices steps source = do if steps &lt;= 0 then return 1 else do previouslyReachable &lt;- countReachable vertices (steps - 1) source evalStateT (countReachableInduct vertices previouslyReachable steps source) (0, 0, False) -- figuring out how many vertices are reachable in (i+1) steps -- given the number of vertices reachable in i steps countReachableInduct :: [Vertex] -&gt; Int -&gt; Int -&gt; Vertex -&gt; NonDetState (Int, Int, Bool) Int countReachableInduct vertices previouslyReachable steps source = do -- initialize the counters to 0 put (0, 0, False) forM_ vertices $ \v -&gt; do -- set the first counter to 0 -- and unset the flag that says you have -- checked that v is a neighbor of u or u itself (previousCount, currentCount, b) &lt;- get put (0, currentCount, False) forM_ vertices $ \u -&gt; do -- guess if u reachable from the source in (steps - 1) steps guess &lt;- lift [True, False] if not guess -- if not, then we can move ahead to the next u then return () else do -- since we guessed that u is reachable, -- we should verify it lift $ evalStateT (guessPath (steps - 1) source u) 0 (previousCount, currentCount, b) &lt;- get put ((previousCount + 1), currentCount, b) if (u == v) then do (previousCount, currentCount, _) &lt;- get put (previousCount, currentCount, True) else do neighbor &lt;- lift $ getNextVertex u if (u == neighbor) then do (previousCount, currentCount, _) &lt;- get put (previousCount, currentCount, True) else -- if v is neither u nor a neighbor of u, -- we just move to the second iteration return () guard (previousCount == previouslyReachable) (previousCount, currentCount, b) &lt;- get -- if v was at most distance 1 from u, which -- we verfied to be a vertex reachable in -- (steps - 1) steps, then v is reachable -- in steps steps put (previousCount, (currentCount + if b then 1 else 0), b) (_, currentCount, _) &lt;- get return currentCount -- finally put all the methods together and show that -- target is unreachable from source certifyUnreach :: [Vertex] -&gt; Vertex -&gt; Vertex -&gt; NonDet () certifyUnreach vertices source target = do c &lt;- countReachable vertices (length vertices) source evalStateT (certifyUnreachAux vertices c source target) 0 </code></pre> <p>I'd like general comments on how I could improve coding style. One particular thing is the awkward use of <code>get</code> and <code>put</code> to get the three counters but update one of them. I would like to know how this can be done more elegantly with lenses.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T15:52:19.367", "Id": "412264", "Score": "0", "body": "`guard (previousCount == previouslyReachable)` <- did you mean to use the previousCount defined in the line after `-- checked that v is a neighbor of u or u itself`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T04:34:55.960", "Id": "412439", "Score": "0", "body": "I meant to use the latest value of ```previousCount```. So you are correct, I should have used a new ```get``` to get that value" } ]
[ { "body": "<p>I was going to use lens, but everything worked out mundanely. :/</p>\n\n<pre><code>-- is there a path from `source` to `target` in `bound` steps\nguessPath :: Int -&gt; Vertex -&gt; Vertex -&gt; NonDet ()\nguessPath bound source target = nonDeterministicWalk source bound where\n nonDeterministicWalk v bound = do\n guard $ bound &gt;= 0\n unless (v == target) $ do\n w &lt;- getNextVertex v\n nonDeterministicWalk w (bound - 1)\n\n-- figure out the number of vertices reachable from source\n-- in `steps` steps\ncountReachable :: [Vertex] -&gt; Int -&gt; Vertex -&gt; NonDet Int\ncountReachable vertices steps source = if steps &lt;= 0 then return 1 else do\n previouslyReachable &lt;- countReachable vertices (steps - 1) source\n fmap sum $ for vertices $ \\v -&gt; (`evalStateT` False) $ do\n -- the state flag witnesses that \n -- v has at most distance 1 from u\n guard . (== previouslyReachable) . sum =&lt;&lt; vertices `for` \\u -&gt;\n -- guess if u reachable from the source in (steps - 1) steps\n return 0 &lt;|&gt; 1 &lt;$ do -- if not, then we can move ahead to the next u\n -- since we guessed that u is reachable, we should verify it\n guessPath (steps - 1) source u\n if u == v then put True\n else do\n neighbor &lt;- lift $ getNextVertex u\n when (u == neighbor) $ put True\n -- if v is neither u nor a neighbor of u,\n -- we just move to the second iteration\n -- if v was at most distance 1 from u, which\n -- we verfied to be a vertex reachable in\n -- (steps - 1) steps, then v is reachable\n -- in steps steps\n gets $ bool 0 1\n\n-- finally put all the methods together and show that\n-- target is unreachable from source\ncertifyUnreach :: [Vertex] -&gt; Vertex -&gt; Vertex -&gt; NonDet ()\ncertifyUnreach vertices source target = do\n c &lt;- countReachable vertices (length vertices) source\n guard . (== c) . sum =&lt;&lt; vertices `for` \\v -&gt;\n -- guess whether the vertex v is reachable and not the target\n return 0 &lt;|&gt; 1 &lt;$ do\n -- verify that the vertex is indeed reachable and not the target\n guard $ v /= target\n guessPath (length vertices) source v\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T14:27:41.580", "Id": "213143", "ParentId": "213077", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T03:08:00.253", "Id": "213077", "Score": "4", "Tags": [ "algorithm", "haskell", "graph", "complexity" ], "Title": "Modelling Immerman–Szelepcsényi in Haskell" }
213077
<p>There is a function to convert object to the GET parameters for the ASP.Net controller. Is it possible to minimize the redundancy of the code, but not to the detriment of its readability?</p> <pre><code>function getUrlPairs(obj, prefix = "") { var getTypeOf = function (obj) { if (typeof obj == "undefined") { return "undefined"; } if (obj === null) { return "null"; } return Object.getPrototypeOf(obj).constructor.name; }; var urlPairs = [], objType = getTypeOf(obj), propType; if (objType === "Object") { for (var propName in obj) { if (obj.hasOwnProperty(propName)) { propType = getTypeOf(obj[propName]); switch (propType) { case "String": urlPairs.push(prefix + propName + "=" + encodeURIComponent(obj[propName])); break; case "Number": case "Boolean": case "null": urlPairs.push(prefix + propName + "=" + obj[propName]); break; case "Date": urlPairs.push(prefix + propName + "=" + encodeURIComponent(obj[propName].toJSON())); break; case "Object": urlPairs = urlPairs.concat(getUrlPairs(obj[propName], prefix + propName + ".")); break; case "Array": urlPairs = urlPairs.concat(getUrlPairs(obj[propName], prefix + propName)); break; default: break; } } } } else if (objType === "Array") { for (var i = 0; i &lt; obj.length; i++) { propType = getTypeOf(obj[i]); switch (propType) { case "String": urlPairs.push(prefix + "[" + i + "]" + "=" + encodeURIComponent(obj[i])); break; case "Number": case "Boolean": case "null": urlPairs.push(prefix + "[" + i + "]=" + obj[i]); break; case "Date": urlPairs.push(prefix + "[" + i + "]=" + encodeURIComponent(obj[i].toJSON())); break; case "Object": urlPairs = urlPairs.concat(getUrlPairs(obj[i], prefix + "[" + i + "]" + ".")); break; case "Array": urlPairs = urlPairs.concat(getUrlPairs(obj[i], prefix + "[" + i + "]")); break; default: break; } } } else { throw "support only arrays and objects"; } return urlPairs; } </code></pre> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = { dirty: "&amp;%[]?", nullable: null, numberProp: 123, now: new Date(), boolProp: true, obj: { objProp1: "objStr", objProp2: false, nullable: null, objInObj: { aa:"aa", bb: true } }, arr: [{ arrProp11: "str", arrProp12: 321, arrProp13: true, arrProp14: { a: "absdefg", b: true } }, { arrProp21: "rts", arrProp22: 987, arrProp23: false }, ["arrInArr1", "arrInArr2"], [{test:"str"}], null, new Date() ] }, getTypeOf = function(obj) { if (typeof obj == "undefined") { return "undefined"; } if (obj === null) { return "null"; } return Object.getPrototypeOf(obj).constructor.name; }, getUrlPairs = function(obj, prefix = "") { var urlPairs = [], objType = getTypeOf(obj), propType; if (objType === "Object") { for (var propName in obj) { if (obj.hasOwnProperty(propName)) { propType = getTypeOf(obj[propName]); switch (propType) { case "String": urlPairs.push(prefix + propName + "=" + encodeURIComponent(obj[propName])); break; case "Number": case "Boolean": case "null": urlPairs.push(prefix + propName + "=" + obj[propName]); break; case "Date": urlPairs.push(prefix + propName + "=" + encodeURIComponent(obj[propName].toJSON())); break; case "Object": urlPairs = urlPairs.concat(getUrlPairs(obj[propName], prefix + propName + ".")); break; case "Array": urlPairs = urlPairs.concat(getUrlPairs(obj[propName], prefix + propName)); break; default: break; } } } } else if (objType === "Array") { for (var i = 0; i &lt; obj.length; i++) { propType = getTypeOf(obj[i]); switch (propType) { case "String": urlPairs.push(prefix + "["+i+"]" + "=" + encodeURIComponent(obj[i])); break; case "Number": case "Boolean": case "null": urlPairs.push(prefix + "["+i+"]=" + obj[i]); break; case "Date": urlPairs.push(prefix + "["+i+"]=" + encodeURIComponent(obj[i].toJSON())); break; case "Object": urlPairs = urlPairs.concat(getUrlPairs(obj[i], prefix + "["+i+"]" + ".")); break; case "Array": urlPairs = urlPairs.concat(getUrlPairs(obj[i], prefix + "["+i+"]")); break; default: break; } } } else { throw "support only arrays and objects"; } return urlPairs; }; var res = getUrlPairs(obj); document.getElementById("output").innerHTML = res.join("\n") + "\n\n" + res.join("&amp;");</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body, textarea { margin: 0; overflow:hidden; } textarea { width: 100vw; height: 100vh; overflow:hidden; resize: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;textarea id="output"&gt;&lt;/textarea&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T09:42:31.453", "Id": "412206", "Score": "0", "body": "@chiril.sarajiu see `obj` in example above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:48:45.793", "Id": "412217", "Score": "0", "body": "I would look in to `JSON.stringify()`, this could be written in a few lines of code with the JSON object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:56:59.900", "Id": "412219", "Score": "1", "body": "@konijn JSON.stringify is not suitable, because need a format that the ASP.Net controller would \"understand\"." } ]
[ { "body": "<p>First, I would step away from the code and look for tools in the ecosystem that already deals with this or other viable approaches. You could:</p>\n\n<ul>\n<li>Just send JSON either by <code>GET</code> queries or <code>POST</code> request bodies. Surely ASP.NET has libraries to deserialize JSON into native objects.</li>\n<li>Spring (Java) is able to map query parameters and request bodies into Java objects (<code>@RequestBody</code>, <code>@RequestParam</code>, and friends). Check if ASP.NET has similar libraries or APIs that allow you to do this.</li>\n<li>If you really have no choice but to use <code>GET</code> params, check out <a href=\"https://api.jquery.com/jquery.param/\" rel=\"nofollow noreferrer\"><code>jQuery.param()</code></a>. Not sure if it's the format ASP.NET uses, but works great in PHP.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T17:40:59.973", "Id": "213109", "ParentId": "213083", "Score": "1" } }, { "body": "<h2>General points</h2>\n\n<h3>Not cyclic safe</h3>\n\n<p>The function is recursive so you have the danger of encountering cyclic references. If you are sure that they will not happen then you should be OK just don't call this function from another recursive function as the call stack is not infinite.</p>\n\n<h3>Avoid throwing</h3>\n\n<p>You are throwing an error at entry yet ignore the very same as you recurse. Why is the error not handled before you call the function. Having the error there means you need to wrap the call in a try catch. Are you unsure of the object you are passing, Where is it coming from and why would it not be as expected? Surely if its not as expected you would expect an empty array returned, rather than having to deal with an error.</p>\n\n<p>If you must throw dont throw strings. See points below.</p>\n\n<h3>Be efficient</h3>\n\n<p>It cost money to run code so always be efficient</p>\n\n<p>It is more efficient to close over a recursive function with objects that are shared. You create an new array <code>urlPairs</code> each time you recure. Then on returning you create yet another array when you concat the result. You can eliminate that overhead using closure.</p>\n\n<p>Each time you you recurse you call <code>getTypeOf</code> on the object you pass. But you already know the type or you would not be recursing. Pass the object type when known, it will make things a little simpler.</p>\n\n<h2>Your code</h2>\n\n<p>Every line of code counts as a locations for a bug. Reducing the number of lines of codes is the best way to reduce the number of bugs.</p>\n\n<ul>\n<li>Use function declarations <code>function name() {...</code> or arrow function <code>const name = () =&gt; {...</code> in favour over function expressions <code>var name = function(){...</code>. If you do use an expression then use a constant.</li>\n<li>Use <code>for of</code> rather than <code>for in</code></li>\n<li>Using <code>for of</code> and <code>Object.entries</code> will get you the property name and value. <code>for(const [name, value] of Object.entries(obj)) {</code>\n.</li>\n<li><p>NEVER throw strings. Always throw error like object and have a preference for already defined error types. eg <code>...} else { throw new RangeError(\"support only arrays and objects\") ...</code></p></li>\n<li><p>Use <code>===</code> and <code>!==</code> rather than <code>==</code> and <code>!=</code></p></li>\n<li><p>Reduce noise by keeping it as simple as possible. </p>\n\n<ul>\n<li>The line <code>if (typeof obj == \"undefined\") { return \"undefined\"; }</code> can be simplified to <code>if (ob === undefined) { return \"undefined\" }</code>. </li>\n<li>On the same point you return the string <code>\"undefined\"</code> yet never test for it, it could be almost any value. So you can just as well return <code>undefined</code> as follows <code>if (ob === undefined) { return }</code></li>\n<li><code>return Object.getPrototypeOf(obj).constructor.name;</code> can be <code>return obj.constructor.name</code>. </li>\n<li><code>Array.concat(array)</code> is slow and a memory and GC thrasher. Use <code>Array.push(...array)</code> Thus <code>urlPairs = urlPairs.concat(getUrlPairs(obj[propName], prefix + propName)),</code> becomes <code>urlPairs.push(...getUrlPairs(obj[propName], prefix + propName)),</code>,</li>\n<li>You add <code>prefix</code> to index 10 times, code should never have the same operation repeated within one function so many times.</li>\n<li>If you don't do anything in the default clause of a switch then don't add it, it's just needless noise.</li>\n</ul></li>\n<li><p>You have repeated the same code for <code>\"Objects\"</code> and <code>\"Array\"</code> items, the only difference is that the array index is wrapped in <code>[]</code> and the object key is not. You can create a function to wrap the key depending on the object type.</p></li>\n<li>You can use bracket notation to replace long switch case lists. (See example)</li>\n</ul>\n\n<h2>Example</h2>\n\n<p>The example ignores the throw and iterate recursively via an internal function. If the start object is not the correct type it just returns an empty array.</p>\n\n<p>The different object types are handle via an object containing named calls <code>typeFunc</code>. Eg <code>typeFunc.Date</code> will handle Date type objects.</p>\n\n<p>The iteration start via <code>typeFunc.Object</code> or <code>typeFunc.Array</code> These functions also pass on how to deal with the object path via <code>iterate</code> function <code>wrap</code> argument.</p>\n\n<p>Everything is pushed onto the one <code>pairs</code> array that is return when complete.</p>\n\n<p>The function IS NOT cyclic safe.</p>\n\n<pre><code>function getUrlPairs(obj) {\n const getType = obj =&gt; obj === undefined ? \"\" : (obj === null ? \"null\" : obj.constructor.name);\n const encode = str =&gt; encodeURIComponent(str);\n const simple = (path, val) =&gt; path + \"=\" + encode(val);\n const typeFunc = {\n Number: simple, Boolean: simple, null: simple, String: simple,\n Date: (path, val) =&gt; path + \"=\" + encode(val.toJSON()),\n Object: (path, val, dot = \".\") =&gt; iterate(val, path + dot, name =&gt; name),\n Array: (path, val) =&gt; iterate(val, path, name =&gt; `[${name}]`),\n }\n const pairs = [], type = getType(obj);\n function iterate (obj, prefix, wrap) {\n for (const [name, val] of Object.entries(obj)) {\n const call = typeFunc[getType(val)];\n call &amp;&amp; pairs.push(call(prefix + wrap(name), val));\n }\n }\n typeFunc[type] &amp;&amp; typeFunc[type](\"\", obj, \"\");\n return pairs;\n}\n</code></pre>\n\n<h3>Running example</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getUrlPairs(obj) {\n const getType = obj =&gt; obj === undefined ? \"\" : (obj === null ? \"null\" : obj.constructor.name);\n const encode = str =&gt; encodeURIComponent(str);\n const simple = (path, val) =&gt; path + \"=\" + encode(val);\n const typeFunc = {\n Number: simple, Boolean: simple, null: simple, String: simple,\n Date: (path, val) =&gt; path + \"=\" + encode(val.toJSON()),\n Object: (path, val, dot = \".\") =&gt; iterate(val, path + dot, name =&gt; name),\n Array: (path, val) =&gt; iterate(val, path, name =&gt; `[${name}]`),\n }\n const pairs = [], type = getType(obj);\n function iterate (obj, prefix, wrap) {\n for (const [name, val] of Object.entries(obj)) {\n const call = typeFunc[getType(val)];\n call &amp;&amp; pairs.push(call(prefix + wrap(name), val));\n }\n }\n typeFunc[type] &amp;&amp; typeFunc[type](\"\", obj, \"\");\n return pairs;\n}\n\n\ngetUrlPairs({\n dirty: \"&amp;%[]?\",\n nullable: null,\n numberProp: 123,\n now: new Date(),\n boolProp: true,\n obj: {\n objProp1: \"objStr\",\n objProp2: false,\n nullable: null,\n objInObj: {\n aa:\"aa\",\n bb: true\n }\n },\n arr: [{\n arrProp11: \"str\",\n arrProp12: 321,\n arrProp13: true,\n arrProp14: {\n a: \"absdefg\",\n b: true\n }\n },\n {\n arrProp21: \"rts\",\n arrProp22: 987,\n arrProp23: false\n },\n [\"arrInArr1\", \"arrInArr2\"],\n [{test:\"str\"}],\n null,\n new Date()\n ]\n}).forEach(str =&gt; \n show.appendChild(Object.assign(document.createElement(\"div\"),{textContent: str}))\n)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;code id=\"show\"&gt;&lt;/code&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T08:52:06.790", "Id": "412720", "Score": "0", "body": "It is necessary to fix the line `call && pairs.push(call(prefix + wrap(name), val));` in iterate function, since there is no check for undefined. Otherwise, the resulting array will contain undefined elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T10:38:09.850", "Id": "412727", "Score": "0", "body": "@XelaNimed There is no function for \"undefined\" (empty \"\" string returned by `getType` for var that is undefined) in `typeFunc` so how can you get undefined items? The type must be defined by name in the obj `typeFunc` to make it into the result." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T04:42:23.943", "Id": "213127", "ParentId": "213083", "Score": "1" } } ]
{ "AcceptedAnswerId": "213127", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T09:33:49.697", "Id": "213083", "Score": "0", "Tags": [ "javascript", "asp.net", "url" ], "Title": "The function to convert an object to a URL string" }
213083
<p>We all face questions that forget to include their code. Sometimes all of it, sometimes only parts, that make the rest of the question unfortunately incomplete and therefore off-topic.</p> <p>What if it was possible to remedy that behavior with a simple script? What if said script <strong>fits in a single comment</strong>, at least in a less featured variant?</p> <h1>Goals</h1> <p>A POSIX compatible script that prints all files in the current directory in the following format:</p> <pre><code>## File: &lt;path-to-file&gt; source code line 1 source code line 2 source code line 3 ... </code></pre> <p>Therefore, no bashism (like variable arrays), GNU extensions to <code>find</code> or similar.</p> <p>The script must only depend on POSIX variants of <code>sh</code>, <code>find</code> and <code>sed</code>. <a href="https://www.shellcheck.net/" rel="nofollow noreferrer">Shellcheck</a> must pass without errors or warnings.</p> <p>By default, it should print only C/C++ related files and skip the <code>.git</code> and <code>build</code> folders that are often found in those projects. Both options should be configurable via environment variables.</p> <h1>The complete script</h1> <pre><code>#!/bin/sh FILE_HEADING="## File: %s\n\n" IGNORED_DIRS="${IGNORED_DIRS:-build .git}" EXTENSIONS="${EXTENSIONS:-c cc cpp h hpp}" PRUNE_RULES="" for dir in ${IGNORED_DIRS}; do PRUNE_RULES="${PRUNE_RULES} -name ${dir} -prune" done RULE_GLUE="" if [ -n "${PRUNE_RULES}" ]; then RULE_GLUE="-o" fi NAME_RULES="" for ext in ${EXTENSIONS}; do if [ -z "${NAME_RULES}" ]; then NAME_RULES="-name '*.${ext}'" else NAME_RULES="${NAME_RULES} -o -name '*.${ext}'" fi done if [ -n "${NAME_RULES}" ]; then NAME_RULES="\\( ${NAME_RULES} \\)" fi sh &lt;&lt; EOF find . ${PRUNE_RULES} ${RULE_GLUE} ${NAME_RULES} \ -exec sh -c "printf '${FILE_HEADING}' {} &amp;&amp; sed 's/^/ /' {}" \\; EOF </code></pre> <p>Usage:</p> <pre><code>cd repository EXTENSIONS=rb IGNORED_DIRS="gem .git" path/to/script.sh </code></pre> <p>The second <code>sh</code> call is necessary as <code>find</code> doesn't work with multiple-options in a single argument. Every option for <code>find</code> needs to be in its own argument (e.g. <code>find . '-name' '*'</code> is fine, <code>find . '-name *'</code> is not).</p> <h1>Wait, I was promised a command that fits in a single comment!</h1> <p>For a comment, we can make some adjustements. First of all, we don't need to <code>prune</code>, as <code>.git</code> folders don't contain source code (not counting hooks). However multiple spaces in comments will get replaced by a single one, even in code, so you have to use a tabulator instead:</p> <pre><code>find . -name '*.hs' -exec sh -c 'printf "## File: %s\n\n" {} &amp;&amp; sed "s/^/\t/" {}' \; </code></pre> <p>You should adjust the file type to the users question, of course. If you're sure that they have GNU <code>find</code> installed, it gets a little bit easier:</p> <pre><code>find . -o -name '*.rb' -printf "## File: %P\n\n" -exec sed "s/^/\t/" {} \; </code></pre> <p>That being said, for some languages like Rust or JavaScript, you <strong>really</strong> should ignore their additional directories, or at least tell the user to check their post.</p> <p>Those two variants are also eligible for review, although the latter doesn't follow the POSIX and the settings goals anymore</p>
[]
[ { "body": "<p>An alternative to defaulting variables by self-assigning with fallback is to use <code>${parameter:=word}</code> at the point of first use:</p>\n<pre><code>for dir in ${IGNORED_DIRS:=build .git}; do\n</code></pre>\n\n<pre><code>for ext in ${EXTENSIONS:=c cc cpp h hpp}; do\n</code></pre>\n<p>Actually, since those are the only uses, we could get away with <code>:-</code> expansion, even there.</p>\n<p>Also, it makes sense to allow user to specify <em>no</em> ignored dirs and/or no extensions (and we check for that later in the code), so perhaps remove the <code>:</code> from those expansions.</p>\n<hr />\n<p><code>RULE_GLUE</code> can also be simplified:</p>\n<pre><code>RULE_GLUE=${PRUNE_RULES:+-o}\n</code></pre>\n<p>Again, it's not necessary to name this, but it might aid clarity. Personally, I'd just add it directly to the end of the <code>PRUNE_RULES</code>:</p>\n<pre><code>PRUNE_RULES=&quot;${PRUNE_RULES} ${PRUNE_RULES:+-o}\n</code></pre>\n<p>or just ensure that each prune rule contains its own <code>-o</code> as it should:</p>\n<pre><code>for dir in ${IGNORED_DIRS}; do\n PRUNE_RULES=&quot;${PRUNE_RULES} -name ${dir} -prune -o&quot; \ndone\n</code></pre>\n<hr />\n<p>The name rules can be simplified by starting with with the <code>-false</code> predicate (did you ever wonder what it's useful for?):</p>\n<pre><code>NAME_RULES=${EXTENSIONS:+-false}\nfor ext in ${EXTENSIONS}; do\n NAME_RULES=&quot;${NAME_RULES} -o -name '*.${ext}'&quot;\ndone\n</code></pre>\n<hr />\n<p>It's unspecified whether <code>find</code> expands <code>{}</code> when it's a substring of an argument; the safer POSIX way is to pass it as a positional argument and have the child shell expand it:</p>\n<pre><code> -exec sh -c &quot;printf '${FILE_HEADING}' \\&quot;<span class=\"math-container\">\\$1\\\" &amp;&amp; sed 's/^/ /' \\$</span>1&quot; -- {} ';'\n</code></pre>\n<p>It's probably a good idea to only match plain files (including symlinks to plain files), rather than everything that matches the name rules. Especially if <code>$NAME_RULES</code> is empty, it's quite possible for a directory name to match.</p>\n<p>I don't see why we need the explicit <code>sh</code> subshell as the final command (since we expand the &quot;rules&quot; predicates unquoted, so word splitting happens - though we'll need to disable globbing: <code>set -f</code>). There's no good reason not to <code>exec</code> the final command.</p>\n<p>Also, we need to be careful if <code>$FILE_HEADING</code> ever contains <code>'</code>: it might be safer to also pass this as a positional parameter, or to export the variable and have it expanded later:</p>\n<pre><code>export FILE_HEADING\n</code></pre>\n\n<pre><code>exec find . ${PRUNE_RULES} ${NAME_RULES} -type f\n -exec sh -c 'printf &quot;${FILE_HEADING}&quot; &quot;$1&quot; &amp;&amp; sed &quot;s/^/ /&quot; &quot;$1&quot;' -- {} ';'\n</code></pre>\n<p>I think that rather than <code>-exec sh</code>, it might be simpler to have two <code>-exec</code> predicates:</p>\n<pre><code>... -exec printf &quot;${FILE_HEADING}&quot; {} \\; -exec sed 's/^/ /' {} \\;\n</code></pre>\n<p>(and we no longer need to export <code>$FILE_HEADING</code>).</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#!/bin/sh\n\n# user-modifiable parameters\nFILE_HEADING='## File: %s\\n\\n'\nDEFAULT_IGNORED_DIRS='build .git'\nDEFAULT_EXTENSIONS='c cc cpp h hpp'\n\n# end of user variables; code starts here\n\nset -eu # Usual safety\nset -f # Don't expand pathnames when expanding $NAME_RULES below\n\nfor dir in ${IGNORED_DIRS-$DEFAULT_IGNORED_DIRS}; do\n PRUNE_RULES=&quot;${PRUNE_RULES-} -name ${dir} -prune -o&quot; \ndone\n\nfor ext in ${EXTENSIONS-$DEFAULT_EXTENSIONS}; do\n NAME_RULES=&quot;${NAME_RULES:--false} -o -name *.${ext}&quot;\ndone\n\n# We intend word splitting of rules variables\n# shellcheck disable=SC2086\nexec find -L . ${PRUNE_RULES-} ${NAME_RULES:+'(' $NAME_RULES ')'} -type f \\\n -exec printf &quot;${FILE_HEADING}&quot; {} \\; \\\n -exec sed 's/^/ /' {} \\;\n</code></pre>\n<hr />\n<h1>Modified one-liner</h1>\n<pre><code>find . -name \\*.sh -exec printf '## File: %s\\n\\n' {} \\; -exec sed 's/^/ /' {} \\;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:05:17.947", "Id": "412221", "Score": "0", "body": "Thanks for the review. Ad default expansion: I'm aware of that one, but it makes it harder for users to change their defaults. For example, if I'm a Ruby developer, I'd change the `EXTENSIONS` to `rb`. Having all variables at the top makes it easier to set them, rather than go on a hunt for default expansions, IMHO. That being said I'm not able to get any output with your (complete) variant, which was the reason I used `sh << EOF`. Do you have a full script at hand ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:56:30.297", "Id": "412233", "Score": "0", "body": "Okay, I've tried out my suggestions, and debugged them. See what you think of the replacement code. I'm reasonably certain it's fully POSIX (I referenced [`sh`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html) and [`find`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/find.html) specifications), and I only needed one Shellcheck suppression (oh, how I miss Bash array variables!)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:57:58.540", "Id": "213088", "ParentId": "213084", "Score": "1" } } ]
{ "AcceptedAnswerId": "213088", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:01:41.597", "Id": "213084", "Score": "3", "Tags": [ "formatting", "stackexchange", "sh", "posix", "markdown" ], "Title": "Easy to use code preparation script for CodeReview questions" }
213084
<p>I'm using JDK 11.</p> <p>This is my code:</p> <pre><code>public class ReferenceService { private final transient Cache&lt;String, Reference&gt; cache; private final transient EntityManager entityManager; public ReferenceService( Cache&lt;String,Reference&gt; cache, EntityManager entityManager ) { this.cache = cache; this.entityManager = entityManager; } public Optional&lt;Reference&gt; get(String id) { return Optional.ofNullable(this.cache.get(id)) .or(() -&gt; Optional.ofNullable(this.entityManager.find(Reference.class, id))); } } </code></pre> <p>I would like to know to write this code again in order to it's more elegant:</p> <pre><code>return Optional.ofNullable(this.cache.get(id)) .or(() -&gt; Optional.ofNullable(this.entityManager.find(Reference.class, id))); </code></pre> <p>I guess I'm using too much <code>Optional.ofNullable</code> each time I need to get a reference from cache or from persistence layer.</p> <p><strong>ADITIONAL CODE</strong></p> <pre><code>private &lt;T&gt; Cache&lt;String, T&gt; getOrCreateCache(String name, Class&lt;T&gt; type) { Cache&lt;String, T&gt; cache = cacheManager.getCache(name, String.class, type); if (cache == null) { CompleteConfiguration&lt;String, T&gt; config = new MutableConfiguration&lt;String, T&gt;() .setTypes(String.class, type); cache = cacheManager.createCache(name, config); } return cache; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T17:28:15.543", "Id": "412273", "Score": "0", "body": "I've updated my answer now. I hope that answers your questions" } ]
[ { "body": "<h3>Design Fix</h3>\n\n<p>The correct solution to this is to make your <strong>cache</strong> responsible for retrieving the entity on cache-miss.</p>\n\n<p>Consider for a moment the goals of a cache:</p>\n\n<ul>\n<li>Keep expensive to calculate / retrieve information in a manner suitable to quick access</li>\n<li>Abstract away cache handling (invalidation, cache-misses, ...) from consumers</li>\n<li>Give certain guarantees for the consistency of cached information</li>\n</ul>\n\n<p>As it stands the way this code is setting up and using the cache utterly fails on the second point. Luckily <code>javax.caching.Cache</code> does support loading entries into the cache on misses using a <code>CacheLoader</code>.</p>\n\n<p>For this to happen you need to create a CacheLoader that is aware of the EntityManager used to access the entities:</p>\n\n<pre><code>[..] config = new MutableConfiguration&lt;String, T&gt;()\n .setTypes(String.class, type)\n .setReadThrough(true) // enables silent loading\n .setCacheLoaderFactory(new FactoryBuilder.SingletonFactory(\n new CacheLoader&lt;String, T&gt;() {\n @Override\n public T load(String key) {\n return entityManager.find(type, key);\n }\n @Override\n public Map&lt;String, T&gt; loadAll(Iterable&lt;? extends String&gt; keys) {\n return Stream.of(keys)\n .collect(Collectors.toMap(Function.identity(), this::load));\n }\n });\n</code></pre>\n\n<p>You should notice at this point that you're locking yourself into caching on a single primary key (namely <code>String</code>). This is something that might bite you in the backside down the road, but if you only use Strings as primary keys for entities that should be alright.</p>\n\n<p>n.b. that I haven't even checked whether this code compiles.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T09:53:43.787", "Id": "412455", "Score": "0", "body": "Could I ask you for giving some lights me about why it's a better practice a `ClassLoader` is aware of handling the `entityManager` or whatever data-access layer?\nI mean, my straightforward first approach was to try to get the entity from cache, and at the same method on service layer, try to get it using the entity manager.\nI guess, it's better to use a `ClassLoader` approach instead of, but I don't quite figure out how come." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T13:15:02.343", "Id": "412478", "Score": "0", "body": "Not `ClassLoader`, `CacheLoader`. It's better practice, because it makes sure the Cache is filled correctly. It also allows you to build on the abstraction that a Cache exposes to you. That way your code doesn't need to care about the peculiarities of the cache mechanic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T14:33:46.237", "Id": "412479", "Score": "0", "body": "I'm struggling with an issue related with this behavior. Guess on a `create(dto)`, shere `dto` has no an `id` field. So, when I call the `cache.putIfAbsent(key??, dto)`, with `key` hould I use if it's not resolved until it's written on db. I hope I've explained so well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T15:06:24.227", "Id": "412487", "Score": "0", "body": "Creating an entry in you database should not affect the cache in any way. That's not the job of the cache. The cache is a tool to avoid roundtripping to the database on repeated reads. A write to the database is usually only reflected in the cache upon a subsequent read request. For that request, you will need to have the key in the first place. So the question as I understood it shouldn't pose itself" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T15:29:50.157", "Id": "412491", "Score": "0", "body": "Could take a look on [this question](https://stackoverflow.com/questions/54633892/jcache-write-through-without-key)?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T11:14:07.253", "Id": "213090", "ParentId": "213086", "Score": "2" } } ]
{ "AcceptedAnswerId": "213090", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T10:49:40.140", "Id": "213086", "Score": "3", "Tags": [ "java", "cache", "optional" ], "Title": "Reference service for a cache" }
213086
<p>I'm currently attending ERAU (online), and in my Computing for Engineers class we are learning C#. An ongoing project throughout the class is to build a "quiz" program that asks 10 questions, in order, and then repeats missed questions (in order) on a second iteration. There are 2 types: T/F and multiple choice. 4 T/F and 6 mc; the mc questions can have 4 possible answers. The program must keep track of the number of each type of question that was answered correctly and display that at the end.</p> <p>I'm just learning about loops, conditional statements, arrays and methods (last week), and here's the code I came up with (it compiles and runs, and does exactly what I want it to do, but my instructor said it is too long and not optimized):</p> <pre><code>using System; using System.Threading; namespace Quiz { class Program { static void Main(string[] args) { //start the quiz by telling the student the details of the structure of the quiz and the subject being tested Console.WriteLine("Kenneth Myers, ENGR115, Assignment: Checkpoint 4 &amp; 5"); Console.WriteLine("You are about to take a 10 question quiz on Binary Number Systems."); Console.WriteLine("Each question will be displayed with either a True/False or Multiple-choice answer key. Select the correct answer by pressing the corresponding key."); Console.WriteLine("If you get the question wrong, you will be notified of the wrong answer and the next question will be displayed."); Console.WriteLine("Once all questions have been displayed once, questions answered incorrectly will be displayed in the original order; you may attempt the question again."); Console.WriteLine("After all missed questions have been displayed a second time and answered, the results of your quiz will be displayed, by category of question and number answered correctly, and the total number answered correctly."); Thread.Sleep(5000);//adds a 5 second delay before the next operation to give the user time to read the instructions Console.Clear(); //clears the screen before starting the test //create an array with all the questions and possible answers to display to the user var questions = new string[] { "Question 1: True or False – Binary numbers consist of a sequence of ones and zeros? Press T or F and enter to submit", "Question 2: Multiple choice – Add the following binary numbers: 1011+0011. Answers: 1) 1110, 2) 1022, 3) 1010, 4) 1032. Select the number (1,2,3 or 4) of the correct answer and enter to submit", "Question 3: Multiple choice – Add the following binary numbers: 11011011+01100110. Answers: 1) 11000001, 2) 11111111, 3) 12111121, 4) 101000001. Select the number (1,2,3 or 4) of the correct answer and enter to submit", "Question 4: True or False – Binary numbers are base-10? Press T or F and enter to submit", "Question 5: Multiple choice – Subtract the following binary numbers: 1110-0101. Answers: 1) 1010, 2) 1001, 3) 1000, 4) 0100. Select the number (1,2,3 or 4) of the correct answer and enter to submit", "Question 6: Multiple choice – Subtract the following binary numbers: 10010011-01101100. Answers: 1) 01101111, 2) 00010111, 3) 00100111, 4) 11011101. Select the number (1,2,3 or 4) of the correct answer and enter to submit", "Question 7: True or False – Binary numbers are base-2? Press T or F and enter to submit", "Question 8: Multiple choice – the binary number 1011 equates to what base-10 number? Answers: 1) 11, 2) 22, 3) 14, 4) 7. Select the number (1,2,3 or 4) of the correct answer and enter to submit", "Question 9: Multiple choice – what is the binary equivalent of the base-10 number 127? Answers: 1) 01101111, 2) 11111111, 3) 10111011, 4) 11111110. Select the number (1,2,3 or 4) of the correct answer and enter to submit", "Question 10: True or False: an 8-bit binary number can have a maximum value of 128 in base-10? Press T or F and enter to submit" }; var questionAnswer = new string[] { "t", "1", "4", "f", "2", "3", "t", "1", "2", "f" };//creating array of correct answers var questionInput = new string[10];//create the input variables for each question to accept user input in an array var questionStatus = new string[] { "n", "n", "n", "n", "n", "n", "n", "n", "n", "n" };//create question status array to track if the question was answered correctly the first time var questionType = new string[] { "tf", "mc", "mc", "tf", "mc", "mc", "tf", "mc", "mc", "tf" };//define the question types (tf or mc) in an array var questionIteration = 0;//set the question iteration globally var questionCount = 0;//set the question count globally var trueFalseCount = 0; var multipleChoiceCount = 0; //sets the true/false counter and multiple choice counters to zero //start the quiz - display each question, in order starting at question 1, and accept the user input for that question, then display the user input and move to the next question Console.Clear();//clear the screen for (questionIteration = 1; questionIteration &lt; 3; questionIteration++)//set up a for loop to run 2 iterations of the questions { questionCount = 0; if (questionIteration == 2) { Console.WriteLine("Second attempt. Previously incorrectly answered questions will be displayed again. Good luck!"); } foreach (string question in questions)//foreach loop to handle each question and the answer input by the user, plus logic to test for invalid and correct/incorrect answers { if (questionStatus[questionCount] == "n")//first attempt at the question { Console.WriteLine(question); //displays the question, starting with question 1 if (questionType[questionCount] == "tf")//logic for true/false questions { questionInput[questionCount] = InvalidTrueFalseEntry(); //accepts user input for answer to question and stores in variable; later, passes input to method to test if valid input type questionInput[questionCount] = CheckForCorrectAnswer();//checks for correct answer } else if (questionType[questionCount] == "mc")//logic for multiple choice questions { questionInput[questionCount] = InvalidMultipleChoiceEntry(); //accepts user input for answer to question and stores in variable; later, passes input to method to test if valid input type questionInput[questionCount] = CheckForCorrectAnswer();//checks for correct answer } Console.Clear();//clear the screen } //else if (questionStatus[questionCount] == "y") //{ //Console.WriteLine("Second attempt!");//tell the user it's their second attempt //} questionCount++;//increment the question counter for the next iteration } } Console.WriteLine("Test Complete!");//tells user the test is over Console.WriteLine("You answered " + trueFalseCount + " T/F questions correctly and " + multipleChoiceCount + " multiple choice questions correctly.");//tells user their performance Console.WriteLine("You missed " + (4 - trueFalseCount) + " T/F questions and " + (6 - multipleChoiceCount) + " multiple choice questions."); Thread.Sleep(5000); Console.Clear();//clear the screen string InvalidMultipleChoiceEntry()//this method will check multiple choice answers to ensure they are a number 1-4 { var answer = Console.ReadLine(); if (answer != "1" &amp;&amp; answer != "2" &amp;&amp; answer != "3" &amp;&amp; answer != "4")//did the user input a numner between 1 and 4? { Console.WriteLine("Invalid answer type (not 1-4), try again.");//if not, try again until they do! return InvalidMultipleChoiceEntry(); } return answer; } string InvalidTrueFalseEntry()//this method will check true/false answers to ensure input was a "t" or an "f" { var answer = Console.ReadLine();//get the user input if (answer != "t" &amp;&amp; answer != "f")//did the user input a t or f? { Console.WriteLine("Invalid answer type (not t or f), try again.");//if not, try again until they do! return InvalidTrueFalseEntry(); } return answer; } string CheckForCorrectAnswer()//this method will check the answer to see if it is correct or not, if the entry was valid for the questionType { var answer = questionInput[questionCount]; if (answer != questionAnswer[questionCount])//tests for incorrect answer given from a valid input by question type { Console.WriteLine("Your answer was: " + questionInput[questionCount]); //displays the answer chosen by the user Console.WriteLine("Sorry, wrong answer. :-("); Thread.Sleep(2000); questionStatus[questionCount] = "n";//make sure the question status reflects "n" return answer; } else //it must be correct, since we've checked against invalid and incorrect answers! { Console.WriteLine("Your answer was: " + questionInput[questionCount]); //displays the answer chosen by the user Console.WriteLine("Correct answer!"); questionStatus[questionCount] = "y"; if (questionType[questionCount] == "tf") { trueFalseCount++;//increment the true/false counter to total the number answered correctly } else { multipleChoiceCount++;//increment the multiple choice counter to total the number answered correctly } Thread.Sleep(2000); return answer; } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T15:14:57.887", "Id": "412260", "Score": "0", "body": "Welcome to Code Review! Have they taught you how to write your own functions yet? How much do you know about passing arguments? You say you're learning OOP, but I don't see much of it in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T17:43:57.267", "Id": "412276", "Score": "0", "body": "I'm sorry, let me clarify: this week we are starting the chapter on OOP. We have not implemented anything in our code yet, but we are learning about the 4 fundamentals of OOP and creating and using objects. As for functions, I don't recall learning functions, unless you mean methods, which according to my textbook are called \"functions\" in other programming languages. I assume that is what you mean, and yes, we went over methods last week. I'm still struggling with methods right now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T17:49:45.727", "Id": "412279", "Score": "0", "body": "C# still has functions, but methods are special in that they are functions belonging to a class/object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T19:46:09.373", "Id": "412422", "Score": "0", "body": "I've re-written the code I had posted originally, and it is more efficient and works as I intended, but now I need to do this using OOP principles; meaning, separate objects (classes?). This is where I need some help. If I create a class, for example, for the questions (class Questions), would it make sense to define within that class the following: list of questions, whether they have been asked already, and if they have been answered correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T09:51:01.713", "Id": "412454", "Score": "1", "body": "Learning path: I'd not create a class for the list of questionS but a class for a single `Question` (with question, answer and type). Then redo this using a single array of them. Then remove the _type_ field (which should not be a string but an enum) and use derived classes (if you learned about them). Then abstract input logic away into a separate function. Side note: remove those `Thread.Sleep()`...just leave the text on the screen without `Clear()` as a favor for your _users_!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:11:29.233", "Id": "412659", "Score": "0", "body": "@ Roland, Thanks for your advice, example code, and explanations! This has helped me immensely; exactly what I needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:19:22.263", "Id": "412664", "Score": "0", "body": "@ Adriano - thanks for your reply. I implemented your suggestion about the thread.sleep and clear statements, thanks. I am going to attempt to use your other suggestions as I re-write this code yet again using a question class and separate logic function. I *think* I understand what you are suggesting (except for derived classes)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:24:09.693", "Id": "412665", "Score": "0", "body": "@ Roland - also, yes, I agree that the order of the questions should be random, but the professor stipulated the order must remain the same for the second iteration and only to display the missed questions for a second try. I'm sure there is a way to randomize the order AND still only show the missed questions, but that is above my ability right now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:53:06.523", "Id": "412674", "Score": "0", "body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T00:34:52.260", "Id": "412848", "Score": "0", "body": "@ Sam - thank you. I did not understand that this was an incorrect way to respond. I understand now, and will start a new question and link back to this one." } ]
[ { "body": "<p>The first thing I noticed about your code is that it is very compressed. There are almost no empty lines, and the lines are quite long.</p>\n\n<p>The longest line in your code is 1745 characters long. Assuming that a single character is 2 mm wide, I'd need a screen of 3.5 meters to show the whole line. I don't have such a screen.</p>\n\n<p>To understand that single line, I had to split it up into this block of code:</p>\n\n<pre><code>//create an array with all the questions and possible answers to display to the user\nvar questions = new[] {\n \"Question 1: True or False – Binary numbers consist of a sequence of ones and zeros? \"\n + \"Press T or F and enter to submit\",\n\n \"Question 2: Multiple choice – Add the following binary numbers: 1011+0011. \"\n + \"Answers: 1) 1110, 2) 1022, 3) 1010, 4) 1032. \"\n + \"Select the number (1,2,3 or 4) of the correct answer and enter to submit\",\n\n \"Question 3: Multiple choice – Add the following binary numbers: 11011011+01100110. \"\n + \"Answers: 1) 11000001, 2) 11111111, 3) 12111121, 4) 101000001. \"\n + \"Select the number (1,2,3 or 4) of the correct answer and enter to submit\",\n\n \"Question 4: True or False – Binary numbers are base-10? \"\n + \"Press T or F and enter to submit\",\n\n \"Question 5: Multiple choice – Subtract the following binary numbers: 1110-0101. \"\n + \"Answers: 1) 1010, 2) 1001, 3) 1000, 4) 0100. \"\n + \"Select the number (1,2,3 or 4) of the correct answer and enter to submit\",\n\n \"Question 6: Multiple choice – Subtract the following binary numbers: 10010011-01101100. \"\n + \"Answers: 1) 01101111, 2) 00010111, 3) 00100111, 4) 11011101. \"\n + \"Select the number (1,2,3 or 4) of the correct answer and enter to submit\",\n\n \"Question 7: True or False – Binary numbers are base-2? \"\n + \"Press T or F and enter to submit\",\n\n \"Question 8: Multiple choice – the binary number 1011 equates to what base-10 number? \"\n + \"Answers: 1) 11, 2) 22, 3) 14, 4) 7. \"\n + \"Select the number (1,2,3 or 4) of the correct answer and enter to submit\",\n\n \"Question 9: Multiple choice – what is the binary equivalent of the base-10 number 127? \"\n + \"Answers: 1) 01101111, 2) 11111111, 3) 10111011, 4) 11111110. \"\n + \"Select the number (1,2,3 or 4) of the correct answer and enter to submit\",\n\n \"Question 10: True or False: an 8-bit binary number can have a maximum value of 128 in base-10? \"\n + \"Press T or F and enter to submit\"\n};\n</code></pre>\n\n<p>I have no idea how you could ever edit all this text in a single line. Having it split into multiple lines has these benefits:</p>\n\n<ul>\n<li>readers of your code can see all the questions on one screen</li>\n<li>the strings are split at natural boundaries (using the <code>+</code> operator)</li>\n<li>redundant information becomes clearly visible\n\n<ul>\n<li>the question number is written explicitly into each question. This means that the questions cannot be shuffled. Any good quiz program must shuffle the questions as much as possible to avoid learning patterns like \"the first question is f\".</li>\n<li>each mc question has the same structure: <code>&lt;Question&gt; Answer: 1) &lt;A1&gt;, 2) &lt;A2&gt;, 3) &lt;A3&gt;, 4) &lt;A4&gt;</code>. This structure should not be encoded in a string but in the code of the program. That's something that will hopefully be covered later in class.</li>\n<li>each tf question ends with the \"Press T or F\" sentence</li>\n<li>each mc question ends with the \"Select\" sentence</li>\n</ul></li>\n</ul>\n\n<p>These redundancies do not occur in good programs. The redundant text should better be handled when printing the question, in code like this:</p>\n\n<pre><code>if (questionType[questionCount] == \"tf\") {\n Console.WriteLine(\"Press T or F and Enter to submit\");\n} else if (questionType[questionCount] == \"mc\") {\n Console.WriteLine(\"Select the number (1, 2, 3 or 4) of the correct answer and press Enter to submit\");\n}\n</code></pre>\n\n<p>This brings me directly to the next item, which is the variable <code>questionCount</code>. A <code>count</code> by convention means the total number of something. The count of questions in this program is 10, and this count doesn't change. Therefore the variable name is misleading. It should rather be named <code>questionIndex</code>. By convention, an <code>index</code> is typically between 0 and the corresponding <code>count</code>, which is exactly the case here.</p>\n\n<p>In the very first part of my answer I said that your code looks very compressed. This is because it doesn't contain empty lines in the usual places. Empty lines should mark all places where in traditional writing you would end a paragraph. One of these places is before a function is defined, such as <code>string InvalidMultipleChoiceEntry()</code>. Before each function definition there should be an empty line. The comment describing the function should be in an extra line before the function definition. Like this:</p>\n\n<pre><code>// This method will check multiple choice answers to ensure they are a number 1-4\nstring InvalidMultipleChoiceEntry() \n{\n var answer = Console.ReadLine();\n if (answer != \"1\" &amp;&amp; answer != \"2\" &amp;&amp; answer != \"3\" &amp;&amp; answer != \"4\") //did the user input a numner between 1 and 4?\n {\n Console.WriteLine(\"Invalid answer type (not 1-4), try again.\"); //if not, try again until they do!\n return InvalidMultipleChoiceEntry();\n }\n\n return answer;\n}\n</code></pre>\n\n<p>Calling <code>InvalidMultipleChoiceEntry</code> from inside <code>InvalidMultipleChoiceEntry</code> is a dangerous technique in most programming languages. It can lead to unexpected memory consumption. To test this, replace the call <code>Console.ReadLine();</code> with a simple <code>\"invalid\"</code> and run the program. It will run for some seconds and then crash with this error message:</p>\n\n<blockquote>\n <p>Process is terminating due to StackOverflowException.</p>\n</blockquote>\n\n<p>To avoid this error, rewrite the function like this:</p>\n\n<pre><code>string InvalidMultipleChoiceEntry()\n{\n while (true) {\n var answer = Console.ReadLine();\n if (answer == \"1\" || answer == \"2\" || answer == \"3\" || answer == \"4\") {\n return answer;\n }\n\n Console.WriteLine(\"Invalid answer type (not 1-4), try again.\");\n }\n}\n</code></pre>\n\n<p>When I ran the program for the first time, the 5 seconds you gave me to read the intro were way too short. Or maybe the intro was too long, who knows. If you remove the <code>Thread.Sleep(5000);</code> and replace the <code>Console.Clear</code> with <code>Console.WriteLine</code>, everything is fine.</p>\n\n<p>There's probably more to say, but on the other hand the above is already enough work for one or two hours.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:14:18.643", "Id": "412660", "Score": "0", "body": "@ Roland, Thanks for your advice, example code, and explanations! This has helped me immensely; exactly what I needed. I also re-wrote my code and implemented your suggestions, and also changed the other function for true false questions to be a while loop instead of an if loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T12:58:34.473", "Id": "213241", "ParentId": "213099", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T15:10:13.770", "Id": "213099", "Score": "4", "Tags": [ "c#", "beginner", "quiz" ], "Title": "Quiz program that asks 10 questions, repeats incorrectly answered ones a second time, gives results at end" }
213099
<h2>Problem Statement</h2> <p>Calculate the exact value of the n-th Fibonacci number, say the one-billionth. </p> <h2>Algorithm</h2> <p>The algorithm is based on the idea that <a href="https://medium.com/@andrew.chamberlain/the-linear-algebra-view-of-the-fibonacci-sequence-4e81f78935a3" rel="nofollow noreferrer">Fibonacci numbers can be represented as 2x2 matrices</a>, in particular as powers of the matrix <code>[ 1 1; 1 0]</code>. Matrices of this form can be represented <em>implicitly</em> without having to store all 4 elements as <code>[ a+b a; a b ]</code>. In particular, we only need to store <code>a</code> and <code>b</code> to represent the matrix. This not only saves memory but we can perform fewer operations when multiplying or squaring matrices if we work on the implicit form. </p> <p>The other aspect of the algorithm is <a href="https://en.wikipedia.org/wiki/Exponentiation_by_squaring" rel="nofollow noreferrer">exponentiation by squaring</a>, the idea that we can calculate <code>a^(2^n)</code> very quickly by starting with <code>a</code> and repeatedly squaring. To calculate the n-th Fibonacci number, we simply compute the n-th power of the basis matrix (using the implicit form) and read off the diagonal element <code>a</code>. </p> <h2>Build and Implementation Details</h2> <p>For performance we use the <a href="https://www.boost.org/doc/libs/1_57_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/gmp_int.html" rel="nofollow noreferrer">boost::multiprecision::mpz_int</a> wrapper around the <a href="https://gmplib.org/" rel="nofollow noreferrer">Gnu MP library</a>. The mpz_int type is a lightweight wrapper around GMP which gives it a C++-style interface with overloaded operators. The GMP is an "arbitrary precision arithmetic" library for doing math with numbers that don't fit into 64 bits. I installed these libraries on Debian/Ubuntu like so:</p> <pre><code>sudo apt install libboost-all-dev libgmp-dev </code></pre> <p>The following program was built like so:</p> <pre><code>g++ -std=c++17 -O3 -o fib main.cpp -lgmp </code></pre> <h2>Program</h2> <pre><code>#include &lt;iostream&gt; #include &lt;boost/multiprecision/gmp.hpp&gt; typedef boost::multiprecision::mpz_int bigint; namespace fib { class ImplicitMatrix { public: bigint a; bigint b; ImplicitMatrix(const ImplicitMatrix&amp; other) : a(other.a) , b(other.b) { } ImplicitMatrix( const bigint&amp; _a, const bigint&amp; _b) : a(_a) , b(_b) { } }; ImplicitMatrix multiply( const ImplicitMatrix&amp; x, const ImplicitMatrix&amp; y) { return { y.a * (x.a + x.b) + x.a * y.b, x.a * y.a + x.b * y.b }; } ImplicitMatrix square(const ImplicitMatrix&amp; x) { // we save one bigint multipication by // specializing for the case of squaring. bigint a2 = x.a * x.a; bigint _2ab = (x.a * x.b) &lt;&lt; 1; bigint b2 = x.b * x.b; return { a2 + _2ab, a2 + b2 }; } ImplicitMatrix power( const ImplicitMatrix&amp; x, const bigint&amp; m) { if (m == 0) { return { 0, 1 }; } else if (m == 1) { return x; } // powers of two by iterated squaring ImplicitMatrix powerOfTwo = x; bigint n = 2; while (n &lt;= m) { powerOfTwo = square(powerOfTwo); n = n * 2; } // recurse for remainder ImplicitMatrix remainder = power(x, m - n / 2); return multiply(powerOfTwo, remainder); } } // end namespace fib bigint fibonacci(const bigint&amp; n) { fib::ImplicitMatrix f1{ 1, 0 }; return fib::power(f1, n).a; } int main(int argc, const char* argv[]) { // require the first command line argument if (argc &lt; 2) { std::cerr &lt;&lt; "USAGE: fib N" &lt;&lt; std::endl; return 1; } // parse the first argument into a bigint bigint n(argv[1]); // force the calculation of the n-th fibonacci // number but do not print it. volatile bigint f = fibonacci(n); return 0; } </code></pre> <p>I am looking for style advice, modern C++ tips, performance suggestions, and best practices.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T22:58:35.247", "Id": "412307", "Score": "0", "body": "I don't see the point of defining your own class here, it's just a placeholder for two (public) member variables. I'd rather just typedef your ImplicitMatrix as say std::pair" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T15:28:02.887", "Id": "213101", "Score": "3", "Tags": [ "c++", "matrix", "c++17", "fibonacci-sequence", "boost" ], "Title": "Calculate huge Fibonacci Numbers in C++ using GMP and boost::multiprecision" }
213101
<p>You can find the "part 1" <a href="https://codereview.stackexchange.com/questions/213049/switch-case-pattern-for-non-constant-types">here</a>.</p> <hr> <h1>1. Objectives</h1> <p>The main goal of this post is to build a switch-like structure, which allows to use non-constant Type (e.g. <code>Type</code>, <code>Drawing.Point</code>, or any custom type). This implementation should understand three different cases:</p> <ul> <li>Equality case (like a regular case statement)</li> <li>'Predicate' case (like a <code>case n when n &lt; 0</code>)</li> <li>Default case (like a regular default statement)</li> </ul> <p>This custom <code>switch</code> must have the exact same <strong>outputs</strong> that a regular <code>switch</code>.</p> <h1>2. Usage</h1> <p>As <a href="https://codereview.stackexchange.com/users/31886/flater">@Flater</a> pointed it out <a href="https://codereview.stackexchange.com/a/213055/182398">here</a>, the switch should be created first, and should be able to evaluate multiple values. This is an example of what I want:</p> <pre><code>var mySwitch = Bar.Switch&lt;Response&gt;() .CaseWhen(r =&gt; r.Id &lt; 0, ErrorMethod) .Case(Response.OK, OkMethod) .Case(Response.Warning, WarningMethod) .Case(null, NullMethod) .Default(DefaultMethod); var response = Client.Post(content); mySwitch.EvaluateFor(response); </code></pre> <h1>3. Implementation</h1> <p><a href="https://i.stack.imgur.com/wo267.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wo267.png" alt="Classes diagram"></a></p> <h2>3.a. Public interfaces</h2> <pre><code>/// &lt;summary&gt; /// Simulates an evaluable-only switch /// &lt;/summary&gt; public interface IEvaluable&lt;T&gt; { /// &lt;summary&gt; /// Executes the switch with the given value, and executes the first case that matches this value, if any /// &lt;/summary&gt; /// &lt;param name="value"&gt;Value used to execute the switch&lt;/param&gt; void EvaluateFor(T value); } </code></pre> <hr> <pre><code>/// &lt;summary&gt; /// Simulates a switch instruction /// &lt;/summary&gt; public interface ISwitch&lt;T&gt; : IEvaluable&lt;T&gt; { /// &lt;summary&gt; /// Add a case to the switch (at the end), and return the aforesaid switch /// &lt;/summary&gt; /// &lt;param name="query"&gt;Value that will be tested for equality, using default EqualityComparer&lt;/param&gt; /// &lt;param name="action"&gt;Action to perform if case matches&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; ISwitch&lt;T&gt; Case(T query, Action action); /// &lt;summary&gt; /// Add a case to the switch (at the end), and return the aforesaid switch /// &lt;/summary&gt; /// &lt;param name="predicate"&gt;Predicate that will test the value&lt;/param&gt; /// &lt;param name="action"&gt;Action to perform if case matches&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; ISwitch&lt;T&gt; CaseWhen(Predicate&lt;T&gt; predicate, Action action); /// &lt;summary&gt; /// Add a default-case to the switch (at the end), and return the aforesaid (evaluable-only) switch /// &lt;/summary&gt; /// &lt;param name="action"&gt;Action to perform if no case matches before&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; IEvaluable&lt;T&gt; Default(Action action); } </code></pre> <h2>3.b. Internal interfaces</h2> <pre><code>internal interface IHasNextCase&lt;T&gt; { void Append(ICase&lt;T&gt; nextCase); } internal interface ICase&lt;T&gt; : IHasNextCase&lt;T&gt; { void EvaluateFor(T value); } </code></pre> <h2>3.c. Switch section</h2> <pre><code>internal abstract class SwitchCaseBase&lt;T&gt; : IEvaluable&lt;T&gt;, IHasNextCase&lt;T&gt; { protected ICase&lt;T&gt; Next { get; set; } public virtual void Append(ICase&lt;T&gt; nextCase) { if (ReferenceEquals(Next, null)) Next = nextCase; else Next.Append(nextCase); } public abstract void EvaluateFor(T value); } internal sealed class Switch&lt;T&gt; : SwitchCaseBase&lt;T&gt;, ISwitch&lt;T&gt; { IEqualityComparer&lt;T&gt; Comparer { get; } internal Switch() { Comparer = EqualityComparer&lt;T&gt;.Default; } internal Switch(IEqualityComparer&lt;T&gt; comparer) { Comparer = comparer; } public ISwitch&lt;T&gt; Case(T query, Action action) { Append(new Case&lt;T&gt;(query, Comparer, action)); return this; } public ISwitch&lt;T&gt; CaseWhen(Predicate&lt;T&gt; predicate, Action action) { if (ReferenceEquals(predicate, null)) throw new ArgumentNullException("predicate"); Append(new CaseWhen&lt;T&gt;(predicate, action)); return this; } public IEvaluable&lt;T&gt; Default(Action action) { Append(new Default&lt;T&gt;(action)); return this; } public override void EvaluateFor(T value) =&gt; Next?.EvaluateFor(value); } </code></pre> <h2>3.d. Case section</h2> <pre><code>internal abstract class CaseBase&lt;T&gt; : SwitchCaseBase&lt;T&gt;, ICase&lt;T&gt; { protected Action Action { get; } internal CaseBase(Action action) { Action = action; } protected void Execute() =&gt; Action?.Invoke(); } internal sealed class Case&lt;T&gt; : CaseBase&lt;T&gt; { private T Query { get; } private IEqualityComparer&lt;T&gt; Comparer { get; } internal Case(T query, IEqualityComparer&lt;T&gt; comparer, Action action) : base(action) { Query = query; Comparer = comparer; } public override void EvaluateFor(T value) { if (Comparer.Equals(Query, value)) Execute(); else Next?.EvaluateFor(value); } } internal sealed class CaseWhen&lt;T&gt; : CaseBase&lt;T&gt; { Predicate&lt;T&gt; Predicate { get; } internal CaseWhen(Predicate&lt;T&gt; predicate, Action action) : base(action) { Predicate = predicate; } public override void EvaluateFor(T value) { try { if (Predicate(value)) { Execute(); return; } } catch { } Next?.EvaluateFor(value); } } internal sealed class Default&lt;T&gt; : CaseBase&lt;T&gt; { internal Default(Action action) : base(action) { } // throws an error because after a default, // switch shouldn't be able to add another case public override void Append(ICase&lt;T&gt; nextCase) { throw new InvalidOperationException(); } public override void EvaluateFor(T value) =&gt; Execute(); } </code></pre> <h2>3.e. Public facade</h2> <pre><code>public static class Bar // still no idea about how to name this class... { /// &lt;summary&gt; /// Creates a simulated switch instance /// &lt;/summary&gt; /// &lt;returns&gt;The aforesaid switch&lt;/returns&gt; public static ISwitch&lt;T&gt; Switch&lt;T&gt;() =&gt; new Switch&lt;T&gt;(); /// &lt;summary&gt; /// Creates a simulated switch instance /// &lt;/summary&gt; /// &lt;param name="comparer"&gt;Comparer used to compare evaluated-value and case-value&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static ISwitch&lt;T&gt; Switch&lt;T&gt;(IEqualityComparer&lt;T&gt; comparer) =&gt; new Switch&lt;T&gt;(comparer); } </code></pre> <h1>4. Example</h1> <pre><code>class Program { static void Main(string[] args) { var mySwitch = Bar.Switch&lt;Response&gt;() .CaseWhen(r =&gt; r.Id &lt; 0, ErrorMethod) .Case(Response.OK, OkMethod) .Case(Response.Warning, WarningMethod) .Case(null, NullMethod) .Default(DefaultMethod); for (int content = -10; content &lt; 10; content++) { var response = Client.Post(content); mySwitch.EvaluateFor(response); } Console.ReadLine(); } static void ErrorMethod() { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error, your content is badly formatted"); } static void OkMethod() { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("OK"); } static void WarningMethod() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Warning, there might be a problem"); } static void NullMethod() { Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Timeout, please check your connection"); } static void DefaultMethod() { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Unknown response, please check the logs"); } static class Client { public static Response Post(int content) { if (content % 7 == 0) return null; if (content % 5 == 0) return Response.Warning; if (content % 3 == 0) return Response.OK; if (content % 2 == 0) return new Response(content, "Hello"); return new Response(-content, "Error"); } } class Response : IEquatable&lt;Response&gt; { public static readonly Response OK = new Response(0, "OK"); public static readonly Response Warning = new Response(1, "Warning"); public int Id { get; } public string Message { get; } public Response(int id, string message) { Id = id; Message = message; } public bool Equals(Response other) =&gt; other.Id == Id; } } </code></pre>
[]
[ { "body": "<p>I saw a mistake, in the <code>CaseWhen.EvaluateFor</code> method. If an exception is thrown in the <code>Execute()</code> part, this exception will be caught. Instead, I should have write:</p>\n\n<pre><code>public override void EvaluateFor(T value)\n{\n bool success;\n\n try\n { success = Predicate(value); }\n catch\n { success = false; }\n\n if (success)\n Execute();\n else\n Next?.EvaluateFor(value);\n}\n</code></pre>\n\n<p>I think I also should test if <code>comparer</code> is not null here:</p>\n\n<pre><code>public static ISwitch&lt;T&gt; Switch&lt;T&gt;(IEqualityComparer&lt;T&gt; comparer)\n{\n if (ReferenceEquals(comparer, null)) \n throw new ArgumentNullException(\"comparer\");\n\n return new Switch&lt;T&gt;(comparer);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T21:15:56.547", "Id": "412301", "Score": "3", "body": "I know you were told not to edit your initial post after receiving answers. You could have have edited the post with the above, but since it is now a posted answer, you are back to not being allowed to update your initial post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T10:58:05.220", "Id": "412378", "Score": "0", "body": "@RickDavin In some cases both options are also viable, in this case I think it's a reasonable answer too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T21:11:00.427", "Id": "213119", "ParentId": "213106", "Score": "-1" } }, { "body": "<p>I still don't like this implementation because:</p>\n\n<ul>\n<li>it's waaaay to complex</li>\n<li>it isn't easily extendable</li>\n<li>doesn't provide the basic <code>switch</code> logic one expects from it, this is, it cannot fall through multiple cases</li>\n<li>it requires to repeat the same logic multiple times with every <code>EvaluateFor</code></li>\n</ul>\n\n<hr>\n\n<p>What you have build is a <code>SwitchBuilder</code> that you also should name like that. I prefer to create and use it where it belongs e.g. inside a loop and not before so I suggest a much simpler approach with a <code>readonly struct</code>.</p>\n\n<hr>\n\n<p>What you need is a single interface for the value and a continuation flag like:</p>\n\n<pre><code>public interface ISwitch&lt;T&gt;\n{\n T Value { get; }\n\n bool CanEvaluateNext { get; }\n}\n</code></pre>\n\n<p>an <code>internal readonly struct</code> that implements it and doesn't cost a penny to create so it can be used it loops:</p>\n\n<pre><code>internal readonly struct Switch&lt;T&gt; : ISwitch&lt;T&gt;\n{\n public Switch(T value, bool canEvaluateNext)\n {\n Value = value;\n CanEvaluateNext = canEvaluateNext;\n }\n\n public T Value { get; }\n\n public bool CanEvaluateNext { get; }\n}\n</code></pre>\n\n<p>a single core extension for the interface that you'll use to implement every other convenience extension like <code>Default</code>, <code>CaseWhen</code> or whatever you like using custom comparers etc. You don't need anything else and you can build every other API by calling this extension (which is your homework).</p>\n\n<pre><code>public static class SwitchExtensions\n{\n public static ISwitch&lt;T&gt; Case&lt;T&gt;(this ISwitch&lt;T&gt; @switch, Predicate&lt;T&gt; predicate, Action&lt;T&gt; action, bool canEvaluateNext)\n {\n if (!@switch.CanEvaluateNext)\n {\n return @switch;\n }\n\n if (predicate(@switch.Value))\n {\n action(@switch.Value);\n return new Switch&lt;T&gt;(@switch.Value, canEvaluateNext);\n }\n else\n {\n return @switch;\n }\n }\n}\n</code></pre>\n\n<p>Since <code>Switch&lt;T&gt;</code> is internal you'll need a helper-factory-class for a nice fluent syntax:</p>\n\n<pre><code>public static class Switch\n{\n public static ISwitch&lt;T&gt; For&lt;T&gt;(T value)\n {\n return new Switch&lt;T&gt;(value, false);\n }\n}\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>Switch\n .For(5)\n .Case(x =&gt; x == 4, x =&gt; Console.WriteLine(x), false) // nope\n .Case(x =&gt; x == 5, x =&gt; Console.WriteLine(x), false) // 5\n .Case(x =&gt; x == 6, x =&gt; Console.WriteLine(x), false); // nope\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Switch\n .For(5)\n .Case(x =&gt; x == 4, x =&gt; Console.WriteLine(x), true) // nope\n .Case(x =&gt; x == 5, x =&gt; Console.WriteLine(x), true) // 5\n .Case(x =&gt; x &lt; 6, x =&gt; Console.WriteLine(x), true); // 5\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T10:33:30.980", "Id": "412375", "Score": "0", "body": "Does a basic `switch` \"can fall through multiple cases\"? Tell me if I'm wrong, but at the end of a `case`, we have to choose between `break`, `return` or `goto`, don't we? So the only way to \"fall through multiple cases\" is by using `goto`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T10:35:50.820", "Id": "412376", "Score": "0", "body": "@MaximeRecuerda no, you don't have to use `break`, it's optional, you can have muliple `case`s and only one `break`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:02:08.657", "Id": "412379", "Score": "0", "body": "But for this, the first `case`s have to be _empty_? Like `switch(x) { case 1: case 2: case 3: doSomething(); break; }`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:43:33.163", "Id": "412387", "Score": "0", "body": "Following [Eric Lippert answer here](https://stackoverflow.com/a/3049601/9757968), there is no \"fall-through\" in C#, but one statement-list can have multiple case-labels. To do so, I should add an extension with this signature: `Case<T>(this ISwitch<T> @switch, IEnumerable<Predicate<T>> predicates, Action action)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T13:21:27.883", "Id": "412393", "Score": "0", "body": "@MaximeRecuerda potato-potahto ;-] You can add as many extensions as you want as long as you don't just copy paste them but reuse one of two with the most generic signature to create those with more convenient ones that cover the most common use-cases." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T09:50:30.373", "Id": "213175", "ParentId": "213106", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T16:29:25.370", "Id": "213106", "Score": "4", "Tags": [ "c#" ], "Title": "Switch-Case pattern for non-constant types (part 2)" }
213106
<p>I am writing a numerical analysis library in golang for which I need to implement a polynomial struct. Here is the source code:</p> <pre><code>package numerical import ( "strconv" ) type Poly struct { Coeffs []float64 } func (p *Poly) Str() string { d := p.Deg() if d == -1 { return "0" } s := "" if p.Coeffs[d] == -1 { if d == 0 { s += "-1" } else { s += "-" } } else if p.Coeffs[d] != 1 || d == 0 { s += strconv.FormatFloat(p.Coeffs[d], 'g', -1, 64) } if d == 1 { s += "x" } else if d &gt; 1 { s += "x^" + strconv.Itoa(d) } for i := d-1; i &gt;= 0; i-- { if p.Coeffs[i] &gt; 0 { s += " + " if p.Coeffs[i] != 1 || i == 0 { s += strconv.FormatFloat(p.Coeffs[i], 'g', -1, 64) } } else if p.Coeffs[i] &lt; 0 { s += " - " if p.Coeffs[i] != -1 || i == 0 { s += strconv.FormatFloat(-p.Coeffs[i], 'g', -1, 64) } } if p.Coeffs[i] != 0 { if i == 1 { s += "x" } else if i &gt; 1 { s += "x^" + strconv.Itoa(i) } } } return s } func (p *Poly) Deg() int { i := len(p.Coeffs) - 1 for ; i &gt;= 0 &amp;&amp; p.Coeffs[i] == 0; i-=1 { } return i } func (p *Poly) Eval(x float64) float64 { val := p.Coeffs[0] pow := 1.0 for i:=1; i &lt;= p.Deg(); i+=1 { pow *= x val += p.Coeffs[i]*pow } return val } func PolyAdd(p, q Poly) Poly { var big, small, r Poly if p.Deg() &gt; q.Deg() { big = p small = q } else { big = q small = p } r = big for i := 0; i &lt;= small.Deg(); i+=1 { r.Coeffs[i] += small.Coeffs[i] } return r } func PolySub(p, q Poly) Poly { degp := p.Deg() degq := q.Deg() big := degp if degp &lt; degq { big = degq } r := Poly{make([]float64, big+1)} for i := 0; i &lt;= big; i++ { if i &lt;= degp { r.Coeffs[i] = p.Coeffs[i] } if i &lt;= degq { r.Coeffs[i] -= q.Coeffs[i] } } return r } func PolyMul(p, q Poly) Poly { m, n := p.Deg(), q.Deg() r := Poly{make([]float64, m+n+1)} for i := 0; i &lt;= m; i++ { for j := 0; j &lt;= n; j++ { r.Coeffs[i+j] += p.Coeffs[i]*q.Coeffs[j] } } return r } func PolyDiv(a, b Poly) (Poly, Poly) { var q Poly for b.Deg() &lt;= a.Deg() { dega := a.Deg() degb := b.Deg() qc := a.Coeffs[dega]/b.Coeffs[degb] qp := dega - degb qi := Poly{make([]float64, qp+1)} qi.Coeffs[qp] = qc a = PolySub(a, PolyMul(qi, b)) q = PolyAdd(q, qi) } return q, a } </code></pre> <p>A few things that I observed about the code are:</p> <ul> <li><p>The <code>Poly.Deg</code> is a method. I should probably make a non-method field (<em>what are they called?</em>) for that purpose, but then I will have to create a <code>Poly.UpdateDeg</code> which will set the degree for a new polynomial, and then I will have to call this <code>UpdateDeg</code> in all the other functions like <code>PolyAdd</code>, <code>PolyMul</code> etc. Is their a better way to achieve this.</p></li> <li><p>The <code>Poly.Str</code> method, which basically pretty-prints the polynomial looks very complicated. The purpose of this method is to return a string containing the polynomial in human readable form. For example, the polynomial <code>{-1, 2, -1}</code> will give <code>-x^2 + 2x - 1</code> (pay special attention to the leading coefficients and spaces around <code>+</code> and <code>-</code>). Can this method be simplified?</p></li> </ul> <p>Any other suggestion/improvements are welcome, in particular, I would like to know if the code is idiomatic Go. I am new to Go, and would like to learn the Go-way of doing things.</p> <p><strong>EDIT</strong>: Here is the code on <a href="https://play.golang.org/p/sM79zEdIFV8" rel="nofollow noreferrer">Playground</a> (slightly modified to run on Playground).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T17:50:42.370", "Id": "412280", "Score": "0", "body": "@200_success I am sorry, but your edit was at the same time as my update and it undid my update. So I had to rollback to my update but I have included the tag suggested by you." } ]
[ { "body": "<p>Your code is missing automatic tests.</p>\n\n<p>One test case you definitely need is to ensure that <code>PolyAdd</code> and the related functions do not modify their arguments. As far as I can see by reading the code, the current version of <code>PolyAdd</code> modifies the bigger of its arguments, which is unexpected.</p>\n\n<p>The reason that the argument is modified is that slices are essentially pointers, and when passing them as arguments, their content is not copied.</p>\n\n<p>You should define a constructor function <code>NewPoly(deg int)</code> to hide all the implementation details. Using this constructor will also solve the aliasing problem mentioned above.</p>\n\n<p>Regarding the long code for <code>Str</code>, you can merge some of the duplicate code:</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code> c := p.Coeffs[i]\n if c == 0 {\n continue;\n }\n\n if c &gt; 0 {\n s += \" + \"\n } else {\n s += \" - \"\n }\n\n if (c != 1 &amp;&amp; c != -1) || i == 0 {\n s += strconv.FormatFloat(c, 'g', -1, 64)\n }\n if i &gt; 1 {\n s += \"x^\" + strconv.Itoa(i)\n } else if i == 1 {\n s += \"x\"\n }\n</code></pre>\n\n<p>By extracting the expression <code>p.Coeffs[i]</code> into a variable, the code gets a bit cleaner. </p>\n\n<p>If you need to speed up <code>Str</code>, use a <code>strings.Builder</code> instead of the <code>+=</code> operator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T05:56:35.120", "Id": "474297", "Score": "0", "body": "I added a section on making `Str` shorter." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T19:17:28.073", "Id": "213114", "ParentId": "213107", "Score": "1" } } ]
{ "AcceptedAnswerId": "213114", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T17:04:18.420", "Id": "213107", "Score": "4", "Tags": [ "formatting", "go", "numerical-methods", "symbolic-math" ], "Title": "Polynomial implementation in Golang" }
213107
<p>I got a coding problem to solve and was wondering if I got a commonly acceptable and efficient/clean solution. If there is a better way I'd gladly hear it. </p> <blockquote> <p>given a list with numbers return if the sum of 2 elements in the list = k</p> </blockquote> <pre><code>def is_sum_of_2nums_in_list_k(list, k): for i in list: if k - i in list: return True return False </code></pre> <p>They also mentioned you get bonus points if you do it in one 'pass'. What does this mean? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T21:01:54.200", "Id": "412297", "Score": "1", "body": "that seems to be very efficient and will finish in one pass. They just dont want you to iterate over the list multiple times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T21:04:27.713", "Id": "412299", "Score": "6", "body": "I think this would require multiple passes. `in` is O(len) for lists afaik. In the worst case, both the `for` and `in` will do a full pass. If `list` was a set, this would be much more efficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T21:21:47.547", "Id": "412303", "Score": "0", "body": "@Carcigenicate If I understand correctly, a pass is a full iteration over the list. If that is the case, how would I do this in one iteration? (from what I understand `in` also iterates, meaning I iterate twice in my given solution)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T21:27:38.330", "Id": "412304", "Score": "2", "body": "Yes, a \"pass\" over a list means an iteration over it. And I'm not sure of an algorithm off the top of my head. If you were allowed to start with a set instead of a list, your function would already work, but that likely isn't an option. You could try doing something like having a local set, and you add each difference to it as you find them. I'm not sure if that would work though. I can see a couple problems with that." } ]
[ { "body": "<p>You are using one explicit pass over the list (<code>for i in list</code>), and one implicit pass over the list (<code>k - i in list</code>). This means your algorithm is <span class=\"math-container\">\\$O(N^2)\\$</span>.</p>\n\n<p>Note: You can reduce your implementation to one line:</p>\n\n<pre><code>return any(k - i in list for i in list)\n</code></pre>\n\n<p>But you have a bug. <code>is_sum_of_2nums_in_list_k([5], 10)</code> returns <code>True</code>.</p>\n\n<p>A one pass algorithm</p>\n\n<ul>\n<li>starts with an empty set,</li>\n<li>takes each number in the list, \n\n<ul>\n<li>tests if k-i is in the set,\n\n<ul>\n<li>return true if it is,</li>\n</ul></li>\n<li>adds i to the set. </li>\n</ul></li>\n<li>returns false</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T21:48:32.170", "Id": "213120", "ParentId": "213111", "Score": "8" } }, { "body": "<p>(Quick note: please do not use <code>list</code> as a variable name, as it's also the name of a type. I'm going to use <code>list_</code> instead)</p>\n\n<p>Depending on the interpretation, it could be that they want you to iterate over the list just once.</p>\n\n<p>The statement \"v in list\" potentially iterates over the full list, which means it's yet another pass.</p>\n\n<p>If you know nothing about the list, except that they are numbers, one approach would be to store the values seen so far in a set, which has a more efficient \"in\".</p>\n\n<pre><code>def is_sum_of_2nums_in_list_k(list_, k):\n seen = set()\n for i in list_:\n if k - i in seen:\n return True\n seen.add(i)\n return False\n</code></pre>\n\n<p>This works the same as your initial solution, but for each new number, it only checks if the sum of that number and an <em>earlier</em> number add up <code>k</code>.</p>\n\n<p>As a downside: storage needs to be allocated for the set <code>seen</code>, so this does not work with constant memory.</p>\n\n<p>If on the other hand, we have also been told that the list was ordered, we can go for a different approach</p>\n\n<pre><code>def is_sum_of_2nums_in_list_k(list_, k):\n # Assumption: `list_` is ordered.\n left, right = 0, len(list_) - 1\n while left &lt; right:\n total = list_[left] + list_[right]\n\n if total == k:\n return True\n\n if total &lt; k:\n left += 1\n if total &gt; k:\n right -= 1\n return False\n</code></pre>\n\n<p>This is a bit more complicated, but requires constant extra storage.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T08:29:14.763", "Id": "213131", "ParentId": "213111", "Score": "5" } } ]
{ "AcceptedAnswerId": "213120", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T18:44:28.213", "Id": "213111", "Score": "2", "Tags": [ "python", "python-3.x", "interview-questions", "k-sum" ], "Title": "Is the sum of 2 numbers in list k" }
213111
<p>I need your opinion about my practice. I want to improve it. </p> <p>The requirements are the following:</p> <ul> <li>RESTFUL + OWIN (SelfHosted)</li> <li>Endpoint - Upload a file asynchronously</li> <li>Make a request to the endpoint from Postman</li> </ul> <p>Well, This is what I got</p> <p>For the OWIN selfhosted I followed the Microsoft Documentation</p> <p><a href="https://docs.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api" rel="nofollow noreferrer">OWIN Self-host</a></p> <p>Endpoint:</p> <p>FileController.cs</p> <pre><code> [HttpPost] [Route("api/v1/upload")] public HttpResponseMessage Post([FromUri]string filename) { var task = this.Request.Content.ReadAsStreamAsync(); task.Wait(); Stream requestStream = task.Result; try { Stream fileStream = File.Create("./" + filename); requestStream.CopyTo(fileStream); fileStream.Close(); requestStream.Close(); } catch (IOException) { throw new HttpResponseException( HttpStatusCode.InternalServerError); } HttpResponseMessage response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.Created; return response; } </code></pre> <p>Postman:</p> <p>The postman returns Status Code 201</p>
[]
[ { "body": "<p>Seems a bit needlessly complicated and not exactly async at all. You're just forcing an async call to be synchronous with <code>.Wait()</code>. Proper way is to use async \"all the way down\":</p>\n\n<pre><code>[HttpPost]\n[Route(\"api/v1/upload\")]\npublic async Task&lt;HttpResponseMessage&gt; Post([FromUri]string filename)\n{\n try\n {\n using (Stream requestStream = await this.Request.Content.ReadAsStreamAsync())\n using (Stream fileStream = File.Create(\"./\" + filename))\n {\n await requestStream.CopyToAsync(fileStream);\n }\n\n return new HttpResponseMessage { StatusCode = HttpStatusCode.Created };\n }\n catch (IOException)\n {\n throw new HttpResponseException(HttpStatusCode.InternalServerError);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T19:30:11.670", "Id": "213115", "ParentId": "213112", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T18:50:02.830", "Id": "213112", "Score": "2", "Tags": [ "c#", "asynchronous", "http", "network-file-transfer", "owin" ], "Title": "Upload a file asynchronously" }
213112
<p>I am trying to make a router in Rust using Rocket.rs. I'd like to devise a way to use a default router for my more simple db tables that don't require different logic, to prevent rewriting the same functions over and over and only replacing just the type of output and input it takes.</p> <pre><code>struct Router&lt;T&gt; { router_type: T, } trait DefaultRouter&lt;T&gt; { #[get("/")] pub fn get_list(&amp;self, connection: DbConn) -&gt; Result&lt;Json&lt;Vec&lt;T&gt;&gt;, Failure&gt;; #[get("/&lt;id&gt;")] pub fn get(&amp;self, id: String, connection: DbConn) -&gt; Result&lt;Json&lt;T&gt;, Failure&gt;; #[post("/", format = "application/json", data = "&lt;data&gt;")] pub fn insert(&amp;self, data: T, connection: DbConn) -&gt; Result&lt;status::Created&lt;Json&lt;T&gt;&gt;, Failure&gt;; #[put("/&lt;id&gt;", format = "application/json", data = "&lt;data&gt;")] pub fn update(&amp;self, id: String, data: Json&lt;T&gt;, connection: DbConn) -&gt; Result&lt;status::Created&lt;Json&lt;T&gt;&gt;, Failure&gt;; #[delete("/&lt;id&gt;")] pub fn delete(&amp;self, id: String, connection: DbConn) -&gt; Result&lt;status::NoContent, Failure&gt;; fn created(&amp;self, data: T) -&gt; status::Created&lt;Json&lt;T&gt;&gt;; fn error_status(error: Error) -&gt; Failure; fn host() -&gt; String; fn port() -&gt; String; } impl &lt;T&gt; DefaultRouter&lt;T&gt; for Router&lt;T&gt; { #[get("/")] pub fn get_list(&amp;self, connection: DbConn) -&gt; Result&lt;Json&lt;Vec&lt;T&gt;&gt;, Failure&gt; { //... } } </code></pre> <p>What this code attempts to do is to apply the functionality defined in the trait to a given router_type. I want to be able to return data of a specific schema type without needing to define this functionality for each individual schema I have defined. Does this approach align with the intentions of rust? Or is there something better? I am still definitely a beginner, so any constructive criticism is welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T23:13:07.040", "Id": "213122", "Score": "3", "Tags": [ "beginner", "object-oriented", "generics", "rust", "url-routing" ], "Title": "Generic router in Rust" }
213122
<p>I am a beginner Python developer and I wrote a script in Python which fetches 50 latest jobs from <strong>jobs.af</strong> (a jobs portal) API, categories them based on jobs gender and write each to a separate CSV and Excel sheet files. I want my code cleaner and more readable, so I really like to get comments on code structure and how to make the code more readable and nice.</p> <pre><code>#! /usr/bin/python '''This is a simple command line python program which fetches maximum 50 latest jobs from jobs.af API and accept two optional arguments (--category='job category --title='job title') and can filter jobs bassed on them, then it prints the result to a .xlsxworksheet with three sheets Male, Female and Any according the gender of jobs. ''' import urllib2 import json import sys import csv import xlsxwriter import argparse # Create an ArgumentParser parser = argparse.ArgumentParser(description = 'Fetch and list maximum 50 latest\ jobs from "jobs.af" based on title, category, with \ both of them or with out of them.' ) # Create arguments using argparse object parser.add_argument('--category', help = "takes job category name or it's id ") parser.add_argument('--title' , help = 'takes job title as string') # Some variables used for flag. job_title = '' job_category = '' flag = True # Use tyr except to handle arguments parsing. try: parser.parse_args([]) args = parser.parse_args() # Assgin command line arguments to variables to pass them to urlBuilder method job_category = args.category job_title = args.title except: flag = False print 'please enter your search like this patter: --category="catgory name" \ --title="title name"' # General url for jobs.af API url = 'http://api.jobs.af/jobs?filter=1&amp;per_page=50' # Create the url(filter the request) to get data from jobs.af API def url_builder(category = None, title = None): if category and title: title_query = title and '&amp;position_title=' + title.replace(' ', '%20') or '' category_query = category and '&amp;category=' + category.replace(' ', '%20') or '' global url return url + category_query + title_query elif category and not title: category_query = category and '&amp;category=' + category.replace(' ', '%20') or '' return url + category_query elif title and not category: title_query = title and '&amp;position_title=' + title.replace(' ', '%20') or '' return url + title_query else: url = 'http://api.jobs.af/jobs?per_page=50' return url '''Get data from API as json object and get the specific parts of jobs and print them to a worksheet in differen sheet according to gender. ''' def list_jobs(query): # Use urllib2 to load data as a json object. json_object = urllib2.urlopen(query) json_data = json.load(json_object) # Create a workboo using xlsxwriter to write data in it. workbook = xlsxwriter.Workbook('listJobs.xlsx') male_sheet = workbook.add_worksheet('Male') male_sheet.write_row('A1',['PSITION TITILE', 'SKILLS', 'EXPIRE-DATE', 'GENDER', 'LOCATION', 'CATEGORY' ]) female_sheet = workbook.add_worksheet('Female') female_sheet.write_row('A1',['PSITION TITILE', 'SKILLS', 'EXPIRE-DATE', 'GENDER', 'LOCATION', 'CATEGORY' ]) any_sheet = workbook.add_worksheet('Any') any_sheet.write_row('A1',['PSITION TITILE', 'SKILLS', 'EXPIRE-DATE', 'GENDER', 'LOCATION', 'CATEGORY' ]) # Open a CSV file. csv_file = open('jobs.csv', 'a') # Create an object of csv.writer to write to a csv file. csv_writer = csv.writer(csv_file) # Write to CSV file. csv_writer.writerow(['Position Title', 'skill', 'Expire Date', 'Gender', 'Location', 'Category' ]) # Counters any_counter = 1 female_counter = 1 male_counter = 1 count = 0 k = 0 # Loop over dictionary to fetch jobs attributes for item in json_data['data']: # Get items and encode and decode them to write items to xlsx files. title = item['position_title'].encode('utf-8') dtitle = title.decode('unicode-escape') skills = item['skills_requirement'].encode('utf-8') dskills = skills.decode('unicode-escape') expire = item['expire_date'].encode('utf-8') dexpire = expire.decode('unicode-escape') gender = item['gender'].encode('utf-8') dgender = gender.decode('unicode-escape') loc = item.get('location').get('data') state = '' for i in range(len(loc)): province = loc[i] state = state + province['name_en'].encode('utf-8') dstate = state.decode('unicode-escape') category = item.get('category').get('data') category = category['name_en'].decode('utf-8') dcategory = category.decode('unicode-escape') # Update counter for counting number of jobs that are ftching. count = count + 1 # Get gender attribute and check it to specify the sheet to write in to it. gender = item['gender'] if gender == 'Male': male_sheet.write_row(male_counter,k,[dtitle, dskills, dexpire, dgender, dstate, dcategory ]) male_counter = male_counter + 1 elif gender == 'Female': female_sheet.write_row(female_counter, k,[dtitle, dskills, dexpire, dgender, dstate, dcategory ]) female_counter = female_counter + 1 else: any_sheet.write_row(any_counter, k,[dtitle, dskills, dexpire, dgender, dstate, dcategory ]) any_counter = any_counter + 1 # Write to CSV file csv_writer.writerow([title, skills, expire, gender, state, category]) # Close workbook workbook.close() # Prompt for user based on the result of fetching of jobs from jobs.af result1 = '' result2 = '' if job_category == None: result1 = 'any category' else: result1 = job_category if job_title == None: result2 = 'any title.' else: result2 = job_title if count == 0: print 'No job/s were/was found in jobs.af for category: ' + str(result1) + \ ' and title: ' + str(result2) elif job_category == None and job_title == None: print str(count) + ' latest jobs founded in jobs.af for category: ' + str(result1) + \ ' and title: ' + str(result2) + ' were writen to listJobs.xlsx.' print str( any_counter -1 ) + ' of founded job/s are/is for any gender.' print str(male_counter -1) + ' of founded job/s are/is for males.' print str(female_counter -1) + ' of founded job/s are/is for females.' else: print str(count) + ' job/s were/was found in jobs.af for category: ' + str(result1) + \ ' and title: ' + str(result2) + ' were writen to listJobs.xlsx.' print str( any_counter -1 ) + ' of founded job/s are/is for any gender.' print str(male_counter -1) + ' of founded job/s are/is for males.' print str(female_counter -1) + ' of founded job/s are/is for females.' if flag == True: # Call urlBuilder method and assgin it's returned url to url variable url_query = url_builder(job_category, job_title) # Call listJobs method with the epecified URL list_jobs(url_query) else: print 'Run program with correct argument pattern' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T07:22:20.110", "Id": "412319", "Score": "0", "body": "Welcome to Code Review, nice question! I don't have time to write a review, but `requests` would simply or remove your `url_builder` class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T09:20:15.320", "Id": "412322", "Score": "0", "body": "@Peilonrayz, Thanks for your comment. Actually it's a method and if I remove url_buidler method, how can I pass the appropriate URL for list_jobs method based on query condition the user supply in command line? Do you have any suggestion instead of using this method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T10:02:03.773", "Id": "412324", "Score": "0", "body": "yeah I realized I used the wrong word a minute too late you just need to build a dictionary such as `requests.get(url, {'category': category})`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T10:23:56.280", "Id": "412328", "Score": "0", "body": "@Peilonrayz, Thank you again. I wrote this script with out considering **requests** module, so this script got dirty. I will certainly use requests module in next version." } ]
[ { "body": "<p>As alluded to <a href=\"https://codereview.stackexchange.com/questions/213129/read-jobs-from-jobs-af-a-jobs-portal-categories-them-and-write-them-to-separ#comment412319_213129\">in the comments</a> by <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">@Peilonrayz</a>, using the <code>requests</code> module would simplify your URL building and reading the result of the request:</p>\n\n<pre><code>import requests\n\nurl = 'http://api.jobs.af/jobs'\nparams = {\"filter\": 1, \"per_page\": 50, \"category\": category, \"title\": title}\njson_data = requests.get(url, params=params).json()\n</code></pre>\n\n<p>If <code>category</code> or <code>title</code> are <code>None</code>, they will just be skipped and both the parameter names as well as the values will be URL encoded (so not only spaces replaced by <code>%20</code>, but also all other possible entities).</p>\n\n<hr>\n\n<p>In your argument parsing you use a <code>try..except</code> block in which you first parse without any arguments, then try to parse what the user supplied and then output a help message if it is not correct.</p>\n\n<p>This is wrong on almost all accounts. You should not need the first empty parsing, you should basically never use a bare <code>except</code> clause (it also catches things like the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd>) and <code>argparse</code> will already generate an error message for you on wrong input. In addition with your version the program will continue running with invalid parameters. Instead it should just fail and stop right there.</p>\n\n<hr>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code>s</a> should go into the scope of the function:</p>\n\n<pre><code>def f(a, b):\n \"\"\"Sums the values `a` and `b`.\"\"\"\n return a + b\n</code></pre>\n\n<p>This way you can actually access it:</p>\n\n<pre><code>&gt;&gt;&gt; print f.__doc__\n# Sums the values `a` and `b`.\n\n&gt;&gt;&gt; help(f)\n# Help on function f in module __main__:\n# \n# f(a, b)\n# Sums the values `a` and `b`.\n</code></pre>\n\n<hr>\n\n<p>For the writing to excel sheets I would use a less manual approach. <a href=\"http://pandas.pydata.org/\" rel=\"nofollow noreferrer\"><code>pandas</code></a> has data frames and a <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html\" rel=\"nofollow noreferrer\"><code>to_excel</code></a> method:</p>\n\n<pre><code>import pandas as pd\n\ndef combine_location(row):\n return \" \".join(x[\"name_en\"] for x in row['data'])\n\ndf = pd.DataFrame(json_data[\"data\"])\ndf = df[[\"position_title\", \"skills_requirement\", \"expire_date\", \"gender\",\n \"location\", \"category\"]]\ndf[\"location\"] = df.location.apply(combine_location)\ndf[\"category\"] = df.category.apply(lambda row: row[\"data\"][\"name_en\"])\ndf.columns = ['Position Title', 'skill', 'Expire Date', 'Gender', 'Location',\n 'Category']\n\nwriter = pd.ExcelWriter('listJobs.xlsx')\ngdf = df.groupby(\"Gender\", as_index=False)\ngdf.apply(lambda df: df.to_excel(writer, df.iloc[0].Gender, index=False))\nwriter.save()\n\nprint \"Number of jobs for:\"\nfor gender, jobs in gdf.groups.items():\n print gender, len(jobs)\n</code></pre>\n\n<hr>\n\n<p>You should put your code that executes the rest under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> so that you can import from this script without executing everything.</p>\n\n<hr>\n\n<p><a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">Python 2 will stop being officially supported in less than a year</a>. Now is a good time to switch to Python 3.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T06:49:27.107", "Id": "412354", "Score": "0", "body": "Thanks for your nice comments, suggestions and solutions. I will change my python version very soon. I really like to learn python deep, do you have any suggestion on which modules and libraries I should work with?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T07:20:11.067", "Id": "412355", "Score": "0", "body": "@IbrahimRahimi The [`itertools`](https://docs.python.org/3/library/itertools.html) module is a must. If you want to do webscraping look at [`bs4.BeautifulSoup`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) and if you want to do anything related to data analysis there is no way around [`numpy`[(http://www.numpy.org/) and [`pandas`](http://pandas.pydata.org/)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T10:03:35.193", "Id": "213135", "ParentId": "213129", "Score": "6" } } ]
{ "AcceptedAnswerId": "213135", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T07:03:02.537", "Id": "213129", "Score": "6", "Tags": [ "python", "json" ], "Title": "Read jobs from jobs.af (a jobs portal), categories them and write them to separate CSV files based on jobs gender" }
213129
<p>I'm reading "Code Complete" by McConnel and I'm practicing using object oriented programming to "reduce complexity". (By that McConnel means, among other things, that it should be very easy to read through any given tiny part of a project and know what is happening without thinking at all about the rest of the program). To practice, I have written a Python program that reproduces the known win-rate results for random-move tic tac toe games. The main file uses an instance of the below Game class to call the play_game method... the parameter to the method indicates how many games are to be played. I'm just curious if an experienced OOP/Python person could let me know if the classes below are cohesive and well built.</p> <p>There are two other classes in the program, one is a Board class that knows everything about the state and rules of the board at each point of the game, and the other is a Statistics class that tracks and reports the results. I have also included the Board class. I suppose issues such as "do the rules on wins and ties belong in the Board class or the Game class" could go either way: Does the Board know when a win is on itself... or does the Game know when there is a win?</p> <p>By the way, when I pass 1000000 to play_game to run one million games, the whole program does reproduce the exact results of a 58.5% win rate for X, a 28.8% win rate for O, and a 12.7% tie rate for random Tic Tac Toe. (These values are for X always moving first). I'd love some feedback on whether the below classes are cohesive and well built.</p> <pre><code>from board import Board class Game: # makes Game class a singleton _singleton = None def __new__(cls, *args, **kwargs): if not cls._singleton: cls._singleton = super(Game, cls).__new__(cls, *args, **kwargs) return cls._singleton def __init__(self): self.b = None # responsible for playing the number of games requested from main.py def play_game(self, number_of_games): i = 1 while i &lt;= number_of_games: # create a fresh board object for the next game self.b = Board() # play one game game_in_progress = True while game_in_progress: game_in_progress = self.make_move() i = i + 1 def make_move(self): # randomly select an available square position = self.b.select_random_square() # make a move self.b.board[position] = self.b.next_move # call game_over to see if the game is over if self.b.game_over(): return False # update who moves next temp = self.b.next_move self.b.next_move = self.b.previous_move self.b.previous_move = temp return True </code></pre> <p>And here is the Board class...</p> <pre><code>import random from statistics import Statistics class Board(Statistics): end_of_game_report = False def __init__(self): # the following line causes the __init__ method from the Statistics class to still run Statistics.__init__(self) # game board self.board = [' '] * 9 self.next_move = 'X' self.previous_move = 'O' self.all_possible_wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] self.letter_dict = {'X': -1, 'O': 1} self.x_won = False self.o_won = False self.tie = False # Printing an instance of the class will display a standard # tic tac toe game image. def __str__(self): return "\n" + self.board[0] + "|" + self.board[1] + "|" + self.board[2] + "\n"+ self.board[3] + "|" + self.board[4] + "|" + self.board[5] + "\n" + self.board[6] + "|" + self.board[7] + "|" + self.board[8] @classmethod def turn_on_end_of_game_reporting(cls): cls.end_of_game_report = True # call turn_on_end_of_game_reporting from main.py to run this report method def end_of_game_reporter(self): if self.x_won is True: print(self) print('X won\n') elif self.o_won is True: print(self) print('O won\n') else: print(self) print('Its a tie\n') def get_available_squares(self): # creates a list containing the position of all open squares list_of_open_squares = [] i = 0 for j in self.board: if j == ' ': list_of_open_squares.append(i) i = i + 1 return list_of_open_squares def select_random_square(self): list_of_open_squares = self.get_available_squares() # return a randomly selected available square return random.choice(list_of_open_squares) def game_won(self): for three_contiguous in self.all_possible_wins: row = 0 for i in three_contiguous: if self.board[i] == ' ': break row = row + self.letter_dict[self.board[i]] if row == -3 or row == 3: if row == -3: self.x_won = True self.track_game_outcomes('x_won') if row == 3: self.o_won = True self.track_game_outcomes('o_won') # self.brain.prep_dict_entry(three_contiguous, self.board, self.previous_move) if Board.end_of_game_report is True: self.end_of_game_reporter() return True return False def game_tied(self): if ' ' not in self.board[:9]: self.tie = True self.track_game_outcomes('tie') if Board.end_of_game_report is True: self.end_of_game_reporter() return True return False def game_over(self): if self.game_won(): return True elif self.game_tied(): return True else: return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T18:02:34.633", "Id": "412343", "Score": "0", "body": "I suggest that you include your `Board` class as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T22:27:05.297", "Id": "412346", "Score": "0", "body": "@200_success Great! I went ahead and added the Board class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T22:39:37.070", "Id": "412347", "Score": "0", "body": "@200_succes Also, I reread my post and there was a typo: I said that the main file uses an instance of the Board class... but I meant to say that the main file uses an instance of the Game class. (...the Game class has boards)." } ]
[ { "body": "<p>You got the result you wanted, so that is a good thing. However, I'm not convinced as to the build up of your classes and the responsibilities of them. A class should to me be self-contained, and have a defined set of responsibilities. </p>\n\n<p>The <code>Board</code> class should only handle stuff directly related to the <code>Board</code>, that is initialisations, placing moves, reporting stuff like free spaces and status of the <code>Board</code>. It shouldn't do game logic like selecting a random move, and I'm a bit uncertain on the end of game reporter. </p>\n\n<p>The <code>Game</code> class, could possible get a better name, would be the better place for me to place the logic of selecting the next position, and most likely the end of game reporter. <code>Game</code> shouldn't update the board directly either, that should have been a method of the <code>Board</code>. That way the game logic and game state would have been better separated.</p>\n\n<p>In addition to that I've got some comments on the actual code, which in general is mostly nice and clean:</p>\n\n<h3><code>Game</code> class</h3>\n\n<ul>\n<li><em>Why a singleton?</em> – Is there any reason why your game class is a singleton? It doesn't keep tags across instances, and neither does it have any class methods illustrating the need for it be a singleton.</li>\n<li><em>No need for <code>i</code> to count games</em> – You could instead just count down on <code>number_of_games</code>, and check if larger than zero.</li>\n<li><p><em>Why is <code>game_in_progress</code> linked to <code>make_move()</code></em> – To me it's unnatural that making a move updates whether the game is in progress or not. Expected return of <code>make_move()</code> would be whether the move was successful or not. I'd rather see something like:</p>\n\n<pre><code>while number_of_games &gt; 0:\n board = Board()\n while board.game_in_progress():\n available_moves = board.get_available_squares()\n board.next_move(random(available_moves))\n\nnumber_of_games -= 1\n</code></pre></li>\n<li><em>Next move should be in <code>Board</code></em> – Most of this logic should be in the <code>Board</code> class, with exception of the bits shown in previous code excerpt. This would also allow for safer moves, and easier handling of win/lose situations, as they can be calculated when the move is made.</li>\n<li><em>Statistics should be done in this class</em> – It seems a little strange for the <code>Board</code> class to keep statistics, as that belongs more to the one playing the game. Imagine a scenario where you would allow your code to test out various game strategies, like always placing in the first available space, or trying to avoid wins on the other player, or random placements (like you do currently). The statistics connected directly to the <code>Board</code> class would then have a hard time differentiating between the various options. It would be better placed where the games where actually played.</li>\n</ul>\n\n<h3><code>Board</code> class</h3>\n\n<ul>\n<li><em>Don't test for <code>True</code></em> – In <code>end_of_game_reporter()</code> you test whether <code>self.x_won is True</code>, when a simpler <code>self.x_won</code> would suffice. </li>\n<li><em>Extract similar bits of code</em> – Also in <code>end_of_game_reporter()</code>, you do <code>print(self)</code> in all three blocks. Move this in front of the <code>if</code>-statements, and you've saved yourself three code lines, and it's easier to read.</li>\n<li><em>Avoid repeated computations</em> – For every time a move is made, you re-calculate the <code>list_of_open_squares</code>. You could have started out with a set of all available positions, and just remove the last move done. Easier to read, and faster.</li>\n<li><em>Calculation of win</em> – Various strategy for win calculations exists, and doing the brute force option is not optimal. One better way could be use a little bit of extra memory, and store the sum of each winning combinations. That is have variables containing the sum of each of the three rows, each of the three columns, and each of the two diagonals. When a move is made, you correct the sum of corresponding row, column and diagonals. If the absolute value of either sum equals 3, you've got a winner.</li>\n<li><em>Tie game calculation</em> – Using the set from before, if there are no more places available in the set of possible moves, and no one has won yet, it's a tie.</li>\n<li><em>Simplify <code>if true: return True</code></em> – In <code>game_over()</code> you could simplify the code a lot as you return the value of the <code>if</code> statement: \n\n<pre><code>return self.game_won() or self.game_tied()\n</code></pre></li>\n<li><em>Changing state on end game reporting</em> – By default no end of game reporting is on, if you turn it on, there is no way of turning it back off again. Having a method to set this state, like <code>set_game_reports()</code> accepting a boolean value, and possible move the test inside of <code>end_of_game_reporter()</code> would look nicer.</li>\n</ul>\n\n<p><strong>PS!</strong> I'm somewhat rusty in reviewing code, so there might be bits and pieces I've left out, and I've not provided a refactor solution but leaving that for you to work out. Hopefully some of this will help you develop even better code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T00:58:22.880", "Id": "213161", "ParentId": "213132", "Score": "3" } } ]
{ "AcceptedAnswerId": "213161", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T09:15:41.103", "Id": "213132", "Score": "4", "Tags": [ "python", "object-oriented", "tic-tac-toe", "simulation" ], "Title": "Reproducing the known results for random tic tac toe play using Python" }
213132
<p>I have rolled a simple program for controlling a sliding tile puzzle via command line. I would like to hear comments on how to make it more idiomatic C++17 and efficient. Here is my code:</p> <p><strong>SlidingTilePuzzleNode.hpp</strong></p> <pre><code>#pragma once #include &lt;ostream&gt; #include &lt;stdexcept&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; class ZeroTileOutsideException : public std::logic_error { public: ZeroTileOutsideException(std::string&amp; error_message) : std::logic_error(error_message) { } }; class SlidingTilePuzzleNode; class SlidingTilePuzzleNodeRowSelector { public: SlidingTilePuzzleNodeRowSelector() = default; SlidingTilePuzzleNodeRowSelector( SlidingTilePuzzleNode* node, std::size_t start_index); int&amp; operator[](std::size_t x); private: SlidingTilePuzzleNode* m_node; std::size_t m_offset_index; }; class SlidingTilePuzzleNode { public: SlidingTilePuzzleNode(std::size_t width, std::size_t height); SlidingTilePuzzleNode(const SlidingTilePuzzleNode&amp; other); SlidingTilePuzzleNode&amp; operator=(const SlidingTilePuzzleNode&amp; other); SlidingTilePuzzleNode&amp; operator=(SlidingTilePuzzleNode&amp;&amp; other); //SlidingTilePuzzleNode(SlidingTilePuzzleNode&amp;&amp; other); ~SlidingTilePuzzleNode(); SlidingTilePuzzleNode slideUp(); SlidingTilePuzzleNode slideDown(); SlidingTilePuzzleNode slideLeft(); SlidingTilePuzzleNode slideRight(); std::size_t getWidth() const { return m_width; } std::size_t getHeight() const { return m_height; }; SlidingTilePuzzleNodeRowSelector&amp; operator[](size_t y); friend std::ostream&amp; operator&lt;&lt;( std::ostream&amp; out, SlidingTilePuzzleNode &amp; node); private: std::vector&lt;int&gt; m_state; std::unordered_map&lt;std::size_t, SlidingTilePuzzleNodeRowSelector&gt; m_row_map; std::size_t m_width; std::size_t m_height; std::size_t m_zero_tile_x; std::size_t m_zero_tile_y; // Let ...RowSelector access m_state: friend class SlidingTilePuzzleNodeRowSelector; // Check that a slide is possible: void checkOnSlideUp () const; void checkOnSlideDown () const; void checkOnSlideLeft () const; void checkOnSlideRight() const; inline void setZeroTileCoordinates(std::size_t x, std::size_t y); }; </code></pre> <p><strong>SlidingTilePuzzleNode.cpp</strong></p> <pre><code>#include "SlidingTilePuzzleNode.hpp" #include &lt;algorithm&gt; #include &lt;cmath&gt; #include &lt;iomanip&gt; #include &lt;ios&gt; #include &lt;iostream&gt; #include &lt;ostream&gt; #include &lt;string&gt; void SlidingTilePuzzleNode::checkOnSlideUp() const { if (m_zero_tile_y == 0) { ZeroTileOutsideException exception(std::string("'m_zero_tile_y == 0' upon slideUp")); throw exception; } } void SlidingTilePuzzleNode::checkOnSlideDown() const { if (m_zero_tile_y == m_height - 1) { ZeroTileOutsideException exception(std::string("'m_zero_tile_y == m_height - 1' upon slideDown")); throw exception; } } void SlidingTilePuzzleNode::checkOnSlideLeft() const { if (m_zero_tile_x == 0) { ZeroTileOutsideException exception( std::string("'m_zero_tile_x == 0' upon slideLeft")); throw exception; } } void SlidingTilePuzzleNode::checkOnSlideRight() const { if (m_zero_tile_x == m_width - 1) { ZeroTileOutsideException exception( std::string("'m_zero_tile_x == m_width - 1' upon slideRight")); throw exception; } } // Initial constructor building the solved slide puzzle: SlidingTilePuzzleNode::SlidingTilePuzzleNode(std::size_t width, std::size_t height) : m_width(width), m_height(height), m_zero_tile_x(width - 1), m_zero_tile_y(height - 1) { // Copy the state: m_state.resize(m_width * m_height); std::size_t n{}; std::generate(m_state.begin(), m_state.end(), [n = 1]() mutable { return n++; }); // Deal with the empty tile: m_state[width * height - 1] = 0; // Build the row index: for (std::size_t y = 0; y &lt; m_height; y++) { SlidingTilePuzzleNodeRowSelector row_selector(this, y * width); m_row_map[y] = row_selector; } } // Copy constructor. SlidingTilePuzzleNode::SlidingTilePuzzleNode(const SlidingTilePuzzleNode&amp; other) { // Copy the easy stuff. this-&gt;m_height = other.m_height; this-&gt;m_width = other.m_width; this-&gt;m_zero_tile_x = other.m_zero_tile_x; this-&gt;m_zero_tile_y = other.m_zero_tile_y; this-&gt;m_state = other.m_state; std::size_t y = 0; for (auto const&amp; entry : other.m_row_map) { SlidingTilePuzzleNodeRowSelector row_selector(this, y); this-&gt;m_row_map[entry.first] = row_selector; y += m_width; } } // Copy assignment. SlidingTilePuzzleNode&amp; SlidingTilePuzzleNode::operator=(const SlidingTilePuzzleNode&amp; other) { this-&gt;m_height = other.m_height; this-&gt;m_width = other.m_width; this-&gt;m_zero_tile_x = other.m_zero_tile_x; this-&gt;m_zero_tile_y = other.m_zero_tile_y; this-&gt;m_state = other.m_state; this-&gt;m_row_map = other.m_row_map; // Correct the map values to row selectors of this tile: for (auto&amp; entry : m_row_map) { SlidingTilePuzzleNodeRowSelector row_selector(this, entry.first); entry.second = row_selector; } return *this; } // Move assignment. SlidingTilePuzzleNode&amp; SlidingTilePuzzleNode::operator=(SlidingTilePuzzleNode&amp;&amp; other) { m_height = other.m_height; m_width = other.m_width; m_zero_tile_x = other.m_zero_tile_x; m_zero_tile_y = other.m_zero_tile_y; m_state = std::move(other.m_state); m_row_map = std::move(other.m_row_map); std::size_t y = 0; for (auto&amp; entry : m_row_map) { SlidingTilePuzzleNodeRowSelector row_selector(this, y); entry.second = row_selector; y += m_width; } return *this; } SlidingTilePuzzleNode::~SlidingTilePuzzleNode() = default; SlidingTilePuzzleNode SlidingTilePuzzleNode::slideUp() { checkOnSlideUp(); SlidingTilePuzzleNode node(*this); auto x2 = m_zero_tile_x; auto y2 = m_zero_tile_y - 1; std::swap(node[m_zero_tile_y][m_zero_tile_x], node[y2][x2]); node.setZeroTileCoordinates(x2, y2); return node; } SlidingTilePuzzleNode SlidingTilePuzzleNode::slideDown() { checkOnSlideDown(); SlidingTilePuzzleNode node(*this); auto x2 = m_zero_tile_x; auto y2 = m_zero_tile_y + 1; std::swap(node[m_zero_tile_y][m_zero_tile_x], node[y2][x2]); node.setZeroTileCoordinates(x2, y2); return node; } SlidingTilePuzzleNode SlidingTilePuzzleNode::slideLeft() { checkOnSlideLeft(); SlidingTilePuzzleNode node(*this); auto x2 = m_zero_tile_x - 1; auto y2 = m_zero_tile_y; std::swap(node[m_zero_tile_y][m_zero_tile_x], node[y2][x2]); node.setZeroTileCoordinates(x2, y2); return node; } SlidingTilePuzzleNode SlidingTilePuzzleNode::slideRight() { checkOnSlideRight(); SlidingTilePuzzleNode node(*this); auto x2 = m_zero_tile_x + 1; auto y2 = m_zero_tile_y; std::swap(node[m_zero_tile_y][m_zero_tile_x], node[y2][x2]); node.setZeroTileCoordinates(x2, y2); return node; } SlidingTilePuzzleNodeRowSelector::SlidingTilePuzzleNodeRowSelector( SlidingTilePuzzleNode* node, std::size_t start_index) : m_node(node), m_offset_index(start_index) { } int&amp; SlidingTilePuzzleNodeRowSelector::operator[](std::size_t x) { return m_node-&gt;m_state.at(m_offset_index + x); } SlidingTilePuzzleNodeRowSelector&amp; SlidingTilePuzzleNode::operator[](std::size_t y) { return m_row_map[y]; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, SlidingTilePuzzleNode&amp; node) { const auto max_tile_number = node.getHeight() * node.getWidth() - 1; const auto max_tile_number_length = static_cast&lt;std::size_t&gt;( std::floor(std::log10(max_tile_number)) + 1); for (std::size_t y = 0; y &lt; node.getHeight(); y++) { if (y &gt; 0) { out &lt;&lt; '\n'; } for (std::size_t x = 0; x &lt; node.getWidth(); x++) { if (x &gt; 0) { out &lt;&lt; " "; } out &lt;&lt; std::setfill(' ') &lt;&lt; std::setw(max_tile_number_length) &lt;&lt; node[y][x]; } } return out; } inline void SlidingTilePuzzleNode::setZeroTileCoordinates(std::size_t x, std::size_t y) { m_zero_tile_x = x; m_zero_tile_y = y; } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include "SlidingTilePuzzleNode.hpp" #include &lt;iostream&gt; #include &lt;sstream&gt; static SlidingTilePuzzleNode createSourceNode( std::size_t width, std::size_t height) { SlidingTilePuzzleNode node(width, height); int number = 1; for (int y = 0; y &lt; height; y++) { for (int x = 0; x &lt; width; x++) { node[y][x] = number++; } } node[node.getHeight() - 1][node.getWidth() - 1] = 0; return node; } int main() { SlidingTilePuzzleNode node(4, 4); std::string bar(11, '-'); try { while (true) { std::cout &lt;&lt; node &lt;&lt; "\n" &lt;&lt; bar &lt;&lt; '\n'; char choice = static_cast&lt;char&gt;(std::cin.get()); // Ignore all the leftover chars: std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); switch (choice) { case 'u': node = node.slideUp(); break; case 'd': node = node.slideDown(); break; case 'l': node = node.slideLeft(); break; case 'r': node = node.slideRight(); break; case 'q': return 0; } } } catch (ZeroTileOutsideException&amp; ex) { std::cerr &lt;&lt; "Can't move outside of the box.\n"; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T10:02:18.147", "Id": "412325", "Score": "0", "body": "`ZeroTileOutsideException exception(std::string(\"'m_zero_tile_y == m_height - 1' upon slideDown\"));` this line looks weird. Are you using MSVC? This is their non-standard extension that allows non-lvalues to be passed as lvalue-references. Perhaps you wanted to take string in the constructor by const reference?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T10:06:46.993", "Id": "412326", "Score": "1", "body": "@Incomputable Yes, I wrote this using Visual Studio 2017." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-15T00:54:54.980", "Id": "412968", "Score": "0", "body": "@coderodde Just use `ZeroTileOutsideException exception(\"'m_zero_tile_y == m_height - 1' upon slideDown\");`." } ]
[ { "body": "<p>Here are some suggestions that may help you improve your code.</p>\n\n<h2>Be careful with signed and unsigned</h2>\n\n<p>In a few places, the code compares an <code>int</code> <code>x</code> or 'y' with <code>std::size_t</code> values <code>width</code> and <code>height</code>. For consistency, it would be better to declare <code>x</code> and <code>y</code> also as <code>std::size_t</code>. Even better, see the next suggestion.</p>\n\n<h2>Eliminate unused code</h2>\n\n<p>The <code>createSourceNode</code> function is unused and can be eliminated. Code that isn't used doesn't need to be written or maintained, which leads to better overall code quality.</p>\n\n<h2>Write portable code</h2>\n\n<p>As noted in the comments:</p>\n\n<blockquote>\n <p>Are you using MSVC? This is their non-standard extension that allows non-lvalues to be passed as lvalue-references.</p>\n</blockquote>\n\n<p>This is very easy to fix by changing the constructor. Instead of this: </p>\n\n<blockquote>\n<pre><code>ZeroTileOutsideException(std::string&amp; error_message)\n</code></pre>\n</blockquote>\n\n<p>use this:</p>\n\n<pre><code>ZeroTileOutsideException(std::string error_message) \n</code></pre>\n\n<p>Now it complies with standards, and should still work just fine in MSVC. By avoiding non-portable extensions, you make your code easier to port and maintain for years to come.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>The variable <code>n</code> in the constructor for <code>SlidingTilePuzzleNode</code> is defined but never used. Since unused variables are a sign of poor code quality, you should seek to eliminate them. Your compiler is probably smart enough to warn you about such things if you know how to ask it to do so.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>Generally, this code does a good job of using <code>const</code>, but it should also be applied to the <code>ostream&lt;&lt;</code> operator as in:</p>\n\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const SlidingTilePuzzleNode&amp; node) \n</code></pre>\n\n<p>This will require some changes to the code implementing it, but really should be possible to print the node without altering it. That also leads directly to the next suggestion.</p>\n\n<h2>Provide <code>const</code> versions of access methods</h2>\n\n<p>In addtion to the two <code>operator[]</code> functions you already have, I'd suggest adding these:</p>\n\n<pre><code>int SlidingTilePuzzleNodeRowSelector::operator[](std::size_t x) const\n{\n return m_node-&gt;m_state.at(m_offset_index + x);\n}\n\nconst SlidingTilePuzzleNodeRowSelector&amp; SlidingTilePuzzleNode::operator[](std::size_t y) const\n{\n return m_row_map.at(y);\n}\n</code></pre>\n\n<p>This allows you to use the same handy notation in a <code>const</code>-correct way.</p>\n\n<h2>Rethink the class interface</h2>\n\n<p>It's generall a bad idea to provide direct access to internal class data structures, and especially bad in a public interface. The non-<code>const</code> versions of the functions mentioned above should be <code>private</code>, for instance. Another useful thing to do would be to make <code>SlidingTilePuzzleNodeRowSelector</code> a private class inside <code>SlidingTilePuzzleNode</code>. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-private\" rel=\"nofollow noreferrer\">C.9</a> for more detail on that principle.</p>\n\n<h2>Don't use an <code>exception</code> for unexceptional events</h2>\n\n<p>Users do all kinds of interesting things when interacting with computers, and in this case, it's not at all exceptional that a user would attempt an invalid move. For that reason, I would suggest instead that a return value from the various <code>slide</code> methods indicating success or failure would make more sense.</p>\n\n<h2>Check the logic</h2>\n\n<p>I think there's is a problem with the logic of the moves. If we start with this:</p>\n\n<pre><code> 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\n-----------\n</code></pre>\n\n<p>And then mov \"u\" (for Up), the reult is this:</p>\n\n<pre><code>u\n 5 6 7 4\n 1 2 3 8\n13 14 15 0\n 9 10 11 12\n-----------\n</code></pre>\n\n<p>That's not typically how <a href=\"https://en.wikipedia.org/wiki/Sliding_puzzle\" rel=\"nofollow noreferrer\">sliding puzzles</a> actually work. If yours is intended to work this way, a bit more documentation for the user or as comments in the code at least, might be needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T18:20:20.653", "Id": "232958", "ParentId": "213133", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T09:43:49.037", "Id": "213133", "Score": "5", "Tags": [ "c++", "console", "sliding-tile-puzzle" ], "Title": "Command line sliding tile puzzle in C++" }
213133
<p>I wanted to practice my programming skill and I started solving exercises from kata-logs site. The exercise:</p> <blockquote> <p>The game consists of 10 frames. In each frame the player has two rolls to knock down 10 pins. The score for the frame is the total number of pins knocked down, plus bonuses for strikes and spares.</p> <p>A spare is when the player knocks down all 10 pins in two rolls. The bonus for that frame is the number of pins knocked down by the next roll.</p> <p>A strike is when the player knocks down all 10 pins on his first roll. The frame is then completed with a single roll. The bonus for that frame is the value of the next two rolls.</p> <p>In the tenth frame a player who rolls a spare or strike is allowed to roll the extra balls to complete the frame. However no more than three balls can be rolled in tenth frame.</p> </blockquote> <p>My solution:</p> <pre><code>class Frame { private Optional&lt;Integer&gt; firstRole = Optional.empty(); private Optional&lt;Integer&gt; secondRole = Optional.empty(); private Optional&lt;Frame&gt; next = Optional.empty(); public void knock(int knockedPins) { if (secondRole.isPresent() &amp;&amp; firstRole.isPresent()) { if (!next.isPresent()) { Frame nextFrame = new Frame(); nextFrame.knock(knockedPins); next = Optional.of(nextFrame); return; } next.ifPresent(frame -&gt; frame.knock(knockedPins)); return; } if (firstRole.isPresent()) { secondRole = Optional.of(knockedPins); return; } if (knockedPins == 10) { firstRole = Optional.of(knockedPins); secondRole = Optional.of(0); next = Optional.of(new Frame()); return; } firstRole = Optional.of(knockedPins); } public int finishedFramesCount() { if (!next.isPresent()) { if (frameFinished()) { return 1; } return 0; } else { return 1 + next.get().finishedFramesCount(); } } public int points() { int knockedPins = firstRole.orElse(0) + secondRole.orElse(0); int bonusPointsForSpare = isSpare() ? next.map(Frame::firstRoleScore).orElse(0) : 0; int bonusPointsForStrike = isStrike() ? next.map(frame -&gt; frame.firstRoleScore() + frame.secondRoleScore()).orElse(0) : 0; int totalResult = knockedPins + bonusPointsForStrike + bonusPointsForSpare; return next.map(frame -&gt; totalResult + frame.points()).orElse(totalResult); } public Frame lastFrame() { if (!next.isPresent()) { return this; } else { return next.get().lastFrame(); } } public boolean isSpare() { return secondRole.isPresent() &amp;&amp; secondRole.get() &gt; 0 &amp;&amp; firstRole.get() + secondRole.get() == 10; } public boolean isStrike() { return firstRole.isPresent() &amp;&amp; firstRole.get() == 10; } private boolean frameFinished() { return firstRole.isPresent() &amp;&amp; secondRole.isPresent(); } private int firstRoleScore() { return firstRole.orElse(0); } private int secondRoleScore() { return secondRole.orElse(0); } } class StandardBowlingGame implements BowlingGame { private final Frame frame; private int bonusRole; public StandardBowlingGame(Frame frame) { this.frame = frame; } @Override public void roll(int knockedPins) { if (frame.finishedFramesCount() == 10) { if (frame.lastFrame().isStrike() || frame.lastFrame().isSpare()) { bonusRole = knockedPins; return; } throw new IllegalStateException("Game is over"); } frame.knock(knockedPins); } @Override public int score() { return frame.points() + bonusRole; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T11:13:50.963", "Id": "412331", "Score": "0", "body": "this is only part of the code. where is the engine that makes to rolls? where is the `BowlingGame` interface? is it given as part of the question or is it your design?" } ]
[ { "body": "<p>I read the question and understood that <code>BowlingGame</code> interface is given.\nRegardless, your design is overly complex and breaks the SOLID Design Principles (which I understood are part of the purpuses).</p>\n\n<ol>\n<li><p>The <code>Frame</code> class should be concerned about the logic of one frame <strong>and one frame only</strong>.<br>\ninstead, it is also the collection that holds all frames, and it also decides on the implementation of that collection - a user-defined linked list (re-inventing the wheel, since the JDK has a ready made implementation), the class is also responsible for deciding when and how to instantiate a new frame, and even when the game is finished (deciding if it is the last frame). All of these topics are outside of the responsibilities of a single Frame.<br>\nBecause of that, the Game class has indeed really very little to do besides delegete all logic to the frame. </p></li>\n<li><p>Taking linked list as the collection seems unnecessary here, given that the number of frames is constant. in such cases (length is known in advance and it is a relatively small number) it would be better to use a plain array <code>Frame[] game = new Frame[10];</code> that tells in one line how many frames are in one game. (instead of using recursion, really? for such a simple task use recursion??) and of course, declaring and manipulating the array is the responsibility of the <code>Game</code> class.<br>\n...and while we are at the point, there are (usually) two rolls per frame, so why not make that into an array as well instead of two separate variables? the advantages of using an array over two separate variables: a frame gets a new <code>roll()</code> and it assigns the new roll to the next empty place in the array (instead of asking on a seperate variable) and hence the last frame might be initialised with an array of length==3.</p></li>\n<li><p>Regarding the use of <code>Optional</code>: it was introduced to Java 8 mainly as a solution to <code>NullPointerException</code> that gets thrown when the developer forget to explicitly check for this condition. in most cases, it occurs in method chaining such as <code>map.get(key).toString()</code>. since the exception is unchecked and thus gets thrown at run time, there was no way for the compiler to check this and it was a common error. so while it is feasible, its really isn't a good use case. I would go with a primitive <code>int</code> that is initialized to a negative value. to avoid <a href=\"https://codeburst.io/software-anti-patterns-magic-numbers-7bc484f40544\" rel=\"nofollow noreferrer\">magic numbers anti pattern</a> you can define and use a constant <code>public static final int EMPTY_ROLL = -1;</code> </p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T11:48:39.860", "Id": "213138", "ParentId": "213136", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T10:12:33.527", "Id": "213136", "Score": "0", "Tags": [ "java" ], "Title": "Bowling Game Kata" }
213136
<p>These two functions act on a stack, an array of integers (whose first element is the top of the stack, LIFO).</p> <p>The first function retrieves the first element and puts it at the end. The other is the opposite.</p> <p>I would like to combine these two functions into only one function, if possible. (I have a constraint, 25 lines maximum)</p> <pre><code>int *reverse(int value, int size, int *stack) { int value; int i; int *previous; value = *stack; previous = stack; if (!(stack = (int*)malloc(sizeof(int) * size))) return (NULL); i = 1; while (i &lt; size) { stack[i - 1] = previous[i]; i++; } stack[i - 1] = value; free(previous); return (stack); } int *sv_reverse(int value, int size, int *stack) { int value; int i; int *previous; value = stack[size - 1]; previous = stack; if (!(stack = (int*)malloc(sizeof(int) * size))) return (NULL); *stack = value; i = 1; while (i &lt; size) { stack[i] = previous[i + 1]; i++; } free(previous); return (stack); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T16:26:18.510", "Id": "412339", "Score": "1", "body": "ken, What do you expect `value = stack[size - 1];` to do when `size == 0`?" } ]
[ { "body": "<p>I would consider an approach were you think of the array as a circular buffer, with the top of the stack being position 0. Each of your operations becomes a rotation. One position clockwise and one anticlockwise. Or even both clockwise (or anticlockwise), one a single position rotation and one a size-1 rotations.</p>\n\n<p>If you can change the data structure so that the top of the stack can be any position in the circular buffer the these rotations become trivial, just set the top of value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T17:01:59.990", "Id": "213146", "ParentId": "213139", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T12:35:34.763", "Id": "213139", "Score": "0", "Tags": [ "c", "array" ], "Title": "Two functions that move array elements" }
213139
<p>I quite often plot graphs looking at how some property or function varies with different parameters. Normally, I find the analysis code can be written fairly succinctly and separated into a suitable number of functions. However, when I come to plot the graphs my code tends to come unmanageably long.</p> <p>Below is a basic example, while the code for generating the graphic is modest by my standards I hope it highlights the issue. There will often be several more <code>if</code> statements for adding different things to a specific axis.</p> <p>Do you have any pointers for keeping plot generation succinct, or is it inevitable when building custom plots?</p> <pre><code>def get_data(x, order, scale): '''Generates data for this example.''' y = scale * (x**order) return y # generate the example data orders = [2, 2.2, 2.3] scales = [1, 2] scale_grid, order_grid = np.meshgrid(scales, orders) parameters = list(zip(order_grid.ravel(), scale_grid.ravel())) my_x = np.arange(0, 10.1, 0.1) my_ys = [] for ps in parameters: my_ys.append(get_data(my_x, *ps)) ############################################### # generate the graph my_colors = {0:'r', 1:'b', 2:'g'} fig, ax_rows = plt.subplots(3, ncols=2) for i, ax_row in enumerate(ax_rows): # plot the graphs ax_row[0].plot(my_x, my_ys[i*2], lw=2, color=my_colors[i]) ax_row[1].plot(my_x, my_ys[i*2+1], lw=2, color=my_colors[i]) # format the axes ax_row[0].set_ylabel('y (unit)') plt.setp(ax_row[1].get_yticklabels(), visible=False) for ax in ax_row: ax.set_ylim(0, 500) ax.set_xlim(0, 10) if i!=2: plt.setp(ax.get_xticklabels(), visible=False) if i==2: ax.set_xlabel('x (unit)') # add the text displaying parameters ax_row[0].text(0.03, 0.95,'Scale: {0:.2f}\nOrder: {1:.2f}'.format(parameters[i*2][1], parameters[i*2][0]), transform=ax_row[0].transAxes, verticalalignment='top') ax_row[1].text(0.03, 0.95,'Scale: {0:.2f}\nOrder: {1:.2f}'.format(parameters[i*2+1][1], parameters[i*2+1][0]), transform=ax_row[1].transAxes, verticalalignment='top') fig.set_size_inches(5, 5) </code></pre> <p>The output graphic is here. <a href="https://i.stack.imgur.com/XWTdc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XWTdc.png" alt="Example multi-panel graphic"></a></p>
[]
[ { "body": "<p>I'm not a guru of matplotlib but I'll show how I would approach the problem. Maybe you could get something useful out of it. Also, I'm gonna review all the code, not only the plotting part. </p>\n\n<p><strong><code>get_data</code>:</strong></p>\n\n<blockquote>\n<pre><code>def get_data(x, order, scale):\n '''Generates data for this example.'''\n\n y = scale * (x**order)\n\n return y\n</code></pre>\n</blockquote>\n\n<ul>\n<li>For docstrings use <a href=\"https://www.python.org/dev/peps/pep-0008/#string-quotes\" rel=\"nofollow noreferrer\">triple double quotes</a>: <code>\"\"\"Your docstring\"\"\"</code>. </li>\n<li>There is no need to put so many <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">blank lines</a> inside such a small function. </li>\n<li>Exponentiation has a <a href=\"https://docs.python.org/reference/expressions.html#operator-precedence\" rel=\"nofollow noreferrer\">higher precedence</a> than multiplication, that means you can remove parentheses: <code>scale * x ** order</code>. </li>\n<li>Variable <code>y</code> is redundant, just write: <code>return scale * x ** order</code>. </li>\n<li>You can use <a href=\"https://docs.python.org/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> to help readers understand what types of data your function operates with. Also some IDEs are capable of analyzing them and will highlight places where there are inconsistencies between what is supplied to a function and what that function expected to get.</li>\n</ul>\n\n<p>That gives us:</p>\n\n<pre><code>def get_data(x: np.ndarray,\n order: float,\n scale: float) -&gt; np.ndarray:\n \"\"\"Generates data for this example.\"\"\"\n return scale * x ** order\n</code></pre>\n\n<hr>\n\n<p><strong>Generating example data:</strong></p>\n\n<blockquote>\n<pre><code># generate the example data\n\norders = [2, 2.2, 2.3]\nscales = [1, 2]\n\nscale_grid, order_grid = np.meshgrid(scales, orders)\n\nparameters = list(zip(order_grid.ravel(), scale_grid.ravel()))\n\nmy_x = np.arange(0, 10.1, 0.1)\nmy_ys = []\n\nfor ps in parameters:\n\n my_ys.append(get_data(my_x, *ps))\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Obtaining <code>parameters</code> by using <code>np.meshgrid</code>, <code>np.ravel</code> and <code>zip</code> doesn't look good. <code>np.meshgrid</code> will generate 2D arrays which is unnecessary. You can use <a href=\"https://docs.python.org/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product</code></a> to get a Cartesian product of input parameters: <code>list(itertools.product(orders, scales))</code>.</li>\n<li><p>Docs for <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html\" rel=\"nofollow noreferrer\"><code>np.arange</code></a> warn: </p>\n\n<blockquote>\n <p>When using a non-integer step, such as 0.1, the results will often not\n be consistent. It is better to use <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html#numpy.linspace\" rel=\"nofollow noreferrer\"><code>numpy.linspace</code></a> for these cases.</p>\n</blockquote>\n\n<p>So, instead you should have <code>my_x = np.linspace(0, 10, 101)</code>.</p></li>\n<li>There is no need to have blank line after the for-loop first line.</li>\n<li>We don't need to keep all the data in the <code>my_ys</code>. We can calculate it on the fly (see below). </li>\n</ul>\n\n<p>That gives us:</p>\n\n<pre><code>import itertools\nfrom typing import Iterable, Iterator, Tuple\n\n\ndef get_my_ys(x: np.ndarray,\n parameters: Iterable[Tuple[float, float]]\n ) -&gt; Iterator[np.ndarray]:\n \"\"\"Yields data for different parameters\"\"\"\n for order, scale in parameters:\n yield get_data(x, order=order, scale=scale)\n\n...\n\norders = [2, 2.2, 2.3]\nscales = [1, 2]\nparameters = list(itertools.product(orders, scales))\n\nmy_x = np.linspace(0, 10, 101)\nmy_ys = get_my_ys(my_x, parameters)\n</code></pre>\n\n<p>Probably, you would want to extend it later for a variable number of parameters.</p>\n\n<hr>\n\n<p><strong>Generating the graph:</strong> </p>\n\n<ul>\n<li>First of all, why is <code>my_colors</code> a dict (<code>my_colors = {0:'r', 1:'b', 2:'g'}</code>)? When seeing a dict which keys are 0, 1, 2, ... it makes me think that it probably should be a list instead. </li>\n<li><p>In <code>fig, ax_rows = plt.subplots(3, ncols=2)</code> it looks inconsistent that you specify keyword <code>ncols</code> but not <code>nrows</code>. <code>3</code> and <code>2</code> are, in fact, lengths of parameters <code>orders</code> and <code>scales</code>, you should tie them together. And, according to <a href=\"https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html\" rel=\"nofollow noreferrer\">docs</a> you could also specify <code>sharex</code> and <code>sharey</code> as <code>True</code>/<code>'all'</code>. So, you wouldn't have to write: </p>\n\n<blockquote>\n<pre><code>for i, ax_row in enumerate(ax_rows):\n ...\n for ax in ax_row:\n ax.set_ylim(0, 500)\n ax.set_xlim(0, 10)\n</code></pre>\n</blockquote>\n\n<p>for each subplot.</p></li>\n<li><blockquote>\n<pre><code># plot the graphs\nax_row[0].plot(my_x, my_ys[i*2], lw=2, color=my_colors[i])\nax_row[1].plot(my_x, my_ys[i*2+1], lw=2, color=my_colors[i])\n</code></pre>\n</blockquote>\n\n<p>Several issues here. First of all, if you change the number of parameters in <code>scale</code> and <code>order</code>, this won't work as intended. Next, there is a code duplication on these two lines. And this indexing of <code>my_ys</code> just doesn't feel right. Ideally, this should look like:</p>\n\n<pre><code>for ax, y, color in zip(fig.axes, my_ys, colors):\n ax.plot(x, y, lw=linewidth, color=color)\n</code></pre>\n\n<p>Note the <a href=\"https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.axes\" rel=\"nofollow noreferrer\"><code>fig.axes</code></a>. This will give you a list of all axes in the figure.</p></li>\n<li><p>Again, this <code>plt.setp(ax_row[1].get_yticklabels(), visible=False)</code> will remove labels only in the second column. But what if you have more parameters and therefore more columns? Actually, we don't need these lines if you are going to use <code>sharex</code> and <code>sharey</code> when creating the figure. It will take care of them automatically.</p></li>\n<li><p>Instead of checking the indices of the subplots to add labels for x-axis, I suggest simply iterate over the last row of <code>ax_rows</code> returned from <code>plt.subplots</code>:</p>\n\n<pre><code>for ax in ax_rows[-1]:\n ax.set_xlabel(xlabel)\n</code></pre>\n\n<p>Though, we should be careful with the returned type of <code>ax_rows</code>, because, as <a href=\"https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html\" rel=\"nofollow noreferrer\">docs</a> say, it</p>\n\n<blockquote>\n <p>can be either a single Axes object or an array of Axes objects</p>\n</blockquote>\n\n<p>In order to get all the time an array, we should specify <code>squeeze=False</code> in the <code>plt.subplots</code> call.</p></li>\n<li><blockquote>\n<pre><code>ax_row[0].text(0.03, 0.95,'Scale: {0:.2f}\\nOrder: \n {1:.2f}'.format(parameters[i*2][1],\n parameters[i*2][0]), \n transform=ax_row[0].transAxes, \n verticalalignment='top')\nax_row[1].text(0.03, 0.95,'Scale: {0:.2f}\\nOrder: \n {1:.2f}'.format(parameters[i*2+1][1], \n parameters[i*2+1][0]), \n transform=ax_row[1].transAxes, \n verticalalignment='top')\n</code></pre>\n</blockquote>\n\n<p>Same problems here: code duplication, clumsy indexing, and it won't work if you add more input parameters in <code>orders</code> or <code>scales</code>. Here is how I suggest to generate labels:</p>\n\n<pre><code>label_template = 'Scale: {1:.2f}\\nOrder: {0:.2f}'\nlabels = itertools.starmap(label_template.format, parameters)\n</code></pre>\n\n<p>Here I use <a href=\"https://docs.python.org/library/itertools.html#itertools.starmap\" rel=\"nofollow noreferrer\"><code>itertools.starmap</code></a> to supply tuples of parameters to the <code>str.format</code> method of the <code>label_template</code>. </p>\n\n<p>In the end, plotting would look like something like this: </p>\n\n<pre><code>for ax, y, label, color in zip(fig.axes, my_ys, labels, colors):\n ax.plot(x, y, lw=linewidth, color=color)\n ax.text(s=label,\n transform=ax.transAxes,\n **text_properties)\n</code></pre>\n\n<p>where <code>text_properties</code> is a dict that would keep all the properties like positions, alignment, etc.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Revised code:</strong> </p>\n\n<pre><code>import itertools\nfrom functools import partial\nfrom typing import (Any,\n Dict,\n Iterable,\n Iterator,\n List,\n Tuple)\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nTEXT_PROPERTIES = dict(x=0.03,\n y=0.95,\n verticalalignment='top')\n\n\ndef main():\n my_colors = ['r', 'b', 'g']\n orders = [2, 2.2, 2.3]\n scales = [1, 2]\n\n parameters = list(itertools.product(orders, scales))\n\n my_x = np.linspace(0, 10, 101)\n my_ys = get_my_ys(my_x, parameters)\n\n label_template = 'Scale: {1:.2f}\\nOrder: {0:.2f}'\n labels = itertools.starmap(label_template.format, parameters)\n colors = replicate_items(my_colors, times=len(scales))\n\n plot(x=my_x,\n ys=my_ys,\n nrows=len(orders),\n ncols=len(scales),\n labels=labels,\n colors=colors,\n xlim=[0, 10],\n ylim=[0, 500],\n xlabel='x (unit)',\n ylabel='y (unit)')\n plt.show()\n\n\ndef get_my_ys(x: np.ndarray,\n parameters: Iterable[Tuple[float, float]]\n ) -&gt; Iterator[np.ndarray]:\n \"\"\"Yields data for different parameters\"\"\"\n for order, scale in parameters:\n yield get_data(x, order=order, scale=scale)\n\n\ndef get_data(x: np.ndarray,\n order: float,\n scale: float) -&gt; np.ndarray:\n \"\"\"Generates data for this example.\"\"\"\n return scale * x ** order\n\n\ndef replicate_items(seq: Iterable[Any],\n times: int) -&gt; Iterable[Any]:\n \"\"\"replicate_items('ABC', 2) --&gt; A A B B C C\"\"\"\n repeat = partial(itertools.repeat, times=times)\n repetitions = map(repeat, seq)\n yield from itertools.chain.from_iterable(repetitions)\n\n\ndef plot(x: np.ndarray,\n ys: Iterable[np.ndarray],\n nrows: int,\n ncols: int,\n labels: Iterable[str],\n colors: Iterable[str],\n xlim: List[float],\n ylim: List[float],\n xlabel: str,\n ylabel: str,\n text_properties: Dict[str, Any] = None,\n linewidth: float = 2,\n fig_size: Tuple[float, float] = (5, 5)) -&gt; plt.Figure:\n \"\"\"TODO: add docstring\"\"\"\n if text_properties is None:\n text_properties = TEXT_PROPERTIES\n fig, ax_rows = plt.subplots(nrows=nrows,\n ncols=ncols,\n sharex='all',\n sharey='all',\n squeeze=False)\n fig.set_size_inches(fig_size)\n plt.xlim(xlim)\n plt.ylim(ylim)\n\n for ax, y, label, color in zip(fig.axes, ys, labels, colors):\n ax.plot(x, y, lw=linewidth, color=color)\n ax.text(s=label,\n transform=ax.transAxes,\n **text_properties)\n for ax in ax_rows[:, 0]:\n ax.set_ylabel(ylabel)\n for ax in ax_rows[-1]:\n ax.set_xlabel(xlabel)\n\n return fig\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>I'm sure that there are other things that could be improved. But this should get you going. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T11:41:01.510", "Id": "412737", "Score": "0", "body": "Hi Georgy, \n\nThanks for your comprehensive answer! I shall review when I have some time and accept it,\n\nThere seems a lot of useful content here and a lot I can clearly do too improve! \n\nOne question you had: `my_colors` is a dictionary because usually I will have a key for each row (e.g., 'Small', 'Medium', 'Large')." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T10:53:18.823", "Id": "213366", "ParentId": "213140", "Score": "1" } } ]
{ "AcceptedAnswerId": "213366", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T12:41:18.243", "Id": "213140", "Score": "5", "Tags": [ "python", "numpy", "matplotlib", "data-visualization" ], "Title": "Code to plot graphs with multiple panels efficiently" }
213140
<p>The task:</p> <blockquote> <p>Given a string and a set of characters, return the shortest substring containing all the characters in the set.</p> <p>For example, given the string "figehaeci" and the set of characters {a, e, i}, you should return "aeci".</p> <p>If there is no substring containing all the characters in the set, return null.</p> </blockquote> <p>My solution:</p> <pre><code>// init const originalStr = 'figehaeci'; const set = Object.freeze(['a', 'e', 'i']); // helpers const isEmpty = s =&gt; s.length === 0; const copy = s =&gt; s.slice(0); const getNextResult = (currRes, endRes) =&gt; { if (!endRes || isEmpty(endRes)) { return currRes; } return currRes.length &lt; endRes.length ? currRes : endRes; }; // main const contains = (str, endResult) =&gt; { const currStr = str; const currSet = copy(set); let pushIt; const currResult = currStr .split('') .reduce((acc, item) =&gt; { if (pushIt === false) { return acc; } if (currSet.includes(item)) { currSet.splice(currSet.indexOf(item), 1); pushIt = true; } if (pushIt) { acc.push(item); } if (isEmpty(currSet)) { pushIt = false; } return acc; }, []); const nextStr = str .split('') .slice(1) .join(''); // exit case if (isEmpty(nextStr)) { return endResult ? endResult.join('') : null; } // recursive case const nextResult = isEmpty(currSet) ? getNextResult(currResult, endResult) : endResult; return contains(nextStr, nextResult); } // result console.log(contains(originalStr, null)); </code></pre> <p>I don't like the many <code>if</code>s and the flag (<code>pushIt</code>). Do you know how to get rid of them without sacrificing readability and maintainability? </p> <p>Doesn't have to be in functional programming style. Just looking for an elegant solution.</p>
[]
[ { "body": "<p>I couldn't remove the <code>if</code>s and the flag , so i thought about a diffrent aproach, </p>\n\n<p>Using regular expressions seem more reasonable aproach, you can have a function that returns all the possible combinations of the letters in the array, create regular expressions from the resulting combinations and match against the <code>orignalStr</code>, </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function perm(xs) {\n let ret = [];\n for (let i = 0; i &lt; xs.length; i = i + 1) {\n let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));\n\n if (!rest.length)\n ret.push([xs[i]]);\n else\n for (let j = 0; j &lt; rest.length; j = j + 1)\n ret.push([xs[i]].concat(rest[j]));\n }\n return ret;\n}\n\nconst originalStr = 'figehaeci', letters = ['a', 'e', 'i'];\nlet result = originalStr;\n\nconst combinations = perm(letters).map(combo =&gt; combo.join('.*?'));\n\n// combinations : [\"a.*?e.*?i\",\"a.*?i.*?e\",\"e.*?a.*?i\",\"e.*?i.*?a\",\"i.*?a.*?e\",\"i.*?e.*?a\"]\n\ncombinations.forEach(combo =&gt; {\n const exp = new RegExp(combo, 'g');\n const matches = originalStr.match(exp) || [];\n\n matches.forEach(match =&gt; {\n if (match.length &lt;= result.length)\n result = match;\n });\n});\n\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The code you posted returns only one value if there's more substrings containing those letters, here's a tweak to store all possible shortest combinations in an array :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function perm(xs) {\n let ret = [];\n for (let i = 0; i &lt; xs.length; i = i + 1) {\n let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));\n\n if (!rest.length)\n ret.push([xs[i]]);\n else\n for (let j = 0; j &lt; rest.length; j = j + 1)\n ret.push([xs[i]].concat(rest[j]));\n }\n return ret;\n}\n\nconst originalStr = 'figehaecizaexi', letters = ['a', 'e', 'i'];\nlet shortestLength = originalStr.length, result = [];\n\nconst combinations = perm(letters).map(combo =&gt; combo.join('.*?'));\n\n// combinations : [\"a.*?e.*?i\",\"a.*?i.*?e\",\"e.*?a.*?i\",\"e.*?i.*?a\",\"i.*?a.*?e\",\"i.*?e.*?a\"]\n\ncombinations.forEach(combo =&gt; {\n const exp = new RegExp(combo, 'g');\n const matches = originalStr.match(exp) || [];\n\n matches.forEach(match =&gt; {\n if (match.length &lt; shortestLength) {\n shortestLength = match.length;\n result = [match];\n }\n if (match.length === shortestLength) {\n result.push(match);\n }\n });\n});\n\nconst deduped = [...new Set(result)];\n\nconsole.log(deduped);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T10:18:43.920", "Id": "412371", "Score": "0", "body": "I haven't thought about this approach. Really interesting!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T21:21:28.587", "Id": "213157", "ParentId": "213145", "Score": "3" } }, { "body": "<h1>Too complex</h1>\n<p>Your complexity is very high. My guess is between <span class=\"math-container\">\\$O(n^2)\\$</span> and <span class=\"math-container\">\\$O(n^3)\\$</span>. I can think of a <span class=\"math-container\">\\$O(nLog(n))\\$</span> solutions and there is likely a <span class=\"math-container\">\\$O(n)\\$</span> solution.</p>\n<p>You are very wasteful of CPU cycles, some example follow...</p>\n<p>String don't need to be arrays to manipulate.</p>\n<pre><code>const nextStr = str.split('').slice(1).join(''); // cost O(3n-2) n = str.length\n// Can be O(n-1)\nconst nextStr = str.substring(1);\n</code></pre>\n<p>Don't add code not needed.</p>\n<pre><code>currStr = str // cost O(n) n = str.length\n// Can be O(0) as you don't need to copy it\n</code></pre>\n<p>Don't repeat operations.</p>\n<pre><code>if (currSet.includes(item)) { currSet.splice(currSet.indexOf(item), 1) // cost O(2n) \n // n = currSet.length\n// Can be O(n)\nconst idx = currSet.indexOf(item);\nif (idx &gt; -1) { currSet.splice(idx, 1) }\n</code></pre>\n<h3>Strings</h3>\n<p>When you copy a string the computer must step over every character. Unlike many languages in JS strings are not passed by reference, they are copied, thus passing a string to a function will have a complexity cost that matches the string length. You should avoid making copies of strings whenever you can.</p>\n<h3>Fast search with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a></h3>\n<p>Use Sets and Maps. They create hash tables (cost <span class=\"math-container\">\\$O(n)\\$</span>) that make finding items very fast <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n<h3>Optimise and use information you have</h3>\n<p>Check for opportunities to exit the function early. Eg if the remain characters to search is less than the number of characters in the set there is no need to search. If you find a match that is the same length as the set you dont need to search further. If the set is longer than the string to search you don't need to do the search.</p>\n<hr />\n<h2>Use appropriate language features.</h2>\n<ul>\n<li>Copy arrays with <code>[...array]</code> not <code>array.slice(0)</code></li>\n<li>Iterate strings without splitting <code>for(const char of &quot;A string of chars&quot;) {...</code></li>\n</ul>\n<h2>Example</h2>\n<p>This uses Set to make locating matching character quick. If a match is found another set is used to count off characters as they are found. This gives you a complexity of around <span class=\"math-container\">\\$O(nLog(n))\\$</span></p>\n<p>It returns an empty string if nothing is found and it avoids copying string.</p>\n<p>I have a feeling that there is an <span class=\"math-container\">\\$O(n)\\$</span> solution but your question does not clearly define the problem and thus I will not invest any more time as it may all be for naught.</p>\n<pre><code>function shortestSubStrContaining(str, chars){\n const charSet = new Set(chars);\n if (str.length &lt; chars.length) { return &quot;&quot; }\n var i = 0, start, minSize = str.length;\n done: while (i &lt; str.length) {\n if (charSet.has(str[i])) {\n const check = new Set(chars);\n check.delete(str[i]);\n let j = i + 1;\n while (j &lt; str.length) {\n if (check.has(str[j])) {\n check.delete(str[j]);\n if (check.size === 0) {\n if (j - i &lt; minSize) {\n minSize = j - i + 1;\n start = i;\n if (minSize === chars.length || str.length - (i + 1) &lt; minSize ) { \n break done;\n }\n }\n }\n }\n j++\n }\n }\n i++;\n if (str.length - i &lt; chars.length) { break }\n }\n return str.substring(start, start + minSize); // if start undefined will return &quot;&quot; \n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T08:10:09.380", "Id": "412356", "Score": "0", "body": "You opened my eyes. I wish I could upvote more than once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T09:20:31.447", "Id": "412362", "Score": "0", "body": "What is `done` exactly doing? How do you call it? Never seen that before `done: while (i < str.length) {`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T09:54:44.347", "Id": "412367", "Score": "0", "body": "I found it: Labled statement https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T10:17:46.050", "Id": "412370", "Score": "0", "body": "There are some inefficiency in my code, I totally agree with you. But how would you rate the readability of your code in comparison to mine?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:13:47.490", "Id": "412381", "Score": "0", "body": "@thadeuszlay You have a function called `contains` that gives nothing away. The helper functions `copy`(copy what?), `isEmpty` (is what empty) and `getNextResult` (get next result for what) are isolated and outside the calling function and also give no clue as to what they are for and why. If I found that in a sea of code I would be left guessing. If I found `shortestSubStrContaining(str, chars){` I would not have to read another line to know what it does. Readability is how an experienced proficient coder outside the problem sees the code, not the author" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:36:18.590", "Id": "412383", "Score": "0", "body": "I think, I understand what you mean. However, I also get the impression that deep nested code is also not the best practice and detrimental to readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T15:15:04.817", "Id": "412398", "Score": "0", "body": "@thadeuszlay The inner loop could be a function defined at the top of the function. I put the limit of indentation such that its no more than half the page width, or that the functions functional length is more than one page long. I use 4 space tabs rather than 2 space to be clear. Where these limits are set is subjective, but generally being able to see the whole function within one page without scrolling means reading the code does not require interruption from UI manipulation." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T04:25:16.843", "Id": "213167", "ParentId": "213145", "Score": "3" } } ]
{ "AcceptedAnswerId": "213167", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T17:01:28.010", "Id": "213145", "Score": "4", "Tags": [ "javascript", "functional-programming" ], "Title": "Return the shortest substring containing all the characters in the set" }
213145
<p>Let <span class="math-container">\$\mathcal{C} = \{ C_1, \dots, C_n \}\$</span> bet a set of <span class="math-container">\$n\$</span> different countries. We associate with each country <span class="math-container">\$C_i\$</span> with its potential <span class="math-container">\$P_i\$</span>. We choose a specific country <span class="math-container">\$C_e\$</span> in <span class="math-container">\$\mathcal{C}\$</span>. The battle operator <span class="math-container">\$B\$</span> is given as <span class="math-container">$$ B(C_i, C_j) = \arg\max_{c \in \{ C_i, C_j \}} P_c, $$</span> or, informally, it returns the stronger country among <span class="math-container">\$\{C_i, C_j\}\$</span>, and its potential will reduce to <span class="math-container">\$\vert P_i - P_j \vert\$</span>. We wish to compute such a sequence of battles that the remaining country has minimal potential, which would improve the probability of <span class="math-container">\$C_e\$</span> winning the entire war.</p> <p>Below, there is my attempt and the algorithm runs in <span class="math-container">\$\mathcal{O}(n \log n)\$</span> time:</p> <p><strong>WarScheduler.java</strong></p> <pre><code>package net.coderodde.fun; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.PriorityQueue; import java.util.Queue; /** * This class implements a war scheduling algorithm. In each iteration, two * weakest countries are selected, after which the two battle. The weaker of the * two cease to exist, but the potential of the winner country reduces by the * potential of the weaker one before the battle. This iteration continues until * only two countries remain: the expected winner (chosen prior the war) and the * country that survived. * * @author Rodion "rodde" Efremov * @version 1.6 (Feb 9, 2019) */ public final class WarScheduler { public static final class Schedule { public final List&lt;Battle&gt; battles; public final Country remainingCountry; public Schedule(List&lt;Battle&gt; battles, Country remainingCountry) { this.battles = new ArrayList&lt;&gt;(Objects.requireNonNull(battles)); this.remainingCountry = remainingCountry; } } public Schedule schedule(List&lt;Country&gt; countries, Country expectedWinner) { List&lt;Battle&gt; battles = new ArrayList&lt;&gt;(); Queue&lt;Country&gt; queue = new PriorityQueue&lt;&gt;((c1, c2) -&gt; Float.compare(c2.getPotential(), c1.getPotential())); queue.addAll(countries); queue.remove(expectedWinner); while (queue.size() &gt; 1) { Country stronger = queue.remove(); Country weaker = queue.remove(); Battle battle = new Battle(stronger, weaker); battles.add(battle); Country winner = battle.battle(); queue.add(winner); } return new Schedule(battles, queue.remove()); } } </code></pre> <p><strong>Country.java</strong></p> <pre><code>package net.coderodde.fun; import java.util.Objects; /** * This class describes a country. * * @author Rodion "rodde" Efremov * @version 1.6 (Feb 9, 2019) */ public class Country { private final String name; private final float potential; public Country(String name, float potential) { this.name = Objects.requireNonNull(name, "The country name is null."); this.potential = potential; } public String getName() { return name; } public float getPotential() { return potential; } @Override public String toString() { return String.format("[%s, potential=%f]", name, potential); } } </code></pre> <p><strong>Battle.java</strong></p> <pre><code>package net.coderodde.fun; /** * * @author rodde */ public final class Battle { private final Country winner; private final Country loser; public Battle(Country country1, Country country2) { if (country1.getPotential() &gt; country2.getPotential()) { winner = country1; loser = country2; } else { winner = country2; loser = country1; } } public Country getWinner() { return winner; } public Country getLoser() { return loser; } public Country battle() { float potentialDifference = winner.getPotential() - loser.getPotential(); return new Country(winner.getName(), potentialDifference); } @Override public String toString() { return String.format("[%s(%f) &gt; %s(%f)] -&gt; %s(%f)", winner.getName(), winner.getPotential(), loser.getName(), loser.getPotential(), battle().getName(), battle().getPotential()); } } </code></pre> <p><strong>Main.java</strong></p> <pre><code>package net.coderodde.fun; import java.util.Arrays; import java.util.List; /** * Implements a demonstration of a war scheduling algorithm. * * @author Rodion "rodde" Efremov * @version 1.6 (Feb 9, 2019) */ public class Main { public static void main(String[] args) { Country expectedWinner = new Country("UK", 16.5f); List&lt;Country&gt; countries = Arrays.asList(new Country("France", 10.0f), new Country("Germany", 14.0f), new Country("Finland", 3.5f), expectedWinner, new Country("Russia", 27.0f), new Country("US", 33.5f)); WarScheduler.Schedule schedule = new WarScheduler() .schedule(countries, expectedWinner); int lineNumber = 1; for (Battle battle : schedule.battles) { System.out.println(lineNumber++ + ": " + battle); } System.out.println("Expected winner: " + expectedWinner); System.out.println("Actual winner: " + new Battle(schedule.remainingCountry, expectedWinner)); } } </code></pre> <p><strong>Critique request</strong></p> <p>I would like to receive any critique: coding style, maintainability, readability, efficiency, to name a few.</p>
[]
[ { "body": "<p>The main thing that I don't understand is why you are passing the \"expected winner\" into the schedule at all. If it's not in the list, then it doesn't enter the queue, and doesn't need to be removed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T18:30:48.403", "Id": "213150", "ParentId": "213148", "Score": "0" } }, { "body": "<ul>\n<li><p>The comment</p>\n\n<pre><code>In each iteration, two weakest countries are selected, after which the two battle.\n</code></pre>\n\n<p>seems misleading. Correct me if I am wrong, but the algorithm select two <em>strongest</em> countries.</p></li>\n<li><p>It doesn't seem right to pass <code>expectedWinner</code> to <code>WarScheduler</code>. The expected winner is not scheduled for any battle, and the only thing the scheduler does with it is removing it from the queue. I recommend to prune it in <code>main</code>.</p></li>\n<li><p>A battle creating new country is an interesting geopolitical concept. In this case, however, making countries mutable seems more reasonable.</p>\n\n<p>In particular, since the scheduler already knows which country is stronger, consider a </p>\n\n<pre><code>Battle Country::defeat(Country other)\n</code></pre>\n\n<p>method, which adjusts the winner's potential. Notice that the <code>Battle</code> itself is now reduced purely to a historical record, and doesn't need to know intimate details of <code>Country</code>.</p></li>\n<li><p>An opportunistic optimization is to keep the running tally of the remaining potentials. Once it becomes less than the potential of the expected winner, the order of remaining battles does not matter.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T21:54:14.650", "Id": "213158", "ParentId": "213148", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T17:45:59.710", "Id": "213148", "Score": "2", "Tags": [ "java", "algorithm" ], "Title": "Simple war scheduling algorithm in Java" }
213148
<p>We are writing program which makes XML file which is a calendar with all free days in Poland (Saturdays, Sundays, and all hollidays). We tried to write this code as readable as possible so probably no comments are needed. What do You think about this code? What do You think is better in multiple files or maybe with Built-In Classes. And one more... which one is better and why?</p> <p>in two lines</p> <pre><code>XMLInterior xmlInterior = new XMLInterior(whatYear); Document document = xmlInterior.newDocumentXML(); </code></pre> <p>or in one line</p> <pre><code>Document document =new XMLInterior(whatYear).newDocumentXML(); </code></pre> <p>Here is whole code:</p> <p>Main.java</p> <pre><code>public class Main { public static void main(String[] argc) throws Exception { int year = 2009; WhatFirstDayOfYear whatFirstDayOfYear = new WhatFirstDayOfYear(year); System.out.println(whatFirstDayOfYear.calculateWhatFirstDayOfYear()); XMLMaker a = new XMLMaker(year); } } </code></pre> <p>EasterCalculations.java</p> <pre><code>class EasterCalculations { int calculateEasterDate(int year, boolean isLeapYear) { final int centuryPaschalFullMoon = 24, cycleOfDaysOfWeek = 5; //valid until 2099 A.D. int cycleMetonic, leapJulian, nonLeapYear, datePaschalFullMoon, firstSundayAfterPaschalFullMoon; cycleMetonic = year % 19; leapJulian = year % 4; nonLeapYear = year % 7; datePaschalFullMoon = (cycleMetonic * 19 + centuryPaschalFullMoon) % 30; firstSundayAfterPaschalFullMoon = (2 * leapJulian + 4 * nonLeapYear + 6 * datePaschalFullMoon + cycleOfDaysOfWeek) % 7; if (29 == datePaschalFullMoon &amp;&amp; 6 == firstSundayAfterPaschalFullMoon) return isLeapYear ? 31 + 29 + 31 + 19 : 31 + 28 + 31 + 19; else if (28 == datePaschalFullMoon &amp;&amp; 6 == firstSundayAfterPaschalFullMoon &amp;&amp; cycleMetonic &gt; 10) return isLeapYear ? 31 + 29 + 22 + datePaschalFullMoon + firstSundayAfterPaschalFullMoon - 7 : 31 + 28 + 22 + datePaschalFullMoon + firstSundayAfterPaschalFullMoon - 7; return isLeapYear ? 31 + 29 + 22 + datePaschalFullMoon + firstSundayAfterPaschalFullMoon : 31 + 28 + 22 + datePaschalFullMoon + firstSundayAfterPaschalFullMoon; } } </code></pre> <p>WhatFirstDayOfYear.java</p> <pre><code>class WhatFirstDayOfYear { private int whatYear; WhatFirstDayOfYear(int whatYear) { this.whatYear = whatYear; } int calculateWhatFirstDayOfYear(){ int tempYear = 2019; int tempYearFirstDay = 2; if(whatYear &gt; tempYear){ while(whatYear != tempYear){ if(tempYear % 4 == 0 &amp;&amp; tempYear % 100 != 0 || tempYear % 400 == 0) tempYearFirstDay += 2; else tempYearFirstDay++; tempYear++; } } else if(whatYear &lt; tempYear){ while(whatYear != tempYear){ if(whatYear % 4 == 0 &amp;&amp; whatYear % 100 != 0 || whatYear % 400 == 0) tempYearFirstDay -= 2; else tempYearFirstDay--; whatYear++; } } else return tempYearFirstDay; return (tempYearFirstDay%7+7)%7; } } </code></pre> <p>XMLInterior.java</p> <pre><code>import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; class XMLInterior { private Document document; private Element element; private Element month; private Attr holiday; private int startYearDay; private int currentYearDay; private int dateEaster; private int dateCorpusCristi; private int datePentecost; private boolean isLeapYear; XMLInterior(int whatYear) { EasterCalculations easterCalculations = new EasterCalculations(); WhatFirstDayOfYear whatFirstDayOfYear = new WhatFirstDayOfYear(whatYear); this.startYearDay = whatFirstDayOfYear.calculateWhatFirstDayOfYear(); this.currentYearDay = 1; isLeapYear = whatYear % 4 == 0 &amp;&amp; whatYear % 100 != 0 || whatYear % 400 == 0; dateEaster = easterCalculations.calculateEasterDate(whatYear, isLeapYear); dateCorpusCristi = dateEaster + 40; datePentecost = dateEaster + 60; } Document newDocumentXML() throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); element = document.createElement("Year"); document.appendChild(element); makeYear(); return document; } private void createMonthInterior(int numberMonth, int numberDays) { int dayOfMonth = 1; Attr noOfDay; Element day; for (int i = 1; i &lt;= numberDays; i++) { day = document.createElement("Day"); holiday = document.createAttribute("Holiday"); checkHoliday(numberMonth, dayOfMonth); day.setAttributeNode(holiday); noOfDay = document.createAttribute("NoDay"); noOfDay.setValue(Integer.toString(i)); day.setAttributeNode(noOfDay); month.appendChild(day); startYearDay++; currentYearDay++; dayOfMonth++; } } private void createMonth(String name, int numberDays, int monthNumber) { month = document.createElement(name); element.appendChild(month); Attr noDays = document.createAttribute("NoDays"); noDays.setValue(Integer.toString(numberDays)); month.setAttributeNode(noDays); Attr noMonth = document.createAttribute("NoMonth"); noMonth.setValue(Integer.toString(monthNumber)); month.setAttributeNode(noMonth); createMonthInterior(monthNumber, numberDays); } private void makeYear() {//enum createMonth("January", 31, 1); if (isLeapYear) createMonth("February", 29, 2); else createMonth("February", 28, 2); createMonth("March", 31, 3); createMonth("April", 30, 4); createMonth("May", 31, 5); createMonth("June", 30, 6); createMonth("July", 31, 7); createMonth("August", 31, 8); createMonth("September", 30, 9); createMonth("October", 31, 10); createMonth("November", 30, 11); createMonth("December", 31, 12); } private void checkHoliday(int noMonth, int currentMonthDay) { if (6 == startYearDay % 7 || 0 == startYearDay % 7) holiday.setValue("1"); else if (1 == noMonth &amp;&amp; (1 == currentMonthDay || 6 == currentMonthDay)) holiday.setValue("1"); else if (5 == noMonth &amp;&amp; (1 == currentMonthDay || 3 == currentMonthDay)) holiday.setValue("1"); else if (8 == noMonth &amp;&amp; 15 == currentMonthDay) holiday.setValue("1"); else if (11 == noMonth &amp;&amp; (11 == currentMonthDay || 1 == currentMonthDay)) holiday.setValue("1"); else if (12 == noMonth &amp;&amp; (25 == currentMonthDay || 26 == currentMonthDay)) holiday.setValue("1"); else if (currentYearDay == dateEaster || currentYearDay == dateEaster + 1) holiday.setValue("1"); else if (currentYearDay == dateCorpusCristi) holiday.setValue("1"); else if (currentYearDay == datePentecost) holiday.setValue("1"); else holiday.setValue("0"); } } </code></pre> <p>XMLMaker.java</p> <pre><code>import org.w3c.dom.Document; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; class XMLMaker { XMLMaker( int whatYear) throws Exception { makeXML( whatYear); } private void makeXML( int whatYear) throws Exception { XMLInterior xmlInterior = new XMLInterior(whatYear); Document document = xmlInterior.newDocumentXML(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource src = new DOMSource(document); String pathName = "C:\\XML"; checkDirectory(pathName); StreamResult streamResult = new StreamResult(new File(pathName + "\\" + whatYear + ".xml")); transformer.transform(src, streamResult); } private void checkDirectory(String pathName) { File directoryXML = new File(pathName); if (!directoryXML.exists()) if (!directoryXML.mkdir()) System.out.println("Can't mkdir directory"); if (!directoryXML.isDirectory()) System.exit(1); } } </code></pre>
[]
[ { "body": "<h3>Easter: Leap Year Check Is Redundant</h3>\n\n<p>Given that it is easy to calculate whether a year is a leap year, any performance loss from re-calculating it will be miniscule compared to the risk of the two being inconsistent.</p>\n\n<h3>Easter: DRY (Don't Repeat Yourself)</h3>\n\n<p>There are several places which, essentially, amount to this:</p>\n\n<pre><code>return isLeapYear ? (stuff) + 1 : (stuff)\n</code></pre>\n\n<p>It would reduce the amount of repetition by calculating as if it weren't a leap year, then adding an extra day if necessary.</p>\n\n<h3>What First Day Of Year?</h3>\n\n<p>Isn't this always January 1st? I can't work out what it is calculating. Consider renaming it.</p>\n\n<h3>XMLInterior: Revisit Your Fields</h3>\n\n<p>Fields are meant to be used across calls to various methods of an object. In your case, most of the fields set by <code>newDocumentXML</code> won't be accessible. These should be passed around as parameters and return values instead.</p>\n\n<h3>XMLInterior: What are these holidays?</h3>\n\n<p>It would make this code a lot clearer to have methods that tested each holiday, such as <code>isNewYearsDay(date)</code>.</p>\n\n<h3>XMLMarker: Consider using NIO methods for creating directories</h3>\n\n<p>Methods in <a href=\"https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html\" rel=\"nofollow noreferrer\"><code>java.nio.Files</code></a> throw exceptions on failure, rather than returning a boolean to indicate success or not. These will make the code significantly cleaner.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T18:49:50.717", "Id": "213152", "ParentId": "213149", "Score": "0" } } ]
{ "AcceptedAnswerId": "213152", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T18:10:15.400", "Id": "213149", "Score": "2", "Tags": [ "java", "datetime", "xml" ], "Title": "Calendar holidays to XML" }
213149
<p>Just for fun I did the following exercise from <em>"Cracking the coding interview. 4th edition"</em>:</p> <blockquote> <p>You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. </p> <p>EXAMPLE Input: (3 -> 1 -> 5), (5 -> 9 -> 2)</p> <p>Output: 8 -> 0 -> 8</p> </blockquote> <p>Although my solution it seems to return valid results it is significantly different from the proposed solution. I implemented my own structures and I haven't used recursion.</p> <p>I know both solutions are <em>valid</em>, but in case of a real interview: <em>How would the interviewer consider my answer? Which caveats should I consider?</em></p> <pre><code>public class ex24 { public static void Run() { var n1 = CreateNumber(5, 1, 3); var n2 = CreateNumber(2, 9, 5); Figure xF = n1; Figure xY = n2; int alpha = 0; Figure prev = null; Figure ini; do { int n1v = n1 != null ? n1.Value : 0; int n2v = n2 != null ? n2.Value : 0; int sum = n1v + n2v + alpha; decimal f = sum / (decimal)10; alpha = (int)f; sum = (int)((f - alpha) * 10); if (prev == null) { ini = new Figure(sum); prev = ini; } else { prev.Next = new Figure(sum); prev = prev.Next; } n1 = n1 != null ? n1.Next : null; n2 = n2 != null ? n2.Next : null; } while (n1 != null || n2 != null || alpha != 0); // Result is stored on 'ini'. } public class Figure { public Figure Next; public int Value; public Figure(int value) { this.Value = value; } public override string ToString() =&gt;"" + this.Value; } public static Figure CreateNumber(params int[] values) { Figure ini = new Figure(values[values.Length - 1]); Figure prev = ini; for (var ix = values.Length - 2; ix &gt;= 0; ix--) { prev.Next = new Figure(values[ix]); prev = prev.Next; } return ini; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T14:32:58.413", "Id": "412397", "Score": "0", "body": "Why not use the linked list type from the framework (`System.Collections.Generic.LinkedList<T>`)?" } ]
[ { "body": "<ul>\n<li><p>Strictly speaking, the code does not solve the problem. As an interviewer I'd expect a clearly defined</p>\n\n<pre><code> List add(List l1, List l2)\n</code></pre>\n\n<p>method.</p>\n\n<p>At the very least, rename <code>Run</code> to <code>add</code>, and do not <code>CreateNumber</code>s in it, but pass them as parameters.</p></li>\n<li><p>Since it is guaranteed that every node contains a <em>digit</em>, the sum may never exceed 19. This means, among other things, that there is no need for <code>decimal</code>. Everything can be done with primitive types, e.g.</p>\n\n<pre><code> alpha = sum &gt; 10;\n sum -= alpha * 10;\n</code></pre>\n\n<p>As a side note, the entity you call <code>alpha</code> is traditionally called <code>carry</code>.</p></li>\n<li><p>The <code>do {} while()</code> approach seems to create more problems than it solves. An immediate manifestation is duplication of <code>n1 != null</code> tests. Consider</p>\n\n<pre><code> while (n1 != null &amp;&amp; n2 != null) {\n // addition logic here\n n1 = n1.Next;\n n2 = n2.Next;\n }\n</code></pre>\n\n<p>and promote the carry along the remainder of the longer list in a separate loop.</p></li>\n<li><p>Consider creating a dummy head for a resulting list. It is a standard trick to avoid a special case of <code>prev == null</code>, e.g.</p>\n\n<pre><code> Figure dummy = new Figure;\n Figure tail = dummy;\n\n while (....) {\n ....\n tail.next = new Figure(sum);\n tail = tail.next;\n }\n ....\n return dummy.next;\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T10:10:18.223", "Id": "412369", "Score": "0", "body": "`alpha = sum > 10; sum -= alpha * 10` won't work in C# (something like `carry = sum / 10; sum -= carry * 10` would). Also worth noting that `List` is the .NET type which represents a dynamic array, rather than a linked-list (`LinkedList`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T18:30:21.963", "Id": "412418", "Score": "0", "body": "On 3rd point. Both numbers might not have the same length so checking for a null value is required, moreover, the while condition has to be an OR instead of AND." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T18:48:39.473", "Id": "412419", "Score": "0", "body": "@arturn The third point explicitly said _promote the carry along the remainder of the longer list in a separate loop_. True, I didn't spell out this separate loop, pretty much intentionally." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T09:40:11.897", "Id": "412721", "Score": "0", "body": "@vnp Sure ;) Sorry,I misunderstood the sentence!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T01:53:59.760", "Id": "213163", "ParentId": "213151", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T18:31:16.967", "Id": "213151", "Score": "2", "Tags": [ "c#", "algorithm", "recursion", "iteration" ], "Title": "Write a function that adds two numbers stored in a linked list and returns the sum" }
213151
<p>I just came through a <a href="https://github.com/frogermcs/LikeAnimation" rel="nofollow noreferrer">GitHub repo</a>, which has an amazing animation for <code>Button</code> in Android.</p> <p>So, I thought why not make that for web buttons too.</p> <p>And I started designed that.</p> <p>Here is my <a href="https://github.com/Zlytherin/SparkingButton" rel="nofollow noreferrer"><strong>repo</strong></a> for the same.</p> <p>Here is my <strong>code:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let icons = $('.magic') for (let i = 0; i &lt; icons.length; ++i) { icons[i].onclick = function (element) { icons[i].classList.toggle('enabled'); } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.magic { display: inline-block; margin: 50px; position: relative; } .magic i { color: orange; filter: grayscale(100%); position: relative; animation: disable 0.5s forwards; } .enabled i { animation: enable 1s forwards; } .magic::before { content: ""; top:calc(50% - 45px); left:calc(50% - 45px); width: 90px; height: 90px; position: absolute; border-color: orange; border-style: solid; border-width: 45px; border-radius: 50%; transform: scale(0); box-sizing: border-box; } .enabled::before { transition: transform 0.5s, border-width 0.5s 0.2s; transform: scale(1); border-width: 0px; } .magic::after, .magic i::after { content: ""; position: absolute; top: calc(50% - 80px); left: calc(50% - 80px); height: 160px; width: 160px; background: radial-gradient(circle, red 50%, transparent 60%), radial-gradient(circle, red 50%, transparent 60%), radial-gradient(circle, red 50%, transparent 60%), radial-gradient(circle, red 50%, transparent 60%), radial-gradient(circle, orange 50%, transparent 60%), radial-gradient(circle, orange 50%, transparent 60%), radial-gradient(circle, orange 50%, transparent 60%), radial-gradient(circle, orange 50%, transparent 60%); background-position: calc(50% - 50px) calc(50% - 50px), calc(50% - 50px) calc(50% + 50px), calc(50% + 50px) calc(50% - 50px), calc(50% + 50px) calc(50% + 50px), calc(50% - 0px) calc(50% - 70px), calc(50% - 70px) calc(50% - 0px), calc(50% - 0px) calc(50% + 70px), calc(50% + 70px) calc(50% - 0px); background-size: 16px 16px; background-repeat: no-repeat; border-radius:50%; transform: scale(0); } .magic i:after { background-size: 10px 10px; transform: rotate(10deg) scale(0); } .enabled::after { transition: transform 0.5s 0.5s, opacity 0.4s 1s, background-size 0.4s 1s; transform: scale(1); opacity: 0; background-size: 0 0; } .enabled i:after { transition: transform 0.5s 0.5s, opacity 0.4s 0.8s, background-size 0.4s 0.8s; transform: rotate(10deg) scale(1); opacity: 0; background-size: 0 0; } @keyframes enable { 50% { filter: grayscale(100%); transform: scale(0); } 51% { filter: grayscale(0%) } 90% { transform: scale(1.3) } 100% { filter: grayscale(0%); transform: scale(1); } } @keyframes disable { 50% { filter: grayscale(0%); transform: scale(1.3); } 100% { transform: scale(1); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;span class="magic"&gt; &lt;i class="fas fa-star fa-5x"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="magic"&gt; &lt;i class="fas fa-bell fa-5x"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="magic"&gt; &lt;i class="fas fa-bolt fa-5x"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="magic"&gt; &lt;i class="fas fa-check fa-5x"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="magic"&gt; &lt;i class="fas fa-thumbs-up fa-5x"&gt;&lt;/i&gt; &lt;/span&gt; &lt;!-- Other stuff --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"&gt;</code></pre> </div> </div> </p> <p>What do you reckon? Is there anything I can improve either in the <em>animation</em> or in the <em>code</em>?</p>
[]
[ { "body": "<p>Wow- that is some sparkly animations effects!</p>\n\n<p>Because <code>icons</code> is only assigned one time, <code>const</code> can be used instead of <code>let</code>. This helps avoid accidental re-assignment.</p>\n\n<p>If jQuery is going to be included on the page, then it can be used to simplify the JavaScript code - with the <a href=\"https://api.jquery.com/click\" rel=\"nofollow noreferrer\"><code>click</code></a> handler:</p>\n\n<pre><code>$('.magic').click(function() {\n $(this).toggleClass('enabled');\n});\n</code></pre>\n\n<p>That way there is no need to iterate over the collection of elements and add an <code>onclick</code> event handler to each one. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-23T00:07:55.860", "Id": "232836", "ParentId": "213153", "Score": "3" } }, { "body": "<p>I'd like to suggest the opposite of Sᴀᴍ Onᴇᴌᴀ: Since you are using jQuery for selecting only, you can drop it altogether.</p>\n\n<pre><code>const icons = $(\".magic\");\n</code></pre>\n\n<p>becomes either</p>\n\n<pre><code>const icons = document.getElementsByClassName(\"magic\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>const icons = document.querySelectorAll(\".magic\");\n</code></pre>\n\n<p>However you shouldn't use <code>on...</code> properties to assign event handlers. <code>on...</code> properties can only hold a single handler so if you or another script would attempt to assign another click handler then they'd overwrite each other. Instead use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>addEventListener</code></a>.</p>\n\n<p>Alternatively to avoid assigning seperate event handlers to each icon you could use event delegation. This means assign an single event handler to a surrounding element (or simply <code>document</code>) and check the target element:</p>\n\n<pre><code>document.addEventListener(\"click\", function (event) {\n if (event.target.classList.contains(\"magic\")) {\n event.target.classlist.toggle(\"enabled\");\n }\n};\n</code></pre>\n\n<p>Finally you could avoid using JavaScript altogether by using an HTML element that has the toggle functionality built in: a checkbox:</p>\n\n<pre><code>&lt;label class=\"magic-wrapper\"&gt;\n &lt;input type=\"checkbox\"&gt;&lt;span class=\"magic\"&gt;&lt;i class=\"fas fa-star fa-5x\"&gt;&lt;/i&gt;&lt;/span&gt;\n&lt;/label&gt;\n</code></pre>\n\n<p>Hide the actual checkbox with:</p>\n\n<pre><code>.magic-wrapper &gt; input {\n opacity: 0;\n position: absolute;\n}\n</code></pre>\n\n<p>(This is more accessable than just using display: none;)</p>\n\n<p>And replace the selector <code>.enabled</code> with <code>input:checked + .magic</code> in the CSS.</p>\n\n<p>Complete example: <a href=\"https://jsfiddle.net/rhy6gfn4/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/rhy6gfn4/</a></p>\n\n<hr>\n\n<p>A small points about the CSS: </p>\n\n<p>You should select not just <code>.enabled</code> but use <code>.magic.enabled</code>, because then it's more obvious that these rules belong to the animated icons. Also \"enabled\" is a common class name and you don't want those styles apply to unrelated elements.</p>\n\n<p>It would be a tiniest bit more performant to select the <code>i</code> elements using <code>.magic &gt; i</code> and not just <code>.magic i</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-24T11:30:40.090", "Id": "232891", "ParentId": "213153", "Score": "4" } } ]
{ "AcceptedAnswerId": "232891", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T18:53:30.637", "Id": "213153", "Score": "5", "Tags": [ "javascript", "css", "event-handling", "animation" ], "Title": "Sparking animation for Button" }
213153
<p>In this code I find a list all of the running <code>java</code> processes and give the below function a name to look for, it will do its best. But since I find my approach a little too <em>ugly</em>, could some <strong>POSIX</strong> shell script writer have a look and possibly give me some simplification recommendations?</p> <hr> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh # here is an ugly constant vuze java process name readonly vuze_java_process_name='org.gudy.azureus2.ui.swt.Main' is_java_program_running() # expected arguments: # $1 = java program name { # there will always be at least one java process: # jdk.jcmd/sun.tools.jps.Jps, which is actually # the program giving us the list of java processes java_process_list=$( jps -l | awk '{print $2}' ) # this behaves strangely if there is zero processes (needs verification) # but since there is always at least one, no problem here java_process_list_count=$(( $( printf '%s\n' "${java_process_list}" | wc -l ) )) # set the result value as if we did not find it result=false # POSIX-ly simulate FOR loop i=1; while [ "${i}" -le "${java_process_list_count}" ] do # here we take one line from the list on $i position java_process_entry=$( echo "${java_process_list}" | sed --posix --quiet "${i}{p;q}" ) # compare the given process entry with given java program name if [ "${java_process_entry}" = "${1}" ] then # set the result value result=true # end this loop break fi # increase iterator i=$(( i + 1 )) done # depending on if we found vuze process running, # return positive or negative result value if [ "${result}" = true ] then return 0 else return 1 fi } ### ### EXAMPLE on Vuze ### # keep Vuze alive forever, check in 5 seconds interval while true do sleep 5s if ! is_java_program_running "${vuze_java_process_name}" then my_date_time=$(date +%Y-%m-%d_%H:%M:%S) printf '%s %s\n' "${my_date_time}" "(re-)starting Vuze" ( /home/vlastimil/Downloads/vuze/vuze &gt; /dev/null 2&gt;&amp;1 &amp; ) fi done </code></pre>
[]
[ { "body": "<p>Instead of simulating a <code>for (( expr1 ; expr2 ; expr3 ))</code> loop, use a POSIX</p>\n\n<pre><code> for java_process_entry in $java_process_list\n</code></pre>\n\n<p>Notice that now you don't need to compute the number of lines, neither invoke <code>sed</code>.</p>\n\n<hr>\n\n<p>There is noting wrong with early return. <code>return 0</code> as soon as the desired process is found.</p>\n\n<hr>\n\n<p>There is no need to store the entire list in a variable, neither invoke <code>awk</code>. Process the <code>jps</code> output sequentially.</p>\n\n<p>All that said, consider </p>\n\n<pre><code> is_java_program_running()\n {\n jps -l | while read pid java_process_entry; do\n if [ $java_process_entry = \"${1}\" ]; then return 0; fi\n done\n return 1\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T18:44:50.327", "Id": "213205", "ParentId": "213156", "Score": "2" } }, { "body": "<p>(On top of what @vnp already wrote.)</p>\n\n<hr>\n\n<p>When these lines are the last in a function:</p>\n\n<blockquote>\n<pre><code>if [ \"${result}\" = true ]\nthen\n return 0\nelse\n return 1\nfi\n</code></pre>\n</blockquote>\n\n<p>Then you can write simply:</p>\n\n<pre><code>[ \"${result}\" = true ]\n</code></pre>\n\n<p>Because the exit code of a function is the exit code of its last executed statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-25T19:06:06.397", "Id": "414328", "Score": "0", "body": "In fact, given that the only other possible value of `$result` is `false`, we can just expand and execute it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-25T18:24:37.840", "Id": "214258", "ParentId": "213156", "Score": "1" } } ]
{ "AcceptedAnswerId": "213205", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-09T21:07:53.273", "Id": "213156", "Score": "2", "Tags": [ "java", "linux", "sh", "posix" ], "Title": "POSIX-ly finding a specific Java process" }
213156
<p>I made a Python 3 class that scrapes data from <a href="https://www.pro-football-reference.com/" rel="nofollow noreferrer">Pro Football Reference</a>. It uses <code>requests</code> and <code>beautifulsoup4</code> to gather the data and places it into a <code>pandas</code> data frame. All you need to do is create an object and use the <code>get_data()</code> method to get the data frame. This method needs a <code>start_year</code>, <code>end_year</code>, and <code>table_type</code> as arguments. Valid table types can be found in the class' docstring.</p> <p>A usage demonstration can be found at the bottom of the code. It scrapes <a href="https://www.pro-football-reference.com/years/2017/passing.htm" rel="nofollow noreferrer">2017 Passing Data</a> and <a href="https://www.pro-football-reference.com/years/2018/passing.htm" rel="nofollow noreferrer">2018 Passing Data</a>. You can also view the code <a href="https://github.com/keving90/NFL-Data-Python/blob/2547cedf36b46fb5ec901a27dbb7eea6ee25708c/pro_football_ref/pro_ref2.py" rel="nofollow noreferrer">on GitHub</a>.</p> <pre><code>""" This module contains a FootballRefScraper class used to scrape NFL data from www.pro-football-reference.com. It places the data into a Pandas data frame, which can be saved as a CSV file. Built using Python 3.7.0. """ import requests import bs4 import pandas as pd class FootballRefScraper(object): """ Scrapes NFL data from www.pro-football-reference.com and places it into a Pandas data frame. Multiple years of data can be scraped and placed into a single data frame for the same statistical category. Each category is referred to as a 'table type'. Possible table types include: 'rushing': Rushing data. 'passing': Passing data. 'receiving': Receiving data. 'kicking': Field goal, point after touchdown, and punt data. 'returns': Punt and kick return data. 'scoring': All types of scoring data, such as touchdowns (defense/offense), two point conversions, kicking, etc. 'fantasy': Rushing, receiving, and passing stats, along with fantasy point totals from various leagues. 'defense': Defensive player stats. Each player on Pro Football Reference has their own unique URL. This URL, combined with the year for the player's specific season of data, is used as a unique identifier for each row in the data frame. It is used as the data frame's index. """ def __init__(self): self._tables = ['rushing', 'passing', 'receiving', 'kicking', 'returns', 'scoring', 'fantasy', 'defense'] self._kicking_cols_to_rename = { 'fga1': 'att_0-19', 'fgm1': 'made_0-19', 'fga2': 'att_20-29', 'fgm2': 'made_20-29', 'fga3': 'att_30-39', 'fgm3': 'made_30-39', 'fga4': 'att_40-49', 'fgm4': 'made_40-49', 'fga5': 'att_50_plus', 'fgm5': 'made_50_plus' } @property def tables(self): """getter: Returns a list of the possible table types to scrape from.""" return self._tables def get_data(self, start_year, end_year, table_type, remove_pro_bowl=True, remove_all_pro=True): """ Gets a data frame of NFL player stats from Pro Football Reference for one for more seasons. :param start_year: First season to scrape data from (string or int) :param end_year: Final season (inclusive) to scrape data from (string or int) :param table_type: Stat category to scrape :param remove_pro_bowl: Boolean - If true, removes Pro Bowl accolade ('*') from player's name :param remove_all_pro: Boolean - If true, removes All-Pro accolade ('+') from player's name :return: Data frame of one or more seasons of data for a given stat category. """ self._check_table_type(table_type) start_year, end_year = self._check_start_and_end_years(start_year, end_year) if start_year == end_year: df = self._get_single_season(start_year, table_type) else: df = self._get_multiple_seasons(start_year, end_year, table_type) # Unique identifier for each player's season of data. df.set_index('player_url', inplace=True) # Change data from string to numeric, where applicable. df = df.apply(pd.to_numeric, errors='ignore') if remove_pro_bowl or remove_all_pro: self._remove_player_accolades(df, remove_pro_bowl, remove_all_pro) if table_type.lower() == 'kicking': # For kicking data, rename some columns so field goal distance is obvious. df = df.rename(index=str, columns=self._kicking_cols_to_rename) return df def _get_multiple_seasons(self, start_year, end_year, table_type): """ Scrapes multiple seasons of data from Pro Football Reference and puts it into a Pandas data frame. :param start_year: First season to scrape data from (string or int) :param end_year: Final season (inclusive) to scrape data from (string or int) :param table_type: Stat category to scrape :return: Data frame with multiple seasons of data for a given stat category. """ # Get seasons to iterate through. year_range = self._get_year_range(start_year, end_year) # Get a data frame of each season. seasons = [self._get_single_season(year, table_type) for year in year_range] # Combine all seasons into one large df. # sort = False prevents FutureWarning when concatenating data frames with different number of columns (1/18/19) big_df = pd.concat(seasons, sort=False) return big_df def _get_year_range(self, start_year, end_year): """ Uses start_year and end_year to build an iterable sequence. :param start_year: Year to begin iterable at. :param end_year: Final year in iterable. :return: An iterable sequence. """ # Build range iterator depending on how start_year and end_year are related. if start_year &gt; end_year: year_range = range(start_year, end_year - 1, -1) else: year_range = range(start_year, end_year + 1) return year_range def _check_start_and_end_years(self, start_year, end_year): """ Tries to convert start_year and end_year to int, if necessary. Raises ValueError for unsuccessful conversions. :param start_year: Data to convert to int :param end_year: Data to convert to int :return: Tuple - (start_year, end_year) """ # Convert years to int, if needed. if not isinstance(start_year, int): try: start_year = int(start_year) except ValueError: raise ValueError('Cannot convert start_year to type int.') if not isinstance(end_year, int): try: end_year = int(end_year) except ValueError: raise ValueError('Cannot convert end_year to type int.') return start_year, end_year def _get_single_season(self, year, table_type): """ Scrapes a single table from Pro Football Reference and puts it into a Pandas data frame. :param year: Season's year. :param table_type: String representing the type of table to be scraped. :return: A data frame of the scraped table for a single season. """ table = self._get_table(year, table_type) header_row = self._get_table_headers(table) df_cols = self._get_df_columns(header_row) player_elements = self._get_player_rows(table) if not player_elements: # Table found, but it doesn't have data. raise RuntimeError(table_type.capitalize() + " stats table found for year " + str(year) + ", but it does not contain data.") season_data = self._get_player_stats(player_elements) # Final data frame for single season return self._make_df(year, season_data, df_cols) def _get_table(self, year, table_type): """ Sends a GET request to Pro-Football Reference and uses BeautifulSoup to find the HTML table. :param year: Season's year. :param table_type: String representing the type of table to be scraped. :return: BeautifulSoup table element. """ # Send a GET request to Pro-Football Reference url = 'https://www.pro-football-reference.com/years/' + str(year) + '/' + table_type + '.htm' response = requests.get(url) response.raise_for_status() # Create a BeautifulSoup object. soup = bs4.BeautifulSoup(response.text, 'lxml') table = soup.find('table', id=table_type) if table is None: # No table found raise RuntimeError(table_type.capitalize() + " stats table not found for year " + str(year) + ".") # Return the table containing the data. return table def _get_table_headers(self, table_element): """ Extracts the top row of a BeautifulSoup table element. :param table_element: BeautifulSoup table element. :return: List of header cells from a table. """ # 'thead' contains the table's header row head = table_element.find('thead') # 'tr' refers to a table row col_names = head.find_all('tr')[-1] # 'th' is a table header cell return col_names.find_all('th') def _get_df_columns(self, header_elements): """ Extracts stat names from column header cells. :param header_elements: List of header cells :return: List of stat names. """ cols_for_single_season = [header_cell['data-stat'] for header_cell in header_elements[1:]] cols_for_single_season.insert(1, 'player_url') return cols_for_single_season def _get_player_rows(self, table_element): """ Gets a list of rows from an HTML table. :param table_element: HTML table. :return: A list of table row elements. """ # 'tbody' is the table's body body = table_element.find('tbody') # 'tr' refers to a table row return body.find_all('tr') def _get_player_stats(self, player_row_elements): """ Gets stats for each player in a table for a season. :param player_row_elements: List of table rows where each row is a player's season stat line. :return: List where each element is a list containing a player's data for the season. """ season_stats = [] for player in player_row_elements: # 'td' is an HTML table cell player_stats = player.find_all('td') # Some rows do not contain player data. if player_stats: clean_stats = self._get_clean_stats(player_stats) season_stats.append(clean_stats) return season_stats def _get_clean_stats(self, stat_row): """ Gets clean text stats for a player's season. :param stat_row: List of table cells representing a player's stat line for a season. :return: List of strings representing a player's season stat line. """ clean_player_stats = [] for stat_cell in stat_row: clean_player_stats.append(stat_cell.text) # Also grab the player's URL so they have a unique identifier when combined with the season's year. if stat_cell['data-stat'] == 'player': url = self._get_player_url(stat_cell) clean_player_stats.append(url) return clean_player_stats def _get_player_url(self, player_cell): """ Get's a player's unique URL. :param player_cell: HTML table cell. :return: String - player's unique URL. """ # 'href' is the URL of the page the link goes to. href = player_cell.find_all('a', href=True) # Return URL string return href[0]['href'] def _make_df(self, year, league_stats, column_names): """ :param year: Season's year. :param league_stats: List where each element is a list of stats for a single player. :param column_names: List used for data frame's column names. :return: A data frame. """ df = pd.DataFrame(data=league_stats, columns=column_names) df.insert(loc=3, column='year', value=year) # Column for current year. # Combined player_url + year acts as a unique identifier for a player's season of data. df['player_url'] = df['player_url'].apply(lambda x: x + str(year)) return df def _remove_player_accolades(self, df, remove_pro_bowl, remove_all_pro): """ Removes Pro Bowl ('*') and All-Pro ('+') accolades from a player's name. :param remove_pro_bowl: Boolean; remove if True :param remove_all_pro: Boolean; remove if True :return: No return value """ if remove_pro_bowl and not remove_all_pro: # Remove '*' in player's name. df['player'] = df['player'].apply(lambda x: ''.join(x.split('*')) if '*' in x else x) elif not remove_pro_bowl and remove_all_pro: # Remove '+' in player's name. df['player'] = df['player'].apply(lambda x: ''.join(x.split('+')) if '+' in x else x) elif remove_pro_bowl and remove_all_pro: # Remove '*', '+', or '*+'. df['player'] = df['player'].apply(self._remove_chars) def _remove_chars(self, string): """ Removes any combination of a single '*' and '+' from the end of a string. :param string: String :return: String """ if string.endswith('*+'): string = string[:-2] elif string.endswith('*') or string.endswith('+'): string = string[:-1] return string def _check_table_type(self, table_type): """ Checks for valid table types. Raises value error for invalid table. :param table_type: String :return: No return value """ # Only scrapes from tables in self._tables. if table_type.lower() not in self._tables: raise ValueError("Error, make sure to specify table_type. " + "Can only currently handle the following table names: " + str(self._tables)) if __name__ == '__main__': football_ref = FootballRefScraper() df = football_ref.get_data(start_year=2017, end_year=2018, table_type='passing') df.to_csv('sample_data.csv') </code></pre>
[]
[ { "body": "<ol>\n<li><p>You need to work on your names. Looking at your github repo, this file is pro_ref2.py? The class name is FootballRefScraper. The site chosen is pro-football-reference.com? What is going on here?</p>\n\n<p>I don't know why this class exists. The class name should make it obvious. Does this thing exist to be a scraper? Or does it exist to be a data source? IMO, it does not exist to be a scraper, because that would imply it was one of many scrapers and so it would probably be a subclass of some <code>AbstractScraper</code> base class. So I think it's a data source, but then why is it called <code>...Scraper</code>? Also, what kind of data source is it? Apparently <code>FootballRef</code>, but again what's that?</p>\n\n<p>Assuming this is really intended to be a data source, give the class a better name. <code>FootballStatistics</code> or <code>NflStatistics</code> make more sense. Alternatively, you might name it after the website, in which case calling it <code>ProFootballReference</code> would seem logical.</p>\n\n<p>If this file contains only the one class, then I suggest you rename the file to <code>pfr.py</code> or <code>profootballreference.py</code> or some such, and then maybe name the class something like <code>Gateway</code> or <code>API</code>. Finally, don't call it <code>get_tables</code>. Call it <code>get_stats</code> since thats what you provide. (You're returning a DataFrame, but you wouldn't call it <code>get_df</code> unless there was some alternate flavor to get...)</p>\n\n<pre><code>import pfr | import pfr\ngateway = pfr.Gateway() | api = pfr.API()\ndf = gateway.get_stats(...) | df = api.get_stats(...)\n</code></pre></li>\n<li><p>As a corollary to #1, consider adding explicit methods for each of the table access calls. Instead of calling <code>df = gateway.get_stats(..., table_type='passing')</code> it would be easier and clearer to simply say <code>df = gateway.get_passing_stats(...)</code>. Not to mention that a missing method name is easier to debug than a call with a misspelled text string (and your editor might auto-suggest/auto-correct the method!).</p></li>\n<li><p>Don't store the table types and kicking table rename data in the instances. That is class data:</p>\n\n<pre><code>class No:\n def __init__(self):\n self.foo = 'foo' # No\n\nclass Yes:\n foo = 'foo' # Yes\n\n def __init__(self):\n pass\n</code></pre></li>\n<li><p>The <code>.tables</code> property should be <code>.table_types</code> or <code>.stats_types</code></p></li>\n<li><p>The <code>get_data</code> (a.k.a. <code>get_stats</code>) function has an awkward interface. Instead of trying to jam everything into <code>start_year</code> and <code>end_year</code>, try allowing multiple named parameters and requiring them to be exclusive. Also, be willing to accept multiple parameter types:</p>\n\n<pre><code># Cannot use year=, years= in same call\ndf = api.get_passing_stats(year=2017) \ndf = api.get_passing_stats(years=(2013, 2017)) # Two explicit years\ndf = api.get_passing_stats(years=range(2011, 2019, 2)) # Only odd year data?\n\n# Cannot use tables= in get_XXX_stats call.\n# Cannot use table= and tables= in same call\ndf = api.get_stats(year=2018, table='kicking')\ndf = api.get_stats(years=(2017, 2018), tables=('passing', 'running', 'scoring'))\n</code></pre>\n\n<ol start=\"6\">\n<li>Don't be afraid of a DataFrame with >2 dimensions. If someone requests passing, running, and kicking data for 2014, 2018, and 2018, then return a single dataframe with 4 dimensions (year, table, player, stats).</li>\n</ol></li>\n<li><p><code>get_data</code> should automatically strip off the pro-bowl and all-pro data, and add separate columns for that. </p></li>\n<li><p>Your _check_start_and_end_years method doesn't actually check. What happens if I request data for 1861?</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T04:40:15.887", "Id": "412441", "Score": "0", "body": "Thanks, I appreciate your input. I have also been working on something that scrapes data from [The Football Database](https://www.footballdb.com/stats/index.html). A lot of the code is similar to the Pro Football Reference scraper, so would it make sense to have a `ProFootballReference` and `FootballDatabase` class that inherit from something like `AbstractNflScraper`? I'm more familiar with abstract classes in Java, where abstract methods don't contain implementation. I'm unsure what to do about potential repeated code because of this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T04:58:57.337", "Id": "412442", "Score": "1", "body": "I think that's going to depend on how similar the two sites are. Does *The Football Database* produce similar stats? Does it make sense for both scrapers to have `get_passing_stats()` methods, for example? If so, then maybe there's a common base class. If not, if TFD provides different data completely, then you will end up \"knowing\" which one you are using, so sharing a common interface doesn't make sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T17:09:05.573", "Id": "412938", "Score": "0", "body": "I see what you're saying. No point in making something that gets data from two places if the data is same. Also, for something like `get_passing_stats()`, is it considered better to have both a `year` and `years` parameter? Why not just have a `years` parameter that can take both an `int` and `list`/`tuple` of `int`s?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T17:42:50.680", "Id": "213200", "ParentId": "213166", "Score": "1" } } ]
{ "AcceptedAnswerId": "213200", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T03:40:09.470", "Id": "213166", "Score": "4", "Tags": [ "python", "python-3.x", "web-scraping", "pandas", "beautifulsoup" ], "Title": "NFL data scraper" }
213166
<p>I was wondering if anyone had anything to recommend for how to clean up the code I made below. Essentially I am asking if my code is messy or not and if there are any recommendations for my improvement.</p> <pre><code># Most basic fantasy combat simulator import random p_health = 5 g_health = 5 goblin_alive = True def status(): if g_health == 5: return "\nA menacing goblin stands before you..." elif g_health &gt;= 3: return "\nThe goblin is looking a little tired, and is bleeding..." elif g_health &gt;= 1: return "\nThe goblin is bleeding horribly and looks enraged..." while goblin_alive: if g_health &lt;= 0: goblin_alive = False print("\nCongrats you slayed the goblin!") again = input("Play again? Y/N: ") if again == 'y' or again == 'Y': goblin_alive = True elif again == 'N' or again == 'n': print("\nGoodbye") exit() if p_health &lt;= 0: print("Oh dear you have died horribly and the goblin cuts your head off for a trophy...") again = input("Play again? Y/N: ") if again == 'y' or again == 'Y': p_health = 5 g_heath = 5 goblin_alive = True elif again == 'N' or again == 'n': print("\nGoodbye") exit() desc = status() print(desc) print("You have " + str(p_health) + ' hit points.') attack = input("Press enter to attack: ") if attack == '': print("\nYou swing your sword fiercely at the goblin!") hit_type = random.randint(1, 2) if hit_type == 1: damage = random.randint(1, 3) print("You deal a fierce blow for " + str(damage) + " damage to the goblin.") g_health = g_health - damage elif hit_type == 2: damage = random.randint(1, 3) print("The goblin slashes you for " + str(damage) + " damage, uh oh...") p_health = p_health - damage else: print("\nYou better do something...") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T18:57:43.020", "Id": "412650", "Score": "0", "body": "@close voters, why?" } ]
[ { "body": "<p>Your code looks good and was easy to understand, at least for me :)</p>\n\n<p>A few things you can do to improve it:</p>\n\n<h1>Python String Format and Upper</h1>\n\n<p>Consider using python <a href=\"https://docs.python.org/3.6/library/stdtypes.html#str.format\" rel=\"nofollow noreferrer\">format()</a> method, instead of:</p>\n\n<pre><code>print(\"You have \" + str(p_health) + ' hit points.')\n</code></pre>\n\n<p>try:</p>\n\n<pre><code>print('You have {} hit points.'.format(p_health))\n</code></pre>\n\n<p>And when checking if a char equals to a given char, you don't have to check both cases you can just use Python upper/lower function so instead of:</p>\n\n<pre><code>if again == 'y' or again == 'Y':\n</code></pre>\n\n<p>try:</p>\n\n<pre><code>if again.lower() == 'y':\n do stuff\n</code></pre>\n\n<hr>\n\n<h1>Better Practice</h1>\n\n<p>The status() function could be improved by assigning a value to result and returning it, this is just better practice:</p>\n\n<pre><code>def status():\n res = ''\n if g_health == 5:\n res = \"\\nA menacing goblin stands before you...\"\n elif g_health &gt;= 3:\n res = \"\\nThe goblin is looking a little tired, and is bleeding...\"\n elif g_health &gt;= 1:\n res = \"\\nThe goblin is bleeding horribly and looks enraged...\"\n return res\n</code></pre>\n\n<hr>\n\n<h1>Python Class</h1>\n\n<p>Perhaps this code will be better in a GoblinGame class, this class will have properties such as goblin_health, player_health and goblin_alive that can be assigned when initializing the class instance, and a run() method to play a round of the game, I've wrote a quick sample class you can follow along from there:</p>\n\n<pre><code>class GoblinGame:\n def __init__(self):\n self.player_health = 5\n self.goblin_health = 5\n\n def goblin_alive(self):\n return self.goblin_health &gt; 0\n\n @property\n def status(self):\n res = ''\n if self.goblin_health == 5:\n res = \"\\nA menacing goblin stands before you...\"\n elif self.goblin_health &gt;= 3:\n res = \"\\nThe goblin is looking a little tired, and is bleeding...\"\n elif self.goblin_health &gt;= 1:\n res = \"\\nThe goblin is bleeding horribly and looks enraged...\"\n return res\n\n def run(self):\n while self.goblin_alive:\n # write the game logic...\n</code></pre>\n\n<p>Good Luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T17:17:46.930", "Id": "412412", "Score": "1", "body": "I fail to see how the changes improve the `status` function. Can you expand a bit on why you consider it's better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:15:31.193", "Id": "412509", "Score": "0", "body": "I feel like the changes for the status function might help me get in the practice of using variables that are a bit easier to change? I also was wondering about the status function changes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T16:49:49.787", "Id": "213197", "ParentId": "213168", "Score": "1" } }, { "body": "<p>The code was clear and readable. Good job.</p>\n\n<p><strong>Bug?</strong></p>\n\n<p>That said, there appears to be a bug in the \"play again\" logic:</p>\n\n<pre><code> if again == 'y' or again == 'Y':\n goblin_alive = True\n elif again == 'N' or again == 'n':\n print(\"\\nGoodbye\")\n exit()\n</code></pre>\n\n<p>It seems like you mark the goblin as alive, but don't give it any health. So the next game the goblin will start out ... dead?</p>\n\n<p><strong>More Functions!</strong></p>\n\n<p>I suggest that you write some more functions. There are places in your code where you are \"repeating yourself\", and this violates the <em>DRY principle</em> (don't repeat yourself)!</p>\n\n<p>Specifically, there is this code in the \"goblin health\" section:</p>\n\n<pre><code> again = input(\"Play again? Y/N: \")\n\n if again == 'y' or again == 'Y':\n goblin_alive = True\n elif again == 'N' or again == 'n':\n print(\"\\nGoodbye\")\n exit()\n</code></pre>\n\n<p>There is similar code (but better) in the \"player health\" section. I'd suggest that you write a function called <code>play_again()</code> that asks the question and evaluates the response and returns either True or False. </p>\n\n<p>Then you can write another function, <code>reset_game()</code> that resets the global variables for you (you'll want to use the <a href=\"https://docs.python.org/3.7/reference/simple_stmts.html#the-global-statement\" rel=\"nofollow noreferrer\"><code>global</code></a> keyword for this).</p>\n\n<p>You can then write code like:</p>\n\n<pre><code>if play_again():\n reset_game()\nelse:\n exit()\n</code></pre>\n\n<p><strong>Magic Numbers</strong></p>\n\n<p>Finally, I encourage you to define a pair of <em>constants</em> to use in place of the <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\"><em>magic numbers</em></a> 1 and 2:</p>\n\n<pre><code># Near the top of the module\nPLAYER_HITS = 1\nGOBLIN_HITS = 2\n\n # Later in the code:\n if hit_type == PLAYER_HITS:\n damage = random.randint(1, 3)\n print(\"You deal a fierce blow for \" + str(damage) + \" damage to the goblin.\")\n g_health = g_health - damage\n elif hit_type == GOBLIN_HITS:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:17:28.377", "Id": "412510", "Score": "0", "body": "Thank you! The magic numbers is definitely something I should be aware of, I also hadn't noticed the play again bug, and I believe you were correct, the goblin was indeed dead upon playing again. I appreciate the tips! My next goal is to create similar programs to practice the above concepts" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T18:52:11.620", "Id": "213207", "ParentId": "213168", "Score": "1" } }, { "body": "<p>If you want to continue expanding this game, you should consider moving the actors to classes. So you can have a <code>Unit</code> class, which is subclassed by both <code>Player</code> and <code>Goblin</code>:</p>\n\n<p>First, the <code>Unit</code> class. A unit should have health, maximum health, attack and a name. It can attack other things, be attacked, display its status, be dead or alive and die:</p>\n\n<pre><code>class Unit:\n def __init__(self, name, health, attack_die):\n self.name = name\n self.max_health = health\n self.health = health\n self.attack_damage = attack_die\n\n def __str__(self):\n return f\"{self.name} ({self.health}/{self.max_health} HP, {self.attack_damage[0]}-{self.attack_damage[1]} ATK)\"\n\n @property\n def alive(self):\n return self.health &gt; 0\n\n def attack(self, other):\n damage = random.randint(*self.attack_damage)\n other.being_attacked(damage)\n return damage\n\n def being_attacked(self, damage):\n self.health -= damage\n\n def die(self, from_what=None):\n if from_what is None:\n print(f\"\\nCongrats you slayed the {self.name}!\")\n else:\n print(f\"{self.name} was slayed by {from_what}!\")\n</code></pre>\n\n<p>Now, the <code>Goblin</code> class just adds your flavor texts on top of that as well as setting the values fro health and attack:</p>\n\n<pre><code>class Goblin(Unit):\n def __init__(self):\n super().__init__(\"Goblin\", 5, (1, 3))\n\n def __str__(self):\n if self.health == self.max_health:\n return \"\\nA menacing goblin stands before you...\"\n elif self.health &gt;= 0.5*self.max_health:\n return \"\\nThe goblin is looking a little tired, and is bleeding...\"\n elif self.health &gt;= 0:\n return \"\\nThe goblin is bleeding horribly and looks enraged...\"\n\n def attack(self, other):\n damage = super().attack(other)\n print(f\"The goblin slashes you for {damage} damage, uh oh...\")\n</code></pre>\n\n<p>And finally the <code>Player</code> class. It also mostly just adds nice prints:</p>\n\n<pre><code>class Player(Unit):\n def __init__(self):\n super().__init__(\"Player\", 5, (1, 3))\n\n def __str__(self):\n return f\"You have {self.health} hit points.\"\n\n def attack(self, other):\n damage = super().attack(other)\n print(f\"You deal a fierce blow for {damage} damage to the {other.name}.\")\n\n def die(self, from_what):\n if isinstance(from_what, Unit):\n print(f\"\\nOh dear you have died horribly and the {from_what.name} cuts your head off for a trophy...\")\n else:\n print(from_what)\n</code></pre>\n\n<p>Now most of the complicated stuff is abstracted away and actually running the game becomes quite minimal:</p>\n\n<pre><code>def play_round(player, enemy):\n units = [player, enemy]\n while player.alive and enemy.alive:\n print(enemy)\n print(player)\n attack = input(\"Press enter to attack: \")\n if attack == '':\n random.shuffle(units)\n attacker, defender = units\n print(f\"\\nYou swing your sword fiercely at the {enemy.name}!\")\n attacker.attack(defender)\n else:\n print(\"\\nYou better do something...\")\n if player.alive:\n enemy.die()\n else:\n player.die(enemy)\n\n\ndef play_game():\n again = True\n while again:\n play_round(Player(), Goblin())\n again = input(\"Play again? Y/N: \").lower() == \"y\"\n print(\"\\nGoodbye\")\n exit()\n\nif __name__ == \"__main__\":\n play_game()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:11:02.453", "Id": "412507", "Score": "1", "body": "Thank you, I found this very helpful as I've considered fidgeting with the code to try and expand it, currently learning a bit about modules, this has been a great exercise to get some practical knowledge on some of the basic concepts i've learned with python so far." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T15:11:23.680", "Id": "213248", "ParentId": "213168", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T04:48:08.840", "Id": "213168", "Score": "5", "Tags": [ "python", "beginner", "battle-simulation" ], "Title": "Most basic fantasy combat simulator" }
213168
<p>This is an extension of the <code>System.ComponentModel.BindingList&lt;T&gt;</code> class that allows for notifications of item changing and deleting. These notifications provided the outgoing item and the incoming item, as well as a <code>Cancel</code> property to cancel the change or deletion.</p> <p>In additon, it also allows for a bulk addition of items, which is just a loop of <code>AddItem</code> (which will trigger a change notification for each item added).</p> <p>On top of bulk addition, there is a <code>SetItems</code> which will clear the collection and add all the items provided, but will only fire one <code>Reset</code> notification.</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; namespace BindingListExtension { public class BindingListEx&lt;T&gt; : BindingList&lt;T&gt; { public event EventHandler&lt;ListItemRemovingEventArgs&lt;T&gt;&gt; ListItemRemoving; public event EventHandler&lt;ListItemChangingEventArgs&lt;T&gt;&gt; ListItemChanging; protected override void RemoveItem(int index) { var args = new ListItemRemovingEventArgs&lt;T&gt;(this[index], index); ListItemRemoving?.Invoke(this, args); if (args.Cancel) return; base.RemoveItem(index); } protected override void SetItem(int index, T item) { var args = new ListItemChangingEventArgs&lt;T&gt;(this[index], item, index); ListItemChanging?.Invoke(this, args); if (args.Cancel) return; base.SetItem(index, item); } public void SetItems(IEnumerable&lt;T&gt; items) { RaiseListChangedEvents = false; Clear(); AddItems(items); RaiseListChangedEvents = true; OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); } public void AddItems(IEnumerable&lt;T&gt; items) { if (items != null) { foreach (T item in items) { Add(item); } } } } public class ListItemRemovingEventArgs&lt;T&gt; : CancelEventArgs { public ListItemRemovingEventArgs(T oldItem, int index) { OldItem = oldItem; } public T OldItem { get; } public int Index { get; } } public class ListItemChangingEventArgs&lt;T&gt; : ListItemRemovingEventArgs&lt;T&gt; { public ListItemChangingEventArgs(T oldItem, T newItem, int index) : base(oldItem, index) { NewItem = newItem; } public T NewItem { get; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T09:04:19.500", "Id": "412360", "Score": "1", "body": "There is not need for a new type. Since `RaiseListChangedEvents` is a public property both methods (`SetItems` & `AddItems`) could be extension methods. I find the behaviour of `SetItems` is pretty unexpected because it clears the collection and not like the original `SetItem` updates items at specific indexes which it should be doing. What you have written is more like `ResetItems` and you seem to have forgotten to disable rasing events in `AddItems`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T22:00:11.763", "Id": "439814", "Score": "0", "body": "@t3chb0t I believe _Add_ calls _SetItem_ internally (not sure), so an event is raised." } ]
[ { "body": "<h3>ListChangedType.Reset</h3>\n\n<p><code>AddItems</code> is nothing more than a glorified wrapper method for calling <code>Add</code> multiple times. However, guidelines suggest that <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.listchangedtype?view=netframework-4.8\" rel=\"nofollow noreferrer\">ListChangedType.Reset</a> could and probably should also be called here. Since <code>Reset</code> should be called when..</p>\n\n<blockquote>\n <p>Much of the list has changed. Any listening controls should refresh\n all their data from the list.</p>\n</blockquote>\n\n<p>To give this method some purpose other than looping elements and call <code>Add</code>, consider using the same deferral strategy as you did with <code>SetItems</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T22:16:11.620", "Id": "226349", "ParentId": "213169", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T05:34:08.927", "Id": "213169", "Score": "1", "Tags": [ "c#", "collections", "databinding" ], "Title": "Extension to BindingList<T> that allows for cancelable notifications of changing and deleting" }
213169
<p>I implemented a simple voting widget like the one used on Stack Exchange sites, to use for other purposes (see live on <a href="http://www.bashoneliners.com/" rel="nofollow noreferrer">bashoneliners.com</a>), as a reusable package, dubbed <a href="https://github.com/janosgyerik/upvotejs" rel="nofollow noreferrer">UpvoteJS</a>.</p> <p>Here's how it works:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>Upvote.create('topic-123');</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://janosgyerik.github.io/upvotejs/dist/upvotejs/upvotejs.css"&gt; &lt;script src="https://janosgyerik.github.io/upvotejs/dist/upvotejs/upvotejs.vanilla.js"&gt;&lt;/script&gt; &lt;div id="topic-123" class="upvotejs upvotejs-serverfault"&gt; &lt;a class="upvote upvote-on"&gt;&lt;/a&gt; &lt;span class="count"&gt;101&lt;/span&gt; &lt;a class="downvote"&gt;&lt;/a&gt; &lt;a class="star star-on"&gt;&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h3>How to use</h3> <p>As you can see in the above snippet, the typical use has the following elements:</p> <ul> <li><p>Include the stylesheet <code>upvotejs.css</code> with a <code>&lt;link&gt;</code> tag. The companion <code>upvotejs.svg</code> is expected in the same directory on the web server.</p></li> <li><p>Add HTML markup with the fields you need. With the stylesheet included, this is enough to get a nicely rendered widget, read-only, since without JavaScript, the clicks will have no effect.</p></li> <li><p>To make the widget interactive, responding to user clicks, include the JavaScript package <code>upvotejs.vanilla.js</code> with a <code>&lt;script&gt;</code> tag, and activate the widget using the provided <code>Upvote.create(topicId)</code> function in JavaScript (to happen after the DOM is loaded). The <code>topicId</code> parameter is mandatory, and it must refer to a unique id in the DOM.</p></li> <li><p>To make the widget save state to a backend (not featured in the snippet), pass to <code>Upvote.create</code> as second parameter a JSON object, with a field named <code>callback</code>, which must be a JavaScript function, for example: <code>Upvote.create(topicId, {callback: your_callback_function})</code>. It is up to the developer to implement <code>your_callback_function</code> to persist its payload. The function will get called on any state change.</p></li> </ul> <p>The above should be enough for typical use cases.</p> <p>Additional notes:</p> <ul> <li><p>All sub-elements in the HTML markup are optional, for example it's possible to have a widget without a star button, or any other element.</p></li> <li><p>The initial state of a widget can be set either with HTML markup (recommended), or using basic markup (without <code>upvote-on</code>, <code>downvote-on</code>, <code>star-on</code> classes) and setting values in the second parameter of the <code>Upvote.create</code> call, for example: <code>Upvote.create(topicId, {count: 123, upvoted: true})</code></p></li> <li><p><code>Upvote.create</code> does some sanity checks, and throws an exception when it detects illegal state, for example (not an exhaustive list):</p> <ul> <li>The specified ID doesn't exist in the DOM</li> <li>The parameter types in the JSON object don't match what's expected (<code>count</code> must be integer, and so on)</li> <li><code>upvoted</code> and <code>downvoted</code> are both <code>true</code></li> </ul></li> <li><p><code>Upvote.create</code> returns an object that represents the widget, and can be used to inspect and control its state. In the typical use case, this is probably not necessary.</p></li> </ul> <h3>Implementation</h3> <p>I'm most interested in a review of the JavaScript part (<a href="https://github.com/janosgyerik/upvotejs/blob/2.1.0/dist/upvotejs/upvotejs.vanilla.js" rel="nofollow noreferrer"><code>upvotejs.vanilla.js</code> (2.1.0)</a>), the complete project is available on <a href="https://github.com/janosgyerik/upvotejs" rel="nofollow noreferrer">GitHub</a>.</p> <pre><code>const Upvote = function() { const upvoteClass = 'upvote'; const enabledClass = 'upvotejs-enabled'; const upvoteOnClass = 'upvote-on'; const downvoteClass = 'downvote'; const downvoteOnClass = 'downvote-on'; const starClass = 'star'; const starOnClass = 'star-on'; const countClass = 'count'; const Utils = { combine: function() { const combined = {}; for (let i = 0; i &lt; arguments.length; i++) { Object.entries(arguments[i]) .filter(e =&gt; e[1] !== undefined) .forEach(e =&gt; combined[e[0]] = e[1]); } return combined; }, isBoolean: v =&gt; typeof v === "boolean", isFunction: v =&gt; typeof v === "function", classes: dom =&gt; dom.className.split(/ +/).filter(x =&gt; x), removeClass: (dom, className) =&gt; { dom.className = dom.className.split(/ +/) .filter(x =&gt; x) .filter(c =&gt; c !== className) .join(' '); }, noop: () =&gt; {} }; const Model = function() { const validate = params =&gt; { if (!Number.isInteger(params.count)) { throw 'error: parameter "count" must be a valid integer'; } if (!Utils.isBoolean(params.upvoted)) { throw 'error: parameter "upvoted" must be a boolean'; } if (!Utils.isBoolean(params.downvoted)) { throw 'error: parameter "downvoted" must be a boolean'; } if (!Utils.isBoolean(params.starred)) { throw 'error: parameter "starred" must be a boolean'; } if (params.callback &amp;&amp; !Utils.isFunction(params.callback)) { throw 'error: parameter "callback" must be a function'; } if (params.upvoted &amp;&amp; params.downvoted) { throw 'error: parameters "upvoted" and "downvoted" must not be true at the same time'; } }; const create = params =&gt; { validate(params); const data = Utils.combine(params); const upvote = () =&gt; { if (data.upvoted) { data.count--; } else { data.count++; if (data.downvoted) { data.downvoted = false; data.count++; } } data.upvoted = !data.upvoted; }; const downvote = () =&gt; { if (data.downvoted) { data.count++; } else { data.count--; if (data.upvoted) { data.upvoted = false; data.count--; } } data.downvoted = !data.downvoted; }; return { count: () =&gt; data.count, upvote: upvote, upvoted: () =&gt; data.upvoted, downvote: downvote, downvoted: () =&gt; data.downvoted, star: () =&gt; data.starred = !data.starred, starred: () =&gt; data.starred, data: () =&gt; Utils.combine(data) }; }; return { create: create }; }(); const View = function() { const create = id =&gt; { const dom = document.getElementById(id); if (dom === null) { throw 'error: could not find element with ID ' + id + ' in the DOM'; } if (Utils.classes(dom).includes(enabledClass)) { throw 'error: element with ID ' + id + ' is already in use by another upvote controller'; } dom.className += ' ' + enabledClass; const firstElementByClass = className =&gt; { const list = dom.getElementsByClassName(className); if (list === null) { throw 'error: could not find element with class ' + className + ' within element with ID ' + id + ' in the DOM'; } return list[0]; }; const createCounter = className =&gt; { const dom = firstElementByClass(className); if (dom === undefined) { return { count: () =&gt; undefined, set: Utils.noop }; } return { count: () =&gt; parseInt(dom.innerHTML || 0, 10), set: value =&gt; dom.innerHTML = value }; }; const createToggle = (className, activeClassName) =&gt; { const createClasses = () =&gt; { const classes = { [className]: true, [activeClassName]: false, }; item.className.split(/ +/) .filter(x =&gt; x) .forEach(className =&gt; classes[className] = true); return classes; }; const formatClassName = () =&gt; { return Object.entries(classes) .filter(e =&gt; e[1]) .map(e =&gt; e[0]) .join(' '); }; const item = firstElementByClass(className); if (item === undefined) { return { get: () =&gt; false, set: Utils.noop, onClick: Utils.noop }; } const classes = createClasses(); return { get: () =&gt; classes[activeClassName], set: value =&gt; { classes[activeClassName] = value; item.className = formatClassName(); }, onClick: fun =&gt; item.onclick = fun }; }; const render = model =&gt; { counter.set(model.count()); upvote.set(model.upvoted()); downvote.set(model.downvoted()); star.set(model.starred()); }; const parseParamsFromDom = () =&gt; { return { count: counter.count(), upvoted: upvote.get(), downvoted: downvote.get(), starred: star.get() }; }; const destroy = () =&gt; { Utils.removeClass(dom, enabledClass); upvote.onClick(null); downvote.onClick(null); star.onClick(null); }; const counter = createCounter(countClass); const upvote = createToggle(upvoteClass, upvoteOnClass); const downvote = createToggle(downvoteClass, downvoteOnClass); const star = createToggle(starClass, starOnClass); return { render: render, parseParamsFromDom: parseParamsFromDom, onClickUpvote: fun =&gt; upvote.onClick(fun), onClickDownvote: fun =&gt; downvote.onClick(fun), onClickStar: fun =&gt; star.onClick(fun), destroy: destroy }; }; return { create: create }; }(); const create = (id, params = {}) =&gt; { var destroyed = false; const view = View.create(id); const domParams = view.parseParamsFromDom(); const defaults = { id: id, count: 0, upvoted: false, downvoted: false, starred: false, callback: () =&gt; {} }; const combinedParams = Utils.combine(defaults, domParams, params); const model = Model.create(combinedParams); const callback = combinedParams.callback; const throwIfDestroyed = () =&gt; { if (destroyed) { throw "fatal: unexpected call to destroyed controller"; } }; const upvote = () =&gt; { throwIfDestroyed(); model.upvote(); view.render(model); callback(model.data()); }; const downvote = () =&gt; { throwIfDestroyed(); model.downvote(); view.render(model); callback(model.data()); }; const star = () =&gt; { throwIfDestroyed(); model.star(); view.render(model); callback(model.data()); }; const destroy = () =&gt; { throwIfDestroyed(); destroyed = true; view.destroy(); }; view.render(model); view.onClickUpvote(upvote); view.onClickDownvote(downvote); view.onClickStar(star); return { id: id, count: () =&gt; { throwIfDestroyed(); return model.count(); }, upvote: upvote, upvoted: () =&gt; { throwIfDestroyed(); return model.upvoted(); }, downvote: downvote, downvoted: () =&gt; { throwIfDestroyed(); return model.downvoted(); }, star: star, starred: () =&gt; { throwIfDestroyed(); return model.starred(); }, destroy: destroy }; }; return { create: create }; }(); </code></pre> <h3>Unit tests</h3> <p>I'm also interested in a review of the unit tests (<a href="https://janosgyerik.github.io/upvotejs/tests/vanilla.html" rel="nofollow noreferrer">live tests of current version</a>):</p> <pre><code>const create = (id, params) =&gt; { return Upvote.create(id, params); }; QUnit.test('throw exception if destroy is called twice', assert =&gt; { const obj = gen(); obj.destroy(); assert.throws(() =&gt; obj.destroy()); }); const gen = function() { var idcount = 0; return (params = {}) =&gt; { ++idcount; const id = params.id || ('u' + idcount); const jqdom = $('#templates div.upvotejs').clone(); jqdom.attr('id', id); $('#tests').append(jqdom); params.callback = params.callback || (data =&gt; {}); return create(id, params, jqdom); }; }(); const uiTester = obj =&gt; { const widget = $('#' + obj.id); const count = widget.find('.count'); const upvote = widget.find('.upvote'); const downvote = widget.find('.downvote'); const star = widget.find('.star'); return { count: () =&gt; parseInt(count.text(), 10), upvoted: () =&gt; upvote.hasClass('upvote-on'), downvoted: () =&gt; downvote.hasClass('downvote-on'), starred: () =&gt; star.hasClass('star-on'), upvote: () =&gt; upvote.click(), downvote: () =&gt; downvote.click(), star: () =&gt; star.click() }; }; QUnit.test('initialize from params', assert =&gt; { const obj = gen(); assert.equal(obj.count(), 0); assert.equal(obj.upvoted(), false); assert.equal(obj.downvoted(), false); assert.equal(obj.starred(), false); assert.equal(gen({count: 17}).count(), 17); assert.equal(gen({upvoted: true}).upvoted(), true); assert.equal(gen({downvoted: true}).downvoted(), true); assert.equal(gen({starred: true}).starred(), true); assert.throws(() =&gt; gen({count: 'foo'}), 'throw if count param is not an integer'); assert.throws(() =&gt; gen({upvoted: 'foo'}), 'throw if upvoted param is not a boolean'); assert.throws(() =&gt; gen({downvoted: 'foo'}), 'throw if downvoted param is not a boolean'); assert.throws(() =&gt; gen({starred: 'foo'}), 'throw if starred param is not a boolean'); assert.throws(() =&gt; gen({callback: 'foo'}), 'throw if callback param is not a function'); assert.throws(() =&gt; gen({upvoted: true, downvoted: true}), 'throw if upvoted=true and downvoted=true'); }); QUnit.test('initialize from dom', assert =&gt; { const v1 = Upvote.create('count-1'); assert.equal(v1.count(), 1); assert.equal(v1.upvoted(), false); assert.equal(v1.downvoted(), false); assert.equal(v1.starred(), false); const v2 = Upvote.create('count-2-upvoted'); assert.equal(v2.count(), 2); assert.equal(v2.upvoted(), true); assert.equal(v2.downvoted(), false); assert.equal(v2.starred(), false); const v3 = Upvote.create('count-3-upvoted-starred'); assert.equal(v3.count(), 3); assert.equal(v3.upvoted(), true); assert.equal(v3.downvoted(), false); assert.equal(v3.starred(), true); const v4 = Upvote.create('count-4-downvoted'); assert.equal(v4.count(), 4); assert.equal(v4.upvoted(), false); assert.equal(v4.downvoted(), true); assert.equal(v4.starred(), false); const v5 = Upvote.create('count-5-downvoted-starred'); assert.equal(v5.count(), 5); assert.equal(v5.upvoted(), false); assert.equal(v5.downvoted(), true); assert.equal(v5.starred(), true); const vLarge = Upvote.create('count-456789'); assert.equal(vLarge.count(), 456789); assert.equal(vLarge.upvoted(), false); assert.equal(vLarge.downvoted(), false); assert.equal(vLarge.starred(), false); const vNegativeLarge = Upvote.create('count-minus-456789'); assert.equal(vNegativeLarge.count(), -456789); assert.equal(vNegativeLarge.upvoted(), false); assert.equal(vNegativeLarge.downvoted(), false); assert.equal(vNegativeLarge.starred(), false); assert.throws(() =&gt; Upvote.create('upvoted-downvoted')); }); QUnit.test('UI updated from params', assert =&gt; { const obj = uiTester(gen()); assert.equal(obj.count(), 0); assert.equal(obj.upvoted(), false); assert.equal(obj.downvoted(), false); assert.equal(obj.starred(), false); assert.equal(uiTester(gen({count: 17})).count(), 17); assert.equal(uiTester(gen({upvoted: true})).upvoted(), true); assert.equal(uiTester(gen({downvoted: true})).downvoted(), true); assert.equal(uiTester(gen({starred: true})).starred(), true); }); QUnit.test('upvote non-downvoted non-upvoted', assert =&gt; { const count = 5; const obj = gen({count: count}); assert.equal(obj.count(), count); obj.upvote(); assert.equal(obj.count(), count + 1); }); QUnit.test('upvote downvoted', assert =&gt; { const count = 6; const obj = gen({count: count, downvoted: true}); assert.equal(obj.count(), count); obj.upvote(); assert.equal(obj.count(), count + 2); }); QUnit.test('upvote upvoted', assert =&gt; { const count = 7; const obj = gen({count: count, upvoted: true}); assert.equal(obj.count(), count); obj.upvote(); assert.equal(obj.count(), count - 1); }); QUnit.test('downvote non-downvoted non-upvoted', assert =&gt; { const count = 5; const obj = gen({count: count}); assert.equal(obj.count(), count); obj.downvote(); assert.equal(obj.count(), count - 1); }); QUnit.test('downvote upvoted', assert =&gt; { const count = 6; const obj = gen({count: count, upvoted: true}); assert.equal(obj.count(), count); obj.downvote(); assert.equal(obj.count(), count - 2); }); QUnit.test('downvote downvoted', assert =&gt; { const count = 7; const obj = gen({count: count, downvoted: true}); assert.equal(obj.count(), count); obj.downvote(); assert.equal(obj.count(), count + 1); }); QUnit.test('star non-starred', assert =&gt; { const obj = gen(); obj.star(); assert.ok(obj.starred(), 'should be starred'); }); QUnit.test('star starred', assert =&gt; { const obj = gen({starred: true}); obj.star(); assert.ok(!obj.starred(), 'should not be starred'); }); QUnit.test('upvote indepently', assert =&gt; { const count1 = 5; const v1 = gen({count: count1}); const count2 = 5; const v2 = gen({count: count2}); v1.upvote(); assert.equal(v1.count(), count1 + 1); assert.equal(v2.count(), count2); }); QUnit.test('downvote indepently', assert =&gt; { const count1 = 5; const v1 = gen({count: count1}); const count2 = 5; const v2 = gen({count: count2}); v1.downvote(); assert.equal(v1.count(), count1 - 1); assert.equal(v2.count(), count2); }); QUnit.test('star indepently', assert =&gt; { const v1 = gen(); const v2 = gen(); v1.star(); assert.equal(v1.starred(), true); assert.equal(v2.starred(), false); }); QUnit.test('call callback on value changes', assert =&gt; { var receivedPayload; const callback = payload =&gt; receivedPayload = payload; const obj1_id = 100; const obj1_origCount = 10; const obj1 = gen({id: obj1_id, count: obj1_origCount, callback: callback}); const obj2_id = 200; const obj2_origCount = 20; const obj2 = gen({id: obj2_id, count: obj2_origCount, callback: callback}); obj1.upvote(); assert.deepEqual(receivedPayload, { id: obj1_id, action: 'upvote', newState: { count: obj1_origCount + 1, downvoted: false, upvoted: true, starred: false } }); obj2.upvote(); assert.deepEqual(receivedPayload, { id: obj2_id, action: 'upvote', newState: { count: obj2_origCount + 1, downvoted: false, upvoted: true, starred: false } }); obj1.upvote(); assert.deepEqual(receivedPayload, { id: obj1_id, action: 'unupvote', newState: { count: obj1_origCount, downvoted: false, upvoted: false, starred: false } }); obj2.star(); assert.deepEqual(receivedPayload, { id: obj2_id, action: 'star', newState: { count: obj2_origCount + 1, downvoted: false, upvoted: true, starred: true } }); obj2.star(); assert.deepEqual(receivedPayload, { id: obj2_id, action: 'unstar', newState: { count: obj2_origCount + 1, downvoted: false, upvoted: true, starred: false } }); obj2.downvote(); assert.deepEqual(receivedPayload, { id: obj2_id, action: 'downvote', newState: { count: obj2_origCount - 1, downvoted: true, upvoted: false, starred: false } }); obj2.downvote(); assert.deepEqual(receivedPayload, { id: obj2_id, action: 'undownvote', newState: { count: obj2_origCount, downvoted: false, upvoted: false, starred: false } }); }); QUnit.test('update model updates UI', assert =&gt; { const obj = gen(); const ui = uiTester(obj); obj.upvote(); assert.equal(ui.count(), 1); assert.equal(ui.upvoted(), true); obj.downvote(); assert.equal(ui.count(), -1); assert.equal(ui.upvoted(), false); assert.equal(ui.downvoted(), true); obj.upvote(); assert.equal(ui.count(), 1); assert.equal(ui.upvoted(), true); assert.equal(ui.downvoted(), false); obj.star(); assert.equal(ui.starred(), true); obj.star(); assert.equal(ui.starred(), false); }); QUnit.test('update UI updates model', assert =&gt; { const obj = gen(); const ui = uiTester(obj); ui.upvote(); assert.equal(obj.count(), 1); assert.equal(obj.upvoted(), true); ui.downvote(); assert.equal(obj.count(), -1); assert.equal(obj.upvoted(), false); assert.equal(obj.downvoted(), true); ui.upvote(); assert.equal(obj.count(), 1); assert.equal(obj.upvoted(), true); assert.equal(obj.downvoted(), false); ui.star(); assert.equal(obj.starred(), true); ui.star(); assert.equal(obj.starred(), false); }); QUnit.test('cannot associate multiple models to the same id', assert =&gt; { const orig = gen(); assert.throws(() =&gt; gen({id: orig.id})); }); QUnit.test('widget stops responding to clicks after destroyed', assert =&gt; { const obj = gen({count: 99}); const ui = uiTester(obj); ui.upvote(); assert.equal(ui.count(), 100); ui.upvote(); assert.equal(ui.count(), 99); obj.destroy(); ui.upvote(); assert.equal(ui.count(), 99); assert.throws(() =&gt; obj.upvote()); assert.throws(() =&gt; obj.downvote()); assert.throws(() =&gt; obj.star()); assert.throws(() =&gt; obj.count()); assert.throws(() =&gt; obj.upvoted()); assert.throws(() =&gt; obj.downvoted()); assert.throws(() =&gt; obj.starred()); const reused = gen({id: obj.id}); assert.equal(reused.count(), 99); ui.upvote(); assert.equal(reused.count(), 100); }); QUnit.test('all sub-elements (upvote/downvote/count/star) are optional in the HTML markup', assert =&gt; { ['upvote', 'downvote', 'count', 'star'].forEach(cls =&gt; { const obj0 = gen(); obj0.destroy(); const jqdom = $('#' + obj0.id); jqdom.find('.' + cls).remove(); const obj = create(obj0.id, {}, jqdom); assert.equal(obj.count(), 0); obj.upvote(); assert.equal(obj.count(), 1); assert.equal(obj.upvoted(), true); obj.downvote(); assert.equal(obj.count(), -1); assert.equal(obj.downvoted(), true); assert.equal(obj.upvoted(), false); obj.downvote(); assert.equal(obj.count(), 0); assert.equal(obj.downvoted(), false); obj.star(); assert.equal(obj.starred(), true); obj.star(); assert.equal(obj.starred(), false); }); } </code></pre> <h3>Code review</h3> <p>I'm looking for a review of the posted code in any and all aspects.</p> <p>Some particular areas do come to mind I'm especially curious about:</p> <ul> <li>Bad practices: is there anything to fix</li> <li>Usability: is there anything that looks hard to use, and how to make it better</li> <li>Are the tests sufficient? Did I miss any important cases?</li> <li>Are the tests overcomplicated? Do you see ways to simplify?</li> <li>I'm used to using QUnit for testing JavaScript packages. Do you think I could benefit greatly by using something else?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T23:22:35.357", "Id": "412434", "Score": "0", "body": "Some comments wouldn't go amiss." } ]
[ { "body": "<h2>Foreword</h2>\n\n<p>There is quite a bit of code here and it has taken a bit of time to process - especially the unit tests. I feel like the thoughts below will be incomplete but if I think of other ideas in the future, I could add those later.</p>\n\n<h2>General Feedback</h2>\n\n<p>I know you have made various versions of this in the past - including <a href=\"https://codereview.stackexchange.com/q/49231/120114\">a jQuery version posted in 2014</a> and this vanilla JS version appears to use <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> features like the <code>let</code> and <code>const</code> keywords, as well as arrow functions. Did you consider using the ES-6 class syntax? I know they are really just \"<em>primarily syntactical sugar over JavaScript's existing prototype-based inheritance</em>\"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">1</a></sup> and \"<em>there’s no way to define private methods, getters and setters</em>\"<sup><a href=\"https://www.sitepoint.com/javascript-private-class-fields/#privateclassfields\" rel=\"nofollow noreferrer\">2</a></sup> so perhaps the revealing module pattern is best here for concealing private methods.</p>\n\n<p>The test code is very lengthy and I can't think of any cases not covered, but there may still be other scenarios that should be considered. I don't see any obvious simplifications for that code. </p>\n\n<p>To DRY out some of that code, you could consider throwing the initialization strings in <code>QUnit.test('initialize from dom', ...)</code> for <code>v1</code> through <code>v5</code> into an array and iterating over them. Perhaps something like below would work (*<em>untested</em>):</p>\n\n<pre><code>const initStrings = [\n 'count-1', \n 'count-2-upvoted', \n 'count-3-upvoted-starred', \n 'count-4-downvoted',\n 'count-5-downvoted-starred', \n];\nconst adjMethods = ['upvoted', 'downvoted', 'starred'];\ninitStrings.forEach(initStr =&gt; {\n const voteObj = Upvote.create(initStr);\n const parts = initStr.split('-'); // could also destructure here\n assert.equal(voteObj.count(), parts[1]);\n adjMethods.forEach(adjMethod =&gt; assert.equal(voteObj[adjMethod](), parts.includes(adjMethod))); \n});\n</code></pre>\n\n<h2>Targeted Feedback</h2>\n\n<ul>\n<li><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a></strong> could be used to simplify some <code>for</code> loops - e.g. in <code>Utils.combine()</code>. That way there wouldn't be a need to make a variable like <code>i</code>, increment it, and use it to access each element.</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\"><strong>Shorthand property names</strong></a> - can be used to simplify assignment - e.g. return objects from: </p>\n\n<ul>\n<li><code>Model.create()</code> </li>\n<li><code>View.create()</code></li>\n<li><code>Model</code></li>\n<li><code>View</code></li>\n</ul>\n\n<p>as well as the <code>defaults</code> object used in <code>Upvote.create()</code></p></li>\n<li><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList\" rel=\"nofollow noreferrer\"><code>Element.classList.add()</code></a></strong> could be used instead of manually altering <code>className</code> property and dealing with spaces to separate names in <code>View.create()</code>, and <code>Element.classList.remove()</code> could likely eliminate the need for <code>Utils.removeClass()</code>.</li>\n<li><strong>Excess filter loop</strong> - in <code>Utils.removeClass()</code> - simplify to <code>x =&gt; x &amp;&amp; x !== className</code></li>\n<li><strong>Repeated <code>Utils.Noop()</code></strong> - appears duplicated within <code>defaults</code> declared in <code>View.create()</code> </li>\n<li><p><strong>Excess wrapper function in unit tests</strong> </p>\n\n<blockquote>\n<pre><code>const create = (id, params) =&gt; {\n return Upvote.create(id, params);\n};\n</code></pre>\n</blockquote>\n\n<p>could be simplified to:</p>\n\n<pre><code>const create = Upvote.create;\n</code></pre>\n\n<p>unless for some reason there is a difference in arguments passed to that function....</p></li>\n</ul>\n\n<hr>\n\n<p>It appears that the unit test helper <code>gen()</code> has changed in the github repo since you posted this, but I was curious about the <code>idcount</code> variable in the code above:</p>\n\n<blockquote>\n<pre><code>const gen = function() {\n var idcount = 0;\n return (params = {}) =&gt; {\n ++idcount;\n const id = params.id || ('u' + idcount);\n</code></pre>\n</blockquote>\n\n<p>I considered suggesting that the <code>++idcount</code> get moved into the usage on the line below, where <code>id</code> is assigned. Maybe you always want that incremented whenever the function is called, but that variable doesn't appear to be used anywhere else in that function or elsewhere, which leads me to believe that it could be incremented only when used and it would still work the same.</p>\n\n<hr>\n\n<p>And even though they are \"<em>constant variables</em>\" declared with <code>const</code>, you might consider using all uppercase numbers for the constant string values, just like you use in Java and other languages - e.g. instead of:</p>\n\n<blockquote>\n<pre><code>const upvoteClass = 'upvote';\nconst enabledClass = 'upvotejs-enabled';\n</code></pre>\n</blockquote>\n\n<p>use uppercase:</p>\n\n<pre><code>const UPVOTED_CLASS = 'upvote';\nconst ENABLED_CLASS = 'upvotejs-enabled';\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes</a></sub></p>\n\n<p><sup>2</sup><sub><a href=\"https://www.sitepoint.com/javascript-private-class-fields/#privateclassfields\" rel=\"nofollow noreferrer\">https://www.sitepoint.com/javascript-private-class-fields/#privateclassfields</a></sub></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T18:45:07.893", "Id": "221737", "ParentId": "213172", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T07:52:55.327", "Id": "213172", "Score": "4", "Tags": [ "javascript", "unit-testing", "ecmascript-6", "event-handling", "dom" ], "Title": "UpvoteJS, a simple voting widget in vanilla JavaScript" }
213172
<p>This is a very simple clone of Flappy Bird using Kivy, to be used for <em>programming class for teens</em>. The game consists of 3 classes: <code>Bird</code>, <code>Game</code>, and <code>ResetBtn</code>. </p> <hr> <p><strong><em>Q:</em></strong> How to make it more efficient, clean, and clear for the students? (without using <code>kv</code> file)</p> <hr> <p><strong><em>Code Explanation:</em></strong></p> <p>The <code>Bird</code> class inherits from <code>Image</code> class, a <code>Clock.schedule_interval</code> will call the <code>update</code> method of the bird class (method for the continuous fall). It also has <code>on_touch_down</code> that sets the height of the bird higher than before (discontinuously). There is also a short time image changing effect (Bird facing up after a mouse press, then facing down again after a short time, by the <code>self.fall</code> increment). I was careful to not put equation of physics equation, so I only use increments for the motion of the bird.</p> <pre><code>flappy_down = "flappy_down.png" flappy_up = "flappy_up.png" class Bird(Image): def __init__(self): super().__init__(source = flappy_down) self.height_frac = 0.5 self.fall = 0 def on_touch_down(self, touch): self.height_frac += 0.15 self.source = flappy_up self.fall = 0 def update(self, dt): self.fall += 1 self.height_frac += -1/100 print(self.height_frac) self.pos_hint = {'x': 0.5, 'y': self.height_frac} if self.source != flappy_down and self.fall == 15: self.source = flappy_down </code></pre> <p>The <code>Game</code> class is a <code>FloatLayout</code> that has 2 children: <code>Bird()</code> and <code>ResetBtn()</code>. The walls/obstacles are made without widgets, they are made using <code>Game.canvas</code> and <code>Rectangle</code>. Collision is counted whenever the center of the bird's image is inside a rectangle. A new wall will be generated every time the previous wall has passed the position at 40% of the window's width, with random height and bottom position. When collision happens, the game will <code>unschedule</code> all scheduled intervals.</p> <pre><code>class Game(FloatLayout): def __init__(self): super().__init__() self.kiwi = Bird() self.resetbtn = ResetBtn() self.label = Label(text = "", halign = 'center', valign = 'center', font_size = 100) self.add_widget(self.kiwi) self.add_widget(self.resetbtn) self.add_widget(self.label) self.kiwi.size_hint = (50/Window.size[0], 50/Window.size[1]) self.kiwi.pos_hint = {'x': 0.5, 'y': 0.5} self.resetbtn.size_hint = (0.25, 0.1) self.resetbtn.pos_hint = {'x': 0.05, 'y': 0.85} self.label.size_hint = (0.5, 0.2) self.label.pos_hint = {'x': 0.25, 'y': 0.75} self.walls = [] self.current_wall = None self.add_random_wall() def add_wall(self, pos, size, color): self.rect = Rectangle(pos=pos, size=size) self.color = Color(*color) self.canvas.add(self.color) self.canvas.add(self.rect) self.walls.append(self.rect) self.current_wall = self.rect def add_random_wall(self): height = random.uniform(100, 400) pos_y = random.uniform(0, Window.size[1]-400) self.add_wall((745, pos_y), (50, height), (1, 0.3, 0, 1)) def update(self, dt): for i in self.walls: i.pos = (i.pos[0]-100*dt, i.pos[1]) self.walls = [i for i in self.walls if i.pos[0] &gt;= -50] if self.walls[-1].pos[0] &lt;= 0.5*Window.size[0] - 70: self.add_random_wall() print(len(self.walls)) kiwi_windowpos = [self.kiwi.pos_hint['x']*Window.size[0], \ self.kiwi.pos_hint['y']*Window.size[1]] print(kiwi_windowpos) if ((self.current_wall.pos[0] &lt;=(kiwi_windowpos[0] + 25) &lt;= self.current_wall.pos[0] + 50) \ and (self.current_wall.pos[1] &lt;=(kiwi_windowpos[1] + 25) &lt;= self.current_wall.pos[1] + self.current_wall.size[1])) \ or (kiwi_windowpos[1] + 25 &lt;= 0) or (kiwi_windowpos[1] + 25 &gt;= Window.size[1]): self.label.text = "Game Over" Clock.unschedule(self.kiwi_update) Clock.unschedule(self.wall_update) def reset(self): self.clear_widgets() for i in self.walls: del i del self.current_wall self.canvas.clear() Clock.unschedule(self.kiwi_update) Clock.unschedule(self.wall_update) self.kiwi = Bird() self.resetbtn = ResetBtn() self.label = Label(text = "", halign = 'center', valign = 'center', font_size = 100) self.add_widget(self.kiwi) self.add_widget(self.resetbtn) self.add_widget(self.label) self.kiwi.size_hint = (50/Window.size[0], 50/Window.size[1]) self.kiwi.pos_hint = {'x': 0.5, 'y': 0.5} self.resetbtn.size_hint = (0.25, 0.1) self.resetbtn.pos_hint = {'x': 0.05, 'y': 0.85} self.label.size_hint = (0.5, 0.2) self.label.pos_hint = {'x': 0.25, 'y': 0.75} self.walls = [] self.current_wall = None self.add_random_wall() self.kiwi_update = Clock.schedule_interval(self.kiwi.update, 0.01) self.wall_update = Clock.schedule_interval(self.update, 0.01) </code></pre> <p>Here is the reset button:</p> <pre><code>class ResetBtn(Button): def __init__(self): super().__init__(text = "Reset", halign = "center", valign = "center") def on_release(self): super().on_release() self.parent.reset() </code></pre> <p>The imports:</p> <pre><code>import random from kivy.app import App from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image from kivy.clock import Clock from kivy.graphics import Rectangle, Color </code></pre> <hr> <p><strong><em>Image files:</em></strong></p> <p><code>flappy_up.png</code>:</p> <p><a href="https://i.stack.imgur.com/JBuRB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JBuRB.png" alt="Flappy Up"></a></p> <p><code>flappy_down.png</code>:</p> <p><a href="https://i.stack.imgur.com/j2zv8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j2zv8.png" alt="Flappy Down"></a></p> <hr> <p><strong><em>Implementation:</em></strong></p> <pre><code>import random from kivy.app import App from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image from kivy.clock import Clock from kivy.graphics import Rectangle, Color flappy_down = "/home/asus/Arief_tempo/Tutor_JKT/Python_Tutor/FlappyKivy-master/images/flappy.png" flappy_up = "/home/asus/Arief_tempo/Tutor_JKT/Python_Tutor/FlappyKivy-master/images/flappyup.png" class ResetBtn(Button): def __init__(self): super().__init__(text = "Reset", halign = "center", valign = "center") def on_release(self): super().on_release() self.parent.reset() class Bird(Image): def __init__(self): super().__init__(source = flappy_down) self.height_frac = 0.5 self.fall = 0 def on_touch_down(self, touch): self.height_frac += 0.15 self.source = flappy_up self.fall = 0 def update(self, dt): self.fall += 1 self.height_frac += -1/100 print(self.height_frac) self.pos_hint = {'x': 0.5, 'y': self.height_frac} if self.source != flappy_down and self.fall == 15: self.source = flappy_down class Game(FloatLayout): def __init__(self): super().__init__() self.kiwi = Bird() self.resetbtn = ResetBtn() self.label = Label(text = "", halign = 'center', valign = 'center', font_size = 100) self.add_widget(self.kiwi) self.add_widget(self.resetbtn) self.add_widget(self.label) self.kiwi.size_hint = (50/Window.size[0], 50/Window.size[1]) self.kiwi.pos_hint = {'x': 0.5, 'y': 0.5} self.resetbtn.size_hint = (0.25, 0.1) self.resetbtn.pos_hint = {'x': 0.05, 'y': 0.85} self.label.size_hint = (0.5, 0.2) self.label.pos_hint = {'x': 0.25, 'y': 0.75} self.walls = [] self.current_wall = None self.add_random_wall() def add_wall(self, pos, size, color): self.rect = Rectangle(pos=pos, size=size) self.color = Color(*color) self.canvas.add(self.color) self.canvas.add(self.rect) self.walls.append(self.rect) self.current_wall = self.rect def add_random_wall(self): height = random.uniform(100, 400) pos_y = random.uniform(0, Window.size[1]-400) self.add_wall((745, pos_y), (50, height), (1, 0.3, 0, 1)) def update(self, dt): for i in self.walls: i.pos = (i.pos[0]-100*dt, i.pos[1]) self.walls = [i for i in self.walls if i.pos[0] &gt;= -50] if self.walls[-1].pos[0] &lt;= 0.5*Window.size[0] - 70: self.add_random_wall() print(len(self.walls)) kiwi_windowpos = [self.kiwi.pos_hint['x']*Window.size[0], \ self.kiwi.pos_hint['y']*Window.size[1]] print(kiwi_windowpos) if ((self.current_wall.pos[0] &lt;=(kiwi_windowpos[0] + 25) &lt;= self.current_wall.pos[0] + 50) \ and (self.current_wall.pos[1] &lt;=(kiwi_windowpos[1] + 25) &lt;= self.current_wall.pos[1] + self.current_wall.size[1])) \ or (kiwi_windowpos[1] + 25 &lt;= 0) or (kiwi_windowpos[1] + 25 &gt;= Window.size[1]): self.label.text = "Game Over" Clock.unschedule(self.kiwi_update) Clock.unschedule(self.wall_update) def reset(self): self.clear_widgets() for i in self.walls: del i del self.current_wall self.canvas.clear() Clock.unschedule(self.kiwi_update) Clock.unschedule(self.wall_update) self.kiwi = Bird() self.resetbtn = ResetBtn() self.label = Label(text = "", halign = 'center', valign = 'center', font_size = 100) self.add_widget(self.kiwi) self.add_widget(self.resetbtn) self.add_widget(self.label) self.kiwi.size_hint = (50/Window.size[0], 50/Window.size[1]) self.kiwi.pos_hint = {'x': 0.5, 'y': 0.5} self.resetbtn.size_hint = (0.25, 0.1) self.resetbtn.pos_hint = {'x': 0.05, 'y': 0.85} self.label.size_hint = (0.5, 0.2) self.label.pos_hint = {'x': 0.25, 'y': 0.75} self.walls = [] self.current_wall = None self.add_random_wall() self.kiwi_update = Clock.schedule_interval(self.kiwi.update, 0.01) self.wall_update = Clock.schedule_interval(self.update, 0.01) class FlApp(App): def build(self): g= Game() g.kiwi_update = Clock.schedule_interval(g.kiwi.update, 0.01) g.wall_update = Clock.schedule_interval(g.update, 0.01) return g if __name__ == "__main__": FlApp().run() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:18:24.937", "Id": "213179", "Score": "2", "Tags": [ "python", "object-oriented", "game", "physics", "kivy" ], "Title": "Simple Flappy Bird Clone using Kivy (with very minimum physics)" }
213179
<p>I work with an API where I need to write code to generate n appointment dates in the coming m months (from today). For the purpose, I write a Random date generator class provided. One condition is I need to use the <code>java.sql.Date</code> for the class. </p> <pre><code>import java.sql.Date; import java.time.LocalDate; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Objects; import java.util.Random; public class RandomDate { private final Random random; private final Date currentDate; private final int months; public RandomDate(Random random, Date currentDate, int months) { this.random = random; this.currentDate = currentDate; this.months = months; } public Date getRangeEndDate() { Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(this.currentDate.getTime()); calendar.add(Calendar.DATE, this.months * 30); return new Date(calendar.getTimeInMillis()); } public Date generateRandomDate(Date endDate) { int start = (int) this.currentDate.toLocalDate().toEpochDay(); int end = (int) endDate.toLocalDate().toEpochDay(); long randomDay = start + random.nextInt(end - start); return Date.valueOf(LocalDate.ofEpochDay(randomDay)); } } </code></pre> <p>I have an issue that within the code I use the time classes from 3 different packages (java.sql, java.time, and java.util). How can I write it more elegantly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T15:24:49.733", "Id": "412400", "Score": "0", "body": "Why would three different packages be a problem? Especially when one of them is `java.util`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T15:39:07.223", "Id": "412405", "Score": "0", "body": "I updated the code with only using the `java.time.LocalDate`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-12T04:20:21.370", "Id": "420347", "Score": "1", "body": "Why do you need to use `java.sql.Date`? This requirement may be 20 years old. Current code uses `java.time.LocalDate` instead." } ]
[ { "body": "<p>I updated the code with only using the <code>java.time.LocalDate</code></p>\n\n<pre><code>public class RandomDate {\n\n private final LocalDate today;\n\n private final Random random;\n private final int months;\n\n\n public RandomDate(Random random, int months) {\n\n this.today = LocalDate.now();\n\n this.random = random;\n this.months = months;\n }\n\n\n public LocalDate getRangeEndDate() {\n\n LocalDate rangeEndDay = this.today.plusDays(this.months * 30);\n return rangeEndDay;\n }\n\n public LocalDate generateRandomDate(LocalDate endDate) {\n\n int start = (int) this.today.toEpochDay();\n int end = (int) endDate.toEpochDay();\n\n long randomDay = start + random.nextInt(end - start);\n return LocalDate.ofEpochDay(randomDay);\n }\n\n\n public LocalDate getToday() {\n return today;\n }\n\n public Random getRandom() {\n return random;\n }\n\n public int getMonths() {\n return months;\n }\n\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof RandomDate)) return false;\n RandomDate that = (RandomDate) o;\n return getMonths() == that.getMonths() &amp;&amp;\n Objects.equals(getToday(), that.getToday()) &amp;&amp;\n Objects.equals(getRandom(), that.getRandom());\n }\n\n @Override\n public int hashCode() {\n\n return Objects.hash(getToday(), getRandom(), getMonths());\n }\n\n @Override\n public String toString() {\n return \"RandomDate{\" +\n \"today=\" + today +\n \", random=\" + random +\n \", months=\" + months +\n '}';\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-12T03:57:58.393", "Id": "420345", "Score": "1", "body": "This code is overly long and hard-codes a month to be exactly 30 days, which is wrong. It also creates a class `RandomDate` for no apparent reason when a utility function would serve the same purpose." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T15:39:33.597", "Id": "213194", "ParentId": "213184", "Score": "-1" } }, { "body": "<p>The essential part of your code is:</p>\n\n<pre><code>static LocalDate random(LocalDate start, int months, Random rnd) {\n LocalDate end = start.plusMonths(months);\n int days = (int) ChronoUnit.DAYS.between(start, end);\n return start.plusDays(rnd.nextInt(days + 1));\n}\n</code></pre>\n\n<p>I have no idea why you need more code than this to express the idea.</p>\n\n<p>I don't see any practical reason to use either the old and ugly <code>java.util.Date</code> or the even uglier <code>java.util.Calendar</code> or the inappropriate <code>java.sql.Date</code> (since this code has nothing to do with databases, let alone SQL). All you need are the classes from <code>java.time</code>, and <code>java.time.temporal</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-12T03:53:28.440", "Id": "217305", "ParentId": "213184", "Score": "3" } } ]
{ "AcceptedAnswerId": "217305", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:45:45.403", "Id": "213184", "Score": "1", "Tags": [ "java", "datetime", "jodatime" ], "Title": "Generate n appointments in the next m months" }
213184
<p>It's an exercise from a Vue.js course I'm enrolled into. The aim is to get comfortable with the Vue.js features <a href="https://vuejs.org/v2/guide/components-slots.html" rel="nofollow noreferrer">Slots</a> and <a href="https://vuejs.org/v2/guide/components.html#Dynamic-Components" rel="nofollow noreferrer">Dynamic components</a>. By clicking on the buttons one shall be able to change the currently selected and rendered component.</p> <p>With green button clicked: </p> <p><a href="https://i.stack.imgur.com/87ME7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/87ME7.png" alt="Screenshot of the App 1"></a></p> <p>With the red button clicked:</p> <p><a href="https://i.stack.imgur.com/L2xfy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L2xfy.png" alt="enter image description here"></a></p> <p>The four main files with the styling where provided by the instructor. I had to write the JavaScript code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// -- App.vue ------------------------------------------------------------ &lt;template&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12"&gt; &lt;h2&gt;Currently active component: {{ selected }}&lt;/h2&gt; &lt;br&gt; &lt;button class="btn btn-primary" @click="onClick($event, 'blue')"&gt;Load Blue Template&lt;/button&gt; &lt;button class="btn btn-success" @click="onClick($event, 'green')"&gt;Load Green Template&lt;/button&gt; &lt;button class="btn btn-danger" @click="onClick($event, 'red')"&gt;Load Red Template&lt;/button&gt; &lt;hr&gt; &lt;component :is="selected"&gt; &lt;h1 slot="blue-headline"&gt;Nicht von im verschwand so deiner und weiter. Liebe sonder.&lt;/h1&gt; &lt;p slot="blue-text"&gt;Youth weary his high he might, heart a his ever his&lt;/p&gt; &lt;h3 slot="green-headline"&gt;Bonan viroj por dum la kun la al mangxu hispanujo&lt;/h3&gt; &lt;p slot="green-text"&gt;Tempor sed kasd et rebum dolor ipsum vero ipsum invidunt. Erat est sed dolores gubergren.&lt;/p&gt; &lt;h2 slot="red-headline"&gt;Intendo cose vita con&lt;/h2&gt; &lt;p slot="red-text"&gt;Bist ich dahinten zurück du der der deiner liebe.&lt;/p&gt; &lt;/component&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import Blue from './components/Blue.vue'; import Green from './components/Green.vue'; import Red from './components/Red.vue'; export default { components: { appBlue: Blue, appGreen: Green, appRed: Red }, data: function() { return { selected: "appBlue" } }, methods: { onClick: function(event, selection) { switch (selection) { case "blue": this.selected = "appBlue"; break; case "green": this.selected = "appGreen"; break; case "red": this.selected = "appRed"; break; default: this.selected = "appBlue"; } } } } &lt;/script&gt; &lt;style&gt; &lt;/style&gt; // -- Blue.vue ----------------------------------------------------------- &lt;template&gt; &lt;div&gt; &lt;slot name="blue-headline"&gt;&lt;/slot&gt; &lt;slot name="blue-text"&gt;&lt;/slot&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; &lt;/script&gt; &lt;style scoped&gt; div { border: 1px solid blue; background-color: lightblue; padding: 30px; margin: 20px auto; text-align: center } &lt;/style&gt; // -- Green.vue ---------------------------------------------------------- &lt;template&gt; &lt;div&gt; &lt;slot name="green-headline"&gt;&lt;/slot&gt; &lt;slot name="green-text"&gt;&lt;/slot&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; &lt;/script&gt; &lt;style scoped&gt; div { border: 1px solid green; background-color: lightgreen; padding: 30px; margin: 20px auto; text-align: center } &lt;/style&gt; // -- Red.vue ------------------------------------------------------------ &lt;template&gt; &lt;div&gt; &lt;slot name="red-headline"&gt;&lt;/slot&gt; &lt;slot name="red-text"&gt;&lt;/slot&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; &lt;/script&gt; &lt;style scoped&gt; div { border: 1px solid red; background-color: lightcoral; padding: 30px; margin: 20px auto; text-align: center } &lt;/style&gt;</code></pre> </div> </div> </p> <p>Full project-directory here on <a href="https://github.com/mizech/vue-js-2/tree/master/assignment08" rel="nofollow noreferrer">GitHub</a>.</p> <p>What do you think about my solution? What would you have done differently and why?</p>
[]
[ { "body": "<p>Your code is overall very neat and clean and easily readable, I think you're ready for the next level!</p>\n\n<hr>\n\n<p>This switch maps from one string to another:</p>\n\n<pre><code>switch (selection) {\n case \"blue\":\n this.selected = \"appBlue\";\n break;\n case \"green\":\n this.selected = \"appGreen\";\n break;\n case \"red\":\n this.selected = \"appRed\";\n break;\n default:\n this.selected = \"appBlue\";\n}\n</code></pre>\n\n<p>This could either be changed into using a lookup dictionary:</p>\n\n<pre><code>let mappedComponents = { red: \"appRed\", blue: \"appBlue\", green: \"appGreen\" };\nthis.selected = mappedComponents[selection];\n</code></pre>\n\n<p>Or you could just skip that remapping and change the names of the components so that they directly match the <code>selection</code> value:</p>\n\n<pre><code>components: {\n blue: Blue,\n green: Green,\n red: Red\n},\n\nthis.selected = selection;\n</code></pre>\n\n<hr>\n\n<p>Other notes that might not have been in your control for the assignment:</p>\n\n<ul>\n<li>The CSS is duplicated. You could extract <code>padding</code>, <code>margin</code> and <code>text-align</code> to a separate CSS class.</li>\n<li>I would recommend having just one component for all three different colors and use a property to inject its colors.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T14:20:55.793", "Id": "213191", "ParentId": "213190", "Score": "4" } } ]
{ "AcceptedAnswerId": "213191", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T13:50:56.847", "Id": "213190", "Score": "2", "Tags": [ "javascript", "vue.js" ], "Title": "Slots and Dynamic Components" }
213190
<p>I'm playing with a simple (for now) project in PHP with Google Calendar API. I have posted the code here in order to improve my programming style about whatever you think it's worth suggesting. Thank you.</p> <p>As you can see, at the moment the script <code>listEvents.php</code> retrieves all the events in the last 7 days from <code>primary</code> calendar, and deletes the events whose title is included in the array <code>deletable</code>.</p> <p>Below is the code so far:</p> <p><strong>listEvents.php</strong></p> <pre><code>&lt;?php require_once (__DIR__."/beAuthorized.php"); require_once (__DIR__."/calConfig.php"); $beAuthorized = new beAuthorized(); $calConfig = calConfig::getInstance(); $deletable = $calConfig-&gt;getDeletable(); $calendarId = $calConfig-&gt;getCalendarId(); $optParams = array( 'orderBy' =&gt; 'startTime', 'singleEvents' =&gt; true, 'timeMin' =&gt; date('Y-m-d\TH:i:sP', strtotime('-7 days')), 'timeMax' =&gt; date('c'), ); try { $service = $beAuthorized-&gt;getService(); $results = $service-&gt;events-&gt;listEvents($calendarId, $optParams); $events = $results-&gt;getItems(); } catch (Exception $e) { echo 'Caught exception: ', $e-&gt;getMessage(), "\n"; } if (!empty($events)) { foreach ($events as $event) { if (in_array($event-&gt;getSummary(), $deletable)) { $service-&gt;events-&gt;delete($calendarId, $event-&gt;getId()); } } } </code></pre> <p><strong>beAuthorized.php</strong></p> <pre><code>&lt;?php require __DIR__ . '/vendor/autoload.php'; if (php_sapi_name() != 'cli') { throw new Exception('This application must be run on the command line.'); } class beAuthorized { /** * Returns an authorized API client. * @return Google_Client the authorized client object */ private function getClient() { $client = new Google_Client(); $client-&gt;setApplicationName('calendar-utilities'); $client-&gt;setScopes(Google_Service_Calendar::CALENDAR_READONLY); $client-&gt;addScope(Google_Service_Calendar::CALENDAR); $client-&gt;addScope(Google_Service_Calendar::CALENDAR_EVENTS); $client-&gt;setAuthConfig('credentials.json'); $client-&gt;setAccessType('offline'); $client-&gt;setPrompt('select_account consent'); // Load previously authorized token from a file, if it exists. // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. $tokenPath = 'token.json'; if (file_exists($tokenPath)) { $accessToken = json_decode(file_get_contents($tokenPath), true); $client-&gt;setAccessToken($accessToken); } // If there is no previous token or it's expired. if ($client-&gt;isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($client-&gt;getRefreshToken()) { $client-&gt;fetchAccessTokenWithRefreshToken($client-&gt;getRefreshToken()); } else { // Request authorization from the user. $authUrl = $client-&gt;createAuthUrl(); printf("Open the following link in your browser:\n%s\n", $authUrl); print 'Enter verification code: '; $authCode = trim(fgets(STDIN)); // Exchange authorization code for an access token. $accessToken = $client-&gt;fetchAccessTokenWithAuthCode($authCode); $client-&gt;setAccessToken($accessToken); // Check to see if there was an error. if (array_key_exists('error', $accessToken)) { throw new Exception(join(', ', $accessToken)); } } // Save the token to a file. if (!file_exists(dirname($tokenPath))) { mkdir(dirname($tokenPath), 0700, true); } file_put_contents($tokenPath, json_encode($client-&gt;getAccessToken())); } return $client; } /** * Returns a service object. */ public function getService() { // Get the API client and construct the service object. $client = $this-&gt;getClient(); $service = new Google_Service_Calendar($client); return $service; } } </code></pre> <p><strong>calConfig.php</strong></p> <pre><code>&lt;?php require_once (__DIR__."/singleton.php"); class calConfig extends singleton { private $calendarId; private $deletable; protected function __construct() { if(!isset($this-&gt;calendarId)) { $this-&gt;calendarId = 'primary'; } if(!isset($this-&gt;deletable)) { $this-&gt;deletable = array('Test', 'bye', 'one'); } } public function getCalendarId() { return $this-&gt;calendarId; } public function getDeletable() { return $this-&gt;deletable; } } </code></pre> <p><strong>singleton.php</strong></p> <pre><code>&lt;?php class singleton { private static $instances = []; protected function __construct() { } protected function __clone() { } public function __wakeup() { throw new \Exception("Cannot unserialize singleton"); } public static function getInstance() { $subclass = static::class; if (!isset(self::$instances[$subclass])) { self::$instances[$subclass] = new static; } return self::$instances[$subclass]; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T14:54:20.027", "Id": "213192", "Score": "2", "Tags": [ "php", "object-oriented", "datetime", "api" ], "Title": "PHP project with Google Calendar API" }
213192
<p>I'm a java programmer by trade and starting to learn C/C++. I'd appreciate any pointers on glaring issues with my code style which is acceptable in java but not in C. I feel like open_files is probably bad in C I'm used to that sort of thing in java to make code easier to scan ( setting *src_file on one line and testing the next)</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; void get_paths(char *src, char *dest, int buf_size) { fprintf(stdout, "Please enter src path:\n"); fgets(src, buf_size, stdin); src[strcspn(src, "\r\n")] = 0; fprintf(stdout, "\nPlease enter dest path:\n"); fgets(dest, buf_size, stdin); dest[strcspn(dest, "\r\n")] = 0; } int open_files(char *src, char *dest, FILE **src_file, FILE **dest_file) { *src_file = fopen(src, "r"); if(!*src_file) { fprintf(stderr, "\n%s is not a valid file or permission denied\n", src); return 0; } *dest_file = fopen(dest, "w"); if(!*dest_file) { fprintf(stderr, "\ncould not open %s for writing, check path exists and you have write permissions\n", dest); fclose(*src_file); return 0; } return 1; } int cpy(char *cpy_buf, FILE *src_file, FILE *dest_file) { size_t num_elements; while((num_elements = fread(cpy_buf, sizeof(char), sizeof(cpy_buf), src_file)) &gt; 0) { if(fwrite(cpy_buf, sizeof(char), num_elements, dest_file) != num_elements) { fprintf(stderr, "\nError while writing to destination \nAborting..."); return 0; } } return 1; } int main() { const int buf_size = 256; const int cpy_buf_siz = 64; char src[buf_size]; char dest[buf_size]; char cpy_buf[cpy_buf_siz]; FILE *src_file; FILE *dest_file; get_paths(src, dest, buf_size); fprintf(stdout, "\nAttempting to copy from %s to %s...\n", src, dest); if(!open_files(src, dest, &amp;src_file, &amp;dest_file)) return -1; fprintf(stdout, "\nStarting copy from %s to %s...\n", src, dest); int success = cpy(cpy_buf, src_file, dest_file); fclose(src_file); fclose(dest_file); return success ? 0 : 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T08:56:39.023", "Id": "412450", "Score": "1", "body": "You should not use `fread()` in units of more than one byte. It is designed to allow transfers of any multiple of any length, but it is misdesigned to return the number of transfers rather than the number of bytes, so it cannot report a short transfer. As a consequence it is almost certainly going to misreport the data count at end of file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T10:58:17.870", "Id": "412465", "Score": "2", "body": "If you're learning C++, then I don't necessarily recommend going via C. OTOH if you're learning both C and C++, prepare for a bumpy ride!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T04:41:18.503", "Id": "412859", "Score": "0", "body": "Good use of `src[strcspn(src, \"\\r\\n\")] = 0;`." } ]
[ { "body": "<h2>Prefer Symbolic Constants Over Magic Numbers</h2>\n<p>There is a header file that should be included, <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdlib.h.html\" rel=\"noreferrer\">stdlib.h</a>, that provides some standard symbolic constants such as <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status.\" rel=\"noreferrer\">EXIT_SUCCESS and EXIT_FAILURE</a>. It might also be better to define <code>buf_size</code> and <code>cpy_buf_siz</code> as symbolic constants. If you are using a C compiler use <code>#define</code> to define your constants, if you are using the c++ compiler use the <a href=\"http://www.enseignement.polytechnique.fr/informatique/INF478/docs/Cpp/en/cpp/language/constexpr.html\" rel=\"noreferrer\">const or constexpr</a>. The <code>open_files</code> function could also return these values.</p>\n<p>By using EXIT_SUCCESS and EXIT_FAILURE as the return values in the <code>cpy</code> function when main exists <code>success</code> doesn't need to be tested it can just be returned.</p>\n<h2>Test for Success or Failure on all User Input</h2>\n<p>The input value from <code>fgets()</code> is not checked to see if it is a valid value. NULL would not be a valid value in this case. The user could be prompted in a loop for each file name.</p>\n<h2>DRY Code</h2>\n<p>The function <code>get_paths()</code> could use a function such as <code>char *get_path(char* prompt)</code> that takes a prompt and returns a single string or NULL on failure. The error handling for <code>fgets()</code> could be in this function.</p>\n<p>It might be better if <code>cpy()</code> <code>called open_files()</code>. That would simplify the <code>cpy()</code> interface to</p>\n<pre><code>int cpy(char* src, char* dest);\n</code></pre>\n<p>If the C++ compiler is being used, it would probably be better to use <code>std::cin</code> and <code>std::cout</code> rather than <code>fgets()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T19:21:28.147", "Id": "412420", "Score": "0", "body": "I assume it's acceptable to keep using 0 and 1 for return values for other functions like open_files or should the code be refactored to also use EXIT_SUCCESS/FAILURE instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T19:44:07.120", "Id": "412421", "Score": "1", "body": "@SMC generally functions can return anything, but if I were writing the code for open_files I'd use EXIT_SUCCESS/FAILURE because that's what the code is doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T10:16:24.200", "Id": "412457", "Score": "3", "body": "@pacmaninbw since `open_files` does not exit at all, using the `EXIT_*` constants is completely wrong for that function." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T16:23:17.563", "Id": "213195", "ParentId": "213193", "Score": "11" } }, { "body": "<p>Regarding these kinds of statements: </p>\n\n<pre><code>fprintf(stderr, \"\\n%s is not a valid file or permission denied\\n\", src);\n</code></pre>\n\n<p>When the error indication is from a C library function, we should call </p>\n\n<pre><code>perror( \"my error message\" );\n</code></pre>\n\n<p>That will output to <code>stderr</code> both your error message AND the text reason the system thinks the error occurred.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T17:36:21.163", "Id": "213199", "ParentId": "213193", "Score": "6" } }, { "body": "<ul>\n<li><p>You test the return value of <code>fwrite</code>, which is good. However, <code>fread</code> may fail as well. Since <code>fread</code> doesn't distinguish error from end of file, you should call <code>ferror</code>:</p>\n\n<pre><code> while ((num_elements = fread(....)) &gt; 0) {\n ....\n }\n if (ferror(src)) {\n handle_error\n }\n</code></pre></li>\n<li><p><code>fprintf(stdout)</code>, while technically valid, looks strange. A <code>printf</code> suffices.</p></li>\n<li><p><code>cpy_buf</code> doesn't belong to <code>main</code>. Define it directly in <code>cpy</code>.</p></li>\n<li><p>Prefer passing file names via command line arguments.</p></li>\n<li><p>The <code>\"Aborting...\"</code> message doesn't have a terminating newline, and the next prompt will be printed on the same line (on any shell except <code>cmd.exe</code>). Make a habit to print a newline at the end of the message.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T18:09:04.053", "Id": "213203", "ParentId": "213193", "Score": "12" } }, { "body": "<p>One additional issue is with <code>sizeof(cpy_buf)</code> in <code>cpy</code>. This will be the size of a pointer (usually 4 or 8 bytes) and not the size of the buffer that <code>cpy_buf</code> points to. If you follow the advice given in other answers to define <code>cpy_buf</code> within <code>cpy</code>, rathar than pass it in as a parameter, this won't be a problem.</p>\n\n<p>Also a small read/write buffer is inefficient. You should use at least 512 bytes, and preferably something much larger (like 2048 or 16384 bytes).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T02:02:33.250", "Id": "213226", "ParentId": "213193", "Score": "4" } }, { "body": "<p>In your functions, you're outputting a string showing an error occurred, then returning <code>0</code>, which usually means \"Success!\". Then in your <code>main()</code> function, you're checking whether or not the functions succeed or fail. Have you tested the return codes and whether you're getting the correct return values?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T16:49:16.300", "Id": "412629", "Score": "0", "body": "This is probably one of those java things. In my mind 0 = false = failed but I know that the opposite is true for main exit codes since you can return specific ints to indicate what type of error occurred. It doesn't confuse me but that's why I'm asking for reviews from experienced C devs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:23:57.150", "Id": "412636", "Score": "0", "body": "And I've never programmed in Java, so I had no idea about that, lol. Glad it helped though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T03:16:21.130", "Id": "213228", "ParentId": "213193", "Score": "1" } } ]
{ "AcceptedAnswerId": "213195", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T15:16:49.833", "Id": "213193", "Score": "10", "Tags": [ "c", "file" ], "Title": "Basic C copy file implementation" }
213193
<p>So, i recently wrote code that can count the number of monotonic items (increasing, decreasing and constant). For an input such as <code>x = [1,2,3,3,2,0]</code> The provided example was:</p> <pre><code>1. Increasing: [1,2], [2,3], [1,2,3] 2. Constant: [3,3] 3. Decreasing: [3,2], [2,0], [3,2,0] </code></pre> <hr> <p>So, i broke the problem into two steps, firstly just getting all biggest monotonic sequences, and then finding all sub-lists within those sequences. During the process it seemed to me that things started getting rather long and i was surprised by how "big" the whole thing seemed by the end of it. I was wondering if there are any tricks i missed or steps i could have done better. Also looking for tips on code readability as well. Code starts below:</p> <pre><code>x = [1,2,3,3,2,0] prev = x[0] curr = x[1] #keep track of two items together during iteration, previous and current result = {"increasing": [], "equal": [], "decreasing": [], } def two_item_relation(prev, curr): #compare two items in list, results in what is effectively a 3 way flag if prev &lt; curr: return "increasing" elif prev == curr: return "equal" else: return "decreasing" prev_state = two_item_relation(prev, curr) #keep track of previous state result[prev_state].append([prev]) #handle first item of list x_shifted = iter(x) next(x_shifted) #x_shifted is now similar to x[1:] for curr in x_shifted: curr_state = two_item_relation(prev, curr) if prev_state == curr_state: #compare if current and previous states were same. result[curr_state][-1].append(curr) else: #states were different. aka a change in trend result[curr_state].append([]) result[curr_state][-1].extend([prev, curr]) prev = curr prev_state = curr_state def all_subcombinations(lst): #given a list, get all "sublists" using sliding windows if len(lst) &lt; 3: return [lst] else: result = [] for i in range(2, len(lst) + 1): for j in range(len(lst) - i + 1): result.extend([lst[j:j + i]]) return result print(" all Outputs ") result_all_combinations = {} for k, v in result.items(): result_all_combinations[k] = [] for item in v: result_all_combinations[k].extend(all_subcombinations(item)) print(result_all_combinations) #Output: {'increasing': [[1, 2], [2, 3], [1, 2, 3]], 'equal': [[3, 3]], 'decreasing': [[3, 2], [2, 0], [3, 2, 0]]} </code></pre>
[]
[ { "body": "<p>A few changes:</p>\n\n<p>Strings shouldn't be used here for keeping track of comparison results. Strings are prone to being typo'd, and may lead to unexpected results (like indexing <code>result</code> causing <code>KeyError</code>s at runtime). I'd take a page from Java (and other languages) and use <code>-1</code>, <code>0</code> and <code>1</code> to indicate the results of a comparison. You can see it being used in an <a href=\"https://stackoverflow.com/a/2839165/3000206\">answer here</a>. I'd make the following changes:</p>\n\n<pre><code>result = {1: [], # Increasing\n 0: [], # Equal\n -1: [] # Decreasing \n }\n\ndef two_item_relation(prev, curr):\n if prev &lt; curr:\n return 1\n elif prev == curr:\n return 0\n else:\n return -1\n</code></pre>\n\n<p>It's much harder to mistype <code>-1</code> than it is, for example, <code>\"decreasing\"</code>.</p>\n\n<p>If you really wanted Strings for pretty printing purposes (like for your output at the bottom), you could maintain a dictionary mapping comparison numbers to strings:</p>\n\n<pre><code>pp_result = {1: \"Increasing\",\n 0: \"Equal\",\n -1: \"Decreasing\" \n }\n</code></pre>\n\n<p>The point is that you shouldn't use easily mistyped things as keys unless necessary.</p>\n\n<p>Strings also <em>may</em> be slower to compare, and <em>may</em> take more memory, but hash caching and String interning may negate those problems in some cases.</p>\n\n<p>You could also write that function as something like:</p>\n\n<pre><code>def two_item_relation(prev, curr):\n return 1 if prev &lt; curr else \\\n 0 if prev == curr else \\\n -1\n</code></pre>\n\n<p>But I'm probably going to get yelled at for even bringing that up. Conditional expressions/ternaries are nice in many cases when you want to conditionally return one or another thing, but they get a little murky as soon as you're using them to decide between three different things. It's especially bad here because this pretty much needs to be split over a few lines, which necessitates the use of line continuation characters, which are a little noisy.</p>\n\n<p>I'm bringing it up in case you're unaware of conditional expressions, not because I'm necessarily suggesting their use here.</p>\n\n<hr>\n\n<p>You could use <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enums</a> as well:</p>\n\n<pre><code>from enum import Enum\n\nclass Compare_Result(Enum):\n INCREASING = 1\n EQUAL = 0\n DECREASING = -1\n\ndef two_item_relation(prev, curr):\n if prev &lt; curr:\n return Compare_Result.INCREASING\n elif prev == curr:\n return Compare_Result.EQUAL\n else:\n return Compare_Result.DECREASING\n</code></pre>\n\n<p>This has the benefit that it makes it obvious what each result actually means. They also prints out semi-nicely, so the \"pretty-printing map\" may not be as necessary:</p>\n\n<pre><code>&gt;&gt;&gt; str(Compare_Result.INCREASING)\n'Compare_Result.INCREASING'\n\n&gt;&gt;&gt; repr(Compare_Result.INCREASING)\n'&lt;Compare_Result.INCREASING: 1&gt;'\n</code></pre>\n\n<p>And, if you do typo a name (which is harder to do since IDEs can autocomplete <code>Compare_Result.</code>), it will fail outright with an error:</p>\n\n<pre><code>&gt;&gt;&gt; Compare_Result.INCRESING\n\nTraceback (most recent call last):\n File \"&lt;pyshell#5&gt;\", line 1, in &lt;module&gt;\n Compare_Result.INCRESING\n File \"C:\\Users\\slomi\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\enum.py\", line 324, in __getattr__\n raise AttributeError(name) from None\nAttributeError: INCRESING\n</code></pre>\n\n<p>Unfortunately though, this error does not happen immediately like it does in other languages. The faulty code needs to actually be interpreted before the error is caught. This seems to make enums less useful in Python than in languages like Java or C++, but it's still less error-prone than using Strings or Numbers.</p>\n\n<hr>\n\n<p>Honestly, I'm too tired right now to comment on the algorithm, but hopefully this was helpful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:18:06.860", "Id": "412511", "Score": "0", "body": "Thanks a lot. I am used to making booleans for flags, but i couldn't think of a good alternative to a 3 way flag on my own. really like using the ints for keys but a mapping for pretty printing the outputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:34:12.293", "Id": "412513", "Score": "0", "body": "@ParitoshSingh No problem. Note though, numbers are a simple solution, but they still aren't ideal. They don't carry any information about what they mean. I did a quick dive into using Enums, and edited an example of their use into the bottom of my answer. It's worth a look since they offer an even better solution." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T17:49:05.603", "Id": "213202", "ParentId": "213198", "Score": "6" } }, { "body": "<p><strong>Organize</strong></p>\n\n<p>I believe you would do well to restructure your code. You have two functions, why not write one more, and then separate your testing from your actual code? </p>\n\n<pre><code>if __name__ == '__main__':\n x = [1,2,3,3,2,0]\n\n result = find_monotone_sequences(x) # Wrap your code in this function\n\n print(\" all Outputs \")\n result_all_combinations = {}\n\n for k, v in result.items():\n result_all_combinations[k] = []\n for item in v:\n result_all_combinations[k].extend(all_subcombinations(item))\n\n print(result_all_combinations)\n #Output:\n #{'increasing': [[1, 2], [2, 3], [1, 2, 3]],\n # 'equal': [[3, 3]],\n # 'decreasing': [[3, 2], [2, 0], [3, 2, 0]]}\n</code></pre>\n\n<p><strong>Use <code>collections.defaultdict</code></strong></p>\n\n<p>Next, take advantage of some built-in features:</p>\n\n<pre><code>result = {\"increasing\": [],\n \"equal\": [],\n \"decreasing\": [],\n }\n</code></pre>\n\n<p>This is a dictionary where every value <em>defaults to an empty list</em>. Another word for that is a <code>collections.defaultdict</code>:</p>\n\n<pre><code>from collections import defaultdict\n\nresult = defaultdict(list) # Note: no parens after list - passing in function\n</code></pre>\n\n<p>Now you don't have to provide the explicit names and values!</p>\n\n<p><strong>Use your iterators</strong></p>\n\n<p>Next, you should take advantage of the iterator you are <em>already creating!</em></p>\n\n<pre><code>prev = x[0] \ncurr = x[1] #keep track of two items together during iteration, previous and current\n\nprev_state = two_item_relation(prev, curr) #keep track of previous state\nresult[prev_state].append([prev]) #handle first item of list\n\nx_shifted = iter(x)\nnext(x_shifted) #x_shifted is now similar to x[1:]\n</code></pre>\n\n<p>Instead of accessing <code>x[0]</code> and <code>x[1]</code>, why not use the iterator? </p>\n\n<pre><code>xiter = iter(x)\nprev = next(xiter)\ncurr = next(xiter)\nprev_state = two_item_relation(prev, curr) #keep track of previous state\nresult[prev_state].append([prev]) #handle first item of list\n\nfor curr in xiter:\n # etc...\n</code></pre>\n\n<p><strong>Recognize patterns in your code (use <code>itertools</code>!)</strong></p>\n\n<p>Finally, I'd like to point out the behavior of your main loop:</p>\n\n<pre><code>for curr in x_shifted: \n curr_state = two_item_relation(prev, curr)\n if prev_state == curr_state: #compare if current and previous states were same.\n result[curr_state][-1].append(curr) \n else: #states were different. aka a change in trend\n result[curr_state].append([])\n result[curr_state][-1].extend([prev, curr])\n prev = curr\n prev_state = curr_state\n</code></pre>\n\n<p>This loops over the input values, comparing each value with the prior one, and determines a 'state'. Depending on the state, the input values are broken into <em>groups</em> corresponding to the state. </p>\n\n<p>Or: the input sequence is <em>grouped by</em> the computed state.</p>\n\n<p>It turns out there's an app for that: <a href=\"https://docs.python.org/3.5/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby</code></a> will take a sequence and a key function, and break the sequence into groups according to the values taken on by the key!</p>\n\n<p>This means your can rewrite your code into a simple processing loop that computes the state and associates it with the values (except the initial member, of course). Furthermore, if you investigate the <strong>recipes</strong> section of the <code>itertools</code> module, you will find a function named <code>pairwise</code> that allows a sequence to be processed in pairs:</p>\n\n<pre><code>def pairwise(iterable):\n \"s -&gt; (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n</code></pre>\n\n<p>Adding this function to your code enables you to do this:</p>\n\n<pre><code>seq = x # x is not a very good name\nrelations = [(two_item_relation(*pair), *pair) for pair in pairwise(seq)]\n</code></pre>\n\n<p>There is still the matter of the special treatment of the first value, but you can do it with the values all in hand.</p>\n\n<p>(If you're just learning Python, the <code>*pair</code> syntax \"flattens\" the pair in place. It is equivalent to writing: <code>pair[0], pair[1]</code> where-ever <code>*pair</code> is seen. Thus <code>relation(*pair)</code> is like <code>relation(pair[0], pair[1])</code>.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:19:51.330", "Id": "412512", "Score": "0", "body": "Thanks a ton, this was super helpful! The grouper thing is something i am not sure i understand enough to apply just yet im afraid, but will see. A Question about tee, does it create a copy of the list in memory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:56:57.280", "Id": "412515", "Score": "0", "body": "`tee` duplicates the *iterator,* not the sequence being iterated. If you want to copy a list, try `b = a[:]` for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T18:03:48.483", "Id": "412517", "Score": "0", "body": "perfect, ty. in this case, i wanted to ensure i didn't make an unnecessary copy, it was why i avoided slicing in the first place." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T18:17:44.323", "Id": "213204", "ParentId": "213198", "Score": "5" } } ]
{ "AcceptedAnswerId": "213204", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T17:01:26.747", "Id": "213198", "Score": "5", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "Get all monotonic sublists from a list" }
213198
<p>This program prints out a table in the console. Suggestions for improvements are welcome.</p> <p><strong>Example output</strong></p> <pre><code>Name Sex Age Klaus Ulbrecht male 12 Dieter male 14 Ursula female 16 </code></pre> <p><a href="https://repl.it/@Dexter1997/Textual-Table-View" rel="nofollow noreferrer">You can test and modify the program here.</a></p> <pre><code>import java.util.Arrays; import java.util.List; import java.util.ArrayList; class Main { private static List&lt;List&lt;String&gt;&gt; table; public static void main(String[] args) { initTable(); int spacing = 3; printTable(spacing); } private static void initTable() { List&lt;String&gt; row1 = Arrays.asList("Name", "Klaus Ulbrecht", "Dieter", "Ursula"); List&lt;String&gt; row2 = Arrays.asList("Sex", "male", "male", "female"); List&lt;String&gt; row3 = Arrays.asList("Age", "12", "14", "16"); table = Arrays.asList(row1, row2, row3); } private static void printTable(int spacing) { List&lt;Integer&gt; maxLengths = findMaxLengths(); StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; table.get(0).size(); i++) { for (int j = 0; j &lt; table.size(); j++) { String currentValue = table.get(j).get(i); sb.append(currentValue); for (int k = 0; k &lt; (maxLengths.get(j) - currentValue.length() + spacing); k++) { sb.append(' '); } } sb.append('\n'); } System.out.println(sb); } private static List&lt;Integer&gt; findMaxLengths() { List&lt;Integer&gt; maxLengths = new ArrayList&lt;&gt;(); for (List&lt;String&gt; row : table) { int maxLength = 0; for (String value : row) { if (value.length() &gt; maxLength) { maxLength = value.length(); } } maxLengths.add(maxLength); } return maxLengths; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T09:09:38.370", "Id": "412452", "Score": "0", "body": "is \"being robust\" one of your requirements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T10:49:28.120", "Id": "412463", "Score": "0", "body": "I would say robustness is always a good thing! I am in the process of improving my code and adding a few features (CSV parsing, pseudo-graphics, etc.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T10:58:13.067", "Id": "412464", "Score": "0", "body": "think what would happen if `List<String> row1 = Arrays.asList(\"Name\", \"Klaus Ulbrecht\", \"Dieter\");` - heck, we lost *Ursula* ... that's even a harmless case... but if you forget an entry in `List<String> row2 = ...` you are in serious problems ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T11:00:27.667", "Id": "412467", "Score": "1", "body": "have you considered the usage of existing classes, even though they may be kind of \"misplaced\" (heck, swing in console???), but maybe have a look at https://docs.oracle.com/javase/7/docs/api/javax/swing/table/DefaultTableModel.html" } ]
[ { "body": "<p>Printing arbitrary data as a table is a nice task of work for a utility function.</p>\n\n<p>Such utility functions are usually defined in a utility class, which looks like this:</p>\n\n<pre><code>public final class Tables {\n private Tables() {}\n\n public static void print(List&lt;List&lt;String&gt;&gt; table, int spacing) {\n ...\n }\n}\n</code></pre>\n\n<p>The name of the utility class usually takes the plural form of the main data ingredient. In this case that is a table, therefore <code>Tables</code>. The Java programming environment already defines similar utility classes named <code>Collections</code> and <code>Arrays</code>.</p>\n\n<p>There is one important difference to your current code. All the variables needed by the <code>Tables.print</code> method are passed via parameters. There is no <code>static</code> field anywhere. This allows the <code>print</code> method to be called several times in the same moment and unambiguously lists all the data you have to provide when calling that method.</p>\n\n<p>Citing from your code:</p>\n\n<pre><code>private static void initTable() {\n List&lt;String&gt; row1 = Arrays.asList(\"Name\", \"Klaus Ulbrecht\", \"Dieter\", \"Ursula\");\n List&lt;String&gt; row2 = Arrays.asList(\"Sex\", \"male\", \"male\", \"female\");\n List&lt;String&gt; row3 = Arrays.asList(\"Age\", \"12\", \"14\", \"16\");\n table = Arrays.asList(row1, row2, row3);\n}\n</code></pre>\n\n<p>You are mixing up the terms <em>row</em> and <em>column</em> here. A <em>row</em> in <code>initTable</code> will later be output as a <em>column</em> in <code>printTable</code>. That's confusing.</p>\n\n<p>Several parts of your <code>printTable</code> method should be changed:</p>\n\n<ul>\n<li>The table should be passed as a parameter, instead of being a <code>static</code> field in the <code>Main</code> class.</li>\n<li>In the innermost <code>for</code> loop, the complicated expression is calculated several times, which is unnecessary. You should rather count from <code>k</code> downto 0: <code>for (int k = ...; k &gt; 0; k--) { ... }</code></li>\n<li>The final <code>System.out.println</code> prints 2 newlines. One of the may or may not be desired. In the latter case, replace the <code>println</code> with <code>print</code>.</li>\n</ul>\n\n<p>In the <code>findMaxLengths</code> method:</p>\n\n<ul>\n<li>The table should be passed as a parameter, as above.</li>\n<li>Instead of the <code>if</code> clause, you can just write <code>maxLength = Math.max(maxLength, value.length());</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T11:49:57.117", "Id": "213239", "ParentId": "213208", "Score": "0" } }, { "body": "<p>Hello and thank your for your code. I dont' know what kind of improvements you want but from an Object Oriented perspective I see some improvements.</p>\n\n<p>The first one is to get rid of all the static methods and fields. You can easily move all your methods to an <code>AsciiTable</code> class with a <code>print(OutputStream out):void</code> method.</p>\n\n<p>You can also use <em>arrays</em> instead of list and split the single argument to one for the columns titles and another for the content. This will clarify the initiliazation of your table.</p>\n\n<pre><code>Table table = new Table(\n new String[]{\"Name\", \"Sex\", \"Age\"},\n new Object[][]{\n {\"Klaus Ulbrecht\", \"male\", 12},\n {\"Dieter\", \"male\", 14},\n {\"Ursula\", \"female\", 16}\n });\n</code></pre>\n\n<p>As you can see I changed the order so that the cognitive load is reduced, by \nlooking at the declaration we alrdeay have an idea of what are the titles and the content. We read for top to bottom, so it is more easier to have a declaration that already looks like that. This avoid your brain to switch the representation.</p>\n\n<p>Another improvement that you can do is apply the <em>separation of concerns</em> principle by moving the \"printing\" away of the table. This is done easily with the <em>builder</em> where your <code>Table</code> is a director that drive a <code>Format</code>.</p>\n\n<p>With this pattern you should be able to add another representation without changing the <code>Table</code>.</p>\n\n<pre><code>interface Format {\n void startHeader();\n void endHeader();\n\n void startBody();\n void endBody();\n\n void startRow();\n void endRow();\n\n void addColumn(Object value);\n}\n\nFormat console = new Ascii(System.out, \" \"); \ntable.writeTo(console);\n</code></pre>\n\n<p>Now that your model (<code>Table</code>) is separated from the view (<code>Format</code>) you may discover that the model is quite simple and exists mainly to drive the view as the director in the builder pattern. But you can add new methods to filter or sort your table.</p>\n\n<pre><code>Table table = new Table(\n new String[]{\"Name\", \"Sex\", \"Age\"},\n new Object[][]{\n {\"Klaus Ulbrecht\", \"male\", 12},\n {\"Dieter\", \"male\", 14},\n {\"Ursula\", \"female\", 16}\n });\ntable.filter(1, \"male\"::equalsIgnoreCase)\n .sort(2, Comparator.naturalOrder())\n .writeTo(console);\n\nName Sex Age \nKlaus Ulbrecht male 12 \nDieter male 14 \n</code></pre>\n\n<p>If you don't want to migrate to the object oriented way you can still improve the robustness of your code by dealing with empty columns or rows.</p>\n\n<p>[1] Single Responsibility Priniciple is part of the S.O.L.I.D. acronym. <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/SOLID</a></p>\n\n<p>[2] When I speak about the builder pattern I refer to the creational pattern. Not the \"fluent way of writing\". <a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Builder_pattern</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T15:52:59.480", "Id": "213251", "ParentId": "213208", "Score": "2" } } ]
{ "AcceptedAnswerId": "213251", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T19:05:22.137", "Id": "213208", "Score": "3", "Tags": [ "java", "console" ], "Title": "Printing out a table in console" }
213208
<p>The task:</p> <blockquote> <p>Given a list of integers and a number K, return which contiguous elements of the list sum to K.</p> <p>For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4].</p> </blockquote> <p>My solution</p> <pre><code>// init const arr = [1, 2, 3, 4, 5]; const K = 9; // main const getContiguousElementsSum = (arr, K) =&gt; { if (arr.length === 0 || K &lt; 0) { return null; } let sum = 0; const returnResult = []; const found = arr.some(x =&gt; { sum += x; returnResult.push(x); return sum === K; }); // exit case if (found) { return returnResult; } // recursive case return getContiguousElementsSum(arr.slice(1), K); }; console.log(getContiguousElementsSum(arr, K)); </code></pre> <p>Is there a shorter and/or more readable solution?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T23:12:28.703", "Id": "412433", "Score": "1", "body": "Could it also return [4, 5] ? I'm thinking work the array backwards (if it's always in order)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T08:49:05.630", "Id": "412449", "Score": "0", "body": "Not from the given task. It explicitly says `[2,3,4]` for `K=9`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T08:58:01.130", "Id": "412451", "Score": "0", "body": "You haven't said what the source of the specification was, but I think the point implicit in Matthew Page's question (which I was also going to raise) is that if you can you should push back on the specifier and ask them for an unambiguous ruling on which of multiple possible answers should be returned." } ]
[ { "body": "<p>The current implementation sums the values of <code>arr[0] + arr[1] + ...</code> until the amount is equal to <code>K</code>,\nor if not found, then recursively call the function again, with the first element of the input array sliced off.\nFor example if the input array is <code>[3, 2, 1]</code> and <code>K</code> is 1,\nit will compute <code>3 + 2 + 1</code>, then <code>2 + 1</code>, then <code>1</code>.\nThis is effectively trying all possible contiguous sub-sequences until a match is found, brute-force.</p>\n\n<p>The only given example input used only positive numbers.\nIf we can assume this is the case for all inputs,\nthen a more efficient algorithm exists.\nIn that case you could keep track of two index pointers in the array,\n<code>start</code> and <code>end</code>, and a running <code>sum</code>.\nRead elements one by one,\nmoving forward <code>start</code> or <code>end</code> or both as needed,\naccording to the current running sum.\n(This is technique is also known as the <em>caterpillar method</em>.)\nThis will require a single pass over the elements (<span class=\"math-container\">\\$O(n)\\$</span>),\nwithout unnecessary summing or slicing.</p>\n\n<pre><code>const getContiguousElementsSum = (arr, K) =&gt; {\n for (let sum = 0, start = 0, end = 0; end &lt; arr.length; end++) {\n sum += arr[end];\n\n while (K &lt; sum) {\n sum -= arr[start];\n start++;\n }\n\n if (sum == K) {\n return arr.slice(start, end + 1);\n }\n }\n return null;\n};\n</code></pre>\n\n<p>However, if there are negative values in the input, this technique will not work. When there are negative values, it's no longer obvious how to move the index pointers. One path may be to increase the range to compensate, another path may be to omit the negative element. With the logic branching, a linear solution can no longer work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T21:25:28.857", "Id": "412427", "Score": "2", "body": "Your function fails when the OP's solution finds the correct sequence. Consider the array `[1,2,3,1,-1967,3,1,2,3,1,45,2,3,1]` your function fails for many values. Eg sequences summing from 45 to 58 (inclusive) are not found." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T06:14:05.457", "Id": "412445", "Score": "0", "body": "@Blindman67 good point, thanks. I updated the post with a crucial assumption that was missed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T20:40:02.527", "Id": "213212", "ParentId": "213210", "Score": "3" } }, { "body": "<blockquote>\n<pre><code>// init\nconst arr = [1, 2, 3, 4, 5];\nconst K = 9;\n\n// main\nconst getContiguousElementsSum = (arr, K) =&gt; {\n</code></pre>\n</blockquote>\n\n<p>It seems to me to be unnecessarily confusing to alias variable identifiers like this.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (arr.length === 0 || K &lt; 0) {\n return null;\n }\n</code></pre>\n</blockquote>\n\n<p>I don't see this anywhere in the specification you've quoted. I would expect the function to handle <code>K === 0</code> by returning <code>[]</code>, and to give <code>[-1,-2,-3]</code> for <code>getContiguousElementsSum([-1,-2,-3,-4], -6)</code>.</p>\n\n<p>Also, since the specification doesn't say anything about error cases, I would assume by default that it should throw something (probably <code>RangeError</code>) if no matching subarray can be found.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> const found = arr.some(x =&gt; {\n sum += x;\n returnResult.push(x);\n return sum === K;\n });\n</code></pre>\n</blockquote>\n\n<p>It would be kinder to the garbage collector to just track indexes and use <code>slice</code> when you find a match.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // recursive case\n return getContiguousElementsSum(arr.slice(1), K);\n</code></pre>\n</blockquote>\n\n<p>The overall complexity of this implementation is <span class=\"math-container\">\\$O(n^2)\\$</span>. It can be done quite easily in <span class=\"math-container\">\\$O(n \\lg n)\\$</span> in full generality using just arrays, and in <span class=\"math-container\">\\$O(n)\\$</span> if you have an efficient set implementation, by using the property <span class=\"math-container\">$$\\sum_{i=a}^b A[i] = \\left(\\sum_{i=0}^a A[i]\\right) - \\left(\\sum_{i=0}^{b-1} A[i]\\right)$$</span>To build an array of <span class=\"math-container\">\\$\\left(\\sum_{i=0}^a A[i]\\right)\\$</span> takes linear time; then either convert it into a set or sort it; and for each element in the array of partial sums you need to test for the presence of that partial sum minus the target.</p>\n\n<p>And, of course, it can be done in <span class=\"math-container\">\\$O(n)\\$</span> time with just arrays if you're guaranteed that the elements are positive, as described in <a href=\"/a/213212/1402\">janos' answer</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T09:15:19.750", "Id": "213237", "ParentId": "213210", "Score": "4" } }, { "body": "<h1>Some points regarding readability.</h1>\n\n<p>Source code noise reduces overall readability. Noise is anything that is redundant or does not aid in the understanding of the code.</p>\n\n<p>There are many way to introduce noise.</p>\n\n<h2>Not addressing the reader</h2>\n\n<p>One assumes that the reader of your code is proficient in the language and does not need to be told what various tokens do. You have two comments that assume the coder knows nothing.</p>\n\n<ul>\n<li><code>// exit case</code> adds nothing to the code or the readability, thus it is noise and actually detracts from readability.</li>\n<li><code>// recursive case</code> Really, and I thought it was flying a kite... :P</li>\n</ul>\n\n<p>If you are writing code as a teaching example then you assume the reader has limited knowledge and in that case the obvious is stated in properly structured english (or whatever language)</p>\n\n<ul>\n<li><p><code>// exit case</code> would be <code>// When found exit the function returning the returnResult array.</code> </p>\n\n<p>Note that if you add a comment it should be above the line it refers to with a blank line above it. Or it should be at the end of the line not going past the right margin (80 or I prefer 120 characters)</p>\n\n<p>Thus the example above would be</p></li>\n</ul>\n\n<p>.</p>\n\n<pre><code> ...\n return sum === K;\n});\n\n// When found exit the function returning the returnResult array.\nif (found) {\n return returnResult;\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code> ...\n return sum === K;\n}); \nif (found) { // When found exit the function returning the returnResult array.\n return returnResult;\n}\n</code></pre>\n\n<h2>Misleading the reader</h2>\n\n<p>This is the worst type of noise.</p>\n\n<p>Comments are not subject to compilation, verification, or any type of vetting process. The author quickly becomes blind to comments and will overlook them when making changes. \nThe result is that comments can be in direct opposition of the code they are commenting. This will confuse the reader as to the intent of the code. They are left to guess, is the code in error or the comment.</p>\n\n<ul>\n<li><code>// main</code> is a pullover from other languages and is general the entry point of the entire app, there is only one main, and it is only ever called once. It does not apply to JS and should not be used as a comment.</li>\n<li><code>// init</code> initialize is not accurate, you are defining variable not reenstating them. Some constants can not be initialized as they can not change eg <code>K</code>. Others can be initialized eg initialize the array <code>arr.length = 0; arr.push(...[1,2,3,4,5]);</code></li>\n</ul>\n\n<h2>Naming noise</h2>\n\n<p>We humans read words not by scanning each character in turn, but rather by recognising the shape, and using cues (such as the start and end characters). </p>\n\n<p>Good names are short and to the point. They rely strongly on the context in which they are created to give them meaning. The more frequently a variable is used the shorter it is the better, as you reduce the overall bulk of the code.</p>\n\n<ul>\n<li><code>returnResult</code> does the verb <code>return</code> add to the understanding of the name and what the variable represents. Not at all and thus can be considered naming noise. <code>result</code> is clear. \nWe also use abbreviations in code, though you must use the common form, do not make up abbreviations. The common abbreviation for <code>result</code> is <code>res</code></li>\n<li><p><code>getContiguousElementsSum</code> is incorrect. When you <code>get...</code> something you know it exists and where it is. The function does not <code>get</code> a result, it searches for a result and if it exists returns it. Thus replace the <code>get</code> with <code>find</code></p>\n\n<p><code>...Elements...</code> In JS and most languages the content of an array is referred to as array items, not array elements. In JS this is particularly important as in many contextes <code>elements</code> refer to DOM objects and thus using the term elements is misleading.</p>\n\n<p><code>...Sum</code> No you get items that sum to. <code>getBlahBlahSum</code> inferes a numeric result which the function does not do.</p>\n\n<p>The function name could be <code>findContiguousItemsSummingTo</code> It infers how the function works (a search), what the search criteria is (summing to), and what it returns (an array of items).</p>\n\n<p>The name is rather long and there are no convenient abbreviations but the <code>find</code> in this case can be dropped, <code>items</code> to <code>arr</code>, and <code>to</code> to <code>2</code> <code>contiguousArrSumming2</code></p></li>\n</ul>\n\n<h2>Verbosity</h2>\n\n<p>There are many ways to stone a crow, and in most languages that remains true. The best way is the shortest way, less code is more readable by simple virtue of reducing time to read, and making it easier to scan large sections of code.</p>\n\n<p>Readability is in part the ability to write a large code base. A good coder can create apps that have hundreds of thousands of lines of code. Saving 10% is substantial, saving 50% is a order of magnitude easier to comprehend.</p>\n\n<p>You have 6 lines for something that could be one line.</p>\n\n<pre><code>// exit case\nif (found) {\n return returnResult;\n}\n// recursive case\nreturn getContiguousElementsSum(arr.slice(1), K);\n</code></pre>\n\n<p>You have 3 lines that could be one. </p>\n\n<pre><code>if (arr.length === 0 || K &lt; 0) {\n return null;\n}\n</code></pre>\n\n<p>They become</p>\n\n<pre><code>if (arr.length === 0 || K &lt; 0) { return }\n\nreturn found ? res : contiguousArrSumming2((arr.shift(), arr), val);\n</code></pre>\n\n<h3>Note on null</h3>\n\n<p>Javascript functions do not return <code>null</code> Null is a placeholder, it means I have something that I reserve a reference for (Note The <strike>idiots</strike> people that wrote the DOM API miss used <code>null</code>). When something is not defined it is <code>undefined</code> To help reduce code size in JS <code>undefined</code> is the default return type and need not be defined. <code>return null</code> is both semantically incorrect and too verbose.</p>\n\n<h2>Reducing source code bulk</h2>\n\n<p>You can reduce code size using commas to separate lines. We use them in english to keep the size of a text document small and compact, you should do the same in code.</p>\n\n<pre><code>const contiguousArrSumming2 = (arr, val) =&gt; {\n var sum = 0;\n const res = [];\n const scan = num =&gt; (sum += num, res.push(num), sum === bal);\n if (arr.length === 0 ) { return res }\n return arr.some(scan) ? res : contiguousArrSumming2(arr.slice(1), val);\n};\nconsole.log(contiguousArrSumming2([1, 2, 3, 4, 5], 9));\n</code></pre>\n\n<p>Personally I would further reduce to </p>\n\n<pre><code>function contiguousArrSumming2(arr, val, res = []) {\n var sum = 0;\n const scan = num =&gt; (sum += num, res.push(num), sum === bal);\n return !arr.length || arr.some(scan) ? res : contiguousArrSumming2((arr.shift(), arr), val);\n}\n</code></pre>\n\n<p>A competent coder will have no trouble reading the above code and should instantly spot the very important difference from your original.</p>\n\n<h2>Be professional.</h2>\n\n<p>Remember those that read your code are professionals. When you present your code and it looks like its a tutorial piece all you do is put distrust in your code as poor/simple language use and pointless comments make you look like a beginner, the result is they will rather rewrite than update or fix, making your efforts pointless.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:07:07.600", "Id": "213255", "ParentId": "213210", "Score": "2" } } ]
{ "AcceptedAnswerId": "213255", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T19:26:53.613", "Id": "213210", "Score": "2", "Tags": [ "javascript", "algorithm", "functional-programming", "k-sum" ], "Title": "Contiguous elements of the list sum to K" }
213210
<p>My latest school project was to implement <code>malloc()</code>, <code>free()</code>, <code>realloc()</code> and <code>calloc()</code> from the standard C library. I came up with something a bit similar to the glibc <code>malloc()</code>. It supports multi-threading; speed is pretty good according to my tests. Not very portable (meant for Linux 64bits and Darwin 64bits). You will notice I do not use <code>sbrk()</code>: the reason is that the project explicitly forbids us to; we have to use <code>mmap()</code> and <code>mmap()</code> only.</p> <p>I started coding a year and a half ago, I obviously have a lot to learn still, but I would like to know what do you guys think about it. Not only the implementation, but also the coding style, the readability, etc.</p> <p>The project is available here: <a href="https://github.com/terry-finkel/ft_malloc/tree/a8a6f2c7293d81b6235289be37a159b4f784adda" rel="nofollow noreferrer">https://github.com/terry-finkel/ft_malloc</a>.</p> <hr> <p>malloc.c:</p> <pre><code>#include "mallocp.h" t_arena_data *g_arena_data = NULL; __attribute__((always_inline)) static inline void update_max_chunk (t_bin *bin, t_chunk *next_chunk, unsigned long old_size) { unsigned long req_size = __mchunk_type_match(bin, CHUNK_TINY) ? SIZE_TINY : SIZE_SMALL; if (next_chunk != __mbin_end(bin) &amp;&amp; __mchunk_not_used(next_chunk) &amp;&amp; __mchunk_size(next_chunk) &gt;= req_size) { bin-&gt;max_chunk_size = __mchunk_size(next_chunk); } else { t_chunk *biggest_chunk = bin-&gt;chunk; unsigned long remaining = 0; while (biggest_chunk != __mbin_end(bin)) { if (__mchunk_not_used(biggest_chunk)) { if (__mchunk_size(biggest_chunk) &gt; remaining) remaining = __mchunk_size(biggest_chunk); if (remaining &gt;= req_size) break; } biggest_chunk = __mchunk_next(biggest_chunk); } bin-&gt;max_chunk_size = remaining; } __marena_update_max_chunks(bin, old_size); } __attribute__((always_inline)) static inline void * user_area (t_bin *bin, t_chunk *chunk, size_t size, pthread_mutex_t *mutex, int zero_set) { /* Populate chunk headers. A chunk header precedes the user area with the size of the user area (to allow us to navigate between allocated chunks which are not part of any linked list, and defragment the memory in free and realloc calls) and the pool header address. We also use the size to store CHUNK_USED to know if the chunk is used or not. */ size += sizeof(t_chunk); bin-&gt;free_size -= size; unsigned long old_size = __mchunk_size(chunk); chunk-&gt;size = size | (1UL &lt;&lt; CHUNK_USED); chunk-&gt;bin = bin; t_chunk *next_chunk = __mchunk_next(chunk); if (next_chunk != __mbin_end(bin) &amp;&amp; next_chunk-&gt;size == 0) next_chunk-&gt;size = old_size - size; if (old_size == bin-&gt;max_chunk_size) update_max_chunk(bin, next_chunk, old_size); pthread_mutex_unlock(mutex); if (zero_set == 1) memset(chunk-&gt;user_area, 0, size - sizeof(t_chunk)); return (void *)chunk-&gt;user_area; } __attribute__((always_inline)) static inline t_bin * create_new_bin (t_arena *arena, int chunk_type, unsigned long size, long pagesize, pthread_mutex_t *mutex) { static unsigned long headers_size = sizeof(t_bin) + sizeof(t_chunk); /* Allocate memory using mmap. If the requested data isn't that big, we allocate enough memory to hold CHUNKS_PER_POOL times this data to prepare for future malloc. If the requested data exceeds that value, nearest page data will do. */ unsigned long mmap_size; if (chunk_type != CHUNK_LARGE) mmap_size = sizeof(t_bin) + (size + sizeof(t_chunk)) * CHUNKS_PER_POOL; else mmap_size = size + headers_size; mmap_size = mmap_size + (unsigned long)pagesize - (mmap_size % (unsigned long)pagesize); t_bin *bin = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if (__builtin_expect(bin == MAP_FAILED, 0)) { errno = ENOMEM; pthread_mutex_unlock(mutex); return MAP_FAILED; } /* Keep track of the size and free size available. */ bin-&gt;size = mmap_size | (1UL &lt;&lt; chunk_type); bin-&gt;free_size = mmap_size - sizeof(t_bin); bin-&gt;arena = arena; bin-&gt;left = NULL; bin-&gt;right = NULL; bin-&gt;max_chunk_size = bin-&gt;free_size; bin-&gt;chunk-&gt;size = bin-&gt;free_size; __marena_update_max_chunks(bin, 0); return bin; } __attribute__((always_inline)) static inline void * __malloc (size_t size, int zero_set) { static long pagesize = 0; static pthread_mutex_t main_arena_mutex = PTHREAD_MUTEX_INITIALIZER, new_arena_mutex = PTHREAD_MUTEX_INITIALIZER; static t_arena_data arena_data = { .arena_count = 0 }; size = (size + 0xfUL) &amp; ~0xfUL; int chunk_type; if (size &gt;= (1UL &lt;&lt; SIZE_THRESHOLD)) return NULL; else if (size &gt; SIZE_SMALL) chunk_type = CHUNK_LARGE; else chunk_type = (size &lt;= SIZE_TINY) ? CHUNK_TINY : CHUNK_SMALL; /* If first call to malloc, create our arena data struct. */ pthread_mutex_lock(&amp;main_arena_mutex); if (__builtin_expect(g_arena_data == NULL, 0)) { pagesize = sysconf(_SC_PAGESIZE); t_bin *bin = create_new_bin(&amp;arena_data.arenas[0], chunk_type, size, pagesize, &amp;main_arena_mutex); if (bin == MAP_FAILED) return NULL; arena_data.arena_count = 1; arena_data.arenas[0] = (t_arena){ .small_bins = (chunk_type != CHUNK_LARGE) ? bin : NULL, .large_bins = (chunk_type == CHUNK_LARGE) ? bin : NULL, .max_chunk_small = 0, .max_chunk_tiny = 0 }; pthread_mutex_init(&amp;arena_data.arenas[0].mutex, NULL); pthread_mutex_lock(&amp;arena_data.arenas[0].mutex); g_arena_data = &amp;arena_data; pthread_mutex_unlock(&amp;main_arena_mutex); return user_area(bin, bin-&gt;chunk, size, &amp;arena_data.arenas[0].mutex, zero_set); } /* In order to prevent threads to compete for the same memory area, multiple arenas can be created to allow for faster memory allocation in multi-threaded programs. Each arena has it's own mutex that will allow each thread to operate independently. If M_ARENA_MAX is reached, threads will loop over all arenas until one is available. */ pthread_mutex_unlock(&amp;main_arena_mutex); /* Look for an open arena. */ t_arena *arena = &amp;arena_data.arenas[0]; int arena_index = 0; while (pthread_mutex_trylock(&amp;arena-&gt;mutex) != 0) { if (arena_index == arena_data.arena_count - 1) { if (pthread_mutex_trylock(&amp;new_arena_mutex) == 0) { if (arena_data.arena_count &lt; M_ARENA_MAX) { arena_index = arena_data.arena_count - 1; ++arena_data.arena_count; arena = NULL; break; } else pthread_mutex_unlock(&amp;new_arena_mutex); } arena = &amp;arena_data.arenas[(arena_index = 0)]; continue; } arena = &amp;arena_data.arenas[arena_index++]; } /* All arenas are occupied by other threads but M_ARENA_MAX isn't reached. Let's just create a new one. */ if (arena == NULL) { arena = &amp;arena_data.arenas[arena_index + 1]; t_bin *bin = create_new_bin(arena, chunk_type, size, pagesize, &amp;new_arena_mutex); if (bin == MAP_FAILED) return NULL; arena_data.arenas[arena_index + 1] = (t_arena){ .small_bins = (chunk_type != CHUNK_LARGE) ? bin : NULL, .large_bins = (chunk_type == CHUNK_LARGE) ? bin : NULL, .max_chunk_small = 0, .max_chunk_tiny = 0 }; pthread_mutex_init(&amp;arena-&gt;mutex, NULL); pthread_mutex_lock(&amp;arena-&gt;mutex); pthread_mutex_unlock(&amp;new_arena_mutex); return user_area(bin, bin-&gt;chunk, size, &amp;arena-&gt;mutex, zero_set); } /* Otherwise, thread has accessed an arena and locked it. Now let's try to find a chunk of memory that is big enough to accommodate the user-requested size. */ t_bin *bin = (chunk_type == CHUNK_LARGE) ? arena-&gt;large_bins : NULL; unsigned long required_size = size + sizeof(t_chunk); /* Look for a bin with a matching chunk type and enough space to accommodate user request. */ if ((chunk_type == CHUNK_TINY &amp;&amp; arena-&gt;max_chunk_tiny &gt;= required_size) || (chunk_type == CHUNK_SMALL &amp;&amp; arena-&gt;max_chunk_small &gt;= required_size)) { bin = arena-&gt;small_bins; if (bin != NULL &amp;&amp; chunk_type == CHUNK_TINY &amp;&amp; __mchunk_type_match(bin, CHUNK_SMALL)) bin = bin-&gt;left; else if (bin != NULL &amp;&amp; chunk_type == CHUNK_SMALL &amp;&amp; __mchunk_type_match(bin, CHUNK_TINY)) bin = bin-&gt;right; while (bin != NULL &amp;&amp; bin-&gt;max_chunk_size &lt; required_size) { bin = (chunk_type == CHUNK_TINY) ? bin-&gt;left : bin-&gt;right; } } if (bin == NULL || (chunk_type == CHUNK_LARGE &amp;&amp; bin-&gt;max_chunk_size &lt; required_size )) { /* A suitable bin could not be found, we need to create one. */ bin = create_new_bin(arena, chunk_type, size, pagesize, &amp;arena-&gt;mutex); if (bin == MAP_FAILED) return NULL; /* As large bins generally don't need to be searched for empty space, they have their own linked list. For tiny and small bins, we are using a non-circular double linked list anchored to the main bin. Tiny chunks bins will be placed to the left of the main bin, and small chunks bins to it's right. */ t_bin *main_bin = (chunk_type == CHUNK_LARGE) ? arena-&gt;large_bins : arena-&gt;small_bins; if (main_bin != NULL) { t_bin *tmp = (chunk_type == CHUNK_TINY) ? main_bin-&gt;left : main_bin-&gt;right; /* Insert the new bin into the bin list. */ if (chunk_type == CHUNK_TINY) { main_bin-&gt;left = bin; bin-&gt;right = main_bin; bin-&gt;left = tmp; if (tmp != NULL) tmp-&gt;right = bin; } else { main_bin-&gt;right = bin; bin-&gt;left = main_bin; bin-&gt;right = tmp; if (tmp != NULL) tmp-&gt;left = bin; } } else if (chunk_type == CHUNK_LARGE) { arena-&gt;large_bins = bin; } else { arena-&gt;small_bins = bin; } return user_area(bin, bin-&gt;chunk, size, &amp;arena-&gt;mutex, zero_set); } /* Find the first free memory chunk and look for a chunk large enough to accommodate user request. This loop is not protected, ie. if the chunk reaches the end of the bin it is undefined behavior. However, a chunk should NEVER reach the end of the bin as that would mean that a chunk of suitable size could not be found. If this happens, maths are wrong somewhere. */ t_chunk *chunk = bin-&gt;chunk; while (__mchunk_is_used(chunk) || __mchunk_size(chunk) &lt; required_size) { chunk = __mchunk_next(chunk); } return user_area(bin, chunk, size, &amp;arena-&gt;mutex, zero_set); } void *realloc (void *ptr, size_t size) { if (ptr == NULL) { return malloc(size); } else if (size == 0) { free(ptr); return NULL; } t_chunk *chunk = (t_chunk *)((unsigned long)ptr - sizeof(t_chunk)); /* If the pointer is not aligned on a 16bytes boundary, it is invalid by definition. */ if (g_arena_data == NULL || (unsigned long)chunk % 16UL != 0 || __mchunk_invalid(chunk)) { (void)(write(STDERR_FILENO, "realloc(): invalid pointer\n", 27) + 1); abort(); } if (chunk-&gt;size &gt;= size) return ptr; t_bin *bin = chunk-&gt;bin; t_arena *arena = bin-&gt;arena; pthread_mutex_lock(&amp;arena-&gt;mutex); t_chunk *next_chunk = __mchunk_next(chunk); unsigned long req_size = ((size + 0xfUL) &amp; ~0xfUL) + sizeof(t_chunk); if (next_chunk != __mbin_end(bin) &amp;&amp; __mchunk_not_used(next_chunk) &amp;&amp; __mchunk_size(chunk) + __mchunk_size(next_chunk) &gt;= req_size) { unsigned long realloc_size = __mchunk_size(chunk) + __mchunk_size(next_chunk); unsigned long old_size = __mchunk_size(next_chunk); chunk-&gt;size = req_size | (1UL &lt;&lt; CHUNK_USED); memset(next_chunk, 0, sizeof(t_chunk)); next_chunk = __mchunk_next(chunk); if (next_chunk != __mbin_end(bin) &amp;&amp; next_chunk-&gt;size == 0) next_chunk-&gt;size = realloc_size - req_size; if (old_size == bin-&gt;max_chunk_size) update_max_chunk(bin, next_chunk, old_size); pthread_mutex_unlock(&amp;arena-&gt;mutex); return chunk-&gt;user_area; } pthread_mutex_unlock(&amp;arena-&gt;mutex); free(ptr); return malloc(size); } void * malloc(size_t size) { return __malloc(size, 0); } void * calloc (size_t nmemb, size_t size) { return __malloc(nmemb * size, 1); } </code></pre> <p>free.c:</p> <pre><code>#include "malloc.h" #include "arenap.h" void free (void *ptr) { if (ptr == NULL) return; t_chunk *chunk = (t_chunk *)((unsigned long)ptr - sizeof(t_chunk)); /* If the pointer is not aligned on a 16bytes boundary, it is invalid by definition. */ if (g_arena_data == NULL || (unsigned long)chunk % 16UL != 0 || __mchunk_invalid(chunk)) { (void)(write(STDERR_FILENO, "free(): invalid pointer\n", 24) + 1); abort(); } t_bin *bin = chunk-&gt;bin; t_arena *arena = bin-&gt;arena; pthread_mutex_lock(&amp;arena-&gt;mutex); /* We return the memory space to the bin free size. If the bin is empty, we unmap it. */ bin-&gt;free_size += __mchunk_size(chunk); if (bin-&gt;free_size + sizeof(t_bin) == __mbin_size(bin)) { if (__mbin_main(bin)) { chunk = bin-&gt;chunk; chunk-&gt;size = bin-&gt;free_size; bin-&gt;max_chunk_size = chunk-&gt;size; if (__mchunk_type_nomatch(bin, CHUNK_LARGE)) __marena_update_max_chunks(bin, 0); memset(chunk-&gt;user_area, 0, chunk-&gt;size - sizeof(t_chunk)); } else { if (bin-&gt;left != NULL) bin-&gt;left-&gt;right = bin-&gt;right; if (bin-&gt;right != NULL) bin-&gt;right-&gt;left = bin-&gt;left; munmap(bin, bin-&gt;size &amp; SIZE_MASK); } } else { chunk-&gt;size &amp;= ~(1UL &lt;&lt; CHUNK_USED); /* Defragment memory. */ t_chunk *next_chunk = __mchunk_next(chunk); if (next_chunk != __mbin_end(bin) &amp;&amp; __mchunk_not_used(next_chunk)) { chunk-&gt;size += next_chunk-&gt;size; memset(next_chunk, 0, sizeof(t_chunk)); } if (__mchunk_size(chunk) &gt; bin-&gt;max_chunk_size) { bin-&gt;max_chunk_size = __mchunk_size(chunk); __marena_update_max_chunks(bin, 0); } } pthread_mutex_unlock(&amp;arena-&gt;mutex); } </code></pre> <p>mallocp.h:</p> <pre><code>#ifndef __MALLOC_PRIVATE_H # define __MALLOC_PRIVATE_H # include "malloc.h" # include "arenap.h" # include &lt;errno.h&gt; # define CHUNKS_PER_POOL 100 # define SIZE_TINY 256 # define SIZE_SMALL 4096 #endif /* __MALLOC_PRIVATE_H */ </code></pre> <p>arenap.h:</p> <pre><code>#ifndef __ARENA_PRIVATE_H # define __ARENA_PRIVATE_H # include &lt;pthread.h&gt; # include &lt;sys/mman.h&gt; /* For memset. */ # include &lt;string.h&gt; /* For abort. */ # include &lt;stdlib.h&gt; # define M_ARENA_MAX 8 # define SIZE_THRESHOLD 59 enum e_type { CHUNK_USED = SIZE_THRESHOLD + 1, CHUNK_TINY, CHUNK_SMALL, CHUNK_LARGE }; # define FLAG_MASK (~SIZE_MASK) # define SIZE_MASK ((1UL &lt;&lt; (SIZE_THRESHOLD + 1)) - 1) # define __mabs(x) ({ __typeof__(x) _x = (x); _x &lt; 0 ? -_x : _x; }) # define __mbin_end(bin) ((void *)((unsigned long)bin + __mbin_size(bin))) # define __mbin_main(bin) (__mchunk_type_match(bin, CHUNK_LARGE) ? bin == arena-&gt;large_bins : bin == arena-&gt;small_bins) # define __mbin_size(bin) (bin-&gt;size &amp; SIZE_MASK) # define __mchunk_is_used(chunk) (chunk-&gt;size &amp; (1UL &lt;&lt; CHUNK_USED)) # define __mchunk_next(chunk) ((t_chunk *)((unsigned long)chunk + __mchunk_size(chunk))) # define __mchunk_not_used(chunk) (__mchunk_is_used(chunk) == 0) # define __mchunk_size(chunk) (chunk-&gt;size &amp; SIZE_MASK) # define __mchunk_type_match(bin, chunk_type) (bin-&gt;size &amp; (1UL &lt;&lt; chunk_type)) # define __mchunk_type_nomatch(bin, chunk_type) (__mchunk_type_match(bin, chunk_type) == 0) # define __mchunk_invalid(chunk) \ ((chunk-&gt;size &amp; FLAG_MASK) != (1UL &lt;&lt; CHUNK_USED) || __mabs((ssize_t)chunk - (ssize_t)chunk-&gt;bin) &gt; (1UL &lt;&lt; 32)) # define __marena_update_max_chunks(bin, old_size) \ ({ \ if (__mchunk_type_match(bin, CHUNK_TINY) &amp;&amp; (old_size == bin-&gt;arena-&gt;max_chunk_tiny \ || bin-&gt;max_chunk_size &gt; bin-&gt;arena-&gt;max_chunk_tiny)) { \ bin-&gt;arena-&gt;max_chunk_tiny = bin-&gt;max_chunk_size; \ } else if (__mchunk_type_match(bin, CHUNK_SMALL) &amp;&amp; (old_size == bin-&gt;arena-&gt;max_chunk_small \ || bin-&gt;max_chunk_size &gt; bin-&gt;arena-&gt;max_chunk_small)) { \ bin-&gt;arena-&gt;max_chunk_small = bin-&gt;max_chunk_size; \ } \ }) typedef struct s_chunk { unsigned long size; struct s_bin *bin; void *user_area[0]; } __attribute__((packed)) t_chunk; typedef struct s_bin { unsigned long free_size; unsigned long size; unsigned long max_chunk_size; struct s_arena *arena; struct s_bin *left; struct s_bin *right; t_chunk chunk[0]; } __attribute__((packed)) t_bin; typedef struct s_arena { pthread_mutex_t mutex; t_bin *small_bins; t_bin *large_bins; unsigned long max_chunk_tiny; unsigned long max_chunk_small; } t_arena; typedef struct s_arena_data { _Atomic int arena_count; t_arena arenas[M_ARENA_MAX]; } t_arena_data; extern t_arena_data *g_arena_data; #endif /* __ARENA_PRIVATE_H */ <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T23:34:13.713", "Id": "412435", "Score": "0", "body": "I probably missed it, however, I do not see when `realloc()` is called, the prior contents is copied to the new 'chunk'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T04:40:10.727", "Id": "412440", "Score": "0", "body": "Oh geez, you're right, I completely forgot about that....." } ]
[ { "body": "<p>This is a general C code review, not addressing functionality. Overall the code is fairly well-written so most of my remarks are minor nit-picks. Could do with more comments. Your coding style is a bit exotic but as long as you keep it consistent, that's ok.</p>\n\n<p><strong>Program design</strong></p>\n\n<ul>\n<li><p>You don't seem to have an actual API for the functions. Even if they are supposed to replace the standard library ones, you still need some user entry point header where the function declarations and use are found. I suppose this is \"malloc.h\" but you didn't post that one.</p></li>\n<li><p>You need to drop inlining. Both the gcc one and the standard C <code>inline</code>. When writing library/system code, it is frowned upon to use inlining all over, because it leads to big executables. Several of your functions are not great candidates for inlining. The decision when to inline should be made by the compiler, not the programmer. </p>\n\n<p><code>inline</code> is mostly to be regarded as an obsolete keyword, much like <code>register</code>.</p></li>\n</ul>\n\n<p><strong>Standard compliance</strong></p>\n\n<ul>\n<li><p>There's a potential for namespace clashes with stdlib.h. Apart from the obvious names <code>malloc</code> etc: if your code isn't actually part of Glibc or equivalent, then you shouldn't use <code>__</code> prefixes.</p></li>\n<li><p><code>void *user_area[0];</code> etc is not valid C. This is obsolete non-standard gnu since 20 years back and shouldn't be used. Use standard C flexible array members instead, they work the same. </p></li>\n<li><p>Whenever possible, drop non-standard <code>__typeof__</code> in favour of standard C <code>_Generic</code>.</p></li>\n</ul>\n\n<p><strong>Potential bugs</strong></p>\n\n<ul>\n<li><p><code>g_arena_data</code> is occasionally accessed outside mutex locks. Could be problematic and perhaps solved with <code>_Atomic</code>.</p></li>\n<li><p><code>return (void *)chunk-&gt;user_area;</code> is fishy, why the cast? Looks like a cast from <code>void**</code> to <code>void*</code> and thereby a bug?</p></li>\n</ul>\n\n<p><strong>Performance</strong></p>\n\n<ul>\n<li>I'd thread carefully around <code>__attribute__((packed))</code>. While you might want to keep heap memory small, this might lead to various misaligned access and slower code. Would have to be benchmarked in detail.</li>\n</ul>\n\n<p><strong>Coding style</strong></p>\n\n<ul>\n<li><p>Avoid \"secret macro language\" macros. Hiding trivial operations behind macros is bad practice, it makes the code harder to read, not easier. Readability is more important than concerns about potential code repetition. For example instead of this:</p>\n\n<pre><code># define __mchunk_is_used(chunk) (chunk-&gt;size &amp; (1UL &lt;&lt; CHUNK_USED))\n</code></pre>\n\n<p>You should simply write:</p>\n\n<pre><code>bool chunk is_chunk_used = (chunk-&gt;size &amp; (1UL &lt;&lt; CHUNK_USED));\n</code></pre>\n\n<p>There's no need to \"protect\" the programmer against reading code containing bit-wise operators etc. You can assume that the reader knows C, but not the \"secret macro language\".</p></li>\n<li><p>Similarly, there is no reason to implement <code>__marena_update_max_chunks</code> as a function-like macro. Write a function instead, for readability. But also so you can make it <code>static</code> to the specific translation unit instead of the global namespace.</p></li>\n<li><p>if statements such as this one are hard to read and should be avoided:</p>\n\n<pre><code> if (chunk_type != CHUNK_LARGE) mmap_size = sizeof(t_bin) + (size + sizeof(t_chunk)) * CHUNKS_PER_POOL;\n else mmap_size = size + headers_size;\n</code></pre>\n\n<p>Keep the contents indented, at a line of their own. Also, it is good practice to always use braces even when there is just a single expression following if/else.</p></li>\n<li><p>Consistently use <code>size_t</code> for storing the size of an array. Not <code>int</code> or <code>unsigned long</code>.</p></li>\n<li><p>Avoid using the lvalue result of <code>=</code> inside expressions. Something like <code>arena = &amp;arena_data.arenas[(arena_index = 0)];</code> should be rewritten as <code>arena_index = 0; arena = &amp;arena_data.arenas[arena_index];</code></p></li>\n<li><p>The presence of <code>continue</code> in C code almost exclusively means that a loop should be rewritten in more readable ways. For example the <code>while (pthread_mutex_trylock(&amp;arena-&gt;mutex) != 0)</code> loop could likely be rewritten along the lines of <code>for(arena_index = 0; arena_index &lt; N; arena_index++)</code>.</p>\n\n<p>Keep in mind that even if you have a loop condition or loop iterator that needs to be accessed inside mutex locks, that necessarily doesn't mean that you have to write that part in the loop body. Something like <code>for(mystruct* ms=...; access(ms) &lt; count; ...</code> is possible, where <code>access</code> is a wrapper function containing the mutex lock/unlock around the variable.</p></li>\n<li><p><code>t_chunk *chunk = (t_chunk *)((unsigned long)ptr - sizeof(t_chunk));</code> could be rewritten as <code>t_chunk *chunk = (t_chunk*)ptr - 1;</code></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T15:07:15.810", "Id": "412622", "Score": "0", "body": "Thank you for all your inputs. I adjusted my code to take them into consideration." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T10:10:05.223", "Id": "213238", "ParentId": "213213", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T20:56:07.077", "Id": "213213", "Score": "9", "Tags": [ "c", "memory-management", "homework", "pthreads" ], "Title": "My malloc() in C using mmap()" }
213213
<p>Coding problem: </p> <blockquote> <p>Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.</p> </blockquote> <p>My solution:</p> <pre><code>arr = np.array([1, 2, 3, 4, 5]) def coding_solution(_arr): ind = 0 new_arr = [] for n in range(len(_arr)): v = 1 for m, i in enumerate(_arr): v *= i if m != ind else 1 new_arr.append(v) ind += 1 return np.array(new_arr) </code></pre> <p>Output: <code>[120, 60, 40, 30, 24]</code> </p> <p>Is there a faster or less space consuming solution? It takes longer to run then I would've expected or would think is acceptable.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T03:31:34.647", "Id": "412437", "Score": "2", "body": "Possible follow up question https://stackoverflow.com/questions/2680548/given-an-array-of-numbers-return-array-of-products-of-all-other-numbers-no-div" } ]
[ { "body": "<h2>Review:</h2>\n\n<p>So there are some changes that can be made. As you are running a nested for loop that should be the first candidate for removal, python isn't the best with lots of loops. I've made some changes below to improve your code. </p>\n\n<ul>\n<li>Here we actually use <code>n</code>, instead of <code>ind</code>, they are the same, so <code>ind</code> is excessive</li>\n<li>I've expanded the <code>if ... else</code> block as this improves readability</li>\n<li>I've changed <code>i</code> for <code>x</code> as this is easier to quickly differentiate from <code>1</code></li>\n</ul>\n\n<hr>\n\n<pre><code>def coding_solution(_arr):\n new_arr = []\n for n in range(len(_arr)):\n v = 1\n for m, x in enumerate(_arr):\n if m != n:\n v *= x \n else:\n v *= 1\n new_arr.append(v)\n return np.array(new_arr)\n</code></pre>\n\n<hr>\n\n<h2>Alternate solutions:</h2>\n\n<p>I have two methods that work, one is pure python (using two core libraries), but could include numpy; the other is all numpy. They both work on a similar principal, that is that all new values are the same product (the entire array) divided by the value at the same index in the original array. Therefore, you can just divide the product of the entire array by each value in the original array, as long as there are no zero values (thanks One Lyner!).</p>\n\n<h3>Pure python:</h3>\n\n<pre><code>from functools import reduce\nfrom operator import mul\n\narr = [1, 2, 3, 4, 5]\n\ndef f(_arr):\n arr_prod = reduce(mul, _arr) # You could use np.prod(_arr) instead of reduce(...)\n return [arr_prod / x for x in _arr]\n</code></pre>\n\n<p>The pure python function could be a single line, but then you might end up computing the product of the entire array on every iteration.</p>\n\n<h3>Numpy</h3>\n\n<pre><code>\nimport numpy as np\n\narr = np.array([1, 2, 3, 4, 5])\n\ndef g(_arr):\n return np.ones(_arr.shape) * _arr.prod() / _arr\n\n# Even more succinct, thanks Graipher\ndef h(_arr):\n return _arr.prod() / _arr\n</code></pre>\n\n<p>This Numpy solution would be vectorised and would scale well, but may be slower on smaller arrays. It works by creating a new <code>np.array</code> of all <code>1</code>; multiplying it by the product, so all the values are the product; finally dividing the 'product array' by the original array, which is element-wise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T11:55:44.513", "Id": "412475", "Score": "1", "body": "Just `_arr.prod() / _arr` also works (since `int` does not know how to divide by a `numpy.array`, it is delegated to the array which *does* know how to divide and scale itself)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T15:56:38.177", "Id": "412498", "Score": "2", "body": "corner case: note this only works if there is no zero in the array!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T00:52:55.953", "Id": "213223", "ParentId": "213214", "Score": "3" } }, { "body": "<p>To take into account the case where there is some zero values in the array, it's best to avoid divisions.\nTo make this efficiently, you can do two passes, one computing the product of elements before and one computing the product of elements after.</p>\n\n<p>Pure python:</p>\n\n<pre><code>def products_of_others(a):\n L = len(a)\n r = [1]*L\n after = before = 1\n for i in range(1,L):\n before *= a[i-1]\n r[i] = before\n for i in range(L-2,-1,-1):\n after *= a[i+1]\n r[i] *= after\n return r\n</code></pre>\n\n<p>Numpy:</p>\n\n<pre><code>def products_of_others(a):\n after = numpy.concatenate([a[1:], [1]])\n before = numpy.concatenate([[1], a[:-1]])\n a = numpy.cumprod(after[::-1])[::-1]\n b = numpy.cumprod(before)\n return a * b\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T16:51:01.333", "Id": "213254", "ParentId": "213214", "Score": "3" } } ]
{ "AcceptedAnswerId": "213223", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T21:09:49.573", "Id": "213214", "Score": "2", "Tags": [ "python", "python-3.x", "interview-questions" ], "Title": "Return array with products of old array except i" }
213214
<p>I've recently migrated away from floats and have started using flexbox to build my grids.</p> <p>My navigation has 4 menu items. I'd like my logo to sit in the middle of these. To maintain a good page structure for SEO, I don't like the idea of putting my logo within a list item inside the nav.</p> <p>Instead, I've built a solution that uses flexbox and a negative margin.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>/*------------------------ Default grid -------------------------*/ .flex { display: flex; flex-flow: row wrap; justify-content: space-between; } .col { flex: 1; } /*------------------------ Columns -------------------------*/ .has-2-columns .col { flex: none; } .has-2-columns .col { width: 49%; } /*------------------------ Logo -------------------------*/ .site-title { position: relative; /* Enables z-index */ z-index: 1; /* Positions logo above .main-navigation */ width: 80px; margin: 0 auto; background: #ccc; } /*------------------------ Main navigation -------------------------*/ .main-navigation { position: relative; margin-top: -24px; /* Brings nav inline with .site-branding */ z-index: 0; /* Ensures nav is below .site-branding */ } .main-navigation ul { list-style: none; padding: 0; margin: 0; } .main-navigation ul li { display: inline-block; } .left-menu { text-align: left; } .left-menu li { margin-right: 24px; } .right-menu { text-align: right; } .right-menu li { margin-left: 24px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header class="site-header"&gt; &lt;div class="site-branding"&gt; &lt;h1 class="site-title"&gt;&lt;a href="#" rel="home"&gt;Demo&lt;/a&gt;&lt;/h1&gt; &lt;/div&gt; &lt;nav class="main-navigation flex has-2-columns"&gt; &lt;div class="left-menu col"&gt; &lt;ul id="left-menu" class="menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="right-menu col"&gt; &lt;ul id="right-menu" class="menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Store&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/header&gt;</code></pre> </div> </div> </p> <p>Is there a better way? Would this solution cause issues across different devices when it comes to clicking / tapping the menu items or logo to go back home?</p>
[]
[ { "body": "<p>If you're going to use flex, <strong><em>use</em></strong> flex! Flex inherently helps with margin control.</p>\n\n<p>Margins are great, but you're essentially saying, I want to learn flex, except when it's easier/convenient to go back to what I've been doing. </p>\n\n<p>Some key topics of interest regarding your concerns:</p>\n\n<blockquote>\n <p>To maintain a good page structure for SEO...</p>\n</blockquote>\n\n<p>Great! That's a good attitude to have. You should always follow the W3C specs for best practices of what content goes where. If you don't like reading long-winded documentation.. <a href=\"https://developer.mozilla.org/en-US\" rel=\"noreferrer\">MDN</a> always has a great synopsis of elements/attributes/rules/principals/best practices (usually in a blue box). </p>\n\n<p>Buttttt having a header inside <code>&lt;nav&gt;</code> tags isn't necessarily against standards, in fact, all <code>flow content</code> is permitted. <a href=\"https://html.spec.whatwg.org/multipage/sections.html#the-nav-element\" rel=\"noreferrer\">ref</a> </p>\n\n<p>Additionally, in your circumstance, it acts as a main content link, so I would argue it belongs there.</p>\n\n<p>However, keeping in mind the importance of a semantic elements purpose is a very good outlook imo.</p>\n\n<p>Furthermore on this point, <em>I can not tell you how many developers overlook accessibility</em>. Not only does it help you with SEO, it absolutely is critical to how disabled persons rely on their devices. It often takes trivial amount of time to make a website accessible friendly, but developers generally don't consider it because either they themselves aren't disabled and it's in the back of their mind, they haven't had any complaints, they don't work for someone who cares to implement it. But that is beyond the scope of the question, either way you are on the right track with that mentality. </p>\n\n<blockquote>\n <p>I've recently migrated away from floats and have started using flexbox </p>\n</blockquote>\n\n<p>Not a bad thing, will definitely make it easier for you, but try not to consider them synonyms. Float properties apply to <em>all</em> elements, even flex, but flex properties do not apply to all elements. With the following caveats:</p>\n\n<ul>\n<li>float applies but no effect is taken if <code>display</code> = none</li>\n<li>float applies but no effect is taken if element is flex</li>\n</ul>\n\n<p>An example of why they are not synonymous is <code>float:left</code> for an <code>&lt;img&gt;</code> tag around text will allow that text to flow around the content, whereas flexbox is ... well a box and the text will maintain in it's rect bounds instead of wrapping around the box next to it.</p>\n\n<p>An important thing to embrace with flex is that as soon as you set an element to <code>display: flex</code> <strong>the direct children of that container become flex items</strong>. So note the hierarchy there. </p>\n\n<p>Take this example where 'C' is not a direct descendant of <code>.wrapper</code>, therefor it doesn't inherit properties.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.wrapper {\n display: flex;\n flex-flow: column nowrap;\n \n height: 175px; padding: 10px; border-color: red;\n}\n\n.b, .c {\n float: right;\n border-color: green;\n}\n.c {\n background-color: lightgrey;\n} \n\n/** irrelevant **/\ndiv {\n height: 50px;\n border: 1px solid;\n}\n.a { border-color: blue; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"wrapper\"&gt;\n &lt;div class=\"a\"&gt;:::::: A :::::::&lt;/div&gt;\n &lt;div class\"b\"&gt;\n &lt;div&gt;:::::: B ::::::&lt;/div&gt;\n &lt;div class=\"c\"&gt;:::::: C ::::::&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I bring that up, because navigation items are generally top-level children, so we can consider that in circumstances like <code>margin-top: -24px</code>. You can take the following snippet (unchanged from OP, other than color for effect) and see why it can be problematic real fast, and worse, it can easily create a domino effect where you will have to add margins to a lot of other things just to create synergy:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/*------------------------\nDefault grid\n-------------------------*/\n\n.flex {\n display: flex;\n flex-flow: row wrap;\n justify-content: space-between;\n}\n\n.col {\n flex: 1;\n}\n\n\n/*------------------------\nColumns\n-------------------------*/\n\n.has-2-columns .col {\n flex: none;\n}\n\n.has-2-columns .col {\n width: 49%;\n}\n\n\n/*------------------------\nLogo\n-------------------------*/\n\n.site-title {\n position: relative;\n /* Enables z-index */\n z-index: 1;\n /* Positions logo above .main-navigation */\n width: 80px;\n margin: 0 auto;\n background: #ccc;\n}\n\n\n/*------------------------\nMain navigation\n-------------------------*/\n\n.main-navigation {\n position: relative;\n margin-top: -24px;\n /* Brings nav inline with .site-branding */\n z-index: 0;\n /* Ensures nav is below .site-branding */\n}\n\n.main-navigation ul {\n list-style: none;\n padding: 0;\n margin: 0;\n}\n\n.main-navigation ul li {\n display: inline-block;\n}\n\n.left-menu {\n text-align: left;\n}\n\n.left-menu li {\n margin-right: 24px;\n}\n\n.right-menu {\n text-align: right;\n}\n\n.right-menu li {\n margin-left: 24px;\n}\n\n.site-header {\n background: pink;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header class=\"site-header\"&gt;\n\n &lt;div class=\"site-branding\"&gt;\n &lt;h1 class=\"site-title\"&gt;&lt;a href=\"#\" rel=\"home\"&gt;Demo&lt;/a&gt;&lt;/h1&gt;\n &lt;/div&gt;\n\n &lt;nav class=\"main-navigation flex has-2-columns\"&gt;\n\n &lt;div class=\"left-menu col\"&gt;\n &lt;ul id=\"left-menu\" class=\"menu\"&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n\n &lt;div class=\"right-menu col\"&gt;\n &lt;ul id=\"right-menu\" class=\"menu\"&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Store&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n\n &lt;/nav&gt;\n\n&lt;/header&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>So that is why I say, if you're going to use flex, then use flex! <em>Take advantage of it. Let it do all this work and calculations for you</em>. Additionally, I don't know if you have begun plans for this or not, but this isn't really responsive friendly as it stands now. </p>\n\n<hr>\n\n<h1>TLDR;</h1>\n\n<h2>Revisiting requirements</h2>\n\n<blockquote>\n <p>My navigation has 4 menu items. I'd like my logo to sit in the middle of these</p>\n</blockquote>\n\n<p>The way you have set it up, as you can see get's the job done. But they are not apart of the same parent, therefor they can't take advantage of it's inherited properties, and more importantly don't recognize each other as siblings. So I think that's the first thing to address.</p>\n\n<p>Let's assume the following here forward (no margins, no positioning):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/*------------------------\nDefault grid\n-------------------------*/\n\n\n\n/*------------------------\nColumns\n-------------------------*/\n\n.has-2-columns .col {\n flex: none;\n}\n\n.has-2-columns .col {\n width: 49%;\n}\n\n\n/*------------------------\nLogo\n-------------------------*/\n\n.site-title {\n background: #ccc;\n}\n\n\n/*------------------------\nMain navigation\n-------------------------*/\n\n.main-navigation { background-color: lightgrey;}\n\n.main-navigation ul {\n display: inline-flex;\n list-style: none;\n padding: 0;\n margin: 0;\n}\n\n.main-navigation ul li { }\n\n.left-menu {\n text-align: left;\n}\n\n.left-menu li {}\n\n.right-menu {\n text-align: right;\n}\n\n.right-menu li {}\n\n.site-header {\n display: flex;\n flex-flow: row wrap;\n background-color: pink;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header class=\"site-header\"&gt;\n\n &lt;div class=\"site-branding\"&gt;\n &lt;h1 class=\"site-title\"&gt;&lt;a href=\"#\" rel=\"home\"&gt;Demo&lt;/a&gt;&lt;/h1&gt;\n &lt;/div&gt;\n \n &lt;nav class=\"main-navigation has-2-columns\"&gt;\n\n &lt;div class=\"left-menu col\"&gt;\n &lt;ul id=\"left-menu\" class=\"menu\"&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n\n &lt;div class=\"right-menu col\"&gt;\n &lt;ul id=\"right-menu\" class=\"menu\"&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Store&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n\n &lt;/nav&gt;\n\n&lt;/header&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Making them siblings can assistant in limiting any crutches we have on margins and positioning by granting them situational awareness to one another now. </p>\n\n<p>This is also a good time to practice good standards when it comes to classes. Since we stripped all the classes we no longer need, we aren't styling multiple elements anymore, so we can change their selector to an <code>id</code>.</p>\n\n<p>Additionally, let's take advantage of what we learned about direct descendants and apply that now by making the <code>&lt;h1&gt;</code> a direct sibling to both lists as follows:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/*------------------------\n Main navigation\n -------------------------*/\n\n#main-navigation {\n background-color: lightgrey;\n}\n\n#main-navigation ul {\n display: inline-flex;\n list-style: none;\n padding: 0;\n margin: 0;\n}\n\n#site-header {\n display: flex;\n flex-flow: row wrap;\n background-color: pink;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header id=\"site-header\"&gt;\n\n &lt;nav id=\"main-navigation\"&gt;\n\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;h1&gt;&lt;a href=\"#\" rel=\"home\"&gt;Demo&lt;/a&gt;&lt;/h1&gt;\n\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Store&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;/nav&gt;\n\n&lt;/header&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Your needs will vary depending on the project, but this particular example we don't have anything else but the navigation so we are going to promote the <code>&lt;nav&gt;</code> to be the flex parent. In doing this we can take advantage of <code>align</code> properties, <code>justify</code> properties and of course the other flex benefits. The 2 key properties are <code>align-items</code> which (on <code>flex-direction: row</code>) it centers the children vertically in our case, and <code>justify-content</code> which you seem to be familiar with. These 2 properties alone handle everything you've used margins for as intended.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#main-navigation {\n display: flex;\n flex-flow: row wrap;\n align-items: center; /* center the elements (vertically for this axis) in the parent space */\n justify-content: space-between;\n}\n\n#main-navigation ul {\n display: inline-flex;\n list-style: none;\n padding: 0;\n margin: 0;\n}\n#main-navigation li {\n padding: 0 10px;\n}\n\n\n\n/* irrelevant */\n#site-header {\n background-color: pink;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header id=\"site-header\"&gt;\n\n &lt;nav id=\"main-navigation\"&gt;\n\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;h1&gt;&lt;a href=\"#\" rel=\"home\"&gt;Demo&lt;/a&gt;&lt;/h1&gt;\n\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Store&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;/nav&gt;\n\n&lt;/header&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>So that's one way to get your desired outcome on a fundamental level</p>\n\n<p>..... but wait, mobile first right? Naturally, a simple media query can help you adjust things as you wish, that will be arbitrary to your styling needs, but here is a brief example that makes the previous example responsive friendly:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#main-navigation {\n display: flex;\n flex-flow: row wrap;\n align-items: center; /* center the elements (vertically for this axis) in the parent space */\n justify-content: space-between;\n}\n\n#main-navigation ul {\n display: inline-flex;\n list-style: none;\n padding: 0;\n margin: 0;\n}\n#main-navigation li {\n padding: 0 10px;\n}\n\n\n@media only screen and (max-width: 396px) {\n #main-navigation {\n flex-flow: column nowrap;\n }\n \n #main-navigation h1 {\n order: -1;\n }\n}\n\n\n/* irrelevant */\n#site-header {\n background-color: pink;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header id=\"site-header\"&gt;\n\n &lt;nav id=\"main-navigation\"&gt;\n\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;h1&gt;&lt;a href=\"#\" rel=\"home\"&gt;Demo&lt;/a&gt;&lt;/h1&gt;\n\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Store&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;/nav&gt;\n\n&lt;/header&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Notice how in that example, the <code>&lt;h1&gt;</code> element has an <code>order</code> of -1. Flex assigns '0' to an element as the default value. Therefor -1 gives specificity to those elements without needing to change every single one to [..1,2,3 etc]</p>\n\n<p>And if you REALLY REALLY don't feel well about including it there after all that, we can kind of hack it there:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#main-navigation {\n padding: 10px;\n}\n\n#main-navigation ul {\n display: flex;\n flex-flow: row wrap;\n align-items: center;\n /* center the elements (vertically for this axis) in the parent space */\n justify-content: space-evenly;\n list-style: none;\n padding: 0;\n margin: 0;\n}\n\n#branding {\n font-size: 1.75rem;\n}\n\n@media only screen and (max-width: 396px) {\n #main-navigation ul {\n flex-flow: column nowrap;\n }\n #branding {\n order: -1;\n }\n}\n\n\n/* irrelevant */\n\n#site-header {\n background-color: pink;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header id=\"site-header\"&gt;\n\n &lt;nav id=\"main-navigation\"&gt;\n\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;li id=\"branding\"&gt;&lt;a href=\"#\"&gt;Demo&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Store&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;/nav&gt;\n\n&lt;/header&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T18:54:12.987", "Id": "413283", "Score": "2", "body": "Wow! Thank you so much for taking the time to leave this answer. Excellent response. I'll be taking some time to try each technique this week. Rock on!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T09:11:43.687", "Id": "213564", "ParentId": "213216", "Score": "5" } }, { "body": "<p>I'd first point out that I don't think you need to split your menu in two. There is no reason you can't put a blank spot in the menu where you want the logo. I did an example using an empty list item for this: </p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;nav&gt;\n &lt;ul id=\"left-menu\" class=\"menu\"&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;About&lt;/a&gt;&lt;/li&gt;\n &lt;li class='blank-fill'&gt;&lt;/li&gt; \n &lt;li&gt;&lt;a href=\"#\"&gt;Contact&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Store&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/nav&gt;\n &lt;div class=\"site-branding\"&gt;\n &lt;h1 class=\"site-title\"&gt;&lt;a href=\"#\" rel=\"home\"&gt;Demo&lt;/a&gt;&lt;/h1&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>nav{\n background: #5b6ee1;\n}\n\nnav ul{\n list-style: none;\n display: flex;\n flex-flow: row nowrap;\n justify-content: center;\n align-items: center;\n margin: 0;\n}\n\nnav li{\n flex: 1 1 auto;\n text-align: center;\n padding: 1em;\n}\n\nnav a, .site-title a{\n color: white;\n padding: 1em 2em;\n text-decoration: none;\n}\n\n.blank-fill{\n flex: 2 1 auto; /* can update this based on how much space you want in the center */\n}\n\n.site-branding{\n display: flex;\n flex-flow: row nowrap;\n justify-content: center;\n align-items: center;\n\n background: #847e87; /* to show where this div is located */\n /*\n Can put height 0 and change the .site-title to top: -0.8em.\n Note: may have to constantly tweak and update this as you change sizes.\n */\n /* height: 0; */\n}\n.site-title{\n position: relative;\n top: -2em;\n}\n\nbody{\n margin: 0;\n}\n</code></pre>\n\n<p>Then I used position:relative and a negative top value to move the site title up.</p>\n\n<p><a href=\"https://codepen.io/LouBagel/pen/NVBPZv\" rel=\"nofollow noreferrer\">Example on CodePen</a></p>\n\n<p>CSS Grid could take care of this as well and without creating empty elements.</p>\n\n<p>Without seeing the rest of your page I can't really say if your SEO concerns are valid. I'd say I would agree that if you only have one h1 element (as it is okay to put an h1 in each section element) and only list the name of the company/group/page/etc once it would probably be better to have it outside the menu. Though there is nothing wrong with having it in the menu and I'd think there would be opportunities to have it elsewhere, too. If you do put an image in an h1 make sure you add the alt and title tags.</p>\n\n<p>I'd say just put the logo/h1 in the nav menu. Breaking the menu into two and trying quirky fixes isn't semantic. It may look normal but think about the bots reading your code and viewing these quirks as irregular practices.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-28T04:28:05.930", "Id": "221174", "ParentId": "213216", "Score": "1" } } ]
{ "AcceptedAnswerId": "213564", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T21:51:29.937", "Id": "213216", "Score": "6", "Tags": [ "html", "css", "layout" ], "Title": "Position logo in middle of nav" }
213216
<p>I have a class with a property of <code>grid[][]</code> and each value is either true or false. I need to convert this to a string with letters o and b in place of the boolean.</p> <p>First way, simple for loops over the array and return the string:</p> <pre><code> get rle() { let result = ""; for(let y = 0; y &lt; this.grid.length; y++) { for(let x =0; x &lt; this.grid[y].length; x++) { result += ( (this.grid[y][x]) ? "o" : "b" ); } } return result; } </code></pre> <p>Or a more JS style solution?</p> <pre><code>get rle() { return this.grid.reduce( (total, currentValue, currentIndex, arr) =&gt; { return total + arr[currentIndex].reduce( (total, currentValue, currentIndex, arr) =&gt; { return total + ( (arr[currentIndex]) ? "o" : "b" ); }, ""); }, ""); } </code></pre> <p>Is this a good JS style solution, and what in your opinion is better? I prefer the first because anyone can instantly understand it. The JS solution makes me frown with 3 nested returns, looks odd.</p>
[]
[ { "body": "<p>First, a few points of the code you wrote. If you have an array of values, you can <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\"><code>join</code></a> the values together to efficiently create a string. This would eliminate the need for at least one of the <code>reduce</code> calls. Second, in a reduce call, the value of the second callback parameter (<code>currentValue</code> in your code) is the value of the array parameter at the index parameter (<code>arr[currentIndex]</code> in your code). Combining that with Javascript's capability to ignore excess function parameters, your <code>reduce</code> calls should take only two parameters, and use the <code>currentValue</code> in place of the <code>arr[currentIndex]</code>.</p>\n\n<p>You should also avoid using the same variable names in the same scope. Having two sets of <code>total</code>, <code>currentValue</code>, <code>currentIndex</code>, and <code>arr</code> could get confusing quickly, and lead to strange bugs.</p>\n\n<p>Now, for the one-liner:</p>\n\n<pre><code>return this.grid.flat().map((el) =&gt; el ? \"o\" : \"b\").join(\"\");\n</code></pre>\n\n<p>See <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\" rel=\"nofollow noreferrer\"><code>Array#flat</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>Array#map</code></a>, and the aforementioned <code>Array#join</code>. Of these, <code>Array#flat</code> is the newest and possibly unsupported method. It can be easily polyfilled or replaced. The MDN page shows some clever replacements like <code>arr.reduce((all, row) =&gt; all.concat(row), [])</code> and <code>[].concat(...arr)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T12:11:25.790", "Id": "412476", "Score": "0", "body": "Yes, And this method will work faster too..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T12:47:16.833", "Id": "412477", "Score": "0", "body": "That's the one liner I was looking for. Back to the arrays manual for me.. thanks cbojar." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T04:35:41.830", "Id": "213230", "ParentId": "213218", "Score": "2" } } ]
{ "AcceptedAnswerId": "213230", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T23:07:30.417", "Id": "213218", "Score": "0", "Tags": [ "javascript", "array" ], "Title": "Reduce a grid array [][] into a string" }
213218
<p>I wrote this small jQuery plugin to set some fields so that they allow only 0-9 digits to be entered.</p> <p>I intended to do that by preventing user from typing, pasting or dropping non-digit content.</p> <p>It seems to work (on Firefox), but I'd like to know if this code has some issue or unpredicted effect I'm not seeing now.</p> <pre><code>$.fn.onlyDigits = function () { return this.val("").off("keypress").on("keypress", function (evt) { evt = evt || window.evt; return /\d/.test("" + evt.originalEvent.key); } ).off("drop paste").on("drop paste", function (evt) { $(evt.target).on("input", function (evt2) { evt2.target.value = evt2.target.value.replace(/\D+/g, ""); $(evt2.target).off("input"); } ); } ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T20:08:55.010", "Id": "413459", "Score": "1", "body": "Very nice and for me educational. A side effect that could be a problem in some scenario's is that it is not possible to input a decimal point." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T01:21:22.790", "Id": "213224", "Score": "1", "Tags": [ "javascript", "jquery", "validation", "form", "plugin" ], "Title": "jQuery plugin for allowing only digits to be entered in html form input" }
213224
<p>This script is running indefinitely as the Linux background process.</p> <p>I have put an enormous effort to make this <strong>POSIX</strong> shell script containing an <strong>infinite loop</strong> shut down tidily along with the operating system (TERM signal) and by me sending it a HUP signal.</p> <p>Ok, we don't call it <em>exception-handling</em>, but I didn't find any other suitable tag for it. Also did not find an appropriate tag for the script's termination.</p> <p>We have reviewed two big pieces of the puzzle already, so I cut it out.</p> <hr> <pre class="lang-sh prettyprint-override"><code>readonly script_one_instance_lockfile="${HOME}/.PROGRAM/$(basename "${0}").lock" # this is long and not relevant to this question, it does as its name says # you can find a review on it here: https://codereview.stackexchange.com/q/204828/104270 print_error_and_exit() { ... } is_number() { [ "${1}" -eq "${1}" ] 2&gt; /dev/null } # purpose is clear, i.e. to clean up some temp, lock files # which were created during script execution and should not be left in place cleanup_on_exit() { [ -f "${script_one_instance_lockfile}" ] &amp;&amp; rm "${script_one_instance_lockfile}" } # this function is merely for future expansions of the script # it might very well be different from cleanup_on_exit cleanup_on_signal() { cleanup_on_exit } # here we define a generic function to handle signals # treat them as errors with appropriate messages # example calls: # kill -15 this_script_name # POSIX; all shells compatible # kill -TERM this_script_name # Bash and alike; newer shells signal_handler_generic() # expected arguments: # $1 = signal code { # check if exactly one argument has been passed [ "${#}" -eq 1 ] || print_error_and_exit "signal_handler_generic()" "Exactly one argument has not been passed!\\n\\tPassed: ${*}" # check if the argument is a number is_number "${1}" || print_error_and_exit "signal_handler_generic()" "The argument is not a number!\\n\\Signal code expected.\\n\\tPassed: ${1}" number_argument=${1} signal_code=${number_argument} case "${number_argument}" in 1 ) signal_human_friendly='HUP' ;; 2 ) signal_human_friendly='INT' ;; 3 ) signal_human_friendly='QUIT' ;; 6 ) signal_human_friendly='ABRT' ;; 15) signal_human_friendly='TERM' ;; * ) signal_human_friendly='' ;; esac if [ "${signal_human_friendly}" = "" ] then print_error_and_exit "signal_handler_generic()" "Given number code (${signal_code}) does not correspond to supported signal codes." else # tidy up any temp or lock files created along the way cleanup_on_signal # print human friendly and number signal code that has been caught print_error_and_exit "\\ntrap()" "Caught ${signal_human_friendly} termination signal ${signal_code}.\\n\\tClean-up finished. Exiting. Bye!" fi } # use the above function for signal handling; # note that the SIG* constants are undefined in POSIX, # and numbers are to be used for the signals instead trap 'signal_handler_generic 1' 1 trap 'signal_handler_generic 2' 2 trap 'signal_handler_generic 3' 3 trap 'signal_handler_generic 6' 6 trap 'signal_handler_generic 15' 15 # this is long and not relevant to this question, it does as its name says # you can find a review on it here: https://codereview.stackexchange.com/q/213156/104270 is_java_program_running() { ... } #################### ### MAIN PROGRAM ### #################### if [ -f "${script_one_instance_lockfile}" ] then # if one instance of this script is already running, quit to shell print_error_and_exit "\\nmain()" "One instance of this script should already be running.\\n\\tLock file: ${script_one_instance_lockfile}\\n\\tMore than one instance is not allowed. Exiting." else # create a .lock file for one instance handling touch "${script_one_instance_lockfile}" fi # keep the PROGRAM alive forever, check in 5 seconds interval while true do sleep 5s if ! is_java_program_running "${PROGRAM_java_process_identifier}" then my_date_time=$(date +%Y-%m-%d_%H:%M:%S) printf '%s %s\n' "${my_date_time}" "(re-)starting PROGRAM" ( /full/path/to/program &gt; /dev/null 2&gt;&amp;1 &amp; ) fi done # ordinary scripts don't have infinite loops # this code shall be unreachable, but it is good to have it here since I will be # copying / reusing the script and I would definitely forget on this cleanup_on_exit </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T11:19:31.770", "Id": "412472", "Score": "0", "body": "Have you actually found a Unix or `kill` that doesn't deal with signal names? [`man 7 signal`](http://man7.org/linux/man-pages/man7/signal.7.html) says that POSIX does define those names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-10T02:56:42.667", "Id": "425155", "Score": "0", "body": "@OhMyGoodness You are correct! Thanks." } ]
[ { "body": "<h3>Simplify with <code>case</code>, and eliminate a conditional</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>case \"${number_argument}\" in\n 1 ) signal_human_friendly='HUP' ;;\n 2 ) signal_human_friendly='INT' ;;\n 3 ) signal_human_friendly='QUIT' ;;\n 6 ) signal_human_friendly='ABRT' ;;\n 15) signal_human_friendly='TERM' ;;\n * ) signal_human_friendly='' ;;\nesac\n\nif [ \"${signal_human_friendly}\" = \"\" ]\nthen\n print_error_and_exit \"...\"\nelse\n # tidy up ...\nfi\n</code></pre>\n</blockquote>\n\n<p>I suggest to move the <code>print_error_and_exit</code> in the <code>case</code>,\nand then you can eliminate the conditional that follows,\nand \"flatten\" the code:</p>\n\n<pre><code>case \"${number_argument}\" in\n 1 ) signal_human_friendly='HUP' ;;\n 2 ) signal_human_friendly='INT' ;;\n 3 ) signal_human_friendly='QUIT' ;;\n 6 ) signal_human_friendly='ABRT' ;;\n 15) signal_human_friendly='TERM' ;;\n * ) print_error_and_exit \"...\" ;;\nesac\n\n# tidy up ...\n</code></pre>\n\n<h3>Eliminate a low-value conditional statement</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>[ -f \"${script_one_instance_lockfile}\" ] &amp;&amp; rm \"${script_one_instance_lockfile}\"\n</code></pre>\n</blockquote>\n\n<p>Why not simply:</p>\n\n<pre><code>rm -f \"${script_one_instance_lockfile}\"\n</code></pre>\n\n<h3>Sharpen error messages</h3>\n\n<p>Instead of \"Exactly one argument has not been passed! [...] Passed: ...\",</p>\n\n<p>I would write \"Expected one argument. Received: ...\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-25T18:52:06.230", "Id": "414324", "Score": "0", "body": "`rm -f` does produce an error message for `ENOENT`, so the test isn't *completely* useless." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-25T18:13:27.653", "Id": "214257", "ParentId": "213232", "Score": "2" } }, { "body": "<p>Scripts intended to be executable should have a shebang:</p>\n\n<pre><code>#!/bin/sh\n</code></pre>\n\n<p>The repetitive calls to <code>trap</code> could be replaced by a loop:</p>\n\n<pre><code>for i in 1 2 3 6 15\ndo trap \"signal_handler_generic $i\" $i\ndone\n</code></pre>\n\n<p>(Note: if using Shellcheck, you may need <code># shellcheck disable=SC2064</code>: we must not use single-quotes here, as it would make no sense to defer the expansion of <code>$i</code>).</p>\n\n<p>With some small changes, we could trap the signals by name (the names <em>are</em> specified in POSIX, contrary to the code comment), and not need the conversion from number in the handler.</p>\n\n<p>Consider letting <code>SIGHUP</code> mean \"reload configuration\" as is conventional in daemons.</p>\n\n<p>I think the name <code>script_one_instance_lockfile</code> is possibly over-long. As it's the only lock file we use, we could call it simply <code>lockfile</code> and get more of our lines down to a reasonable length.</p>\n\n<p>There's no need to capture the output of <code>date</code> if the only thing we do with it is to immediately print it:</p>\n\n<pre><code> date '+%Y-%m-%d_%H:%M:%S (re-)starting PROGRAM'\n</code></pre>\n\n<p>Use <code>test -e</code> (or <code>[ -e</code>) to test for existence, where the file type is irrelevant. Also consider using a pidfile, so that after unclean shutdown and recovery, invocation isn't inhibited. BTW, is it intentional that the lockfile is in (per-user) <code>$HOME</code>, rather than per-machine in some temporary filesystem (e.g. <code>/run</code> on Linux)?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-10T03:21:18.397", "Id": "425156", "Score": "0", "body": "Thank you Toby for clearing some of the things I was unsure of. I just had to add that comment." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-25T19:10:32.823", "Id": "214265", "ParentId": "213232", "Score": "2" } } ]
{ "AcceptedAnswerId": "214257", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T06:10:29.517", "Id": "213232", "Score": "2", "Tags": [ "error-handling", "sh", "posix" ], "Title": "Lock file and interrupt signals in POSIX shell script running indefinitely" }
213232
<p>I'm a newbie to Selenium and I'm trying to get better at it by taking up interview assignments. <a href="https://www.youtube.com/watch?v=0zfymwDR66E&amp;feature=youtu.be" rel="nofollow noreferrer">This YouTube link</a> describes the workflow that needs to be automated.</p> <p>The following points are worth taking into account.</p> <ol> <li><p>For your purpose, use your own gmail id/password but make it readable from a file in your project. </p></li> <li><p>Use the fashion photo pasted below as input.</p> <p><a href="https://i.stack.imgur.com/URuh4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/URuh4.jpg" alt="enter image description here"></a></p></li> </ol> <p>I implemented the following solution and I'd like to know if there's any way to improve it. I'm interested in any changes that can be made, to make the script more robust in addition to any new concepts or tools in Selenium or Python that might make life easier as well as existing concepts and tools that I could implement a whole lot better. </p> <pre><code>import time,os from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium import webdriver try: # STEP 1 - LOAD PAGE options = webdriver.ChromeOptions() options.add_argument("--start-maximized") chrome_browser = webdriver.Chrome(chrome_options=options) chrome_browser.get("https://huew.co") WebDriverWait(chrome_browser,10).until(EC.title_contains("Huew | Your Catalog of Shoppable Fashion Inspirations")) # STEP 2 - CLICK ON "YOU" you_button = chrome_browser.find_element_by_xpath('//div[@class="desktop-menu-icon-text" and text()="YOU"]') time.sleep(2) you_button.click() # STEP 3 - CLICK ON "LOGIN USING GOOGLE" google_login_button = chrome_browser.find_element_by_xpath('//img[@class="social-login-button" and @ng-click="login(\'google\')"]') google_login_button.click() # STEP 4 - READ USERNAME AND PASSWORD FOR THE GOOGLE ACCOUNT with open("credentials.txt", "r") as f: lines = f.readlines() for line in lines: username, password = line.split(":") # STEP 5 - SWITCH TO THE NEW WINDOW window_handles = chrome_browser.window_handles parent_handle = chrome_browser.current_window_handle for window_handle in window_handles: if window_handle != parent_handle: chrome_browser.switch_to.window(window_handle) break # STEP 6 - TYPE IN USERNAME AND PASSWORD input_field = WebDriverWait(chrome_browser, 5).until(EC.visibility_of_element_located((By.ID, "identifierId"))) input_field.send_keys(username) next_button = chrome_browser.find_element_by_xpath('//span[text()="Next"]') next_button.click() input_field = WebDriverWait(chrome_browser, 5).until(EC.visibility_of_element_located((By.NAME, "password"))) input_field.send_keys(password) next_button = chrome_browser.find_element_by_xpath('//span[text()="Next"]') next_button.click() time.sleep(5) # STEP 7 - SWITCH BACK TO THE OLD WINDOW AND CLICK "DISCOVER" chrome_browser.switch_to.window(parent_handle) discover_button = chrome_browser.find_element_by_xpath('//div[@class="desktop-menu-icon-text" and text()="DISCOVER"]') discover_button.click() # STEP 8 - UPLOAD THE PHOTO AND CLICK ON "SUBMIT" file_upload_panel = WebDriverWait(chrome_browser, 60).until(lambda chrome_browser: chrome_browser.find_element_by_xpath('//input[@type="file"]')) file_upload_panel.send_keys(os.getcwd()+"\\fashion_pic.jpg") submit_button = WebDriverWait(chrome_browser, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button.desktop-photo-submit.ng-scope"))) chrome_browser.execute_script('''document.querySelector('button.desktop-photo-submit.ng-scope').click()''') # STEP 9 - WAIT FOR THE "SAVE" BUTTON TO APPEAR AND CLICK ON IT save_button = WebDriverWait(chrome_browser, 60).until(EC.element_to_be_clickable((By.XPATH, '//button[text()="SAVE"]'))) save_button.click() time.sleep(5) # STEP 10 - CLICK ON "HERE" LINK here_link = chrome_browser.find_element_by_xpath('//a[text()="here"]') here_link.click() except ValueError: print("Please ensure that the input file has the username and password saved in the format specified in readme.txt") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:25:38.663", "Id": "412582", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T07:24:23.397", "Id": "213234", "Score": "1", "Tags": [ "python", "interview-questions", "selenium" ], "Title": "Automating A Workflow Using Selenium - Best Way To Fetch Elements & Make Code More Generic" }
213234
<p>I have taken your inputs on my <a href="https://codereview.stackexchange.com/questions/213027/clean-code-oop-on-monty-hall-simulation-implementation">original question</a> and formed a new implementation of the Monty Hall Simulation: </p> <p>Again keep an eye on <strong>CleanCode</strong> and <strong>OOP</strong></p> <p>The Price to be won:</p> <pre><code>enum Price { GOAT, CAR } </code></pre> <p>The Door keeping that price in secret</p> <pre><code>class Door { private final Price price; Door(Price price){ this.price = price; } Price getPrice() { return price; } } </code></pre> <p>the Player who participates in an Monty Hall Game</p> <pre><code>class Player { private final boolean preferresChange; private int winCounter; Player(boolean preferresChange){ this.preferresChange = preferresChange; } boolean preferresChange(){ return preferresChange; } void increaseWinCounter() { winCounter = winCounter + 1; } int getWinCounter(){ return winCounter; } } </code></pre> <p>the MontyHall in which the player takes action</p> <pre><code>class MontyHall { private final List&lt;Door&gt; doors; private Door selected; private Door openOne; private final Random random; private final int amountOfDoors; MontyHall(int seed, int amount) { random = new Random(seed); amountOfDoors = amount; doors = IntStream.range(0, amountOfDoors). mapToObj(e -&gt; new Door(Price.GOAT)). collect(Collectors.toList()); doors.set(random.nextInt(amountOfDoors), new Door(Price.CAR)); } void chooseDoor(){ selected = doors.get(random.nextInt(amountOfDoors)); } void openDoor(){ openOne = doors.stream(). filter(d -&gt; !d.equals(selected) &amp;&amp; Price.GOAT == d.getPrice()). collect(Collectors.toList()). get(0); } void changeDoor(){ selected = doors.stream(). filter(d -&gt; !d.equals(openOne) &amp;&amp; !d.equals(selected)). collect(Collectors.toList()). get(0); } Price getPrice(){ return selected.getPrice(); } } </code></pre> <p>and the simulator who hosts the games</p> <pre><code>class Simulator { public static void main(String[] args) { Simulator simulator = new Simulator(); simulator.simulate(10000, 3); } private void simulate(int iterations, int amountDoors) { Player changer = new Player(true); Player stayer = new Player(false); Random random = new Random(); for (int i = 0; i &lt; iterations; i ++){ int seed = random.nextInt(); playOneRound(changer, seed, amountDoors); playOneRound(stayer, seed, amountDoors); } System.out.println("changer: "+changer.getWinCounter()); System.out.println("stayer : "+stayer.getWinCounter()); } private void playOneRound(Player player, int seed, int amountDoors) { playOneRound(player, new MontyHall(seed, amountDoors)); } private void playOneRound(Player player, MontyHall montyHall) { montyHall.chooseDoor(); montyHall.openDoor(); if (player.preferresChange()){ montyHall.changeDoor(); } if (Price.CAR == montyHall.getPrice()){ player.increaseWinCounter(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T11:02:04.167", "Id": "412468", "Score": "0", "body": "damn i missed that **Flag-part** totally :-/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T11:03:34.937", "Id": "412469", "Score": "1", "body": "When you change the `3` into a `10`, the probabilities don't change much. But they should. The changer should now have a winning probability of 90%." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T11:12:45.250", "Id": "412470", "Score": "0", "body": "@RolandIllig i didn't undertand the problem fully, monty removes not `n-2 doors` in my simulation but always `1 door ` - this leads to a different behaviour... maybe we'll skipt that part and have a closer look at OOP and CleanCode (i'll add a proper implementation soon, where that flaw would be fixed)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T11:14:25.627", "Id": "412471", "Score": "0", "body": "@RolandIllig it should be named then `opendDoors()` - note the plural s ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:20:49.827", "Id": "412580", "Score": "0", "body": "Just nitpicking so I won't make this an answer, but you mean Prize, not Price. Both are valid English but they don't mean the same thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:25:09.403", "Id": "412581", "Score": "1", "body": "@Theoriok Thank you for pointing that out - one important thing in SW-Development is **to name things properly!** (i'm from Germany - bit still no excuse ^^)" } ]
[ { "body": "<h1>Positive Feedback</h1>\n\n<p>I liked how you follow the rules of <em>Clean Code</em>, that you write small methods and small classes and give all readable names!</p>\n\n<p>You've introduced your own data types that make the code more readable. The MontyHall-Algorithm can now be read like a poem:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>montyHall.chooseDoor();\nmontyHall.openDoor();\nif (player.preferresChange()){\n montyHall.changeDoor();\n}\nif (Price.CAR == montyHall.getPrice()){\n player.increaseWinCounter();\n}\n</code></pre>\n\n<p>And all your methods have only one intention level what makes them so easy to understand.</p>\n\n<h1>Some Criticism</h1>\n\n<h2>Class Names Refer to Unexpected Behavior</h2>\n\n<p>I read on <a href=\"https://en.wikipedia.org/wiki/Monty_Hall_problem\" rel=\"nofollow noreferrer\">Wikipedia</a>: </p>\n\n<blockquote>\n <p>You [the player] pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3</p>\n</blockquote>\n\n<p>After I read your code I was a little bit confused at some places. But not because of the quality of your code, which is for me very high, but because of the quote above.</p>\n\n<p>In your game the <code>Player</code> can't pick a <code>Door</code>. Instead the <code>Player</code> gets picked a door by <code>MontyHall</code>: (<code>montyHall.chooseDoor()</code>).</p>\n\n<p>Additional to that the <code>Player</code> has a <code>winCounter</code>, but actually the <code>Simulation</code> should track how often a <code>Player</code> wins the <code>MontyHall</code>.</p>\n\n<h2>No Outcome</h2>\n\n<p>What would you expect your <code>main</code> to do without any knowledge about our code base?</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Simulator simulator = new Simulator();\n simulator.simulate(10000, 3);\n}\n</code></pre>\n\n<p>It could run something like a game loop or start a GUI to interact with but instead it writes data to the console.</p>\n\n<p>Much cleaner would be:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Simulator simulator = new Simulator();\n simulator.printSimulations(10000, 3);\n}\n</code></pre>\n\n<p>But now imagine you want to compare a \"Changer\" and a \"Stayer\". <strong>You can't do it</strong> because you have <em>no outcome</em>! You through your outcome away by printing it to the console instead of storing and returning it.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Simulator simulator = new Simulator();\n SimulationResult result = simulator.simulate(10000, 3);\n int average = result.calculateAverageOfStayer();\n System.out.println(average);\n}\n</code></pre>\n\n<h2><a href=\"https://refactoring.guru/smells/feature-envy\" rel=\"nofollow noreferrer\">Feature Envy</a></h2>\n\n<blockquote>\n <p>A method accesses the data of another object more than its own data.</p>\n</blockquote>\n\n<p>The method <code>playOneRound</code> in <code>playOneRound</code> is in my eyes a <em>feature envy</em>. All the tasks should be done by <code>MontyHall</code>. So the method <code>playOneRound</code> should look like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void playOneRound(Player player, MontyHall montyHall) {\n montyHall.playGameWith(player);\n}\n</code></pre>\n\n<h1>Use Methods instead of Getters and Operations</h1>\n\n<p>In your code I can find code structure like <code>x.getValue == something</code>, but much better to read would be <code>x.isSomething()</code></p>\n\n<p>Some inspiration for you:</p>\n\n<p><code>Price.GOAT == d.getPrice()</code> means <code>door.isHidingGoat()</code></p>\n\n<p><code>Price.CAR == montyHall.getPrice()</code> means <code>montyHall.isWon()</code></p>\n\n<p><code>!d.equals(selected)</code> means <code>door.notEquals(selected)</code></p>\n\n<hr>\n\n<p>In your older post <a href=\"https://codereview.stackexchange.com/users/31562/simon-forsberg\">@Simon Forsberg</a> mentioned:</p>\n\n<blockquote>\n <p>I have a feeling that using a class for <code>StraightPlayer</code>, <code>ChangePlayer</code> and <code>ShowMaster</code> will be a bit overkill. </p>\n</blockquote>\n\n<p>I know you still have the <a href=\"https://www.martinfowler.com/bliki/FlagArgument.html\" rel=\"nofollow noreferrer\">flag argument</a> in <code>Player</code>. But that's fine. In general, refactoring can be an overkill at all. And you can see that for this little problem you can divide the logic into so many different classes and methods. When you write code, you have to find a balance between all OOP/clean code and your task.</p>\n\n<p>Thanks for this cool problem and that you let me review it. I learned a lot while read your code :] </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T06:40:02.207", "Id": "412563", "Score": "0", "body": "even though i thought this implementation is now much better (ok, it **IS** much better) you still found so many issues - and i am very glad to learn from such an advanced code reviewer! your Answer helped really a lot!! thanks for your input and your kindness!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T06:41:25.463", "Id": "412565", "Score": "0", "body": "i don't think there will be a further follow up question, if i would implement those features from your answer the code would be fine then! thanks again!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T12:46:16.110", "Id": "213240", "ParentId": "213236", "Score": "5" } }, { "body": "<blockquote>\n<pre><code>enum Price {\n</code></pre>\n</blockquote>\n\n<p>Is this what you meant? Why is it a price? Price for what? This would make much more sense if it were a prize. </p>\n\n<blockquote>\n<pre><code> montyHall.chooseDoor();\n montyHall.openDoor();\n if (player.preferresChange()){\n montyHall.changeDoor();\n }\n</code></pre>\n</blockquote>\n\n<p>This seems incorrect. Monty doesn't choose the door; the player does. Monty opens the door. The player chooses and potentially changes that choice. And <code>preferresChange</code> is misspelled. It should be <code>prefersChange</code>. </p>\n\n<p>In the simulation, <strong>Let's Make a Deal</strong> is the name of the show. Monty Hall is the host. So the class that you are calling <code>MontyHall</code> should be named <code>LetsMakeADeal</code> or simply <code>GameShow</code>. </p>\n\n<p>You are hard coding some things. For example, your simulation is the classic Marilyn vos Savant one where Monty always opens a door and never opens the door with a car. That is a strategy. You should probably code that as a particular implementation. There are other possible strategies that will produce different results. For example, what if Monty only ever offers the choice when the player has selected the door with the car behind it? What if Monty can open the door and display the car? These strategies will change the results. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T05:21:20.863", "Id": "412703", "Score": "0", "body": "you are very right, i had a lot olf probolems with the translation as you can see... i thought 'MontyHall`is the game! Now i learned from you the game is called `Let's make a Deal` that makes the whole simulator kind of awkward." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T05:24:11.350", "Id": "412704", "Score": "0", "body": "on the issue with having no proper interception between player and door - i was aware of that but i'm still struggling with it. I can clearly see your point and Roman (see answer above) pointed that issue out as well... i still don't know how to improve the code. can you give me a direction into how one could do it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T05:26:46.217", "Id": "412705", "Score": "0", "body": "As mentioned as comment on my question from Theoriok, **it is priZe not PriCe** again my english language skill played a trick on me." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T16:38:18.860", "Id": "213316", "ParentId": "213236", "Score": "2" } } ]
{ "AcceptedAnswerId": "213240", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T09:03:07.600", "Id": "213236", "Score": "4", "Tags": [ "java", "object-oriented", "simulation" ], "Title": "Follow up Implementation on Monty Hall Simulation" }
213236
<p>(The next iteration: <a href="https://codereview.stackexchange.com/questions/213297/a-simple-java-class-for-implementing-code-stop-watches-follow-up">A simple Java class for implementing code stop watches - follow-up</a>)</p> <p>Here is my attempt at more convenient benchmarking (yes, this time I am aware of JVM warmup, etc.), and it looks like this:</p> <pre><code>package net.coderodde.stopwatch; public final class StopWatch { private long earliestMillis = Long.MAX_VALUE; public StopWatch() { this(System.currentTimeMillis()); } public StopWatch(long earliestMillis) { this.earliestMillis = earliestMillis; } public void push(long earliestMillis) { if (earliestMillis &lt; this.earliestMillis) { throw new IllegalArgumentException("Cannot go back in time."); } this.earliestMillis = earliestMillis; } public long pop() { return System.currentTimeMillis() - earliestMillis; } public long popAndPush() { long ret = pop(); this.earliestMillis = System.currentTimeMillis(); return ret; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("(") .append(System.currentTimeMillis() - earliestMillis) .append(" starting from ") .append(earliestMillis) .append(" ms -&gt; ") .append(System.currentTimeMillis()) .append(")"); return stringBuilder.toString(); } public static void main(String[] args) throws InterruptedException { StopWatch sw = new StopWatch(); Thread.sleep(3_000L); System.out.println(sw.pop()); System.out.println(sw); Thread.sleep(2_000L); System.out.println(sw.pop()); sw.popAndPush(); Thread.sleep(1_230L); System.out.println(sw); } } </code></pre> <p>Is there more reasonable/extensive approach to this? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T14:48:49.617", "Id": "412485", "Score": "4", "body": "`pop` and `push` are really strange names for resetting and reading a stopwatch as those names imply a stack-like structure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T16:29:15.527", "Id": "412502", "Score": "1", "body": "Additional gripe: `push()` and `popAndPush()` are asymmetrical. The former takes an argument to be pushed, but latter doesn't take any argument." } ]
[ { "body": "<pre><code>public final class StopWatch {\n\n private long earliestMillis = Long.MAX_VALUE;\n</code></pre>\n\n<p>There is no reason to initialize this field at this point. Both constructors will overwrite it immediately.</p>\n\n<pre><code> public StopWatch() {\n this(System.currentTimeMillis());\n } \n\n public StopWatch(long earliestMillis) {\n this.earliestMillis = earliestMillis;\n }\n</code></pre>\n\n<p>There should be no reason for the user to provide their own initial start time. The only reason could be to use an entirely different clock for testing this code. For that case, you should use a <a href=\"https://www.joda.org/joda-time/apidocs/org/joda/time/DateTimeUtils.MillisProvider.html\" rel=\"noreferrer\"><code>MillisProvider</code></a> instead of calling <code>System.currentTimeMillis</code> directly. As of now, you have a wild mixture of calling <code>currentTimeMillis</code> and accepting caller-provided timestamps, which can easily lead to confusion.</p>\n\n<pre><code> public void push(long earliestMillis) {\n</code></pre>\n\n<p>Again, I don't see any reason not to hard-code <code>System.currentTimeMillis</code> here.</p>\n\n<pre><code> if (earliestMillis &lt; this.earliestMillis) {\n throw new IllegalArgumentException(\"Cannot go back in time.\");\n }\n</code></pre>\n\n<p>When you measure code for performance, you usually don't expect additional exceptions to be thrown. Changing the system clock backwards should not happen anyway, but still this code should deal a little softer with this situation by just ignoring it.</p>\n\n<pre><code> this.earliestMillis = earliestMillis;\n }\n\n public long pop() {\n return System.currentTimeMillis() - earliestMillis;\n }\n\n public long popAndPush() {\n long ret = pop();\n this.earliestMillis = System.currentTimeMillis();\n return ret;\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"(\")\n .append(System.currentTimeMillis() - earliestMillis)\n .append(\" starting from \")\n .append(earliestMillis)\n .append(\" ms -&gt; \")\n .append(System.currentTimeMillis())\n .append(\")\");\n\n return stringBuilder.toString();\n }\n</code></pre>\n\n<p>Using a <code>StringBuilder</code> here is unnecessary. It is only needed if you have some parts that are added conditionally to the string. Just use plain string concatenation, which is far easier to read. Alternatively, since the <code>toString</code> method is probably not called in the performance-critial part, it's probably ok to use <code>String.format</code> here, to separate the general format of the message from the parameters.</p>\n\n<p>Oh, I just saw that <code>toString</code> calls <code>currentTimeMillis</code>. That's wrong. It's even wronger to call it twice in a row (and expecting both calls to return the same timestamp). Measuring the time should be as fast and light-weight as possible. Building a nice presentation out of the raw measurement values should be clearly separated from the measurement.</p>\n\n<p>To increase the precision of the measurement, you should determine how long it takes to call <code>currentTimeMillis</code> and subtract that from the reported durations.</p>\n\n<pre><code> public static void main(String[] args) throws InterruptedException {\n StopWatch sw = new StopWatch();\n\n Thread.sleep(3_000L);\n System.out.println(sw.pop());\n System.out.println(sw);\n\n Thread.sleep(2_000L);\n System.out.println(sw.pop());\n\n sw.popAndPush();\n Thread.sleep(1_230L);\n System.out.println(sw);\n }\n}\n</code></pre>\n\n<p>As danielspaniol already said in a comment, having a stopwatch with buttons labelled \"push\" and \"pop\" feels strange. Looking at <a href=\"https://en.wikipedia.org/wiki/Stopwatch\" rel=\"noreferrer\">Wikipedia</a>, the second image, your methods should rather be called <code>start</code>, <code>stop</code>, <code>reset</code>, <code>lap</code>, <code>split</code>, <code>recall</code>, <code>pause</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T15:28:06.600", "Id": "213249", "ParentId": "213244", "Score": "5" } } ]
{ "AcceptedAnswerId": "213249", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T14:06:52.593", "Id": "213244", "Score": "1", "Tags": [ "java", "timer", "benchmarking" ], "Title": "A simple Java class for implementing code stop watches" }
213244
<h1>Preface</h1> <p>I'm using <a href="https://www.wireguard.com/" rel="nofollow noreferrer">WireGuard</a> as a VPN solution to connect a remote client permanently to my home server. Unfortunately due to Consumer DSL-related IP address changes, the client loses the connection to the server.<br> Because of its philosophy of simplicity, re-resolution of the server's (DynDNS) hostname is out of scope for WireGuard itself.<br> The official package <code>wireguard-tools</code> contains amongst other stuff, a script <a href="https://github.com/WireGuard/WireGuard/blob/master/contrib/examples/reresolve-dns/reresolve-dns.sh" rel="nofollow noreferrer"><code>reresolve-dns.sh</code></a> which I modeled <a href="https://github.com/conqp/dynwg" rel="nofollow noreferrer">my Python solution</a> upon.</p> <h1>Purpose</h1> <p>The script below is the main part of a watchdog, that iterates over <code>*.netdev</code> and <code>*.network</code> systemd-networkd configuration file pairs that are WireGuard interface configurations.<br> The script performs two tests:</p> <ol> <li>Did the remote server IP change?</li> <li>Is the remote server not reachable over the WireGuard interface?</li> </ol> <p>If at least one is true, it will attempt to recover the WireGuard connection using <code>wg</code>.</p> <pre><code>#! /usr/bin/env python3 """WireGuard over systemd-networkd DynDNS watchdog daemon.""" from configparser import ConfigParser from contextlib import suppress from json import dump, load from pathlib import Path from socket import gaierror, gethostbyname from subprocess import DEVNULL, CalledProcessError, check_call from sys import stderr CACHE = Path('/var/cache/dynwg.json') SYSTEMD_NETWORK = Path('/etc/systemd/network') NETDEVS = SYSTEMD_NETWORK.glob('*.netdev') PING = '/usr/bin/ping' WG = '/usr/bin/wg' def error(*msg): """Prints an error message.""" print(*msg, file=stderr, flush=True) def is_wg_client(netdev): """Checks whether the netdev is a WireGuard client interface.""" try: _ = netdev['WireGuardPeer']['Endpoint'] # Check if endpoint is set. return netdev['NetDev']['Kind'] == 'wireguard' except KeyError: return False def configurations(): """Yields the available configurations.""" for path in NETDEVS: netdev = ConfigParser(strict=False) netdev.read(path) if is_wg_client(netdev): name = path.stem path = path.parent.joinpath(f'{name}.network') network = ConfigParser(strict=False) network.read(path) yield (name, netdev, network) def ip_changed(host, cache): """Determines whether the IP address of the specified host has changed. """ try: current_ip = gethostbyname(host) except gaierror: error(f'Cannot resolve host: "{host}".') cache.delete(host) return False cached_ip = cache.get(host) cache[host] = current_ip if cached_ip is None: return False print(f'Host "{host}":', cached_ip, '→', current_ip, flush=True) return cached_ip != current_ip def gateway_unreachable(network): """Pings the respective gateway to check if it is unreachable.""" try: gateway = network['Route']['Gateway'] except KeyError: error('No gateway specified, cannot ping. Assuming not reachable.') return True command = (PING, '-c', '3', '-W', '3', gateway) try: check_call(command, stdout=DEVNULL, stderr=DEVNULL) except CalledProcessError: print(f'Gateway "{gateway}" is not reachable.', flush=True) return True return False def reset(netdev, current_ip): """Resets the respective interface.""" try: interface = netdev['NetDev']['Name'] except KeyError: error('NetDev→Name not specified. Cannot reset interface.') return False try: pubkey = netdev['WireGuardPeer']['PublicKey'] except KeyError: error('WireGuardPeer→PublicKey not specified. Cannot reset interface.') return False command = (WG, 'set', interface, 'peer', pubkey, 'endpoint', current_ip) try: check_call(command) except CalledProcessError: error('Resetting of interface failed.') return False return True def check(netdev, network, cache): """Checks the respective *.netdev config.""" try: endpoint = netdev['WireGuardPeer']['Endpoint'] except KeyError: error('WireGuardPeer→Endpoint not specified. Cannot check host.') return False host, *_ = endpoint.split(':') # Discard port. if ip_changed(host, cache) or gateway_unreachable(network): try: current_ip = cache[host] except KeyError: error('Current IP unknown. Cannot reset interface.') return False return reset(netdev, current_ip) return True def main(): """Daemon's main loop.""" with Cache(CACHE) as cache: for name, netdev, network in configurations(): print(f'Checking: {name}.', flush=True) check(netdev, network, cache) class Cache(dict): """Host name → IP address cache.""" def __new__(cls, _): return super().__new__(cls) def __init__(self, path): super().__init__() self.path = path self._dirty = False def __setitem__(self, key, value): self.dirty = self.get(key) != value return super().__setitem__(key, value) def __enter__(self): self.load() return self def __exit__(self, *_): self.dump() @property def dirty(self): """Determines whether the cache is considered dirty.""" return self._dirty @dirty.setter def dirty(self, dirty): """Sets whether the cache is dirty.""" self._dirty = self._dirty or dirty def delete(self, key): """Deletes the respective key.""" with suppress(KeyError): del self[key] self.dirty = True def load(self): """Loads the cache.""" try: with self.path.open('r') as file: self.update(load(file)) except FileNotFoundError: self.dirty = True # Ensure initial file creation. def dump(self, force=False): """Dumps the cache.""" if self.dirty or force: with self.path.open('w') as file: dump(self, file, indent=2) if __name__ == '__main__': main() </code></pre> <p>Any suggestions for improvement are welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T16:37:58.693", "Id": "213252", "Score": "4", "Tags": [ "python", "python-3.x", "networking" ], "Title": "dynwg: A DynDNS watchdog for WireGuard via systemd-networkd" }
213252
<p>I'm fairly new to coding and I wrote this script in Python for a house with a roof in Minecraft Pi. I've found different ways to write the coordinates to make the code base shorter, but I'm wondering if it is possible for me to refactor it any further so I don't have to list each coordinate line by line. </p> <pre><code>import mcpi.minecraft as minecraft import mcpi.block as block mc = minecraft.Minecraft.create() p = mc.player.getTilePos() mc.setBlocks(p.x+1, p.y, p.z+1, #Main structure starting coordinates (DO NOT ALTER) p.x+19, p.y+4, p.z+6, #Structure size/coordinates (Alters cube size) block.STONE_BRICK) mc.setBlocks(p.x+2, p.y+1, p.z+2, #Hollowing out main structure interior p.x+18, p.y+3, p.z+5, block.AIR) mc.setBlocks(p.x, p.y+4, p.z, #Main Structure Roof (Front Side, 1st Row) p.x+12, p.y+4, p.z, block.STAIRS_WOOD.id, 2) mc.setBlocks(p.x+20, p.y+4, p.z, p.x+20, p.y+4, p.z, block.STAIRS_WOOD.id, 2) mc.setBlocks(p.x, p.y+5, p.z+1, #Main Structure Roof (Front Side, 2nd Row) p.x+13, p.y+5, p.z+1, block.STAIRS_WOOD.id, 2) mc.setBlocks(p.x+19, p.y+5, p.z+1, p.x+20, p.y+5, p.z+1, block.STAIRS_WOOD.id, 2) mc.setBlocks(p.x, p.y+6, p.z+2, #Main Structure Roof (Front Side, 3rd Row) p.x+14, p.y+6, p.z+2, block.STAIRS_WOOD.id, 2) mc.setBlocks(p.x+18, p.y+6, p.z+2, p.x+20, p.y+6, p.z+2, block.STAIRS_WOOD.id, 2) mc.setBlocks(p.x, p.y+7, p.z+3, #Main Structure Roof (Front Side, 4th Row) p.x+20, p.y+7, p.z+3, block.STAIRS_WOOD.id, 2) mc.setBlocks(p.x, p.y+4, p.z+7, #Main Structure Roof (Rear Side, 1st Row) p.x+20, p.y+4, p.z+7, block.STAIRS_WOOD.id, 3) mc.setBlocks(p.x, p.y+5, p.z+6, #Main Structure Roof (Rear Side, 2nd Row) p.x+20, p.y+5, p.z+6, block.STAIRS_WOOD.id, 3) mc.setBlocks(p.x, p.y+6, p.z+5, #Main Structure Roof (Rear Side, 3rd Row) p.x+20, p.y+6, p.z+5, block.STAIRS_WOOD.id, 3) mc.setBlocks(p.x, p.y+7, p.z+4, #Main Structure Roof (Rear Side, 4th Row) p.x+20, p.y+7, p.z+4, block.STAIRS_WOOD.id, 3) mc.setBlocks(p.x+1, p.y+5, p.z+2, #Main Structure Roof End (Right Side, 1st Row) p.x+1, p.y+5, p.z+5, block.STONE_BRICK) mc.setBlocks(p.x+1, p.y+6, p.z+3, #Main Structure Roof End (Right Side, 2nd Row) p.x+1, p.y+6, p.z+4, block.STONE_BRICK) mc.setBlocks(p.x+19, p.y+5, p.z+2, #Main Structure Roof End (Left Side, 1st Row) p.x+19, p.y+5, p.z+5, block.STONE_BRICK) mc.setBlocks(p.x+19, p.y+6, p.z+3, #Main Structure Roof End (Left Side, 2nd Row) p.x+19, p.y+6, p.z+4, block.STONE_BRICK) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:45:26.913", "Id": "412692", "Score": "0", "body": "You could also introduce functions to do lines and squares instead of just doing volumes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T18:03:21.707", "Id": "413169", "Score": "0", "body": "That's what I was wondering about, but not sure how to pull off. Would I need to have a function for each part of whatever I am building?" } ]
[ { "body": "<p>You can put the different parts of the building in a list and then iterate through this list, using the values in the list.</p>\n\n<p>I would propose this structure:</p>\n\n<pre><code>parts = [\n # x0 y0 z0 x1 y1 z1 block id meta data \n (( 1, 0, 1), (19, 4, 19), (block.STONE_BRICK, 0)), # Main structure\n (( 2, 1, 2), (18, 3, 5), (block.AIR , 0)), # Hollowing out main structure interior\n # ... the other parts\n]\n</code></pre>\n\n<p>You can then use this loop to build the parts:</p>\n\n<pre><code>for (x0, y0, z0), (x1, y1, z1), (block, meta) in parts:\n mc.setBlocks(p.x + x0, p.y + y0, p.z + z0,\n p.x + x1, p.y + y1, p.z + z1,\n block, meta)\n</code></pre>\n\n<p>I would also advice you to follow a few style suggestions from <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, in this case I specifically mean that you should add empty lines after the imports:</p>\n\n<pre><code>import mcpi.minecraft as minecraft\nimport mcpi.block as block\n\nmc = minecraft.Minecraft.create()\np = mc.player.getTilePos()\n</code></pre>\n\n<p>and that you should always add spaces around operators and after <code>#</code>:</p>\n\n<pre><code>mc.setBlocks(p.x+1, p.y, p.z+1 #...\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>mc.setBlocks(p.x + 1, p.y, p.z + 1 # ...\n</code></pre>\n\n<p>This simply eases the reading process.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T22:37:29.787", "Id": "213274", "ParentId": "213253", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T16:46:22.070", "Id": "213253", "Score": "2", "Tags": [ "python", "raspberry-pi", "minecraft" ], "Title": "Refactoring coordinates for Minecraft Pi buildings written in Python" }
213253
<p>For a personal project that I've recently started I have to analyze the rotation of two shapes with sets of spokes, where the spokes are evenly-spaced, and split into a given number.</p> <p>That is, if I have a shape with <code>x</code> evenly-spaced spokes, and a shape with <code>y</code> evenly-spaced spokes, I need to analyze two major properties:</p> <ol> <li><p><strong>What is the "Phase Difference"?</strong> That is, if one shape were rotating, how many degrees would it need to rotate before <em>any</em> spoke overlaps the other shape?</p></li> <li><p><strong>What is the number of overlaps in a single 360° rotation?</strong> That is, if one shape were rotating, how many times would <em>any</em> spoke overlap the other shape?</p></li> </ol> <p>To start with, I'll provide the type of output this program produces. This is an animation of how one shape with 8 spokes and one shape with 9 spokes would overlap.</p> <p><a href="https://i.stack.imgur.com/Ajelx.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ajelx.gif" alt="A rotational diagram"></a></p> <p>Each frame in the GIF is a single overlap. For this one, there are 72 such overlaps.</p> <p>Next, we look at the console output (for this exact set):</p> <blockquote> <pre><code>Shape 1 Angle (8 spokes): 45.000000° / 0.785398 rads Shape 2 Angle (9 spokes): 40.000000° / 0.698132 rads Phase Difference: 5.000000° / 0.087266 rads (0.013889 rotations) Overlaps per Rotation: 72.000000 </code></pre> </blockquote> <p>We note that the console tells us the difference in "Phase" (that is: how far must it rotate to overlap?) is 5°, and the number of overlaps is 72. This means the shapes would overlap 72 times in a given rotation, were either of them spinning.</p> <p>All this stuff happens in three locations:</p> <p><code>Graphics.fs</code> which just helps us draw points and lines from an "origin" properly:</p> <pre><code>module Spoke_Analyzer.Graphics open System.Drawing let drawLine (origin : Point) (g : Graphics) (pen : Pen) (start : Point, stop : Point) = g.DrawLine(pen, Point(start.X + origin.X, start.Y + origin.Y), Point(stop.X + origin.X, stop.Y + origin.Y)) let drawPoint (origin : Point) (g : Graphics) (brush : Brush) (start : Point) width = g.FillEllipse(brush, Rectangle(start.X + origin.X - (width / 2), start.Y + origin.Y - (width / 2), width, width)) </code></pre> <p><code>Input.fs</code> which helps us consume CLI input:</p> <pre><code>module Spoke_Analyzer.Input open System let rec getInput convert validate prompt = printf "%s" prompt let input = () |&gt; Console.ReadLine if input |&gt; validate then input |&gt; convert else printfn "Invalid, please try again." getInput convert validate prompt let getInputInt = getInput Int32.Parse (Int32.TryParse &gt;&gt; function | true, f when f &gt; 0 -&gt; true | _ -&gt; false) let getInputIntOption = getInput (function | "" -&gt; None | s -&gt; s |&gt; Int32.Parse |&gt; Some) (function | "" -&gt; true | s -&gt; s |&gt; Int32.TryParse |&gt; function | true, f when f &gt; 0 -&gt; true | _ -&gt; false) let getInputDoubleOption = getInput (function | "" -&gt; None | s -&gt; s |&gt; Double.Parse |&gt; Some) (function | "" -&gt; true | s -&gt; s |&gt; Double.TryParse |&gt; function | true, f when f &gt;= 0. &amp;&amp; f &lt;= 1. -&gt; true | _ -&gt; false) let getInputDouble = getInput Double.Parse (Double.TryParse &gt;&gt; function | true, f when f &gt;= 0. &amp;&amp; f &lt;= 1. -&gt; true | _ -&gt; false) let getInputFileOption (file : string) = getInput (function | "" -&gt; None | s -&gt; Some s) (function | "" -&gt; true | s -&gt; if Uri.IsWellFormedUriString(sprintf "file:///%s" (s.Replace('\\', '/')), UriKind.RelativeOrAbsolute) then let test = if s.EndsWith(file) = false &amp;&amp; s.EndsWith(sprintf "%s.exe" file) = false then let t = System.IO.Path.Combine(s, file) if System.IO.File.Exists(t) then t else System.IO.Path.Combine(s, sprintf "%s.exe" file) else s if System.IO.File.Exists(test) then true else false else false) </code></pre> <p>And finally, the raw <code>Program.fs</code>:</p> <pre><code>open System open System.Drawing open Spoke_Analyzer let inline degToRad deg = deg * Math.PI / 180. let inline radToDeg rad = rad * 180. / Math.PI [&lt;Literal&gt;] let FULL_CIRCLE = 360. [&lt;Literal&gt;] let ROTATION_OFFSET = -90. // -FULL_CIRCLE / 4. [&lt;Literal&gt;] let IMAGE_DIR = "temp/images" [&lt;EntryPoint&gt;] let main argv = let imageWidth = Input.getInputIntOption "Enter the image dimension (whole number &gt; 0) [160]: " |&gt; Option.defaultValue 160 let spoke1 = Input.getInputInt "Enter the number of spokes for shape 1 (whole number &gt; 0): " let spoke2 = Input.getInputInt "Enter the number of spokes for shape 2 (whole number &gt; 0): " let offset = Input.getInputDoubleOption "Enter the radial offset in percentage (0.0 - 1.0) [0]: " |&gt; Option.defaultValue 0. let ffmpeg = Input.getInputFileOption "ffmpeg" "Enter the location of ffmpeg (if available) []: " let fps = ffmpeg |&gt; Option.bind (fun s -&gt; Input.getInputIntOption "Enter the fps of the output (whole number &gt; 0) [24]: ") |&gt; Option.defaultValue 24 let angleDegrees1 = FULL_CIRCLE / (spoke1 |&gt; float) let angleDegrees2 = FULL_CIRCLE / (spoke2 |&gt; float) printfn "" let rec getRotation small large = if small &gt; large then getRotation large small else if small = large then small elif large = FULL_CIRCLE then small else let v1 = large / small let divisions = v1 |&gt; int |&gt; float let v2 = min (large - small) (large - small * divisions) let v1 = FULL_CIRCLE / v1 min v1 v2 let rotation = getRotation angleDegrees1 angleDegrees2 let rotations = FULL_CIRCLE / rotation let rec drawSaveImage i = use bmp = new Bitmap(imageWidth, imageWidth) do use g = bmp |&gt; Graphics.FromImage g.SmoothingMode &lt;- Drawing2D.SmoothingMode.AntiAlias use fillBrush = new SolidBrush(Color.FromArgb(255, 32, 32, 32)) g.FillRectangle(fillBrush, Rectangle(0, 0, bmp.Width, bmp.Height)) let origin = Point(bmp.Width / 2, bmp.Height / 2) use pen1 = new Pen(Color.FromArgb(255, 224, 32, 32), 2.5f) use brush1 = new SolidBrush(Color.FromArgb(255, 224, 32, 32)) let drawLine1 = Spoke_Analyzer.Graphics.drawLine origin g pen1 use pen2 = new Pen(Color.FromArgb(255, 32, 224, 32), 1.5f) use brush2 = new SolidBrush(Color.FromArgb(255, 32, 224, 32)) let drawLine2 = Spoke_Analyzer.Graphics.drawLine origin g pen2 let drawPoint = Spoke_Analyzer.Graphics.drawPoint origin g let distance = (imageWidth / 2) |&gt; float let rec drawSpoke drawLine distance offset angle max num = if num = max then () else drawLine (Point(0, 0), Point((distance * ((angle * (num |&gt; float) + offset) |&gt; degToRad |&gt; cos)) |&gt; int, (distance * ((angle * (num |&gt; float) + offset) |&gt; degToRad |&gt; sin)) |&gt; int)) drawSpoke drawLine distance offset angle max (num + 1) drawSpoke drawLine1 distance ROTATION_OFFSET angleDegrees1 spoke1 0 drawSpoke drawLine2 distance (angleDegrees2 * offset + ROTATION_OFFSET + rotation * (i |&gt; float)) angleDegrees2 spoke2 0 drawPoint brush1 (Point(0, -distance |&gt; int)) 8 drawPoint brush2 (Point((distance * ((rotation * (i |&gt; float) + ROTATION_OFFSET) |&gt; degToRad |&gt; cos)) |&gt; int, (distance * ((rotation * (i |&gt; float) + ROTATION_OFFSET) |&gt; degToRad |&gt; sin)) |&gt; int)) 6 () bmp.Save(sprintf "%s/rot_%i.png" IMAGE_DIR i, Imaging.ImageFormat.Png) if Double.IsInfinity(rotations) |&gt; not &amp;&amp; (i |&gt; float) + 1. &lt; rotations then drawSaveImage (i + 1) () if IMAGE_DIR |&gt; System.IO.Directory.Exists |&gt; not then IMAGE_DIR|&gt; System.IO.Directory.CreateDirectory |&gt; ignore IMAGE_DIR |&gt; System.IO.Directory.GetFiles |&gt; Array.iter System.IO.File.Delete drawSaveImage 0 printfn "Images saved." match ffmpeg with | Some ffmpeg -&gt; let ffmpeg = if ffmpeg.EndsWith("ffmpeg") = false &amp;&amp; ffmpeg.EndsWith("ffmpeg.exe") = false then System.IO.Path.Combine(ffmpeg, "ffmpeg") else ffmpeg printfn "Running ffmpeg..." System .Diagnostics .Process .Start(ffmpeg, sprintf "-framerate %i -f image2 -i %s/rot_%%d.png -c:v libx264 -crf 0 -r %i -preset ultrafast -tune stillimage %s/temp.avi" fps IMAGE_DIR fps IMAGE_DIR) .WaitForExit() System .Diagnostics .Process .Start(ffmpeg, sprintf "-i %s/temp.avi -pix_fmt rgb24 %s/_final.gif" IMAGE_DIR IMAGE_DIR) .WaitForExit() printfn "Images converted to gif." printfn "" | _ -&gt; () printfn "Shape 1 Angle (%i spokes): %f° / %f rads" spoke1 angleDegrees1 (angleDegrees1 |&gt; degToRad) printfn "Shape 2 Angle (%i spokes): %f° / %f rads" spoke2 angleDegrees2 (angleDegrees2 |&gt; degToRad) printfn "Phase Difference: %f° / %f rads (%f rotations)" rotation (rotation |&gt; degToRad) (rotation / FULL_CIRCLE) printfn "Overlaps per Rotation: %f" (rotations) 0 </code></pre> <p>Overall, nothing overly-complex here.</p> <p>Appreciate any/all advice. Source code is on GitHub:</p> <p><a href="https://github.com/EBrown8534/Spoke_Analyzer/tree/df19e4f281f9c0732d4ac640b35209f07aed4f9c" rel="nofollow noreferrer">https://github.com/EBrown8534/Spoke_Analyzer</a></p>
[]
[ { "body": "<p>The two things that currently bother me most about this code are <strong>Naming</strong> and <strong>Abstraction</strong>.</p>\n\n<p>Don't get me wrong, this is something pretty cool and it's really well-crafted for the most part. But I'm still waiting for this to go the last mile:</p>\n\n<p>There is <strong>12</strong> local variables or functions in your main. I reckon you can easily reduce that to <strong>half</strong> as many by adding some more abstraction.<br>\nWhile we're working on that, we should also look at the naming of these things.</p>\n\n<p>Rough steps to make this much easier to grasp:</p>\n\n<ol>\n<li><p>Extract <code>getRotation</code> into a separate module and rename it to <code>computePhaseDelta</code> or something like that. Note that neither \"Rotation\" nor \"Phase Difference\" are accurate descriptions of what you try to describe.<br>\nA phase difference is really only meaningful when comparing waveforms with the same frequency. For all other waveforms the phase difference is a function of time. I do prefer \"phase difference\" over \"rotation\", though. </p></li>\n<li><p>Extract input-prompting into it's own function and encapsulate all information relating to the problem into a single type. This allows you to utterly abstract all the \"low-level\" prompting and handling away another step.</p></li>\n<li><p>Move the image-drawing local function out of main. It's an infodump that's interrupting the control flow. It also adds another bunch of local variables. </p></li>\n<li><p>Extract the gif conversion into it's own function. It's comparatively long as well.</p></li>\n</ol>\n\n<p>Overall <code>main</code> is intermingling a lot of abstaction levels. To avoid that you'll need to extract more functions.</p>\n\n<hr>\n\n<p>Now that I've bashed around there, I should mention that I found the <code>Input</code> module somewhat annoying to follow, mostly because of the line length and the the way functions are chained. \nThen again writing nice and abstract input functions in a functional language often is somewhat ugly ;)</p>\n\n<p>I like very much the way you've set up <code>drawLine</code> and <code>drawPoint</code>. It's a bit hard to grasp on first reading, but you've made them \"coordinate-system aware\". They are also trivial to partially apply, which lends itself really well to functional programming.</p>\n\n<p>You could've used extended partial application to reduce the complexity inside <code>drawSaveImage</code> after encapsulating it into a separate module (or attaching it to <code>Graphics.fs</code>). While you used it to construct <code>drawLine1</code>, <code>drawLine2</code> and <code>drawPoint</code>, you have not gained that much because all of the setup for colors and pens is still in <code>drawSaveImage</code></p>\n\n<p>On that note: you're recursing inside <code>drawSaveImage</code>. I'd have preferred the function to only draw and save a single image given it's name. That might have also allowed you to simplify the pen and draw* setup across all invocations of the function by passing these as parameters.</p>\n\n<hr>\n\n<p>Overall I very much like this code, but I want to see the abstraction it performs taken to it's logical conclusion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T19:57:24.560", "Id": "412531", "Score": "0", "body": "With regard to \"Phase Difference\": you wouldn't believe how long we spent in the F# Slack trying to come up with a name for that...my original was worse, still trying to find a good one. (Maybe \"Angle Offset\"?)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T19:42:28.247", "Id": "213265", "ParentId": "213259", "Score": "4" } } ]
{ "AcceptedAnswerId": "213265", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:41:39.270", "Id": "213259", "Score": "6", "Tags": [ ".net", "image", "animation", "f#", "graphics" ], "Title": "Analyzing spoke overlaps during rotation" }
213259
<p>After reading <a href="https://github.com/quchen/articles/blob/master/write_yourself_a_brainfuck.md" rel="noreferrer">this article</a> on writing a Brainfuck interpreter in Haskell and achieving awful performance with it (for example, <a href="https://github.com/ErikDubbelboer/brainfuck-jit/blob/master/mandelbrot.bf" rel="noreferrer">mandelbrot</a> generating <strong>37.5 minutes</strong> on an old Intel Atom powered laptop) I've decided to write a compiler for it.</p> <p>I picked <a href="https://nasm.us" rel="noreferrer">NASM</a> for my output language, because that is the only assembly language I somewhat understand, and after some problems (<a href="https://stackoverflow.com/questions/54616492/why-does-a-program-created-by-a-brainfuck-into-assembly-compiler-crash">resolved in this StackOverflow question</a>) I've finally arrived with a working compiler!</p> <p>I would like get more feedback about good coding practices in Haskell more than optimal Assembly generation, because I am interested more in the former language (and also because programs generated by my compiler are quite fast, the same mandelbrot set generator took only <strong>7s 24ms</strong> to execute on the same old laptop, so I feel like it is good enough, although there is a lot of room for improvement).</p> <p>Also, please note that I have a very hard time understanding monads.</p> <h1>Data types</h1> <p>Starting with the data types, the most important one is <code>BfCommand</code>.</p> <pre><code>data BfCommand = GoLeft Int -- &lt; | GoRight Int -- &gt; | Add Int -- + | Sub Int -- - | LoopL Int -- [ | LoopR Int -- ] | WriteChar -- . | ReadChar -- , | BfConst Int -- ??? deriving (Eq, Show) </code></pre> <p>The only thing I do not like about this type, is the <code>BfConst</code> constructor. It just does not feel like it belongs to this data type, because it was added later (to properly represent <code>[-]</code> or <code>[+]</code>, which sets selected cell's value to <code>0</code>). It is just awkward.</p> <p>What would be the correct and elegant way of doing something like this?</p> <h1>Parsing text into instructions</h1> <pre><code>newtype BfSource = BfSource [BfCommand] deriving (Show) parseBf :: String -&gt; BfSource parseBf = optimiseBf . BfSource . pairLoops [] [] . countLoopLs 0 . reduceConsts . mapMaybe char2bfc where char2bfc :: Char -&gt; Maybe BfCommand char2bfc '&lt;' = Just $ GoLeft 1 char2bfc '&gt;' = Just $ GoRight 1 char2bfc '+' = Just $ Add 1 char2bfc '-' = Just $ Sub 1 char2bfc '[' = Just $ LoopL 0 char2bfc ']' = Just $ LoopR 0 char2bfc '.' = Just WriteChar char2bfc ',' = Just ReadChar char2bfc _ = Nothing countLoopLs :: Int -&gt; [BfCommand] -&gt; [BfCommand] countLoopLs _ [] = [] countLoopLs n (LoopL _:bs) = LoopL n : countLoopLs (n + 1) bs countLoopLs n (b:bs) = b : countLoopLs n bs reduceConsts :: [BfCommand] -&gt; [BfCommand] reduceConsts [] = [] reduceConsts (LoopL _:Sub 1:LoopR _:bs) = BfConst 0 : reduceConsts bs reduceConsts (LoopL _:Add 1:LoopR _:bs) = BfConst 0 : reduceConsts bs reduceConsts (b:bs) = b : reduceConsts bs </code></pre> <p>How to rewrite <code>countLoopLs</code> and <code>reduceConsts</code> in a more elegant way? If not for the pattern matching, I would have done it with a <code>fold</code>.</p> <h1>Controlling the flow of the program</h1> <p>To pair the loops correctly I used a stack approach:</p> <pre><code>pairLoops :: [Int] -&gt; [BfCommand] -&gt; [BfCommand] -&gt; [BfCommand] pairLoops _ q [] = reverse q pairLoops st q (LoopL x:bs) = pairLoops (x:st) (LoopL x : q) bs pairLoops (s:st) q (LoopR _:bs) = pairLoops st (LoopR s : q) bs pairLoops st q (b:bs) = pairLoops st (b : q) bs </code></pre> <p>The main flaw here is the lack of syntax error checking, but I did not really know how to add it.</p> <h1>Optimising</h1> <p>This compiler makes very simple optimisations:</p> <ul> <li>Grouping equal elements (<code>+++</code> is represented as <code>Add 3</code>)</li> <li>Reducing excluding operators (<code>+++--</code> is represented as <code>Add 1</code>)</li> <li>Turning <code>[-]</code> and <code>[+]</code> into <code>BfConst 0</code></li> </ul> <p><code>optimiseBf</code> does exactly that (excluding the last point, this is done by <code>reduceConsts</code>).</p> <pre><code>optimiseBf :: BfSource -&gt; BfSource optimiseBf (BfSource bs) = if bs /= obs then optimiseBf (BfSource obs) else BfSource obs where obs = opthelper bs opthelper :: [BfCommand] -&gt; [BfCommand] opthelper [] = [] opthelper [x] = [x] opthelper (x:y:xs) = let r = reduceBf x y single = fromOne r (s1, s2) = fromTwo r in case r of Zero -&gt; opthelper xs (One _) -&gt; single : opthelper xs (Two _ _) -&gt; s1 : opthelper (s2 : xs) </code></pre> <p>This function groups and throws out excluding instructions. Doing it with this <code>if</code></p> <pre><code>if bs /= obs then optimiseBf (BfSource obs) else BfSource obs </code></pre> <p>is probably a horrible way to do it, but I could not think of another one.</p> <p>Reducing individual instructions is done using</p> <pre><code>reduceBf :: BfCommand -&gt; BfCommand -&gt; TwoOrLess BfCommand data TwoOrLess a = Zero | One a | Two a a deriving (Show, Eq) </code></pre> <p>There is not much to talk about <code>reduceBf</code> because it is just hardcoded rules.</p> <h1>Generating assembly</h1> <p>The final stage. This one was surprisingly easy to do (except the loops part).</p> <pre><code>bf2asm :: Handle -&gt; BfCommand -&gt; IO () bf2asm handle (GoLeft x) = hPutStrLn handle $ &quot; &quot; ++ if x == 1 then &quot;dec rcx&quot; else &quot;sub rcx, &quot; ++ show x bf2asm handle (GoRight x) = hPutStrLn handle $ &quot; &quot; ++ if x == 1 then &quot;inc rcx&quot; else &quot;add rcx, &quot; ++ show x bf2asm handle (Add x) = mapM_ (hPutStrLn handle) [ &quot; mov al, [rcx]&quot; , &quot; &quot; ++ if x == 1 then &quot;inc al&quot; else &quot;add al, &quot; ++ show x , &quot; mov [rcx], al&quot; ] bf2asm handle (Sub x) = mapM_ (hPutStrLn handle) [ &quot; mov al, [rcx]&quot; , &quot; &quot; ++ if x == 1 then &quot;dec al&quot; else &quot;sub al, &quot; ++ show x , &quot; mov [rcx], al&quot; ] bf2asm handle (LoopL x) = mapM_ (hPutStrLn handle) [ &quot;_LS&quot; ++ show x ++ &quot;:&quot; , &quot; mov al, [rcx]&quot; , &quot; test al, al&quot; , &quot; jz _LE&quot; ++ show x ] bf2asm handle (LoopR x) = mapM_ (hPutStrLn handle) [ &quot; jmp _LS&quot; ++ show x , &quot;_LE&quot; ++ show x ++ &quot;:&quot; ] bf2asm handle WriteChar = hPutStrLn handle &quot; call _printChar&quot; bf2asm handle ReadChar = hPutStrLn handle &quot; call _readChar&quot; bf2asm handle (BfConst x) = mapM_ (hPutStrLn handle) [ &quot; &quot; ++ if x == 0 then &quot;xor al, al&quot; else &quot;mov al, &quot; ++ show x , &quot; mov [rcx], al&quot; ] </code></pre> <p>Is it better to provide a <code>Handle</code> and write to it like I did, or maybe this function should just create <code>String</code>s?</p> <hr /> <p>If the need arises, feel free to look at the code as a whole <a href="https://github.com/wilbdhm/bfcompiler/tree/b46cf7138840669bfe9c603bde1afd8dc3165607" rel="noreferrer">here</a>.</p>
[]
[ { "body": "<p><code>BfSource</code> isn't Brainfuck, it's an intermediate language that's easier to work with. Don't worry about <code>BfConst</code> more than about <code>Add</code>'s <code>Int</code> parameter. You can reuse the <code>Const</code> identifier, this is not a library.</p>\n\n<pre><code>type BfSource = [BfCommand]\n\nparseBf = optimiseBf . mapAccumL pairLoops []\n . mapAccumL countLoopLs 0 . mapMaybe char2bfc\n\n...\nchar2bfc '[' = Just $ LoopL undefined -- a hack should look like one\n...\n\ncountLoopLs n (LoopL _) = (n+1, LoopL n)\ncountLoopLs n b = (n, b)\n\npairLoops :: [Int] -&gt; BfCommand -&gt; ([Int], BfCommand)\npairLoops st (LoopL x) = (x:st, LoopL x)\npairLoops (s:st) (LoopR _) = (st, LoopR s)\npairLoops st b = (st, b)\n\noptimiseBf :: BfSource -&gt; BfSource\noptimiseBf = head . head . filter ((&gt;1) . length) . group\n . iterate (unfoldr $ uncons . reduceBf)\n\nreduceBf :: [BfCommand] -&gt; [BfCommand]\nreduceBf (Add a : Add b : bs) = Add (a + b) : bs\n...\nreduceBf (LoopL _ : Add 1 : LoopR _ : bs) = BfConst 0 : bs\n\nbf2asm :: Handle -&gt; BfCommand -&gt; IO ()\nbf2asm handle = hPutStrLn handle . \\case\n GoLeft x -&gt; \" \" ++ if x == 1 then \"inc rcx\" else \"add rcx, \" ++ show x\n ...\n Add x -&gt; unlines\n [ \" mov al, [rcx]\"\n , \" \" ++ if x == 1 then \"inc al\" else \"add al, \" ++ show x\n , \" mov [rcx], al\"\n ]\n ...\n</code></pre>\n\n<p><code>Sub</code> is superfluous. Just replace <code>Sub 1</code> with <code>Add (-1)</code>. So is one of <code>GoLeft</code> or <code>GoRight</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T22:25:44.910", "Id": "213273", "ParentId": "213264", "Score": "3" } } ]
{ "AcceptedAnswerId": "213273", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T18:56:40.800", "Id": "213264", "Score": "13", "Tags": [ "haskell", "assembly", "brainfuck", "compiler" ], "Title": "Brainfuck to NASM compiler in Haskell" }
213264
<p>I have a sorted array. It can be empty. I have to find its closest greater and smaller number. If the given number is present in the array, it will be considered as greater number. I implemented it like the below style. But I am not satisfied with my approach. Can anyone suggest better ways?</p> <pre><code>findPreviousNext(array:number[], currentValue: number): ClosestValues { let immediateNextIndex = -1; var closestvalues = new ClosestValues(); for (let i = 0; i &lt; array.length; i++) { if (array[i] &gt;= currentValue) { immediateNextIndex = i; break; } } switch (immediateNextIndex) { case 0: { closestvalues.immediateNext = array[immediateNextIndex]; closestvalues.immediatePrevious = null; break; } case -1: { var prevVal = array[array.length -1]; closestvalues.immediateNext = null; closestvalues.immediatePrevious = (prevVal != null &amp;&amp; prevVal != undefined) ? prevVal : null; break; } default: { let prevVal = array[immediateNextIndex - 1]; closestvalues.immediateNext = array[immediateNextIndex]; closestvalues.immediatePrevious = (prevVal != null &amp;&amp; prevVal != undefined) ? prevVal : null; } } return closestvalues; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T20:25:19.943", "Id": "412534", "Score": "0", "body": "The array is sorted; how about a binary search?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T20:29:57.190", "Id": "412536", "Score": "0", "body": "Why not move the switch statement into it's own function and have it in the if condition. Or change the for loop to a while loop, drop the break in the if condtion and have the return from closestvalues break the while loop? is this supposed to go through the loop all the way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T20:33:49.950", "Id": "412538", "Score": "1", "body": "@AJNeufeld Please put all suggestions for improvements in answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T20:34:05.403", "Id": "412539", "Score": "1", "body": "@Caperneoignis Please put all suggestions for improvements in answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T21:22:26.677", "Id": "412547", "Score": "0", "body": "If possible, state the area where you're dissatisfied with your code: embedded documentation, readability, resource usage?" } ]
[ { "body": "<p>First of all, comments would be nice. Speaking in terms of implementation rarely helps another person understand what the code is doing. Especially when the code uses very generic variable names. My general rule to comments is when the code tries to do something clever, write a comment.</p>\n\n<p>You could short-circuit the logic if the array is empty. No sense having the code run if you know ahead of time it does nothing. </p>\n\n<p>Also, by eliminating cases early, you can start making assumptions. This would allow you to simplify logic or make optimizations to existing logic, turning general-case logic to case-specific logic.</p>\n\n<pre><code>for (let i = 0; i &lt; array.length; i++) {\n if (array[i] &gt;= currentValue) {\n immediateNextIndex = i;\n break;\n }\n}\n</code></pre>\n\n<p>Could be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\" rel=\"nofollow noreferrer\"><code>array.findIndex</code></a>.</p>\n\n<p>Here's my take on it:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const findPreviousNext = (array, currentValue) =&gt; {\n // Short-circuit the code if the array is empty.\n if(array.length === 0){\n return { next: null, prev: null }\n }\n\n // Find the index of the closest greater number.\n const closestIndex = array.findIndex(v =&gt; v &gt;= currentValue)\n\n // A non-existent/negative index is undefined. No need for extensive checks.\n const closestNext = array[closestIndex] || null\n const closestPrev = array[closestIndex - 1] || null\n const lastValue = array[array.length - 1] || null\n\n // The only special case is the non-existent value (index = -1)\n const next = closestIndex === -1 ? null : closestNext\n const prev = closestIndex === -1 ? lastValue : closestPrev\n\n // Build the instance (a simple POJO in this case).\n return { next, prev }\n}\n\nconsole.log(findPreviousNext([], 3))\nconsole.log(findPreviousNext([1], 3))\nconsole.log(findPreviousNext([1, 2], 3))\nconsole.log(findPreviousNext([1, 2, 3], 3))\nconsole.log(findPreviousNext([1, 2, 3, 4], 3))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T21:11:09.543", "Id": "213269", "ParentId": "213267", "Score": "1" } } ]
{ "AcceptedAnswerId": "213269", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T20:10:42.090", "Id": "213267", "Score": "1", "Tags": [ "array", "typescript" ], "Title": "Find closest greater and smaller number from a sorted array" }
213267
<p>Inspired by the various quiz programs on this site, as well as <a href="https://www.chiark.greenend.org.uk/~sgtatham/puzzles/" rel="noreferrer">Simon Tatham's puzzle collection</a>, I thought I'd write a quiz that constructs its questions automatically and randomly. A typical session looks like this:</p> <pre class="lang-none prettyprint-override"><code>What is (true and false)? false What is (true and true)? true What is (true implies false)? false What is (false or false)? false What is not true? false What is (true and (false or false))? false What is (true and (false implies false))? true What is ((true implies false) xor false)? true Wrong. What is (true or (true implies false))? true What is (true or (false and false))? true What is (((true or true) and false) or true)? true </code></pre> <p>The longer you play, the more complicated the expressions get. Every time after answering 5 questions correctly, the expressions get 1 operator longer.</p> <p>A special feature is that the expressions are constructed in a way that guarantees equal probabilities for the outcomes <code>true</code> or <code>false</code>. For the <code>And</code>, <code>Or</code> and <code>Implies</code> operations, this was already a bit harder than I had expected at first. The <code>Xor</code> probabilities took me a bit longer to get right. My first guess was that it should be simpler than the other operators since xor is associative and commutative and already has a 50:50 distribution. It took me a few months until I sat down, did the math again and suddenly had the correct solution.</p> <p>Here is the code implementing the whole quiz:</p> <pre class="lang-kotlin prettyprint-override"><code>package de.roland_illig.boolquiz import java.util.Random import kotlin.math.sqrt /** * A boolean expression is either a literal value, * or a complex expression consisting of at least one subexpression. */ interface Expr { fun eval(): Boolean } /** A boolean literal is either "true" or "false". */ class Literal(private val value: Boolean) : Expr { override fun eval() = value override fun toString() = "$value" } /** Not negates its argument. */ class Not(private val a: Expr) : Expr { override fun eval() = !a.eval() override fun toString() = "$a".run { if (startsWith("(")) "not$this" else "not $this" } } /** * There are 16 binary boolean operators, of which only a few * are interesting enough to be given a name. * * Each of these operators needs to handle 4 different cases for its arguments. * The operators differ in the number of cases in which they return true * (Or returns true in 3 cases, while And returns true only in a single case.) */ enum class BinOp(val sym: String) { And("and"), Or("or"), Impl("implies"), Xor("xor"); fun eval(a: Boolean, b: Boolean): Boolean { return when (this) { And -&gt; a &amp;&amp; b Or -&gt; a || b Impl -&gt; !a || b Xor -&gt; a != b } } /** * Returns the probabilities for the two arguments of a binary expression, * so that the resulting expression becomes true with the given probability. * * To generate such a random expression, the probabilities of the operands * are adjusted by a bias, pointing upwards for And (since it only becomes * true in 1/4 cases), or downwards for Or and Impl (since it becomes true * in 3/4 cases), or really complicated for Xor. */ fun probabilities(prob: Double, rnd: Random): Pair&lt;Double, Double&gt; { return when (this) { And -&gt; sqrt(prob).let { Pair(it, it) } Or -&gt; (1.0 - sqrt(1.0 - prob)).let { Pair(it, it) } Impl -&gt; sqrt(1.0 - prob).let { Pair(it, 1.0 - it) } Xor -&gt; probabilitiesXor(prob, rnd) } } /** * Returns the probabilities for the two arguments of an xor expression, * so that the resulting expression becomes true with the given probability. * * The current implementation aims at keeping the returned probabilities * "interesting". It would have been easy to just return `Pair(0.0, prob)` * or `Pair(prob, 0.0)`, but that would have been boring. * * Instead, the returned probabilities are as close together as possible. * This involves solving a quadratic equation with center point 0.5. Since * Pair(0.3, 0.3) produces the same output probability as Pair(0.7, 0.7), * it is decided randomly whether to return high or low probabilities. */ private fun probabilitiesXor(prob: Double, rnd: Random): Pair&lt;Double, Double&gt; { val pm = if (rnd.nextBoolean()) +1.0 else -1.0 return if (prob &lt; 0.5) { val a = 0.5 + pm * sqrt(0.25 - 0.5 * prob) Pair(a, a) } else { val a = 0.5 + pm * sqrt(0.25 - 0.5 * (1.0 - prob)) Pair(a, 1.0 - a) } } } class Binary(private val a: Expr, private val op: BinOp, private val b: Expr) : Expr { override fun eval() = op.eval(a.eval(), b.eval()) override fun toString() = "($a ${op.sym} $b)" } /** * Constructs a random boolean expression containing [deg] operators * that evaluates to true with probability [prob]. */ fun construct(deg: Int, rnd: Random, prob: Double): Expr { if (deg == 0) return Literal(rnd.nextDouble() &lt; prob) val opIndex = rnd.nextInt(BinOp.values().size + 1) if (opIndex == 0) return Not(construct(deg - 1, rnd, 1.0 - prob)) val leftDeg = rnd.nextInt(deg) val rightDeg = deg - 1 - leftDeg val op = BinOp.values()[opIndex - 1] val (leftProb, rightProb) = op.probabilities(prob, rnd) val left = construct(leftDeg, rnd, leftProb) val right = construct(rightDeg, rnd, rightProb) return Binary(left, op, right) } private enum class Answer { Correct, Wrong, EOF } private fun question(difficulty: Int, rnd: Random): Answer { val expr = construct(difficulty, rnd, 0.5) print("What is $expr? ") val answer = readLine() ?: return Answer.EOF if (answer != "true" &amp;&amp; answer != "false") { println("Answer must be either \"true\" or \"false\".") return Answer.Wrong.also { } } if (answer.toBoolean() == expr.eval()) return Answer.Correct println("Wrong.") return Answer.Wrong } private fun round(difficulty: Int, rnd: Random): Boolean { var correct = 0 while (correct &lt; 5) { when (question(difficulty, rnd)) { Answer.Correct -&gt; correct++ Answer.Wrong -&gt; Unit Answer.EOF -&gt; return false } } return true } fun main() { val rnd = Random() for (difficulty in 1..Integer.MAX_VALUE) if (round(difficulty, rnd).not()) return } </code></pre> <p>I also added a few automatic tests:</p> <pre><code>package de.roland_illig.boolquiz import org.assertj.core.api.Assertions.assertThat import org.assertj.core.data.Offset import org.assertj.core.data.Percentage import org.junit.Test import java.util.Random import kotlin.math.sqrt class BoolQuizKtTest { @Test fun testConstruct() { assertThat(construct(0, Random(0), 0.5).toString()) .isEqualTo("false") assertThat(construct(0, Random(4096), 0.5).toString()) .isEqualTo("true") assertThat(construct(1, Random(0), 0.5).toString()) .isEqualTo("not false") assertThat(construct(1, Random(4096), 0.5).toString()) .isEqualTo("(true xor false)") assertThat(construct(7, Random(0), 0.5).toString()) .isEqualTo("not((true or true) implies " + "((false implies false) xor " + "(true and (false xor true))))") assertThat(construct(7, Random(4096), 0.5).toString()) .isEqualTo("(((true and true) and (false or true)) " + "xor (false or not(true implies false)))") } @Test fun testConstructProbability() { var falseCount = 0 var trueCount = 0 val rnd = Random(0) for (i in 0 until 2_000_000) { val expr = construct(1, rnd, 0.3) if (expr.eval()) trueCount++ else falseCount++ } assertThat(falseCount / (trueCount + falseCount).toDouble()) .isCloseTo(0.70, Percentage.withPercentage(2.0)) assertThat(trueCount / (trueCount + falseCount).toDouble()) .isCloseTo(0.30, Percentage.withPercentage(2.0)) } @Test fun testConstructProbabilityAnd() { var falseCount = 0 var trueCount = 0 val rnd = Random(0) for (i in 0 until 2_000_000) { val a = rnd.nextDouble() &lt; sqrt(0.3) val b = rnd.nextDouble() &lt; sqrt(0.3) val and = a &amp;&amp; b if (and) trueCount++ else falseCount++ } assertThat(falseCount / (trueCount + falseCount).toDouble()) .isCloseTo(0.70, Percentage.withPercentage(2.0)) assertThat(trueCount / (trueCount + falseCount).toDouble()) .isCloseTo(0.30, Percentage.withPercentage(2.0)) } @Test fun testConstructProbabilityXor() { val rnd = Random(12345678) for (percent in 0..100) { val pOutExpected = percent / 100.0 val (pa, pb) = BinOp.Xor.probabilities(pOutExpected, rnd) val pANotB = pa * (1.0 - pb) val pBNotA = pb * (1.0 - pa) val pOutActual = pANotB + pBNotA assertThat(pOutActual) .withFailMessage("$percent") .isCloseTo(pOutExpected, Offset.offset(1.0e-14)) } } @Test fun testEval() { assertThat(Literal(false).eval()) .isEqualTo(false) assertThat(Literal(true).eval()) .isEqualTo(true) assertThat(Not(Literal(false)).eval()) .isEqualTo(true) assertThat(Not(Literal(true)).eval()) .isEqualTo(false) assertThat(Binary(Literal(false), BinOp.And, Literal(true)).eval()) .isEqualTo(false) assertThat(Binary(Literal(true), BinOp.And, Literal(true)).eval()) .isEqualTo(true) assertThat(Binary(Literal(false), BinOp.Or, Literal(false)).eval()) .isEqualTo(false) assertThat(Binary(Literal(false), BinOp.Or, Literal(true)).eval()) .isEqualTo(true) assertThat(Binary(Literal(true), BinOp.Impl, Literal(false)).eval()) .isEqualTo(false) assertThat(Binary(Literal(false), BinOp.Impl, Literal(false)).eval()) .isEqualTo(true) assertThat(Binary(Literal(true), BinOp.Xor, Literal(true)).eval()) .isEqualTo(false) assertThat(Binary(Literal(false), BinOp.Xor, Literal(true)).eval()) .isEqualTo(true) } } </code></pre>
[]
[ { "body": "<p>What stands out to me is the use of <code>when</code> in <code>BinOp</code> instead of object oriented patterns. The <code>eval</code> and <code>probabilities</code> methods could be replaced with lambda properties and/or by overriding abstract methods.</p>\n\n<p>For example:</p>\n\n<pre><code>enum class BinOp(val sym: String, val eval: (Boolean, Boolean) -&gt; Boolean) {\n // For the eval property use a lambda\n And(\"and\", { a, b -&gt; a &amp;&amp; b }) {\n override fun probabilities(prob: Double, rnd: Random): Pair&lt;Double, Double&gt; =\n sqrt(prob).let { Pair(it, it) }\n },\n // .. or reference an existing method\n Xor(\"xor\", Boolean::xor) {\n override fun probabilities(prob: Double, rnd: Random): Pair&lt;Double, Double&gt; {\n val pm = if (rnd.nextBoolean()) +1.0 else -1.0\n return if (prob &lt; 0.5) {\n val a = 0.5 + pm * sqrt(0.25 - 0.5 * prob)\n Pair(a, a)\n } else {\n val a = 0.5 + pm * sqrt(0.25 - 0.5 * (1.0 - prob))\n Pair(a, 1.0 - a)\n }\n }\n };\n\n abstract fun probabilities(prob: Double, rnd: Random): Pair&lt;Double, Double&gt;\n}\n</code></pre>\n\n<hr>\n\n<p>Here a quick example how to group the methods together:</p>\n\n<pre><code>typealias booleanOperation = (Boolean, Boolean) -&gt; Boolean\ntypealias probabilityCalc = (Double, Random) -&gt; Pair&lt;Double, Double&gt;\n\n\nfun andEval(a: Boolean, b: Boolean) = a &amp;&amp; b \nfun xorEval(a: Boolean, b: Boolean) = a xor b \n\n\nfun andProb(prob: Double, rnd: Random) = \n sqrt(prob).let { Pair(it, it) } \n\nfun xorProb(prob: Double, rnd: Random): Pair&lt;Double, Double&gt; {\n val pm = if (rnd.nextBoolean()) +1.0 else -1.0\n return if (prob &lt; 0.5) {\n val a = 0.5 + pm * sqrt(0.25 - 0.5 * prob)\n Pair(a, a)\n } else {\n val a = 0.5 + pm * sqrt(0.25 - 0.5 * (1.0 - prob))\n Pair(a, 1.0 - a)\n }\n}\n\n\nenum class BinOp(val sym: String, val eval: booleanOperation, val probabilities: probabilityCalc) {\n And(\"and\", ::andEval, ::andProb),\n Xor(\"xor\", ::xorEval, ::xorProb);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T16:21:17.923", "Id": "460290", "Score": "0", "body": "What, in your mind, would be the benefit of using object-oriented patterns or abstract methods here? To me, your code looks more complicated. In my code one can directly see how the different operators differ since their implementations are in adjacent lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T08:37:26.837", "Id": "460377", "Score": "0", "body": "Replacing conditionals with polymorphism is a common refactoring pattern (see https://www.google.com/search?q=conditional+vs+polymorphism ). For me the main advantage is that it's impossible to accidentally create a new, bugged instance of `BinOp`, because you forgot to update one of the `when` statements. I personally prefer having all the functionality which form one instance together at one place, however I understand wanting to have all variants close together. One way to do that would be to put the lambdas together in variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T18:18:57.923", "Id": "460450", "Score": "0", "body": "Your \"main advantage\" doesn't apply in this case. I cannot forget one of the branches since the compiler will tell me. I intentionally kept the methods with the `when` expressions quite short. Your second reason for using abstract methods doesn't convince me either. I applied the refactorings you suggested, and the code becomes either more bloated (because of the additional `override` declarations) or becomes so short that it doesn't even offer a convenient place where the `probabilities` function could be documented. Therefore I still prefer my variant." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T10:12:22.733", "Id": "235213", "ParentId": "213270", "Score": "2" } }, { "body": "<p>Very fun game you created here, I like it. Your calculations for the probabilities are also impressive, and well tested.</p>\n\n<hr>\n\n<p>Some small suggestions:</p>\n\n<ul>\n<li>UI improvement: Print a message when \"leveling up\".</li>\n<li><code>Answer.Wrong.also { }</code> has a redundant <code>.also</code> that can be removed.</li>\n<li>Enum constants are usually written in uppercase, making it <code>AND</code>, <code>OR</code>, <code>XOR</code>, <code>IMPLIES</code>.</li>\n<li>The usage of <code>Answer</code> has a <code>EOF</code> result, which gives me a feeling that whether or not the user gives the correct answer could be instead represented as the nullable type <code>Boolean?</code></li>\n<li>The import <code>java.util.Random</code> can be changed to <code>kotlin.random.Random</code>, which you can access a default instance from by using <code>kotlin.random.Random.Default</code> or by using a constructor through <code>kotlin.random.Random(seed)</code>.</li>\n<li>Many names have been unnecessarily shortened, <code>prob</code> -> <code>probability</code>, <code>rnd</code> -> <code>random</code>, <code>deg</code> -> ??? (honestly not sure what this is short for), <code>Expr</code> -> <code>Expression</code>...</li>\n<li>Code organization:\n\n<ul>\n<li>Separate the game model from the view, so that it becomes easier to create other clients (REST service or Desktop application for example).</li>\n<li>Create more classes instead of having many methods as top-level functions.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Some possible changes that could be done but that not necessarily improves anything:</p>\n\n<ul>\n<li><code>Expr</code> could be changed to <code>typealias Expr = () -&gt; Boolean</code></li>\n<li>A <code>toString</code> method is mostly for debugging and logging purposes and not to be displayed to users. It could be separated to a different method.</li>\n<li><p>All your expressions have a <code>toString</code> and <code>eval</code> method, but the constant values of these are known already on creation. This would make it possible to do something like the following:</p>\n\n<pre><code>interface Expression {\n val text: String\n val eval: Boolean\n}\n\n/** A boolean literal is either \"true\" or \"false\". */\nclass Literal(override val value: Boolean) : Expression {\n override val text: String = eval.toString()\n override val eval: Boolean = value\n}\n</code></pre>\n\n<p>Again though, this doesn't necessarily improve anything as your code is already very readable by having both a toString and eval method.</p></li>\n</ul>\n\n<p>I also tried to experiment with other approaches, such as making a class for an expression and to have a <code>ExpressionFactory</code> that could create both literals, the not function, and the binary expressions, but in the end I felt that it became unnecessary complex.</p>\n\n<h3>Summary</h3>\n\n<p>Some organization of the code could be improved to better separate between the game logic and the user interaction, and some different minor improvements as mentioned in the beginning. But overall, nicely done and fun game.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T13:24:43.583", "Id": "460992", "Score": "0", "body": "Thank you for sharing these great insights. When I wrote the code I had thought that the variable names were obvious to any reader. Now that I spelled out all the abbreviations, the code should be even understandable by a beginner trying to learn boolean expressions, which I think could really be the target of this quiz. — Since Kotlin is a different language than Java, I didn't want to blindly follow the \"put everything into classes\" suggestion. Instead I went the other way and moved the `probabilities` out of the `BinaryOperator` class, since these are not general-purpose enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T13:31:39.153", "Id": "460994", "Score": "1", "body": "@RolandIllig It's true that you don't have to put everything into different classes, but another way to structure the code is to put everything into different *files* - which you can still do. Especially the `round`, `question` and `main` methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T13:38:47.853", "Id": "460995", "Score": "0", "body": "Using `kotlin.Random` instead of `java.util.Random` sounded like a great idea at first since it removes the dependency on Java. The only downside is that in `kotlin.Random`, _Future versions of Kotlin may change the algorithm of this seeded number generator_, which would break my tests for no reason. Therefore it would require much more code to get this right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T19:41:54.380", "Id": "461036", "Score": "1", "body": "@RolandIllig Honestly, I don't think you should rely on any randomness in your tests - seeded or not. The loops that randomizes two million times are fine because they make sure that your math is correct. But for generating specific boolean constructs a better approach would be to separate the randomness from the generation a bit so that you can test a specific generation. It's not the randomness that you want to test, `assertThat(construct(7, Random(0), 0.5)....toString..` tests that a very specific construct has a specific result for the toString call - *that* is what you want to test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T19:44:32.477", "Id": "461037", "Score": "1", "body": "@RolandIllig What you could do is to replace `rnd: Random` in your method with `intProvider: (Int) -> Int` and give one implementation in your real usage - `rnd.nextInt(it)` and in your tests you could feed the results from a list of pre-specified numbers. Sure it's a bit more code to write, but it's a lot more bullet-proof." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-11T19:15:19.817", "Id": "235480", "ParentId": "213270", "Score": "6" } } ]
{ "AcceptedAnswerId": "235480", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T21:18:52.217", "Id": "213270", "Score": "8", "Tags": [ "random", "quiz", "kotlin", "expression-trees" ], "Title": "Quiz for random boolean expressions" }
213270
<p>I am learning MPI (via <code>boost::mpi</code>) and wrote this program that takes the euclidean norm of a 1-D vector (represented as an array here.) I want to make sure that I am using <code>boost::mpi</code> properly, in terms of both functions used and the way the code is parallelized.</p> <p>The sample below is the program with just the norm functionality; it takes no input from the user and always uses the same seed for consistency reasons. Another limitation is that the vector size must be evenly divisible into the MPI world size.</p> <p>I appreciate any comments and am thankful for your time.</p> <pre><code>#include &lt;boost/mpi.hpp&gt; #include &lt;chrono&gt; #include &lt;cmath&gt; #include &lt;iostream&gt; #include &lt;numeric&gt; #include &lt;random&gt; #include &lt;utility&gt; #include &lt;vector&gt; int main() { boost::mpi::environment env; boost::mpi::communicator world; //unsigned long TWIST_SEED = std::chrono::system_clock::now().time_since_epoch().count(); unsigned long TWIST_SEED = 2; unsigned long VECT_SIZE = 10; double *main_vector = new double[VECT_SIZE]; if (world.rank() == 0) { std::mt19937 generator(TWIST_SEED); std::uniform_real_distribution&lt;double&gt; dis(-222222.22, 222222.22); for (int i = 0; i &lt; VECT_SIZE; i++) { main_vector[i] = dis(generator); } } int n_bar = VECT_SIZE / world.size(); if (world.rank() == 0) { if (VECT_SIZE &lt;= 10) { std::cout &lt;&lt; "Your vector is small enough to output. It is: \n{"; for (int i = 0; i &lt; VECT_SIZE; i++) { if (i == VECT_SIZE - 1) { std::cout &lt;&lt; main_vector[i]; } else { std::cout &lt;&lt; main_vector[i] &lt;&lt; ", "; } } std::cout &lt;&lt; "}" &lt;&lt; std::endl; } } double *local_vector = new double[n_bar]; boost::mpi::scatter(world, main_vector, local_vector, n_bar, 0); std::vector&lt;double&gt; dot; double local_dot = 0.0; for (int i = 0; i &lt; n_bar; i++) { local_dot += local_vector[i] * local_vector[i]; } boost::mpi::gather(world, local_dot, dot, 0); if (world.rank() == 0) { std::cout &lt;&lt; "The norm is " &lt;&lt; sqrt(std::accumulate(dot.begin(), dot.end(), 0.0)) &lt;&lt; std::endl; } delete[] main_vector; return 0; } </code></pre>
[]
[ { "body": "<p>You've misspelt <code>std::sqrt</code>.</p>\n\n<p>Calculation of 2D and 3D Euclidean norm is more accurate and efficient via <code>std::hypot()</code> - would it be reasonable to use that as a basis for the N-dimensional form?</p>\n\n<p>As always, prefer standard containers such as <code>std::vector</code> over raw pointers created with <code>new[]</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:36:46.783", "Id": "213292", "ParentId": "213271", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T22:06:30.510", "Id": "213271", "Score": "3", "Tags": [ "c++", "boost", "mpi" ], "Title": "Using boost::mpi to take the Euclidean norm of a vector" }
213271
<p>My Base64 encoder class converts a string with ascii characters to a base64 encoded string with padding if required. Note that I'm not using <code>istream</code> as the input because my goal was only to convert a <code>std::string</code> with ascii characters to another <code>std::string</code> with base64 encoded characters.</p> <p>Only resource I used was this <a href="https://en.wikipedia.org/w/index.php?title=Base64&amp;oldid=881457005" rel="nofollow noreferrer">wikipedia article</a>.</p> <p><strong>base64encoder.h</strong>:</p> <pre><code>#ifndef BASE64_BASE64_H #define BASE64_BASE64_H #include &lt;array&gt; class Base64Encoder { public: Base64Encoder() = default; ~Base64Encoder() = default; const std::string encode(const std::string s) const; private: constexpr static std::array&lt;const unsigned char, 64&gt; base64_table = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; constexpr static unsigned char get_base_64_char(ulong number_of_char) { return base64_table.at(number_of_char); } const static unsigned char next_ascii(size_t current_index, const std::string s, size_t length_of_s); const static size_t MINIMAL_B64_STRING_LENGTH = 4; }; #endif //BASE64_BASE64_H </code></pre> <p><strong>base64encoder.cpp:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include "base64encoder.h" // Takes a string and encodes it into a base64 string. const std::string Base64Encoder::encode(const std::string s) const { std::stringstream encoding; const size_t length_of_s = s.length(); size_t i = 0; // Base64 uses 6 bits for encoding. ASCII characters have a size of 8 bits. // We sometimes have to use bits of the next character a.k.a right character. size_t bit_offset = 0; // offset of used bits in current ascii character while (i &lt; length_of_s) { // left_ascii is the current ASCII character which needs to be encoded. auto left_ascii = static_cast&lt;unsigned char&gt;(s.at(i)); // b64 will contain the encoded b64 character. unsigned char b64_encoded = '\0'; if (bit_offset == 0) { left_ascii = left_ascii &gt;&gt; 2; b64_encoded = get_base_64_char(static_cast&lt;ulong&gt;(left_ascii)); bit_offset = 6; // no need to go to the next index, we didn't use any other information except the current char. } else if (bit_offset == 6) { left_ascii = left_ascii &lt;&lt; 6; left_ascii = left_ascii &gt;&gt; 2; auto right_ascii = Base64Encoder::next_ascii(i, s, length_of_s); right_ascii = right_ascii &gt;&gt; 4; left_ascii = right_ascii | left_ascii; b64_encoded = get_base_64_char(static_cast&lt;ulong&gt;(left_ascii)); bit_offset = 4; ++i; } else if (bit_offset == 4) { left_ascii = left_ascii &lt;&lt; 4; left_ascii = left_ascii &gt;&gt; 2; auto right_ascii = Base64Encoder::next_ascii(i, s, length_of_s); right_ascii = right_ascii &gt;&gt; 6; left_ascii = left_ascii | right_ascii; b64_encoded = get_base_64_char(static_cast&lt;ulong&gt;(left_ascii)); bit_offset = 2; ++i; } else { // offset is 2 left_ascii = left_ascii &lt;&lt; 2; left_ascii = left_ascii &gt;&gt; 2; b64_encoded = get_base_64_char(static_cast&lt;ulong&gt;(left_ascii)); bit_offset = 0; ++i; } encoding &lt;&lt; b64_encoded; } // Checking if padding in form of appending '=' is required. if (bit_offset || length_of_s &lt; 2) { encoding &lt;&lt; '='; if (length_of_s == 1) { encoding &lt;&lt; '='; } } return encoding.str(); } // returns next ascii character if index is in string or a zero byte which happens if we are at the end of string // and there is no next ascii character filling up our 6 bits which we need for a base64 encoded char - in this case // we also need padding. const unsigned char Base64Encoder::next_ascii(size_t current_index, const std::string s, size_t length_of_s) { size_t next_index = ++current_index; if (next_index &lt; length_of_s) { return static_cast&lt;unsigned char&gt;(s.at(next_index)); } unsigned char zero_byte = 0; return zero_byte; } </code></pre> <p>Example usage <strong>main.cpp</strong>:</p> <pre><code>#include &lt;iostream&gt; #include "base64encoder.h" int main() { Base64Encoder b; const std::string s("Hello Base64!"); std::cout &lt;&lt; b.encode(s); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T18:47:27.930", "Id": "412647", "Score": "1", "body": "I would change the comment. Your description of Base64 is not totally correct. => \"Base64 encodes 4 bytes of ASCII `A-Za-z0-9+/` characters into 3 bytes. It does this by using 6 bits to encode each character and thus has a limited character set. Messages are always a multiple of 3 in length and the '=' character is used to indicate terminator padding." } ]
[ { "body": "<pre><code> Base64Encoder() = default;\n ~Base64Encoder() = default;\n</code></pre>\n\n<p>In general, if you want to explicitly provide special member functions, then explicitly provide them all. Others will advise that if you can avoid defining the special member functions, then do so. <a href=\"https://abseil.io/tips/131\" rel=\"nofollow noreferrer\">Read more here</a>.</p>\n\n<pre><code>class Base64Encoder {\npublic:\n // ... no default operations declared ...\n const std::string encode(const std::string s) const;\n\nprivate:\n // ...\n</code></pre>\n\n<hr>\n\n<pre><code> const std::string encode(const std::string s) const;\n</code></pre>\n\n<p><code>std::string</code> requires <code>&lt;string&gt;</code> be included.</p>\n\n<p><code>s</code> is passed by value to <code>const</code>, which incurs an unnecessary copy. Consider using <code>std::string_view</code> if you have <a href=\"/questions/tagged/c%2b%2b17\" class=\"post-tag\" title=\"show questions tagged &#39;c++17&#39;\" rel=\"tag\">c++17</a>. <a href=\"https://abseil.io/tips/1\" rel=\"nofollow noreferrer\">Read more here</a>.</p>\n\n<pre><code> std::string encode(const std::string_view s) const;\n</code></pre>\n\n<p>Otherwise, pass by reference to <code>const</code>. </p>\n\n<pre><code> std::string encode(const std::string&amp; s) const;\n</code></pre>\n\n<hr>\n\n<pre><code> constexpr static unsigned char get_base_64_char(ulong number_of_char) {\n return base64_table.at(number_of_char);\n }\n</code></pre>\n\n<p><code>ulong</code> is not a standard unsigned integer type. If you need a fixed-size integer, consider one of the types from <code>&lt;cstdint&gt;</code> (e.g. <code>std::uint8_t</code>). For this use-case, I'd just use <code>std::size_t</code>. </p>\n\n<p>Is <code>number_of_char</code> a clear description of what the value represents? Would <code>index</code> be clearer?</p>\n\n<p>Do you need the bounds checking of <code>base64_table.at()</code>?</p>\n\n<hr>\n\n<pre><code> const static unsigned char next_ascii(size_t current_index, const std::string s, size_t length_of_s);\n</code></pre>\n\n<p>The first <code>const</code> is unnecessary.</p>\n\n<p><code>size_t</code> is not guaranteed by the standard to exist in the global namespace. Use <code>std::size_t</code> and include <code>&lt;cstddef&gt;</code>. <a href=\"https://stackoverflow.com/a/36596739/3762339\">Read more here</a>.</p>\n\n<hr>\n\n<pre><code> const static size_t MINIMAL_B64_STRING_LENGTH = 4;\n</code></pre>\n\n<p>Consider reserving upper case names for the preprocessor.</p>\n\n<p><code>constexpr</code>?</p>\n\n<hr>\n\n<pre><code> std::stringstream encoding;\n</code></pre>\n\n<p>Do we need a <code>std::stringstream</code>? We can actually calculate the destination buffer length. For base64 encoding, every 3 octets maps to 4 sextets. To find the encoded length <span class=\"math-container\">\\$m\\$</span>, find the total number of octets to be read (integral ceiling) and multiply it by the length of each sextet.</p>\n\n<p><span class=\"math-container\">$$m = 4 \\dot ((n + 2) / 3)$$</span></p>\n\n<hr>\n\n<pre><code> while (i &lt; length_of_s) {\n // if first sextet, ...\n // else if second sextet, ...\n // else if third sextet, ...\n // else must be fourth sextet ...\n }\n</code></pre>\n\n<p>Instead of cycling through each branch on every loop until you get to the sextet you are at, consider a modulo approach. Loop through full sextet groups until you have a partial sextet group left at the end (the remainder). Then you can branch based on what you have left.</p>\n\n<pre><code> for (auto remaining_sextets = s.size() / 3; remaining_sextets--;) {\n encoded += /* first sextet masked and shifted */\n encoded += /* second sextet masked and shifted */\n encoded += /* third sextet masked and shifted */\n encoded += /* fourth sextet masked and shifted */\n }\n\n switch (len % 3) {\n case 2:\n encoded += /* first sextet masked and shifted */\n encoded += /* second sextet masked and shifted */\n encoded += /* third sextet masked and shifted */\n encoded += '=';\n break;\n case 1:\n encoded += /* first sextet masked and shifted */\n encoded += /* second sextet masked and shifted */\n encoded += '=';\n encoded += '=';\n break;\n case 0:\n break;\n }\n\n return encoded;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T18:53:07.213", "Id": "412648", "Score": "0", "body": "Note: There are 3 encoded characters per 4 sextet. Thus code should only have 3 instances of `encoded += /* STUFF */;` in each section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T19:01:57.207", "Id": "412651", "Score": "0", "body": "You may want to mention your loop unrolling and switch as an extension of Duff's device." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:29:03.723", "Id": "412667", "Score": "0", "body": "I didn't mention loop unrolling or duff's device because it is neither. This is loop unswitching. Each encoded operation is different, not duplicated, in the loop. The operations in the loop and in the switch only map directly if the switch case is 0 (in which switch case 0 does nothing)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:33:31.670", "Id": "412668", "Score": "0", "body": "On your note, I've interpreted the problem as encoding a series of octets as a padded string of sextets. That means for every group of 3 ASCII characters, there are 4 resulting Base64 encoded characters. ASCII `Man` encodes to `TWFu` in a 6-bit universe represented as ASCII `AZaz09+/`. Similarly, `Ma` encodes to `TWE=` and `M` encodes to `TQ==`. This is essentially how every base64 encoding library operates (plus extras dealing with line length, line separators, and checksums)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T11:38:06.110", "Id": "412736", "Score": "0", "body": "@Snowhawk You should use `1 \\cdot 2` for \\$1 \\cdot 2\\$ instead of `1 \\dot 2`, which looks like \\$1 \\dot 2\\$." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T07:37:50.563", "Id": "213289", "ParentId": "213272", "Score": "3" } } ]
{ "AcceptedAnswerId": "213289", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T22:19:17.003", "Id": "213272", "Score": "2", "Tags": [ "c++", "base64" ], "Title": "C++ ASCII To Base64 String Encoding" }
213272
<p>I've been working with binary files with this last assignment and part of it was to determine the maximum and minimum byte. Initially this was 2 functions but a bonus portion was to make them into 1 function through usage of an <code>enum</code>, I imagine to reinforce their utility. I would like to know if there are better ways of doing this, be it efficient, elegant or otherwise. I'd also like tips on my C code, as this is the first real project I've done in C in several years.</p> <p>I've also included the relevant bits from the header file.</p> <pre><code>#define GOOD 1 #define BAD 0 typedef unsigned int uint; typedef unsigned char byte; typedef enum uMaxOrMin { Max, Min } MaxOrMin; typedef enum uBitStyle { BitsOn, BitsOff } BitStyle; int MaxOrMinValue(byte src[], uint size, byte *val, MaxOrMin mom) { uint srcTemp; uint srcIndex = 0; uint largest; uint smallest; uint* data = src; switch (mom) { case Max: { largest = src[0]; //initialize largest while (*data++) //iterate over binary array { srcTemp = *(src + srcIndex++); //start at beginning of array, grab first byte and increment by 1 if (srcTemp &gt; largest) //current byte is greater than our saved largest byte largest = srcTemp; //set new largest } *val = largest; //return max to caller return GOOD; } case Min: { smallest = src[0]; //initialize smallest while (srcIndex &lt; size) //iterate over binary array { srcTemp = *(src + srcIndex++); //start at beginning of array, grab first byte and increment by 1 if (srcTemp &lt; smallest) //current byte is less than our saved smallest byte smallest = srcTemp; //set new smallest } *val = smallest; //return min to caller return GOOD; } return BAD; //if we hit here, we've failed } } </code></pre> <p>I know that under normal circumstances, C functions should return 0 upon success and -1 or otherwise upon failure, but this configuration was mandated by the assignment.</p> <p>I would like to know why my while loop for BitsOn works but if I use the same construct for BitsOff, <code>while (*data++)</code>, it fails to give me the correct results. Can someone explain this? Perhaps my understanding is lacking here. I'm trying to get more used to pointers so it seems pertinent to maximize my use of them, even in non-ideal circumstances.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T08:04:06.213", "Id": "412572", "Score": "0", "body": "This is off-topic since this code is not working as intended. You could ask for help repairing it at https://stackoverflow.com/." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:55:16.217", "Id": "412586", "Score": "2", "body": "What is `BitStyle`? It doesn't appear to be used anywhere in the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:31:51.047", "Id": "412597", "Score": "0", "body": "It's part of the assignment. It's used to differentiate between on and off bits. It's not used in this function, I mistakenly included it in the post." } ]
[ { "body": "<h1>Program does not work correctly</h1>\n\n<p>Your function says the maximum byte is 0 for the simple test case <code>byte input[] = { 0,0,0,0,0,0,0,1,2,3,4 }</code>. The issue is this line: <code>while (*data++)</code>. You have it correct for the Min case.</p>\n\n<h1>Keep it simple</h1>\n\n<p>A simple for loop is sufficient to iterate through the array, it is much easier to understand. You don't have to deal with pointer arithmetic like <code>*(src + srcIndex++)</code>, just use indexing. </p>\n\n<pre><code>for (index = 0; index &lt; size; ++index)\n{\n if (src[index] &gt; largest)\n {\n largest = src[index];\n }\n}\n</code></pre>\n\n<p>This is still using pointers.</p>\n\n<h1>Check for NULL.</h1>\n\n<p>You have not checked if <code>src</code> or <code>val</code> is NULL. This results in program crash due to dereferencing NULL pointer.</p>\n\n<h1><code>uint* data = src</code>;</h1>\n\n<p>This is dangerous because you are trying to access a <code>char</code> using pointer to <code>int</code>. The result is not what you expect it to be. It should be <code>byte * data = src;</code>. \n<code>uint largest</code> and <code>uint smallest</code> should be <code>byte largest</code> and <code>byte smallest</code>.</p>\n\n<h1>Swap the order of switch condition and loop</h1>\n\n<p>You can simplify your function by swapping the order of iterating over the array and checking if you want maximum or minimum. This way reduces the chance of making copy and paste error like the bug with maximum case.</p>\n\n<p>Your last question is missing some context, you should see if the above solves your problem. If not then post a new question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T07:53:46.003", "Id": "412571", "Score": "0", "body": "\"Check for NULL\" That's nonsense, it is perfectly fine for a function to assume that parameters passed are valid and a superfluous branch checking for NULL only slows the code down." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:50:19.563", "Id": "412686", "Score": "0", "body": "I put check for null because the function return a failure code which I assumed the function should do validation of all its input parameters. Which I now realized the function didn't handle case where mom wasn't min or max." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T03:08:44.750", "Id": "213279", "ParentId": "213275", "Score": "0" } }, { "body": "<p>Your combined function essentially looks like this:</p>\n\n<pre><code>// commonly used variables\nif (min) {\n // code for computing the min\n return minValue;\n} else if (max) {\n // code for computing the max\n return maxValue;\n} else {\n return BAD;\n}\n</code></pre>\n\n<p>Since there is no common code, you should either:</p>\n\n<ul>\n<li>put the calculation for min and max in two separate functions</li>\n<li>merge the code (which makes the code a little slower)</li>\n</ul>\n\n<p>In the current code the variable definitions are too far away from the code that actually uses them. Understanding the code is easier when everything fits on a single screen.</p>\n\n<p>Continuing with your code:</p>\n\n<pre><code>#define GOOD 1\n#define BAD 0\n</code></pre>\n\n<p>These two constants may come from the 1980s or 1990s, when <code>&lt;stdbool.h&gt;</code> was not available yet. Nowadays functions that return success or failure should do so by returning <code>bool</code> instead of <code>int</code>.</p>\n\n<pre><code>typedef unsigned int uint;\ntypedef unsigned char byte;\n\ntypedef enum uMaxOrMin\n{\n Max,\n Min\n} MaxOrMin;\n</code></pre>\n\n<p>Since you don't use the <code>uMaxOrMin</code> name later, you can omit it.</p>\n\n<pre><code>typedef enum uBitStyle\n{\n BitsOn,\n BitsOff\n} BitStyle;\n</code></pre>\n\n<p>This whole enum is unused and should therefore be removed.</p>\n\n<pre><code>int MaxOrMinValue(byte src[], uint size, byte *val, MaxOrMin mom)\n</code></pre>\n\n<p>This function is not supposed to modify the contents of the <code>src</code> array. Therefore it should be declared as <code>const byte src[]</code>.</p>\n\n<p>To avoid the common confusion between <code>*</code> and <code>[]</code> for parameters (only the pointer is passed, not the whole array), it is preferable to write <code>const byte *src</code> instead.</p>\n\n<p>The name of the <code>size</code> param is not as precise as possible. It should rather be <code>src_size</code> to make it unambiguous that it belongs to <code>src</code>.</p>\n\n<pre><code>{\n uint srcTemp;\n</code></pre>\n\n<p>The only time where <code>temp</code> is allowed as part of a variable name is in the popular pattern to swap two variables: <code>tmp = a; a = b; b = tmp</code>. In all other situations there must be a better name.</p>\n\n<pre><code> uint srcIndex = 0;\n</code></pre>\n\n<p>Since there is only one thing that can be indexed here, the <code>src</code> in <code>srcIndex</code> is redundant. The code is short enough that the variable names can be short, too.</p>\n\n<pre><code> uint largest;\n uint smallest;\n uint* data = src;\n\n switch (mom) \n {\n case Max:\n {\n largest = src[0]; //initialize largest\n</code></pre>\n\n<p>Accessing <code>src[0]</code> is only allowed if <code>src_size &gt; 0</code>.</p>\n\n<pre><code> while (*data++) //iterate over binary array\n {\n srcTemp = *(src + srcIndex++); //start at beginning of array, grab first byte and increment by 1\n</code></pre>\n\n<p>There is no point in writing <code>*(ptr + index)</code> since <code>ptr[index]</code> is much clearar to read.</p>\n\n<pre><code> if (srcTemp &gt; largest) //current byte is greater than our saved largest byte\n</code></pre>\n\n<p>Ah, so <code>srcTemp</code> really means \"the current byte\". In that case, the variable should be named <code>curr</code>.</p>\n\n<pre><code> largest = srcTemp; //set new largest \n }\n\n *val = largest; //return max to caller\n</code></pre>\n\n<p>In this assignment, you are storing an <code>unsigned int</code> into a <code>byte</code> variable. Because both are unsigned, this works. Better style would be to make <code>largest</code> a <code>byte</code> variable, too. In other programming languages like Go or Kotlin, assigning values between different-sized variables is a compile-time error, and I find these quite helpful.</p>\n\n<pre><code> return GOOD;\n }\n\n case Min:\n {\n smallest = src[0]; //initialize smallest\n while (srcIndex &lt; size) //iterate over binary array\n</code></pre>\n\n<p>Since <code>min</code> and <code>max</code> are essentially the same algorithms, their code should express this by being essentially the same. You are using two entirely different loops here, which leads to confusion and bugs.</p>\n\n<pre><code> {\n srcTemp = *(src + srcIndex++); //start at beginning of array, grab first byte and increment by 1\n if (srcTemp &lt; smallest) //current byte is less than our saved smallest byte\n smallest = srcTemp; //set new smallest\n }\n\n *val = smallest; //return min to caller\n return GOOD;\n }\n return BAD; //if we hit here, we've failed\n }\n}\n</code></pre>\n\n<p>All in all, your code does not take any advantage of the algorithms being so similar. To combine them in a single piece of code, I suggest this:</p>\n\n<pre><code>#include &lt;assert.h&gt;\n\n#define GOOD 1\n#define BAD 0\n\ntypedef unsigned int uint;\ntypedef unsigned char byte;\n\ntypedef enum {\n Max,\n Min\n} MaxOrMin;\n\nint MaxOrMinValue(const byte *src, uint src_size, byte *result, MaxOrMin mom) {\n if (src_size == 0) {\n return BAD;\n }\n if (mom != Min &amp;&amp; mom != Max) {\n return BAD;\n }\n\n byte mask = (byte) (mom == Max ? -1 : 0);\n byte best = src[0] ^ mask;\n for (uint i = 1; i &lt; src_size; i++) {\n byte curr = src[i] ^ mask;\n if (curr &lt; best) {\n best = curr;\n if (best == 0)\n break;\n }\n }\n\n *result = best ^ mask;\n return GOOD;\n}\n\nint main() {\n byte arr1[] = {0, 1, 2, 3, 4};\n byte arr2[] = {200, 100, 222};\n byte minmax = 13;\n\n assert(MaxOrMinValue(arr1, sizeof arr1, &amp;minmax, Min) == GOOD);\n assert(minmax == 0);\n\n assert(MaxOrMinValue(arr1, sizeof arr1, &amp;minmax, Max) == GOOD);\n assert(minmax == 4);\n\n assert(MaxOrMinValue(arr2, 0, &amp;minmax, Max) == BAD);\n assert(minmax == 4); // unchanged\n\n assert(MaxOrMinValue(arr2, 1, &amp;minmax, Max) == GOOD);\n assert(minmax == 200);\n\n minmax = 123; // to make sure it is overwritten again\n assert(MaxOrMinValue(arr2, 2, &amp;minmax, Max) == GOOD);\n assert(minmax == 200);\n\n assert(MaxOrMinValue(arr2, 3, &amp;minmax, Max) == GOOD);\n assert(minmax == 222);\n\n // Passing neither Min nor Max is bad.\n assert(MaxOrMinValue(arr2, 3, &amp;minmax, 123) == BAD);\n assert(minmax == 222); // unchanged\n}\n</code></pre>\n\n<p>Admitted, using a bitmask to combine the min and max algorithms is tricky. Without using this trick, the code might look like this:</p>\n\n<pre><code>int MaxOrMinValue(const byte *src, uint src_size, byte *result, MaxOrMin mom) {\n if (src_size == 0) {\n return BAD;\n }\n if (mom != Min &amp;&amp; mom != Max) {\n return BAD;\n }\n\n byte best = src[0];\n byte best_possible = mom == Max ? (byte) -1 : (byte) 0;\n for (uint i = 1; i &lt; src_size; i++) {\n byte curr = src[i];\n if (mom == Max ? curr &gt; best : curr &lt; best) {\n best = curr;\n if (best == best_possible) {\n break;\n }\n }\n }\n\n *result = best;\n return GOOD;\n}\n</code></pre>\n\n<p>Oh, nice. The code even got simpler. One thing that bothered me though about this code is the complicated condition in the <code>if (mom == Max ?</code>. I wanted to avoid checking this condition in every loop again <a href=\"https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array\">because of branch prediction and possible performance</a>.</p>\n\n<p>During one call of this function, the outcome of the outer condition will always be the same though (<code>mom</code> does not change at all). Therefore the actual performance penalty might be so small that it is barely measurable. Choosing the faster code would need very careful benchmarks in this case. Therefore, either variant is probably good enough.</p>\n\n<p>Anyway, out of intuition I wanted to avoid as many branches as possible. To avoid the <code>mom == Max</code> condition inside the loop, I quickly analyzed in my head that <code>min == bitinvert(max)</code>, at least for unsigned numbers. And since you defined the <code>byte</code> type as <code>unsigned char</code>, it seemed a good fit. Plus, I wanted to try out this bitmasking idea since I had not seen it anywhere else before.</p>\n\n<p>Finding the idea of using a bitmask to convert between min and max algorithms is something that probably comes with experience, I would be very surprised if any programming beginner would find this by themselves. Even understanding it is difficult enough. For more crazy stuff, have a look at the book <a href=\"https://www.hackersdelight.org/\" rel=\"nofollow noreferrer\">Hacker's Delight</a>.</p>\n\n<p>One nice last thought about this bitmasking technique is that I think it can be extended even further to also allow MinSigned (mask 0b1000_0000) and MaxSigned (mask 0b0111_1111). There might also be even stranger use cases like mask 0b0011_0000 to find the smallest ASCII digit.</p>\n\n<p>Things that the bitmasking technique cannot do are:</p>\n\n<ul>\n<li>find the first uppercase letter from the alphabet (that is, 'A' if it exists somewhere, otherwise 'B', otherwise 'C'). This is because there are 26 uppercase letters, and the <a href=\"https://en.wikipedia.org/wiki/Unicode\" rel=\"nofollow noreferrer\">code point</a> of the 'A' is U+0041, which in binary is 0100_0001. Using this as the bitmask, the smallest bytes would be 'A@CBEDHG', in this order.</li>\n<li>find the largest ASCII digit, for similar reasons.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T11:33:22.937", "Id": "412604", "Score": "0", "body": "Thanks for your criticism. Many of the things you mentioned, such as the `#define` and separating the 2 cases into their own functions, were constraints of the assignment. Otherwise, I would not have written them that way. I appreciate the reasons behind what you said, however. I will respond to the rest of the comment once finished analyzing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T11:59:50.307", "Id": "412606", "Score": "0", "body": "So I've went through and changed my code to reflect your suggestions, and I want to know how you came to this algorithm, using XORs? For example, what was your thought process? I'm only now actually diving into digital logic and I'm finding it difficult to think about algorithms in these terms.\n\nFor everything else, thanks. Appreciate the criticism. Answer accepted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T12:04:24.753", "Id": "412607", "Score": "0", "body": "Also, how does the function know to do the minimum in this scenario? I see the ternary expression, but I would have assumed it would be `mom == Max ? 1 : 0`, yet it still works. How?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T12:43:20.190", "Id": "412610", "Score": "0", "body": "I added some more paragraphs to the answer. Sorry it got so long. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T04:27:54.600", "Id": "412858", "Score": "1", "body": "\"This function is not supposed to modify the contents of the src array. Therefore it must be declared as const byte src[].\" --> _must_ is a bit strong here - yet still a good idea to use `const`. Function would work the same without `const`, yet with `const` 1) may perform faster and 2) work with `const *` arguments." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T11:01:15.210", "Id": "213296", "ParentId": "213275", "Score": "3" } } ]
{ "AcceptedAnswerId": "213296", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T23:27:33.297", "Id": "213275", "Score": "1", "Tags": [ "c", "homework", "search" ], "Title": "Calculating the minimum and maximum of a byte array" }
213275
<p>Here is a program I wrote to reproduce the known win proportions for random Tic Tac Toe games (X always moving first). It takes about a minute to play the one million random games that will be played if you run main.py after putting all the below .py files in the same directory. (The program does reproduce the correct results.)</p> <p>I'm studying design principles for keeping large code bodies structured for easier maintenance.</p> <p>I'm trying to:</p> <ul> <li>focus on classes where everything is at the same level of abstraction</li> <li>make sure that everything in a class very clearly belongs in that class</li> <li>make it so that the reader can understand the current method he/she is reading without knowing what is happening anywhere else in the program</li> </ul> <p>I'd appreciate some feedback on how I can improve on the above issues. The code should be a fast read. But to make it even faster, may I explain what I was thinking about each class? (main.py has no class of its own... it just gets the program going).</p> <ul> <li>For the <code>GamesEngine</code> class I was thinking that no force would cause games to play, moves to be made, or reports to be run, so the engine is the needed force.</li> <li>For the <code>GameState</code> class I tried to put only the minimum information needed to hold the current board and the relevant information the comes with the current board.</li> <li>For the <code>GameRules</code> class I tried to only put the rules that are needed to make conclusions about the current board (i.e. is there a win or a tie on the board).</li> <li>Finally, the <code>ReportOnGame</code> class prints the final board for a single game along with who won, while the <code>ReportOnManyGames</code> class finds the proportions of X wins, O wins, and ties over many games.</li> </ul> <p>Any thoughts on design would be much appreciated. (And if you see any improvements that can be made that aren't design related I'd love to hear about them.)</p> <p><strong>main.py</strong></p> <pre><code>from games_engine import GamesEngine from report_on_game import ReportOnGame from report_on_many_games import ReportOnManyGames games_engine = GamesEngine() report_on_game = ReportOnGame() report_on_many_games = ReportOnManyGames() # Pass True to set_end_of_game_reporting to report on each game report_on_game.set_end_of_game_reporting(False) # parameter passed to play_games determines the number of games that will be played games_engine.play_game(1000000) # shows percentage of wins from X and O as well as percentage of ties report_on_many_games.report_outcome_statistics() </code></pre> <p><strong>games_engine.py</strong></p> <pre><code>import random from game_state import GameState from game_rules import GameRules from report_on_game import ReportOnGame from report_on_many_games import ReportOnManyGames class GamesEngine: def __init__(self): self.game_state = GameState() self.game_rules = GameRules() self.report_on_game = None self.report_on_many_games = ReportOnManyGames() # responsible for playing the number of games requested from main.py def play_game(self, number_of_games): while number_of_games &gt; 0: self.report_on_game = ReportOnGame() self.game_state = GameState() game_in_progress = True while game_in_progress: game_in_progress = self.make_move() number_of_games -= 1 def make_move(self): # randomly select an available square from the available_squares set, and store as a list of length 1 position_as_list_of_list = random.sample(self.game_state.available_squares, 1) row_index = position_as_list_of_list[0][0] column_index = position_as_list_of_list[0][1] # remove the available square we will shortly use from the available_squares list self.game_state.available_squares.remove([row_index, column_index]) # make move self.game_state.board[row_index][column_index] = self.game_state.next_move # call game_over to see if the game is over if self.game_rules.game_over(self.game_state, row_index, column_index): self.between_game_reporting(self.game_rules.winning_letter) return False # update who moves next temp = self.game_state.next_move self.game_state.next_move = self.game_state.previous_move self.game_state.previous_move = temp return True def between_game_reporting(self, win_result='Tie'): if self.report_on_game.end_of_game_report: self.report_on_game.end_of_game_reporter(self.game_state, win_result) self.report_on_many_games.track_game_outcomes(win_result) </code></pre> <p><strong>game_state.py</strong></p> <pre><code>class GameState: def __init__(self): self.board = None self.available_squares = None self.initialize_board_and_available_squares() self.next_move = 'X' self.previous_move = 'O' def initialize_board_and_available_squares(self): self.board = [[' ' for i in range(3)] for j in range(3)] self.available_squares = [[i, j] for i in range(3) for j in range(3)] # Printing an instance of the class will display a standard # tic tac toe game image. def __str__(self): return "\n" + self.board[0][0] + "|" + self.board[0][1] + "|" + self.board[0][2] + "\n"+ self.board[1][0] + "|" + self.board[1][1] + "|" + self.board[1][2] + "\n" + self.board[2][0] + "|" + self.board[2][1] + "|" + self.board[2][2] </code></pre> <p><strong>game_rules.py</strong></p> <pre><code>class GameRules: def __init__(self): self.letter_dict = {'X': -1, 'O': 1, ' ': 0} self.winning_letter = None def game_over(self, game_state, row_index, column_index): # check row containing most recent move for win total = 0 for column in range(3): total = total + int(self.letter_dict[game_state.board[row_index][column]]) if abs(total) == 3: self.winning_letter = game_state.board[row_index][column_index] return True # check column containing most recent move for win total = 0 for row in range(3): total = total + int(self.letter_dict[game_state.board[row][column_index]]) if abs(total) == 3: self.winning_letter = game_state.board[row_index][column_index] return True # check for win on main-diagonal if it contains most recent move if row_index == column_index: total = 0 for diagonal_indexing in range(3): total = total + int(self.letter_dict[game_state.board[diagonal_indexing][diagonal_indexing]]) if abs(total) == 3: self.winning_letter = game_state.board[row_index][column_index] return True # check for win on off-diagonal if it contains most recent move if row_index + column_index == 2: total = 0 for off_diagonal_indexing in range(3): total = total + int(self.letter_dict[game_state.board[off_diagonal_indexing][2 - off_diagonal_indexing]]) if abs(total) == 3: self.winning_letter = game_state.board[row_index][column_index] return True if len(game_state.available_squares) == 0: self.winning_letter = 'Tie' return True return False </code></pre> <p><strong>report_on_game.py</strong></p> <pre><code>class ReportOnGame: end_of_game_report = False @classmethod def set_end_of_game_reporting(cls, boolean_set): cls.end_of_game_report = boolean_set # call turn_on_end_of_game_reporting from main.py to run this report method @staticmethod def end_of_game_reporter(board, result='Its a tie'): print(board) if result == 'X': print(result + ' won\n') elif result == 'O': print(result + ' won\n') else: print(result + '\n') </code></pre> <p><strong>report_on_many_games.py</strong></p> <pre><code>class ReportOnManyGames: number_of_x_wins = 0 number_of_o_wins = 0 number_of_ties = 0 @classmethod def track_game_outcomes(cls, win_result): if win_result == 'X': cls.number_of_x_wins = cls.number_of_x_wins + 1 if win_result == 'O': cls.number_of_o_wins = cls.number_of_o_wins + 1 if win_result == 'Tie': cls.number_of_ties = cls.number_of_ties + 1 @classmethod def report_outcome_statistics(cls): total_games = cls.number_of_x_wins + cls.number_of_o_wins + cls.number_of_ties print('Proportion of X wins: ' + str(cls.number_of_x_wins/total_games)) print('Proportion of O wins: ' + str(cls.number_of_o_wins / total_games)) print('Proportion of ties: ' + str(cls.number_of_ties / total_games)) </code></pre>
[]
[ { "body": "<p>While your goal may be to \"make it so the reader can understand the current method they are reading\", I actually found it very confusing to read the code.</p>\n\n<p>Consider:</p>\n\n<pre><code>from games_engine import GamesEngine\nfrom report_on_game import ReportOnGame\nfrom report_on_many_games import ReportOnManyGames\n</code></pre>\n\n<p>Ok, so <code>games_engine</code>, <code>report_on_game</code>, and <code>report_on_many_games</code> all modules, but only one class from each module is imported to the top-level namespace; the modules themselves are not added to the top-level namespace. Later:</p>\n\n<pre><code>report_on_game.set_end_of_game_reporting(False)\ngames_engine.play_game(1000000)\nreport_on_many_games.report_outcome_statistics()\n</code></pre>\n\n<p>Wait. None of those modules were imported to the top-level namespace. What is going on??? Confusion!!! This continues with <code>self.report_on_game</code> and <code>self.game_state</code> and <code>self.game_rules</code> and so on. Is <code>report_on_game</code> a module name, a global variable name, or a class member??? The answer is all three! This same name different semantics does not help readability.</p>\n\n<p>One class per file is not the Pythonic way of doing things, and as you can see, it is causing naming confusion. I'd recommend one file ... maybe <code>tic_tac_toe.py</code> with all 5 of your classes in that one file, and perhaps even the <code>main</code> function</p>\n\n<hr>\n\n<p><code>GameEngine.play_game</code> doesn't play a game. It plays a bunch of games. Separate this into two functions: one to play a game, and one which repeatedly calls the former to play multiple games.</p>\n\n<pre><code>def play_game(self):\n\n self.game_state = GameState()\n game_in_progress = True\n\n while game_in_progress:\n game_in_progress = self.make_move()\n\n # Maybe add end-of-game reporting here.\n\n\ndef play_games(self, number_of_games):\n\n for _ in range(number_of_games):\n self.play_game()\n\n # Maybe add end-of-all-games reporting here\n</code></pre>\n\n<hr>\n\n<p>Why does <code>self.make_move()</code> return <code>game_in_progress</code>? Perhaps <code>GameState</code> should contain the <code>in_progress</code> member. After all, whether the game is over (and even who won!), is part of the game state!</p>\n\n<pre><code>def play_game(self):\n self.game_state = GameState()\n\n while self.game_state.in_progress:\n self.make_move()\n\n # Maybe add end-of-game reporting here.\n</code></pre>\n\n<hr>\n\n<p><code>make_move()</code> should really be called <code>make_random_move()</code> to be clear that it is just making random moves.</p>\n\n<hr>\n\n<p><code>GameRules.game_over()</code> is both returning a value directly, and returning a value through an evil, secret, underhanded modifying <code>self.winning_letter</code> state variable.</p>\n\n<p>It could simply return one of 4 values: <code>\"X\"</code>, <code>\"O\"</code>, <code>\"Tie\"</code> or <code>\"\"</code>. An empty string, which is a <code>False</code>-ish value would indicate the game is not yet over, while the other three <code>True</code>-ish values would simultaneously indicate the game is over as well as who won.</p>\n\n<hr>\n\n<p>You are confusing classes for method containers, and creating classes with no data.</p>\n\n<p>Consider <code>ReportOnGame</code>. It has no per-instance data, just two static methods and a class variable. There is never a reason to create a <code>ReportOnGame()</code> instance because it doesn't contain any data, and yet you create 1 million instances of it.</p>\n\n<p>Yes, you do access <code>self.report_on_game.end_of_game_report</code> and call <code>self.report_on_game.end_of_game_reporter(...)</code>, which appears to be using an instance of the <code>ReportOnGame()</code> object, but since that instance has no instance data, you could just as easily wrote:</p>\n\n<pre><code>if ReportOnGame.end_of_game_report:\n ReportOnGame.end_of_game_reporter(self.game_state, win_result)\n</code></pre>\n\n<p>and never created the objects.</p>\n\n<p>But it doesn't end there. The <code>.end_of_game_report</code> is a global variable contained in different class in a module from <code>GameEngine</code>. Why does that foreign class &amp; module have a flag that controls what <code>GameEngine</code> does?</p>\n\n<p>It would be (slightly) better for <code>ReportOnGame</code> to internally check the flag when reporting:</p>\n\n<pre><code>class ReportOnGame:\n end_of_game_report = False\n #...\n @staticmethod\n def end_of_game_reporter(board, result='Its a tie'):\n if ReportOnGame.end_of_game_report:\n print(board)\n # ... etc ...\n</code></pre>\n\n<p>And then you could unconditionally call <code>ReportOnGame.end_of_game_reporter(self.game_state, win_result)</code> in <code>GameEngine</code>, without needing to reach into another class in another module to access the global variable.</p>\n\n<p>But <code>ReportOnGame.end_of_game_reporter(...)</code> is still just a static function; it does not warrant a class.</p>\n\n<hr>\n\n<p>How would I re-write this?</p>\n\n<p>As I mentioned above, it would be inside a single <code>tic_tac_toe.py</code> module.</p>\n\n<p>End of game reporting would simply be a function:</p>\n\n<pre><code>def end_of_game_report(board, result):\n print(board)\n if result != 'Tie':\n print(result + ' won.')\n else:\n print(\"Tie game.\")\n</code></pre>\n\n<p><code>GameEngine</code> could have a <code>reporters</code> member, containing a list of methods to call to report the game result:</p>\n\n<pre><code>class GameEngine:\n def __init__(self, *reporters):\n self._reporters = reporters\n\nengine = GameEngine(end_of_game_report)\nengine.play(5)\n</code></pre>\n\n<p>After each game is over, the engine would need to call all of the reporters, passing in the board state and result.</p>\n\n<pre><code>for reporter in self._reporters:\n reporter(self._board, win_result)\n</code></pre>\n\n<p>And if you don't want a report after each game, you simply don't need to pass <code>end_of_game_report</code> in the list of reporters. If it is not in the list, it doesn't get called. No boolean flags required.</p>\n\n<p>As for <code>ReportOnManyGames</code>, the 3 static variables can be replaced with a counter dictionary. An object of that class can be made callable, so it can be used as a reporter, above.</p>\n\n<pre><code>class ReportOnManyGames:\n\n def __init__(self):\n self._counts = { 'X':0, 'O':0, 'Tie':0 }\n\n def __call__(self, board, result):\n self._counts[result] += 1\n\n def report_outcome_statistics(self):\n total_games = sum( self._counts.values() )\n\n print('Proportion of X wins: {:5.2f}%'.format(self._counts['X'] / total_games * 100))\n # ... etc ...\n</code></pre>\n\n<p>Now you can create a callable object which keeps track of the total wins and ties.</p>\n\n<pre><code>summarizer = ReportOnManyGames()\n\nengine = GameEngine(summarizer) # omit end_of_game_report, since we have a million games\nengine.play(1_000_000)\n\nsummarizer.report_outcome_statistics()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T05:45:33.110", "Id": "213283", "ParentId": "213277", "Score": "5" } } ]
{ "AcceptedAnswerId": "213283", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T02:30:03.927", "Id": "213277", "Score": "3", "Tags": [ "python", "object-oriented", "tic-tac-toe", "simulation" ], "Title": "Design of a Tic Tac Toe program in Python" }
213277
<p>The task:</p> <blockquote> <p>Given an integer list where each number represents the number of hops you can make, determine whether you can reach to the last index starting at index 0.</p> <p>For example, <code>[2, 0, 1, 0]</code> returns <code>true</code> while <code>[1, 1, 0, 1]</code> returns <code>false</code>.</p> </blockquote> <p>My solutions:</p> <pre><code>// functional: const reachLastIndexOf = (arr, start) =&gt; { if (arr[start] === undefined) return false; const next = start + arr[start]; if (start === next || next &gt;= arr.length) return false; if (next === arr.length -1) return true; return reachLastIndexOf(arr, next); } console.log(reachLastIndexOf([2, 0, 1, 0], 0) // imperative: const reachLastIndexOf2 = arr =&gt; { let start = 0; while(start &lt; arr.length) { // I'm tempted to write `while(true)` here if (arr[start] === undefined) return false; const next = start + arr[start]; if (start === next || next &gt;= arr.length) return false; if (next === arr.length - 1) return true; start = next; } } console.log(reachLastIndexOf2([1, 1, 0, 1])); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T04:38:07.530", "Id": "412560", "Score": "0", "body": "I dare say you misinterpreted the semantics. The problem says `can`, while you take it as `must`. Usually such problems imply that any hop less or equal than `arr[start]` is valid; otherwise it is trivial indeed. Could you share a link to the original problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T04:53:10.997", "Id": "412561", "Score": "0", "body": "I don't have a link to the original problem. It's all the information that I got." } ]
[ { "body": "<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">Default Parameters</a></h1>\n\n<p>When can compare the method signatures of the iterative approach and the functional one, we can see, that for the functional one we have to append the <code>0</code> on the first call.</p>\n\n<p>If you want to avoid this - and in this case I think it makes sense - you can add a default parameter into the method signature: <code>const reachLastIndexOf = (arr, start = 0)</code></p>\n\n<h1>Long Condition &amp; <a href=\"http://learnyouahaskell.com/syntax-in-functions\" rel=\"nofollow noreferrer\">Pattern Matching</a></h1>\n\n<p>The condition <code>start === next || next &gt;= arr.length</code> is currently in on if-statement. The <code>||</code>-operator operates short-circuit - that means if the first operation is true, the compiler don't validates the second condition. When we split the disjuncture into to two if-statements, we can keep the same short-circuit behavior and create a more <a href=\"http://learnyouahaskell.com/syntax-in-functions\" rel=\"nofollow noreferrer\">pattern-matching</a> look and feel:</p>\n\n<pre><code>if (start === next) return false \nif (next &gt;= arr.length) return false\n</code></pre>\n\n<p>The advantage is that you have a less logical operator. The less code, the fewer errors and at the same time the readability is increased.<br>\nPlease note that I have meant this more generally for conditions, even if in this context only a Boolean operator is avoided, the code is still more readable in my view than before.</p>\n\n<h1>Readable Method Names</h1>\n\n<p>For this algorithm we need to check if:</p>\n\n<ul>\n<li>an index exists (<code>arr[start] === undefined</code>)</li>\n<li>an index stays on the same place (<code>start === next</code>)</li>\n<li>an index is out of the array bound (<code>next &gt;= arr.length</code>) </li>\n<li>an index reached the end (<code>next === arr.length - 1</code>)</li>\n</ul>\n\n<p>We all now what these checks are meaning but it would be much better if we wrap these into their own functions</p>\n\n<pre><code>const reachLastIndexOf = (arr, start = 0) =&gt; {\n if (isIndexDefined(arr, start)) return false; \n\n const next = start + arr[start];\n\n if (isStayingInTheSamePosition(start, next)) return false\n if (isOverArrayBound(next, arr)) return false\n if (isReachingTheEnd(next, arr)) return true\n return reachLastIndexOf(arr, next)\n}\n</code></pre>\n\n<hr>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const reachLastIndexOf = (arr, start = 0) =&gt; {\n if (isIndexDefined(arr, start)) return false;\n\n const next = start + arr[start];\n\n if (isStayingInTheSamePosition(start, next)) return false\n if (isOverArrayBound(next, arr)) return false\n if (isReachingTheEnd(next, arr)) return true\n return reachLastIndexOf(arr, next)\n}\n\n\nconst isIndexDefined = (array, index) =&gt; array[index] === undefined\nconst isStayingInTheSamePosition = (start, next) =&gt; start === next\nconst isOverArrayBound = (next, array) =&gt; next &gt;= array.length\nconst isReachingTheEnd = (next, array) =&gt; next === array.length - 1\n\nconsole.log(reachLastIndexOf([2, 0, 1, 0], 0));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:50:18.697", "Id": "412585", "Score": "0", "body": "What's the advantage of having a \"pattern matching look and feel\" resp. what is the disadvantage if we don't have this \"pattern matching look and feel\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:10:28.293", "Id": "412589", "Score": "0", "body": "@thadeuszlay I added a reason to my answer. In short, you have one less condition and less cause for error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:25:08.530", "Id": "412595", "Score": "0", "body": "I'm not sure whether it's worth it to have separate function for checking each of the conditions, because I'd have to go that function (which may be on a different file or further away, i.e. I have to scroll to the top or bottom of the current file). But writing it out loud in the current line, it makes it more clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:54:01.180", "Id": "412601", "Score": "0", "body": "Maybe I haven't fully understand pattern matching, but I don't see much benefit in comparison to a simple `swtich-case` construct." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:04:50.117", "Id": "213290", "ParentId": "213278", "Score": "1" } }, { "body": "<h2>Undelimited blocks as bad</h2>\n\n<p>While most C syntax like languages allow for undelimited statement blocks <code>if (foo) bar;</code> (proof of just how lazy coders can be) it does contribute to one of the most common and hard to spot syntax derived bugs when later modify code. </p>\n\n<p>You can easily overlook the block delimiters while entering code your mind on the problem, and not the syntax. Later when trying to spot the error it is hard to find as the error looks like a logic error but is in reality a syntax error. </p>\n\n<p>In my view undelimited blocks are a strict no no. If you always add block delimiters then you will save your self many hours of frustration.</p>\n\n<pre><code>// Bad \nif (next === arr.length - 1) \n return true;\n\n// Good\nif (next === arr.length - 1) return true;\n\n// Better\nif (next === arr.length - 1) {\n return true;\n}\n\n// Best\n// Note in JS the semicolon is not required for a line terminated with a } and there\n// are no edge cases that make this problematic\nif (next === arr.length - 1) { return true }\n</code></pre>\n\n<h2>General rule of release.</h2>\n\n<ul>\n<li><p>Never release any code until at minimum every line has been parsed and run. There is a syntax error <code>console.log(reachLastIndexOf([2, 0, 1, 0], 0)</code> is missing a closing <code>)</code></p></li>\n<li><p>You should consider code that has not been thoroughly tested as broken. You test code with an aim to find failure.</p></li>\n</ul>\n\n<p>Your code fails if there is a cyclic loop, eg <code>reachLastIndexOf([2, 1, -2, 0])</code></p>\n\n<p>For the functional style this will throw an error when the call stack overflows, for the imperative style this bug is one of JS ugliest errors as the while loop will run forever and the only way out is via client interaction (navigate off the page, or wait for the timeout dialog to crash the page).</p>\n\n<p><strong>Note</strong> that the functional style throws an error, however with ES6 the language was to have proper tail calls (means that function calls (depending on the way you call/recurse at the end) will not consume the call stack). \nThe implication is that at any time the functional style infinite loop may become blocking like the imperative style so don't use a <code>try catch</code> to solve infinite recursion.</p>\n\n<h2><code>While (true) {</code></h2>\n\n<p>In the past setting up in infinite loop in JS had a severe performance penalty as it confused the optimiser. </p>\n\n<p>To prevent the optimiser from attempting to optimise (wasting precious CPU cycles) code with no clear exit from such a loop it was automatically marked as \"Do not optimise\". The whole function containing the loop and all code within that functions scope was marked.</p>\n\n<p>I am currently unsure if this remains true as Dev Tools no longer displays the <code>Do Not Optimise</code> tag on code. </p>\n\n<p>I am of two minds as to deliberate infinite loops however, favouring your approach, even if it's just a dummy exit condition that is never acted on. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T14:19:52.250", "Id": "213306", "ParentId": "213278", "Score": "1" } }, { "body": "<pre><code>const algo = (arr, idx) =&gt; {\n\n while (idx &lt; arr.length - 1) {\n if (arr[idx] === 0) return false;\n idx += arr[idx];\n }\n return true;\n}\n</code></pre>\n\n<p>shorter and cleaner, edge cases skipped</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T20:29:22.830", "Id": "476044", "Score": "0", "body": "What is `algo` supposed to accomplish? The name suggests nothing to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T21:15:02.670", "Id": "476046", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-19T19:16:54.893", "Id": "242586", "ParentId": "213278", "Score": "1" } } ]
{ "AcceptedAnswerId": "213306", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T03:04:42.293", "Id": "213278", "Score": "3", "Tags": [ "javascript", "functional-programming" ], "Title": "Reach to the last index starting at index 0" }
213278
<p>This is code I wrote to check a product structure from 1 table in a database. It's based on a type which can have area(s) and area(s) can have group(s).</p> <p>I have:</p> <pre><code>type and code area: blank group: blank type and area and code group:blank type and area and group and code </code></pre> <p>As you can see, it is stacked and the lookup is layered to find the correct code. Is there something I can do to improve it?</p> <pre><code>Public Function StackLayeredLookup() Dim Start As Integer Dim lStart As Integer Dim cRows As Integer Dim lRows As Integer Dim TypeValue As String Dim TypeCode As String Dim AreaValue As String Dim AreaCode As String Dim GroupValue As String Dim GroupCode As String Dim aValue As String Dim dValue As String Const TypeCol = "G" Const AreaCol = "H" Const GroupCol = "I" Const RegCol = "E" Const tValueCol = "P" Const aValueCol = "Q" Const gValueCol = "R" 'Region = "MEX" Start = 2 cRows = Worksheets(2).UsedRange.Rows.Count lRows = Worksheets("TagCodes").UsedRange.Rows.Count Do Until Start = cRows TypeValue = Worksheets(2).Range(TypeCol &amp; CStr(Start)).Value AreaValue = Worksheets(2).Range(AreaCol &amp; CStr(Start)).Value GroupValue = Worksheets(2).Range(GroupCol &amp; CStr(Start)).Value If (TypeValue &lt;&gt; "") Then TypeCode = "" lStart = 1 Do Until TypeCode &lt;&gt; "" Or lStart = lRows + 1 If (Worksheets("TagCodes").Range("A" &amp; CStr(lStart)).Value = TypeValue) Then aValue = Worksheets("TagCodes").Range("C" &amp; CStr(lStart)).Value gValue = Worksheets("TagCodes").Range("D" &amp; CStr(lStart)).Value If (aValue = " " And gValue = " ") Then Worksheets(2).Range(tValueCol &amp; CStr(Start)).Value = Worksheets("TagCodes").Range("B" &amp; CStr(lStart)).Value TypeCode = Worksheets(2).Range(tValueCol &amp; CStr(Start)).Value Exit Do End If Else lStart = lStart + 1 End If Loop If (TypeCode = "") Then Worksheets(2).Range(TypeCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) Else Worksheets(2).Range(TypeCol &amp; CStr(Start)).Interior.Color = RGB(0, 255, 0) End If If (TypeCode &lt;&gt; "" And AreaValue &lt;&gt; "") Then AreaCode = "" lStart = 1 Do Until AreaCode &lt;&gt; "" Or lStart = lRows + 1 If (Worksheets("TagCodes").Range("A" &amp; CStr(lStart)).Value = AreaValue) Then gValue = Worksheets("TagCodes").Range("D" &amp; CStr(lStart)).Value If (Worksheets("TagCodes").Range("B" &amp; CStr(lStart)).Value = TypeCode And gValue = " ") Then Worksheets(2).Range(aValueCol &amp; CStr(Start)).Value = Worksheets("TagCodes").Range("C" &amp; CStr(lStart)).Value AreaCode = Worksheets(2).Range(aValueCol &amp; CStr(Start)).Value Exit Do Else lStart = lStart + 1 End If Else lStart = lStart + 1 End If Loop If (AreaCode = "") Then Worksheets(2).Range(AreaCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) Else Worksheets(2).Range(AreaCol &amp; CStr(Start)).Interior.Color = RGB(0, 255, 0) End If If (TypeCode &lt;&gt; "" And AreaCode &lt;&gt; "" And GroupValue &lt;&gt; "") Then GroupCode = "" lStart = 1 Do Until GroupCode &lt;&gt; "" Or lStart = lRows + 1 If (Worksheets("TagCodes").Range("A" &amp; CStr(lStart)).Value = GroupValue) Then If (Worksheets("TagCodes").Range("B" &amp; CStr(lStart)).Value = TypeCode And Worksheets("TagCodes").Range("C" &amp; CStr(lStart)).Value = AreaCode And Worksheets("TagCodes").Range("D" &amp; CStr(lStart)).Value &lt;&gt; " ") Then Worksheets(2).Range(gValueCol &amp; CStr(Start)).Value = Worksheets("TagCodes").Range("D" &amp; CStr(lStart)).Value GroupCode = Worksheets(2).Range(gValueCol &amp; CStr(Start)).Value Exit Do Else lStart = lStart + 1 End If Else lStart = lStart + 1 End If Loop If (GroupCode = "") Then Worksheets(2).Range(GroupCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) Else Worksheets(2).Range(GroupCol &amp; CStr(Start)).Interior.Color = RGB(0, 255, 0) End If Else Worksheets(2).Range(GroupCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) End If Else Worksheets(2).Range(AreaCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) Worksheets(2).Range(GroupCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) End If Else Worksheets(2).Range(TypeCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) Worksheets(2).Range(AreaCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) Worksheets(2).Range(GroupCol &amp; CStr(Start)).Interior.Color = RGB(255, 0, 0) End If Start = Start + 1 Loop End Function </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T04:01:51.347", "Id": "213282", "Score": "2", "Tags": [ "vba" ], "Title": "Stack layered lookup" }
213282
<p>I'm supposed to create a website that adds multiple forms to the page, is responsive and checks if the inputs are valid (validation is not important, just needs to show some attempt at regex). Below is what I've written so far. What I'm looking for is any advice on making it more efficient and compact. Any and all help is appreciated and considered. Thanks in advance!</p> <p><strong>index.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en-US"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;index.html&lt;/title&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt; &lt;/head&gt; &lt;body onload="execute()" id="body"&gt; &lt;h3&gt;Content Below:&lt;/h3&gt; &lt;div id="buffer"&gt; &lt;div id="content"&gt; &lt;!-- Content will go here --&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="info"&gt; &lt;!-- Info will go here --&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>script.js</strong></p> <pre><code>function ContentDisplayer() { this.count = 0; this.show = function(id) { var tag = document.getElementById(id); tag.style.display = 'block'; } this.showText = function(id, content) { var tag = document.getElementById(id); tag.innerHTML = content; } this.constructForm = function(containing_id, question) { //Create div containing the form var div_tag = document.createElement('div'); div_tag.id = 'div_' + this.count; document.getElementById('body').appendChild(div_tag); //Create the form tag var form_tag = document.createElement('form'); form_tag.id = 'form_' + this.count; document.getElementById(div_tag.id).appendChild(form_tag); //Create the fieldset tag var fieldset_tag = document.createElement('fieldset'); fieldset_tag.id = 'fieldset_' + this.count; document.getElementById(form_tag.id).appendChild(fieldset_tag); //Create question label var label_tag = document.createElement('label'); var label_text = document.createTextNode(question); label_tag.appendChild(label_text); label_tag.id = 'label_' + this.count; document.getElementById(fieldset_tag.id).appendChild(label_tag); //insert line break var break_tag = document.createElement('br'); document.getElementById(fieldset_tag.id).appendChild(break_tag); //Create answer label var input_tag = document.createElement('input'); input_tag.id = 'input_' + this.count; input_tag.type = 'text'; document.getElementById(fieldset_tag.id).appendChild(input_tag); //insert line break var break_tag = document.createElement('br'); document.getElementById(fieldset_tag.id).appendChild(break_tag); //Create button var button_tag = document.createElement('button'); var button_text = document.createTextNode('Submit'); button_tag.appendChild(button_text); button_tag.type = 'button'; button_tag.id = 'button_' + this.count; button_tag.onclick = function() { var x = document.getElementById(input_tag.id); if(input_tag.id == 'input_0') { if(/^[a-zA-Z]+$/.test(x.value)) { x.style.backgroundColor = "green"; x.style.borderColor = "green"; } } if(input_tag.id == 'input_1') { if((/^[0-9]+$/.test(x.value)) &amp;&amp; x.value &gt; 0 &amp;&amp; x.value &lt;= 100) { x.style.backgroundColor = "green"; x.style.borderColor = "green"; } } if(input_tag.id == 'input_2') { if(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(x.value)) { x.style.backgroundColor = "green"; x.style.borderColor = "green"; } } if(input_tag.id == 'input_3') { if(/\d{1,5}\s\w{1,10}\s\w{1,10}/.test(x.value)) { x.style.backgroundColor = "green"; x.style.borderColor = "green"; } } if(input_tag.id == 'input_4') { if(/^\d{3}-\d{3}-\d{4}$/.test(x.value)) { x.style.backgroundColor = "green"; x.style.borderColor = "green"; } } } document.getElementById(fieldset_tag.id).appendChild(button_tag); this.count += 1; } } var c; var questions = [ 'Enter your first name', 'Enter your age', 'Enter your email', 'Enter your address', 'Enter your phone number (must use dashes): ###-###-####' ]; var question_ids = [ 'name_content', 'age_content', 'email_content', 'address_content', 'phone_content' ]; function execute() { c = new ContentDisplayer(); c.show('buffer'); c.showText('content', '&lt;h1&gt;Hello!&lt;/h1&gt;'); c.showText('info', 'If the box turns green, the information is valid!'); //create loop to add forms to page for (var i = 0; i &lt; questions.length; i++) { c.constructForm(question_ids[i], questions[i]); } } </code></pre> <p><strong>style.css</strong></p> <pre><code>body { font-family: "Times New Roman", Times, serif; background-color: pink; } .buffer { display: none; } input[type=text] { border: 2px solid red; border-radius: 4px; background-color: #f44242; margin: 1px; } input[type=text]:focus { border: 2px solid blue; border-radius: 4px; background-color: #41dcf4; } button { background-color: green; border: none; border-radius: 6px; color: white; text-align: center; font-size: 16px; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T11:44:14.923", "Id": "413215", "Score": "0", "body": "The question title is a little misleading; my first thought was something like `jsdom`." } ]
[ { "body": "<h1>Duplicate If-Statements</h1>\n\n<p>You have 5 validations that look all the same. You could write a function to get ride of the duplication.</p>\n\n<p>The function could look like:</p>\n\n<pre><code>function makeGreenIfValidationIsValid(tagId, regex) {\n if(input_tag.id == tagId) {\n if(regex.test(x.value)) {\n x.style.backgroundColor = \"green\";\n x.style.borderColor = \"green\";\n }\n }\n}\n</code></pre>\n\n<p>After that, the <code>onClick</code>-calback would look like</p>\n\n<pre><code>button_tag.onclick = function() {\n var x = document.getElementById(input_tag.id);\n makeGreenIfValidationIsValid('input_0', /^[a-zA-Z]+$/)\n makeGreenIfValidationIsValid('input_1', /^[0-9]+$/)\n makeGreenIfValidationIsValid('input_2', /^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$/)\n makeGreenIfValidationIsValid('input_3', /\\d{1,5}\\s\\w{1,10}\\s\\w{1,10}/)\n makeGreenIfValidationIsValid('input_4', /^\\d{3}-\\d{3}-\\d{4}$/)\n\n document.getElementById(fieldset_tag.id).appendChild(button_tag);\n\n this.count += 1;\n}\n</code></pre>\n\n<h1>Extract Class</h1>\n\n<p>The method <code>constructForm</code> in <code>ContentDisplayer</code> should be a own class. An indicator for that is that it is huge (more than 80 lines) and you have many tag-comments in it. </p>\n\n<p>Comments are add all not bad but when you group your code in a method you all ready see semi-independent logic. In Robert C. Martins words: <a href=\"https://www.goodreads.com/author/quotes/45372.Robert_C_Martin?page=2\" rel=\"nofollow noreferrer\">“Don’t Use a Comment When You Can Use a Function or a Variable”</a></p>\n\n<p>For example, the class might be named \"Form\" and could contain several methods. Based on your comments I could look like</p>\n\n<pre><code>function Form() {\n\n //Create div containing the form\n this.createDivTag() {}\n\n //Create the form tag\n this.createFormTag() {}\n\n //Create the fieldset tag\n this.createFieldsetTag() {}\n\n}\n</code></pre>\n\n<p>The logic in <code>create[tag-name]Tag</code> for creating a <code>div</code>, <code>form</code> and <code>fieldset</code> looks very similar. We should extract the common logic into a function.</p>\n\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance\" rel=\"nofollow noreferrer\">Prototyping</a></h1>\n\n<p>Currently <code>ContentDisplayer</code> and <code>Form</code> (the class from above) don't use it.</p>\n\n<p>A disadvantage is that on each creation of an object all methods like <code>show</code> will be recreated each time. The result is that it costs performance.</p>\n\n<p>With prototyping it would look like</p>\n\n<pre><code>function ContentDisplayer() {\n this.count = 0;\n}\n\nContentDisplayer.prototype.show = function(id) {/**/}\n\nContentDisplayer.prototype.showText = function(id, content) {/**/}\n\n// ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T07:51:09.817", "Id": "412570", "Score": "0", "body": "Compiled functions are cached. There is no performance gain by creating an external prototype. External prototypes do not allow the use of closure to create private members. Even way back when compilation was not cached external prototypes provided no benefit for single instance objects which is what is being used in this case. In modern JS external prototypes only provide a benefit when there are many instances (100+ to 1000+) with short lifetimes that are longer than a single GC cycle, with most of the small benifit in reduced GC overhead" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T08:07:07.847", "Id": "412573", "Score": "1", "body": "`makeGreenIfValidationIsValid(tagId, regex)` - I like the name! It's exactly what I'd come up with because I suck at being concise, so I just go with \"long, boring but descriptive\". Still, I'd personally inverse the order of the parameters passed in. That way you can very easily [partially apply](https://en.wikipedia.org/wiki/Partial_application) the function and derive more descriptive functions like `validateNumeric = makeGreenIfValidationIsValid.bind.(this, /^[0-9]+$/)` and then call `validateNumeric(\"input_1\")`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T08:34:28.447", "Id": "412574", "Score": "0", "body": "I'd agree with extracting the form creation into its own class. But I'd go a step further and make it a [Builder](https://en.wikipedia.org/wiki/Builder_pattern). So you'd probably use it like `formBuilder.addDiv(this.count).addForm(this.count).addLabel().addBreak().build()`. Or something similar there is probably a better way to handle this, the point is how the interface is then exposed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T08:37:04.233", "Id": "412575", "Score": "0", "body": "Finally, for Prototyping, I wouldn't say it's a disadvantage. The code works perfectly fine as it is. Using a prototype might help but the claim that \"it costs performance\" is very likely a premature optimisation. Even if it *is* slower, it might not matter, depending on the use case. And for a homework assignment I'd definitely not care about this aspect. I'd leave it as a preference/option but not something that's really \"wrong\" with the code as it is." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T07:09:48.257", "Id": "213285", "ParentId": "213284", "Score": "1" } }, { "body": "<p>I realize the question already has an accepter answer, but I couldn’t help but notice you used the HTML5 doctype, which means you could use its new input types (such as <code>email</code>, <code>tel</code> and <code>number</code>) and their validation attributes (such as <code>min</code>, <code>max</code> and <code>pattern</code>).</p>\n\n<p>That in combination with CSS’ <code>:valid</code> and <code>:invalid</code> pseudo-classes allows for real-time validation with 0 lines of javascript.</p>\n\n<p>A simple quick incomplete example to illustrate above points:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en-US\"&gt;\n &lt;head&gt;\n &lt;meta charset=\"UTF-8\"&gt;\n\n &lt;style&gt;\n body { font-family: sans-serif }\n\n label { display: block }\n label span {\n display: inline-block;\n width: 8em;\n text-align: right;\n margin-right: .25em;\n }\n\n input {\n border-width: 2px;\n border-radius: 1ex;\n border-style: solid;\n }\n input:focus {\n background-color: #41dcf4;\n border-color: blue;\n }\n\n :valid { /* note that without a selector it applies also to whole form */\n background-color: green;\n border-color: green;\n }\n :invalid {\n background-color: #f44242;\n border-color: red;\n }\n &lt;/style&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n &lt;form&gt;\n &lt;h1&gt;Hello!&lt;/h1&gt;\n &lt;p&gt;If the box turns green, the information is valid!&lt;/p&gt;\n\n &lt;label&gt;&lt;span&gt;first name&lt;/span&gt;\n &lt;input\n name=\"name\"\n required\n pattern=\"[A-Z][a-z-]+\"\n &gt;\n &lt;/label&gt;\n\n &lt;label&gt;&lt;span&gt;age&lt;/span&gt;\n &lt;input\n type=\"number\"\n name=\"age\"\n required\n min=\"0\"\n max=\"100\"\n &gt;\n &lt;/label&gt;\n\n &lt;label&gt;&lt;span&gt;email&lt;/span&gt;\n &lt;input\n type=\"email\"\n name=\"email\"\n required\n pattern=\"[\\w-.]+@[\\w-]{1,62}(\\.[\\w-]{1,62})*\"\n &gt;\n &lt;/label&gt;\n\n &lt;label&gt;&lt;span&gt;address&lt;/span&gt;\n &lt;input\n name=\"address\"\n required\n &gt;\n &lt;/label&gt;\n\n &lt;label&gt;&lt;span&gt;phone number&lt;/span&gt;\n &lt;input\n type=\"tel\"\n name=\"phone\"\n required\n pattern=\"\\d{3}-\\d{3}-\\d{4}\"\n &gt;\n &lt;/label&gt;\n\n &lt;input type=\"submit\"&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T11:30:13.573", "Id": "213647", "ParentId": "213284", "Score": "2" } } ]
{ "AcceptedAnswerId": "213285", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T05:57:29.280", "Id": "213284", "Score": "1", "Tags": [ "javascript", "homework", "dom" ], "Title": "JavaScript DOM Implementation" }
213284
<p>I've written a binary-tree using <code>.NET Core 3.0</code>. What can I do to improve my coding style?</p> <pre><code>using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace BinaryTree { /// &lt;summary&gt; /// Represents a binary tree &lt;seealso href="https://en.wikipedia.org/wiki/Binary_tree"/&gt;. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type which this tree should contain.&lt;/typeparam&gt; [Serializable] [DataContract] public class BinaryTree&lt;T&gt; where T : IComparable, new() { #if DEBUG /// &lt;summary&gt; /// Determines whether or not to log actions in the console. /// &lt;/summary&gt; public static bool Log = true; #endif [DataMember] private Node&lt;T&gt; _parentNode; public BinaryTree() { #if DEBUG if (Log) Console.WriteLine("Initializing binary-tree.."); #endif _parentNode = new Node&lt;T&gt;(); } /// &lt;summary&gt; /// Adds the specific item inside the binary-tree using binary-tree logic. /// &lt;/summary&gt; /// &lt;param name="item"&gt;The item that will be added.&lt;/param&gt; public void Add(T item) { #if DEBUG if (Log) Console.WriteLine("Initializing binary-tree.."); #endif _parentNode.Add(item); } /// &lt;summary&gt; /// Removes the specific item inside the binary-tree using binary-tree logic. The root node cannot be removed. /// &lt;/summary&gt; /// &lt;param name="item"&gt;The item that will be removed.&lt;/param&gt; public void Remove(T item) { _parentNode.Remove(item); } /// &lt;summary&gt; /// Searches for a specific item inside this binary-tree using binary-tree logic. /// &lt;/summary&gt; /// &lt;param name="item"&gt;&lt;/param&gt; /// &lt;returns&gt;Returns the count of said item if existing - 0 if otherwise.&lt;/returns&gt; public int Contains(T item) { return _parentNode.Contains(item); } /// &lt;summary&gt; /// Clears everything out of this binary-tree. /// &lt;/summary&gt; public void Clear() { _parentNode = new Node&lt;T&gt;(); } public override bool Equals(object obj) { return obj is BinaryTree&lt;T&gt; tree &amp;&amp; tree._parentNode.Equals(_parentNode); } public void Serialize(string file) { using (var writer = new StreamWriter(file)) { var bf = new BinaryFormatter(); bf.Serialize(writer.BaseStream, this); } } public static BinaryTree&lt;T&gt; Deserialize(string file) { using (var reader = new StreamReader(file)) { var bf = new BinaryFormatter(); return (BinaryTree&lt;T&gt;)bf.Deserialize(reader.BaseStream); } } /// &lt;summary&gt; /// Represents a node of a binary-tree. This may be either a simple node, a parent, or a leaf. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type which this node should contain.&lt;/typeparam&gt; [Serializable] [DataContract] private class Node&lt;T&gt; where T : IComparable, new() { /// &lt;summary&gt; /// Right "lower" arm of current node - this is where everything bigger than this node is getting redirect towards. /// &lt;/summary&gt; [DataMember] private Node&lt;T&gt; _bigger; /// &lt;summary&gt; /// Saved data and count of data - inside this specific node. /// &lt;/summary&gt; [DataMember] private (T data, int count) _item; /// &lt;summary&gt; /// Root node, if existing. /// &lt;/summary&gt; [DataMember] private Node&lt;T&gt; _parent; /// &lt;summary&gt; /// Left "lower" arm of current node - this is where everything smaller than this node is getting redirect towards. /// &lt;/summary&gt; [DataMember] private Node&lt;T&gt; _smaller; private Node(T item) { _item = (item, 1); } public Node() { } public override bool Equals(object obj) { return obj is Node&lt;T&gt; node &amp;&amp; (node._bigger?.Equals(_bigger) ?? _bigger == null) &amp;&amp; (node._item.data?.Equals(_item.data) ?? _item.data == null) &amp;&amp; (node._item.count.Equals(_item.count)) &amp;&amp; (node._parent?.Equals(_parent) ?? _parent==null) &amp;&amp; (node._smaller?.Equals(_smaller) ?? _smaller == null); } private void Set(T data) { if (_item.data.Equals(default(T))) { _item = (data, 1); return; } if (data.Equals(_item.data)) _item.count++; else Add(data); } public void Remove(T data) { if (data.Equals(_item.data)) { if (_item.count &gt; 1) { _item.count--; } else { if (_parent == null) return; var replacement = new Node&lt;T&gt;(data) { _smaller = _smaller, _bigger = _bigger, _parent = _parent }; if (_parent._item.data.CompareTo(_item.data) == 1) _parent._smaller = replacement; else _parent._bigger = replacement; } } else { if (data.CompareTo(_item.data) == 1) { _bigger?.Remove(data); if (_bigger != null) _bigger._parent = this; } else { _smaller?.Remove(data); if (_smaller != null) _smaller._parent = this; } } } public void Add(T item) { if (_item.data.Equals(default(T))) { Set(item); return; } if (item.CompareTo(_item.data) == 1) { #if DEBUG if (Log) Console.WriteLine($"{item} &gt; {_item.data} → move to right lower node.."); #endif (_bigger = CreateOrReturnNode(_bigger)).Set(item); } else { #if DEBUG if (Log) Console.WriteLine($"{item} &lt; {_item.data} → move to left lower node.."); #endif (_smaller = CreateOrReturnNode(_smaller)).Set(item); } } public int Contains(T value) { if (_item.data.Equals(value)) { #if DEBUG if (Log) Console.WriteLine("Item was found!"); #endif return _item.count; } if (value.CompareTo(_item.data).Equals(1)) { #if DEBUG if (Log) Console.WriteLine($"{value} &gt; {_item.data} → search in right lower node.."); #endif return _bigger?.Contains(value) ?? 0; } #if DEBUG if (Log) Console.WriteLine($"{value} &lt; {_item.data} → search in left lower node.."); #endif return _smaller?.Contains(value) ?? 0; } /// &lt;summary&gt; /// Either creates a new node, or returns the existing one. /// &lt;/summary&gt; /// &lt;param name="node"&gt;The node which is getting checked whether it is set or not.&lt;/param&gt; /// &lt;returns&gt;Either a new node, or the already existing one.&lt;/returns&gt; private static Node&lt;T&gt; CreateOrReturnNode(Node&lt;T&gt; node = null) { return node ?? new Node&lt;T&gt;(); } } } } </code></pre> <p><strong>Updated Version: <a href="https://github.com/TheRealVira/binary-tree/blob/master/BinaryTree/BinaryTree.cs" rel="noreferrer">https://github.com/TheRealVira/binary-tree/blob/master/BinaryTree/BinaryTree.cs</a></strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:07:10.727", "Id": "412577", "Score": "0", "body": "Is this finished? `_parent` doesn't seem to be touched outside `Remove`, so it looks like you were half-way through a refactor to either add or remove the field." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:10:43.627", "Id": "412578", "Score": "0", "body": "@PeterTaylor I have added some comments and serialization options to it, but the _parent is as is \"finished\". It seemed like the easiest and quickest way to solve the removal process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T12:13:51.960", "Id": "412609", "Score": "4", "body": "Please, please remove the #if DEBUG everywhere... consider having one method do your logging, marked with [ConditionalCompilation(\"DEBUG\")], to achieve the same outcome without #if all over the place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T12:53:19.003", "Id": "412611", "Score": "0", "body": "I have updated my code to the newest version." } ]
[ { "body": "<p>Well, I would prefer not to have a private Node class inside the BinaryTree class.\nI think that the logic for adding/removing nodes in the tree should be done at the Tree class and not at the Node class level.</p>\n\n<p>Maybe move the Node class into its own file, rename it to BinaryNodeTree and move the add/remove logic to the tree itself, which can use a utility class for searching the node to add the value too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:14:55.633", "Id": "412590", "Score": "1", "body": "This would probably also solve my _parent \"problem\". Thx!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:16:07.367", "Id": "412591", "Score": "2", "body": "Why pollute the namespace with a `BinaryNodeTree` class? The scope in which it will be used is inside the tree, so the class belongs inside the tree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:22:31.033", "Id": "412593", "Score": "0", "body": "@PeterTaylor this may be since my teacher, a \"java specialist\", tried to teach me to do that and called it good practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:22:57.170", "Id": "412594", "Score": "0", "body": "@PeterTaylor Also this is why I have wanted to learn by myself lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:33:30.973", "Id": "412599", "Score": "1", "body": "@TheRealVira, in case it's not clear, I'm disagreeing with Shai Aharoni. Moving the logic out of the node is probably a good idea, and I also suggested that, but in my opinion moving the `Node` class outside the `BinaryTree` class offers only disadvantages." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:13:48.317", "Id": "213293", "ParentId": "213286", "Score": "2" } }, { "body": "<blockquote>\n<pre><code> public class BinaryTree&lt;T&gt; where T : IComparable, new()\n</code></pre>\n</blockquote>\n\n<p>I suspect that you are unaware of the possibility of writing</p>\n\n<pre><code> public class BinaryTree&lt;T&gt; where T : IComparable&lt;T&gt;, new()\n</code></pre>\n\n<p>If you did deliberately choose <code>IComparable</code> over <code>IComparable&lt;T&gt;</code>, it would be helpful to add a comment explaining why.</p>\n\n<p>Why <code>where T : new()</code>? The code doesn't call <code>new T()</code> anywhere.</p>\n\n<p>The class would be a lot more powerful if you also implemented <code>IEnumerable&lt;T&gt;</code>, and ideally you would implement <code>ICollection&lt;T&gt;</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private Node&lt;T&gt; _parentNode;\n</code></pre>\n</blockquote>\n\n<p><code>Node</code> is an inner class, so it doesn't need the type parameter. You can remove it, and <code>T</code> from the outer class will be in scope. If you've come to C# from Java then note that this is one of the bigger differences in their type systems.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#if DEBUG\n if (Log)\n Console.WriteLine(\"Initializing binary-tree..\");\n#endif\n</code></pre>\n</blockquote>\n\n<p>If you use <code>System.Diagnostics.Debug.WriteLine</code> then (a) you can skip all the <code>#if DEBUG</code>; (b) when running in Visual Studio the log will be available in the Output pane even after the process has finished.</p>\n\n<p>Alternatively you could take it up a level and use a proper runtime-configurable logging library like Serilog, log4net, ...</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void Add(T item)\n {\n#if DEBUG\n if (Log)\n Console.WriteLine(\"Initializing binary-tree..\");\n#endif\n _parentNode.Add(item);\n }\n</code></pre>\n</blockquote>\n\n<p>That log message looks suspicious...</p>\n\n<p>Also, I see you've made a design decision to push the majority of the logic into the nodes. Since you appear to be doing this as a learning exercise, I suggest that for comparison you separately implement a version which leaves the nodes as pure data objects and puts all the logic in the methods of <code>BinaryTree</code>. That lets you use tail optimisation (turn recursion into a <code>while</code> loop).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public override bool Equals(object obj)\n {\n return obj is BinaryTree&lt;T&gt; tree &amp;&amp; tree._parentNode.Equals(_parentNode);\n }\n</code></pre>\n</blockquote>\n\n<p>Visual Studio gives me a warning about this: when you override <code>Equals</code> you should override <code>GetHashcode</code> because otherwise you will spend ages debugging if you ever put an instance of this class in a <code>HashSet&lt;&gt;</code> or as the key in a <code>Dictionary</code>.</p>\n\n<p>The same applies to <code>Node</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> /// &lt;summary&gt;\n /// Right \"lower\" arm of current node - this is where everything bigger than this node is getting redirect towards.\n /// &lt;/summary&gt;\n [DataMember]\n private Node&lt;T&gt; _bigger;\n</code></pre>\n</blockquote>\n\n<p>I managed to understand the code ok, but it would be more conventional to call this <code>_right</code>. (Or maybe <code>right</code>, but I don't want to be pedantic about that kind of naming convention).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private (T data, int count) _item;\n</code></pre>\n</blockquote>\n\n<p>That <code>count</code> is unusual. In effect you're implementing an <code>IDictionary&lt;T, int&gt;</code>: perhaps it would make sense to generalise to <code>IDictionary&lt;TKey, TValue&gt;</code> and have a separate wrapper class which turns any <code>IDictionary&lt;TKey, TValue&gt;</code> into a counter.</p>\n\n<hr>\n\n<pre><code> public override bool Equals(object obj)\n {\n return obj is Node&lt;T&gt; node &amp;&amp;\n (node._bigger?.Equals(_bigger) ?? _bigger == null) &amp;&amp;\n (node._item.data?.Equals(_item.data) ?? _item.data == null) &amp;&amp;\n (node._item.count.Equals(_item.count)) &amp;&amp;\n (node._parent?.Equals(_parent) ?? _parent==null) &amp;&amp;\n (node._smaller?.Equals(_smaller) ?? _smaller == null);\n }\n</code></pre>\n\n<p><code>ValueStruct</code> overrides <code>==</code>, so you could simplify this a bit. Unless you want to be paranoid and assume that <code>T</code> might not have <code>Equals</code> consistent with <code>CompareTo</code>, in which case you should use <code>CompareTo</code> here to compare <code>_item.data</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void Remove(T data)\n {\n if (data.Equals(_item.data))\n {\n if (_item.count &gt; 1)\n {\n _item.count--;\n }\n else\n {\n if (_parent == null) return;\n</code></pre>\n</blockquote>\n\n<p>The only place that <code>_parent</code> is touched is in <code>Remove</code>, so if I add one item to the tree and then call <code>Remove</code> with that same item, it won't be removed.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public int Contains(T value)\n {\n if (_item.data.Equals(value))\n</code></pre>\n</blockquote>\n\n<p>I got a <code>NullReferenceException</code> here when I called <code>Contains</code> on an empty tree.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void Add(T item)\n {\n if (_item.data.Equals(default(T)))\n</code></pre>\n</blockquote>\n\n<p>I got a <code>NullReferenceException</code> here when the tree was empty: did you test this code at all?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (_parent._item.data.CompareTo(_item.data) == 1)\n if (data.CompareTo(_item.data) == 1)\n if (item.CompareTo(_item.data) == 1)\n if (value.CompareTo(_item.data).Equals(1))\n</code></pre>\n</blockquote>\n\n<p>The contract of <code>IComparable</code> does not say that the value returned will always be <code>-1</code>, <code>0</code>, or <code>1</code>. I'm not sure why lots of people seem to think that it does. You should always compare the return value against <code>0</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:20:48.910", "Id": "412592", "Score": "0", "body": "So, as far as I understood your reply, in this scenario it would be better to check if a value is greater then 0? Thank you for your reply!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:26:17.393", "Id": "412596", "Score": "2", "body": "Yes. The foolproof way of using `CompareTo` is to write the code without it: `if (_data > _item.data)`, then move the RHS to the argument of `CompareTo` and replace it with `0`: `if (_data.CompareTo(_item.data) > 0)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:32:15.487", "Id": "412598", "Score": "0", "body": "I need \"where T : IComparable, new()\" for my Clear function. This is where I have to create a new node." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:34:17.580", "Id": "412600", "Score": "2", "body": "You create a `new Node<T>()`, but not a `new T()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T13:06:48.393", "Id": "412614", "Score": "0", "body": "I have updated my code and is now accessible on my github repo: https://github.com/TheRealVira/binary-tree/blob/master/BinaryTree/BinaryTree.cs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T08:36:11.273", "Id": "412717", "Score": "0", "body": "@TheRealVira, [it is permitted to post a new question with your revised code](https://codereview.meta.stackexchange.com/q/1763/1402). However, before doing that I strongly advise you to write some unit tests. The \"Remove doesn't remove\" bug is still present, and it's very easy to write a unit test to catch it." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:14:50.593", "Id": "213294", "ParentId": "213286", "Score": "23" } } ]
{ "AcceptedAnswerId": "213294", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T07:12:28.283", "Id": "213286", "Score": "11", "Tags": [ "c#", ".net", ".net-core" ], "Title": "BinaryTree<T> written in C#" }
213286
<p>At the moment I try to get used to SQLite and Python. I started with insert, select and so on. But now i want to get a bit further. Now I have a DB with 200 rows for testing and in want to update two values of each row in this case called "Test2" and "Test3". My problem is that those two values should be the value that they have +200 and +400 so i have to make an select before updating them (at least with my knowledge). </p> <p>I added a simple time measurement to my code to see if i will be able to make my code more efficient and faster!</p> <p>At the moment it takes <code>0.7344 seconds</code> for me to edit 200 rows of data. Which is pretty slow! Especially if i think to do it for bigger DB's.</p> <p>Things I want to achieve:</p> <ol> <li>Is it really necessary to make the select or could I use the present Data in any other way?</li> <li>Make things faster! Is it possible to edit multiple rows at the same time? Like parallelized tasks?</li> </ol> <p>Any other tips are welcome, as i try to improve myself!</p> <p>Here is my code so far:</p> <pre><code>import sqlite3 import time def database_test(): # Open Database conn = sqlite3.connect('SQLite_Test.db') c = conn.cursor() i = 0 for i in range(200): c.execute('SELECT Test2, Test3 FROM Test WHERE Test1 = ?', (i,)) DB_Values = [] DB_Values = c.fetchone() Value1 = DB_Values[0]+200 Value2 = DB_Values[1]+400 c.execute('''UPDATE Test SET Test2 = ?, Test3 = ? WHERE Test1= ?''', (Value1, Value2, i)) i += 1 # Save (commit) the changes conn.commit() start_time = time.time() database_test() print("--- %s seconds ---" % round((time.time() - start_time),4)) </code></pre>
[]
[ { "body": "<p>SQL (and thus SQLite) support a <a href=\"https://www.sqlite.org/lang_expr.html\" rel=\"noreferrer\">variety of operators</a> suitable (amongst others) in UPDATE statements.</p>\n\n<p>This means that you can simplify your whole loop into a single statement:</p>\n\n<pre><code>query = '''\n UPDATE Test SET Test2 = (Test2 + ?), Test3 = (Test3 + ?)\n WHERE Test1 &gt;= 0 AND Test1 &lt; 200\n'''\nc.execute(query, (200, 400))\n</code></pre>\n\n<hr>\n\n<p>Also you should take the habit to use <a href=\"https://docs.python.org/3/library/time.html#time.perf_counter\" rel=\"noreferrer\"><code>perf_counter</code></a> instead of <code>time</code> to measure elapsed time. Or use the dedicated <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"noreferrer\"><code>timeit</code> module</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T09:20:10.040", "Id": "213291", "ParentId": "213288", "Score": "8" } }, { "body": "<p>Mathias’ answer is the correct way of solving your problem but since this is a code review site, let’s look at the rest of your code.</p>\n\n<p>First off, your code style is fundamentally tidy and clear, so that’s very good. Now for some detailed feedback:</p>\n\n<blockquote>\n<pre><code> # Open Database\n</code></pre>\n</blockquote>\n\n<p>Comments such as this one are at best unnecessary and at worst harmful: the comment provides <em>no additional information</em> compared to the code, and at worst they are misleading. Case in point, what happens if the file <code>SQLite_Test.db</code> doesn’t exist yet? Your comment gives no indication — it implies that the file <em>must</em> exist. But SQLite will actually happily create it for you if it doesn’t exist yet.</p>\n\n<p><a href=\"https://jessicabaker.co.uk/2018/09/10/comment-free-coding/\" rel=\"noreferrer\">Jessica Baker has written a very good article explaining how to write comments well</a>. I strongly urge anyone to read it in its entirety.</p>\n\n<blockquote>\n<pre><code> c = conn.cursor()\n</code></pre>\n</blockquote>\n\n<p>Your code doesn’t need database cursors: Although the subsequent code uses <code>c</code>, it could use <code>conn</code> instead.</p>\n\n<blockquote>\n<pre><code> i = 0\n</code></pre>\n</blockquote>\n\n<p>This initialisation is redundant: <code>range(…)</code> does it for you.</p>\n\n<blockquote>\n<pre><code> for i in range(200):\n</code></pre>\n</blockquote>\n\n<p>Why <code>200</code>? Avoid hard-coding “magic” numbers. If this is the size of your database table, don’t put the number in code, compute it from the database. If the number is arbitrary (for testing, say), assign it to a variable stating thus.</p>\n\n<blockquote>\n<pre><code> DB_Values = [] \n DB_Values = c.fetchone()\n</code></pre>\n</blockquote>\n\n<p>The first line here sets <code>DB_Values</code> to an empty list; the second line immediately overrides that value. The first lines is therefore unnecessary.</p>\n\n<p>Apart from this, you should respect <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> naming conventions. Lastly, <code>db_values</code> isn’t a very clear name: <code>db_row</code> might be more expressive.</p>\n\n<blockquote>\n<pre><code> Value1 = DB_Values[0]+200\n Value2 = DB_Values[1]+400\n</code></pre>\n</blockquote>\n\n<p>Same comment regarding names, and same comment regarding magic numbers.</p>\n\n<blockquote>\n<pre><code> c.execute('''UPDATE Test SET Test2 = ?, Test3 = ? WHERE Test1= ?''', (Value1, Value2, i))\n i += 1 \n</code></pre>\n</blockquote>\n\n<p>You might think that it’s necessary to increment <code>i</code> to progress the loop but this isn’t the case. The increment of <code>i</code> fulfils no purpose, since it will be overridden by the <code>for</code> loop anyway.</p>\n\n<blockquote>\n<pre><code> # Save (commit) the changes\n</code></pre>\n</blockquote>\n\n<p>Same as above: this comment isn’t helpful, since it just repeats what the code says.</p>\n\n<blockquote>\n<pre><code> conn.commit()\n</code></pre>\n</blockquote>\n\n<p>If there was an exception in the preceding code, this <code>commit</code> will never be executed. You <em>may</em> have intended this; but chances are, you didn’t. It’s therefore best practice to avoid implicit resource cleanup (including database commits), and to <a href=\"https://docs.python.org/3/reference/compound_stmts.html#the-with-statement\" rel=\"noreferrer\">use Python’s <code>with</code> statement</a> instead.</p>\n\n<hr>\n\n<p>Taking this in account, here’s a rewritten version of your code:</p>\n\n<pre><code>import sqlite3\nimport time\n\nTEST_NUM_ROWS = 200\nTEST2_INC = 200\nTEST3_INC = 400\n\ndef database_test():\n with sqlite3.connect('SQLite_Test.db') as conn:\n for i in range(TEST_NUM_ROWS):\n row = conn.execute(\n 'SELECT Test2, Test3 FROM Test WHERE Test1 = ?',\n (i,)\n ).fetchone()\n new_row = (row[0] + TEST2_INC, row[1] + TEST3_INC)\n conn.execute(\n 'UPDATE Test SET Test2 = ?, Test3 = ? WHERE Test1 = ?',\n new_row + (i,)\n )\n\n\nstart_time = time.time()\ndatabase_test()\nprint(\"--- %s seconds ---\" % round((time.time() - start_time), 4))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T16:30:16.850", "Id": "412626", "Score": "1", "body": "I like this answer except how you use the context manager. There always seem to be some level of confusion about _what_ the context manager on a DB connection is doing. To avoid people thinking that the connection will be _closed_ after executing the with block, I usually separate the `connect` call from the `with` statement [as shown in the docs](https://docs.python.org/3/library/sqlite3.html#using-the-connection-as-a-context-manager) and wrap the `connect` call in a [`with contextlib.closing(..) as conn`](https://docs.python.org/3/library/contextlib.html#contextlib.closing) if need be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:22:52.473", "Id": "412634", "Score": "0", "body": "@MathiasEttinger I understand your concern but separating the initialisation from the context manager doesn’t fix the issue: every competent Python programmer knows that the resulting code is in fact equivalent. Rather, this needs to be fixed at the API level in sqlite3; e.g. as `with conn.transaction() as t: …`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T18:24:00.323", "Id": "412645", "Score": "0", "body": "Well, that is an other argument to separate the `with conn:` call from the `connect` one (as it would be nearly useless to do `with sqlite3.connect(...).transaction()`) ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T18:40:50.773", "Id": "412646", "Score": "0", "body": "@MathiasEttinger *If* that API existed I’d agree, yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T06:32:29.663", "Id": "412707", "Score": "0", "body": "Thank you for your well written answere! I will learn alot from it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T14:08:27.917", "Id": "213305", "ParentId": "213288", "Score": "5" } } ]
{ "AcceptedAnswerId": "213291", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T07:26:21.340", "Id": "213288", "Score": "5", "Tags": [ "python", "performance", "beginner", "sqlite" ], "Title": "Python update SQLite DB Values" }
213288
<p>I'm making note where you can add items that you buy or sell, any suggestions? </p> <pre><code> public class Main { private static Scanner in = new Scanner(System.in); private static String commands = "[-1]Quit, [0]Commands, [1]Available items, [2] Sold items, [3]Add, [4]Delete," + " [5]Edit, [6]Sell. [7]Bilans [8]Details"; public static void main(String[] args) { Storage storage = new Storage(5); storage.addItem(); System.out.println("| RESELL NOTE |"); System.out.println(commands); boolean flag = true; while (flag) { System.out.println("Choose option: (0 - print list)"); int answer = in.nextInt(); switch (answer) { default: System.out.println("Wrong command"); break; case -1: System.out.println("QUIT"); flag = false; break; case 0: System.out.println(commands); break; case 1: storage.availableItems(); break; case 2: storage.soldItems(); break; case 3: storage.addItem(); break; case 4: storage.removeItem(); break; case 5: System.out.println("modify item"); break; case 6: storage.sellItem(); break; case 7: storage.bilans(); break; case 8: storage.details(); } } } } public class Storage { private int maxCapacity; public Storage(int maxCapacity) { this.maxCapacity = maxCapacity; } Scanner in = new Scanner(System.in); private Map&lt;Integer, Item&gt; items = new TreeMap&lt;&gt;(); public void availableItems() { System.out.println("Available items:"); for (Map.Entry&lt;Integer, Item&gt; entry : items.entrySet()) { if (!entry.getValue().sold) { System.out.println(entry.getKey() + ". " + entry.getValue().getName()); } } } public void soldItems() { System.out.println("Sold items:"); for (Map.Entry&lt;Integer, Item&gt; entry : items.entrySet()) { if (entry.getValue().sold) { System.out.println(entry.getKey() + "." + entry.getValue().getName() + " - (" + (entry.getValue().soldPrice - entry.getValue().price + "PLN profit)")); } } } public void addItem() { if (items.size() &gt;= maxCapacity) { System.out.println("You cant add more items, storage full! (" + items.size() + "/" + maxCapacity + ")"); } else { items.put(Item.assignId(), new Shoes("Piraty", 1500, 7, "red", 11)); items.put(Item.assignId(), new Shoes("Belugi", 1500, 7, "red", 11)); items.put(Item.assignId(), new Shoes("Zebry", 1500, 7, "red", 11)); items.put(Item.assignId(), new Shoes("Creamy", 1500, 7, "red", 11)); items.put(Item.assignId(), new Shoes("Sezame", 1500, 7, "red", 11)); System.out.println("Item added"); } } public void modifyItem() { // work in progress printInLine(); System.out.println("\nPick item to modify: "); int id = in.nextInt(); if (items.containsKey(id)) { System.out.println("Enter new name for " + items.get(id).getName()); in.nextLine(); String newName = in.nextLine(); items.get(id).setName(newName); } else { System.out.println("Item not found"); } } public void sellItem() { printInLine(); System.out.println("\nChoose item to mark as sold: "); int id = in.nextInt(); if (items.containsKey(id)) { items.get(id).setSold(true); System.out.println("How much did you get for " + items.get(id).getName() + "?: "); items.get(id).setSoldPrice(in.nextInt()); System.out.println("You marked " + items.get(id).getName() + " as sold"); System.out.println("Your profit is " + (items.get(id).soldPrice - items.get(id).price) + " PLN"); } else { System.out.println("Item not found"); } } public void removeItem() { printInLine(); System.out.println("\nChoose item to remove: "); int id = in.nextInt(); if (items.containsKey(id)) { System.out.println(items.get(id).getName() + " removed"); items.remove(id); } else { System.out.println("Item not found"); } } public void bilans() { int spendMoney = 0; int earnedMoney = 0; int profit = 0; for (Map.Entry&lt;Integer, Item&gt; entry : items.entrySet()) { if (!entry.getValue().sold) { spendMoney += entry.getValue().getPrice(); } else { earnedMoney += entry.getValue().getSoldPrice(); profit += (entry.getValue().getSoldPrice() - entry.getValue().getPrice()); } } System.out.println("You have already spended: " + spendMoney + " PLN"); System.out.println("You sold items for: " + earnedMoney + " PLN"); System.out.println("Current profit: " + profit + " PLN"); if (earnedMoney &gt; spendMoney) { System.out.println("Wow, you are on +"); } else { System.out.println("Keep trying"); } } public void details() { printInLine(); System.out.print("\nPick item: "); int pickItem = in.nextInt(); if (items.containsKey(pickItem)) { System.out.println("\n| Details |"); System.out.println("Name: " + items.get(pickItem).getName() + "\nPrice: " + items.get(pickItem).getPrice() + "\nCondition: " + items.get(pickItem).getCondition() + "/10" + "\nColor: "); } else { System.out.println("Item not found"); } } private void printInLine() { for (Map.Entry&lt;Integer, Item&gt; entry : items.entrySet()) { if (!entry.getValue().isSold()) { System.out.print(" - " + entry.getKey() + "." + entry.getValue().getName()); } } } } </code></pre>
[]
[ { "body": "<h1><a href=\"http://principles-wiki.net/principles:single_responsibility_principle\" rel=\"nofollow noreferrer\">Responsibilities</a></h1>\n\n<p>A class should have only one responsibility. Robert C. Martin describes it with </p>\n\n<blockquote>\n <p>\"There should never be more than one reason for a class to change\".</p>\n</blockquote>\n\n<p>When we have a look into <code>Storage</code> we can find multiple responsibilities:</p>\n\n<ul>\n<li>read inputs from the console\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public void sellItem() {\n // ..\n int id = in.nextInt();\n // ..\n}\n</code></pre>\n</blockquote></li>\n<li>provide the user with information\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public void bilans() {\n // ..\n System.out.println(\"You have already spended: \" + spendMoney + \" PLN\");\n System.out.println(\"You sold items for: \" + earnedMoney + \" PLN\");\n System.out.println(\"Current profit: \" + profit + \" PLN\");\n // ..\n}\n</code></pre>\n</blockquote></li>\n<li>manage <code>items</code></li>\n</ul>\n\n<h2>Focus on one Responsibility</h2>\n\n<p>The class <code>Storage</code> should focus only on the logic to manage <code>items</code>.</p>\n\n<h2>Advantage Over Multiple Responsibilities</h2>\n\n<p>Multiple companies bought your tool. Now imagine the following two scenarios:</p>\n\n<p>5 Years later Company A and B want different customized information. You can't find a class like <code>InformationFormate</code>. But after some search you found it in <code>Storage</code>, you go into it and <em>change</em> it. You built an <code>if</code>-statement to check for A or B and the default case to print some information. </p>\n\n<p>Now company C calls you and sad that you should build them a graphical user interface. And again you go into the <code>Storage</code> after you didn't found a class like <code>UserInterface</code> and build a new <code>if</code>-statement to check for C and have build your gui logic into it and for all other the text user interface.</p>\n\n<p>You can see, that with the number of responsibilities the number of possible changes grows for one class and it gets bigger and bigger. Additional when you search for these task you will not think at first that displaying information would be in a class named <code>Storage</code>.</p>\n\n<h1><a href=\"http://wiki.c2.com/?ReplaceConditionalWithPolymorphism\" rel=\"nofollow noreferrer\">Replace Conditional With Polymorphism</a></h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>switch (answer) {\n default:\n System.out.println(\"Wrong command\");\n break;\n case -1:\n System.out.println(\"QUIT\");\n flag = false;\n break;\n case 0:\n System.out.println(commands);\n break;\n case 1:\n // ...\n case 8:\n storage.details();\n}\n</code></pre>\n</blockquote>\n\n<p>What this huge <code>switch</code> tries to express is </p>\n\n<blockquote>\n <p>Find a <em>command</em> by a number and <em>execute</em> the associated task.</p>\n</blockquote>\n\n<p>We could simplyfy the <code>switch</code> with</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Command command = commandFactory.getBy(answer);\nboolean shouldContinueProgram = command.execute();\n</code></pre>\n\n<h1><a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">Factory Method Pattern</a></h1>\n\n<p>In the Unit above you found </p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Command command = commandFactory.provide(answer);\ncommand.execute();\n</code></pre>\n</blockquote>\n\n<p>This is using the factory method pattern.</p>\n\n<p>The <code>commandFactory</code> is an object which gives you the correct Instance of type <code>Command</code>, which is an interface and could be one of your 8 given commands to choose.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>interface Command {\n boolean execute();\n}\n\nclass WrongInput implements Command {\n @Override\n public boolean execute() {\n System.out.println(\"Wrong command\");\n return true;\n }\n}\n\nclass Quite implements Command {\n @Override\n public boolean execute() {\n System.out.println(\"Wrong command\");\n return false;\n }\n}\n\ninterface CommandFactory&lt;T&gt; {\n Command provide(T t);\n}\n\nclass NumberCommandFactory implements CommandFactory&lt;Integer&gt; {\n\n private Map&lt;Integer, Command&gt; numberByCommand;\n\n public NumberCommandFactory() {\n numberByCommand.put(-1, new Quite());\n // ...\n }\n\n @Override\n public Command provide(Integer numberOfCommand) {\n return numberByCommand.getOrDefault(numberOfCommand, new WrongInput());\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T22:46:10.263", "Id": "214074", "ParentId": "213295", "Score": "1" } }, { "body": "<blockquote>\n<pre><code> boolean flag = true;\n while (flag) {\n System.out.println(\"Choose option: (0 - print list)\");\n\n\n int answer = in.nextInt();\n switch (answer) {\n\n default:\n System.out.println(\"Wrong command\");\n break;\n\n case -1:\n System.out.println(\"QUIT\");\n flag = false;\n break;\n\n case 0:\n System.out.println(commands);\n break;\n case 1:\n storage.availableItems();\n break;\n case 2:\n storage.soldItems();\n break;\n case 3:\n storage.addItem();\n break;\n case 4:\n storage.removeItem();\n break;\n case 5:\n System.out.println(\"modify item\");\n break;\n case 6:\n storage.sellItem();\n break;\n case 7:\n storage.bilans();\n break;\n case 8:\n storage.details();\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Consider </p>\n\n<pre><code> public static void loop() {\n for (;;) {\n int answer = in.nextInt();\n switch (answer) {\n case -1:\n System.out.println(\"QUIT\");\n return;\n case 0:\n System.out.println(commands);\n break;\n case 1:\n storage.availableItems();\n break;\n case 2:\n storage.soldItems();\n break;\n case 3:\n storage.addItem();\n break;\n case 4:\n storage.removeItem();\n break;\n case 5:\n System.out.println(\"modify item\");\n break;\n case 6:\n storage.sellItem();\n break;\n case 7:\n storage.bilans();\n break;\n case 8:\n storage.details();\n break;\n default:\n System.out.println(\"Wrong command\");\n }\n }\n }\n</code></pre>\n\n<p>Now we don't need the <code>flag</code> variable. We simply loop forever until the user enters -1 and we return from the method. </p>\n\n<p>This gives us the option of moving the method to a separate class, simplifying the <code>Main</code> class and allowing the code to be used in more than one program. </p>\n\n<p>I find it easier to read with the <code>default</code> case at the end and with it being the only case without a <code>break</code>. That's not to say that that the other form is not perfectly functional. But unless you are making use of <a href=\"https://www.tutorialspoint.com/Java-fall-through-switch-statements\" rel=\"nofollow noreferrer\">fallthrough</a>, I just find it simpler this way. </p>\n\n<p>Consider displaying the list of commands any time an invalid command is given. Because sometimes a person can't remember that 0 will print the list of commands. And saying \"print list\" might not suggest to them that it will print a list of commands rather than items. </p>\n\n<h3>Separate logic and display</h3>\n\n<p>You have </p>\n\n<blockquote>\n<pre><code> public void availableItems() {\n System.out.println(\"Available items:\");\n for (Map.Entry&lt;Integer, Item&gt; entry : items.entrySet()) {\n if (!entry.getValue().sold) {\n System.out.println(entry.getKey() + \". \" + entry.getValue().getName());\n }\n }\n }\n</code></pre>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n<pre><code> private void printInLine() {\n for (Map.Entry&lt;Integer, Item&gt; entry : items.entrySet()) {\n if (!entry.getValue().isSold()) {\n System.out.print(\" - \" + entry.getKey() + \".\" + entry.getValue().getName());\n }\n }\n }\n</code></pre>\n</blockquote>\n\n<p>What if we instead had </p>\n\n<pre><code> public static void printItemsOnSeparateLines(Iterable&lt;Item&gt; items) {\n for (Item item : items) {\n System.out.println(item.getID() + \". \" + item.getName());\n }\n }\n\n public static void printItemsOnSameLine(Iterable&lt;Item&gt; items) {\n for (Item item : items) {\n System.out.print(\" - \" + item.getID() + \".\" + item.getName());\n }\n }\n\n public List&lt;Item&gt; findAvailableItems() {\n return items.stream.filter(item -&gt; !item.isSold()).collect(Collectors.toList);\n }\n\n public List&lt;Item&gt; findSoldItems() {\n return items.stream.filter(item -&gt; item.isSold()).collect(Collectors.toList);\n }\n</code></pre>\n\n<p>Now we use them like </p>\n\n<pre><code>System.out.println(\"Available items:\");\nprintItemsOnSeparateLines(findAvailableItems());\n</code></pre>\n\n<p>And our methods are each individually simpler. </p>\n\n<p>I also changed from a property access to <code>isSold</code>. This reads better to me and is better encapsulated. </p>\n\n<p>Now if we come up with new criteria, we can add a new simple method and just reuse our existing display method. Or we can add a new display and reuse our business logic. </p>\n\n<p>This would require <code>Item</code> to include its identifier, which may just be in the <code>Map</code> keys. </p>\n\n<h3>Refactor common code into new methods</h3>\n\n<blockquote>\n<pre><code> public void sellItem() {\n printInLine();\n System.out.println(\"\\nChoose item to mark as sold: \");\n int id = in.nextInt();\n\n if (items.containsKey(id)) {\n items.get(id).setSold(true);\n System.out.println(\"How much did you get for \" + items.get(id).getName() + \"?: \");\n items.get(id).setSoldPrice(in.nextInt());\n System.out.println(\"You marked \" + items.get(id).getName() + \" as sold\");\n System.out.println(\"Your profit is \" + (items.get(id).soldPrice - items.get(id).price) + \" PLN\");\n } else {\n System.out.println(\"Item not found\");\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This could be </p>\n\n<pre><code> public void sellItem() {\n printItemsOnSameLine(findAvailableItems());\n Item item = selectItem(\"\\nChoose item to mark as sold: \");\n if (item == null) {\n return;\n }\n\n if (item.isSold()) {\n System.out.println(\"That item already sold.\");\n return;\n }\n\n item.setSold(true);\n System.out.println(\"How much did you get for \" + item.getName() + \"?: \");\n item.setSoldPrice(in.nextInt());\n System.out.println(\"You marked \" + item.getName() + \" as sold\");\n System.out.println(\"Your profit is \" + (item.soldPrice - item.price) + \" PLN\");\n }\n</code></pre>\n\n<p>with </p>\n\n<pre><code> public Item selectItem(String query) {\n System.out.println(query);\n\n Item item = items.get(in.nextInt();\n if (item == null) {\n System.out.println(\"Item not found.\");\n }\n\n return item;\n }\n</code></pre>\n\n<p>Now we don't have to continually rewrite the same code (four times). If we want to select an item, we can just call that method. </p>\n\n<p>I also handled a condition that the original code did not. What if someone entered the ID of an already sold item? </p>\n\n<p>Rather than repeatedly writing <code>items.get(id)</code>, this code just uses <code>item</code>. </p>\n\n<p>We don't have to call <code>containsKey</code>, as we can get the same behavior by simply calling <code>get</code>, which we have to call anyway. And now we don't have to carry around the ID. </p>\n\n<h3>Logic mistake?</h3>\n\n<blockquote>\n<pre><code> for (Map.Entry&lt;Integer, Item&gt; entry : items.entrySet()) {\n if (!entry.getValue().sold) {\n spendMoney += entry.getValue().getPrice();\n } else {\n earnedMoney += entry.getValue().getSoldPrice();\n profit += (entry.getValue().getSoldPrice() - entry.getValue().getPrice());\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Later you compare <code>spendMoney</code> and <code>earnedMoney</code>. But the two aren't comparable. They are on different items. Consider </p>\n\n<pre><code> for (Item item : values()) {\n spentMoney += item.getPrice();\n if (item.isSold()) {\n earnedMoney += item.getSoldPrice();\n profit += item.getSoldPrice() - item.getPrice();\n }\n }\n</code></pre>\n\n<p>Now we have the amount of money spent to procure all the items compared to the amount of money earned on the current sold items. We know if we are currently ahead. Or we can look at profit to see if we are ahead on the items already sold. </p>\n\n<p>I also changed from <code>entrySet</code> to just <code>values</code> because you were never using the key. So we can just say <code>item</code> rather than <code>entry.getValue()</code>. </p>\n\n<p>I changed <code>spendMoney</code> to <code>spentMoney</code> to be consistent with <code>earnedMoney</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-23T05:49:50.593", "Id": "214096", "ParentId": "213295", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T10:41:20.650", "Id": "213295", "Score": "1", "Tags": [ "java", "console", "e-commerce" ], "Title": "Note for monitoring buy/sell item list" }
213295
<p>I have received a nice answer for <a href="https://codereview.stackexchange.com/questions/213244/a-simple-java-class-for-implementing-code-stop-watches">this</a> post. Now, it is my attempt for some improvement:</p> <pre><code>package net.coderodde.time; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * This class provides easy-to-use means for measuring elapsed time. * * @author Rodion "rodde" Efremov * @version 1.6 (Feb 12, 2019) */ public final class StopWatch { private boolean isMeasuring; // false by default. private long startTimeMillis; private long markTimeMillis; private final List&lt;Long&gt; memory = new ArrayList&lt;&gt;(); /** * Starts measuring time. */ public void start() { setImpl(true); } /** * Stops measuring time. */ public void stop() { setImpl(false); } /** * Resets the starting time to the current moment. */ public void reset() { setImpl(true); } private void setImpl(boolean expectedStatus) { if (expectedStatus) { checkMeasuringStatusIsOff(); } else { checkMeasuringStatusIsOn(); } startTimeMillis = System.currentTimeMillis(); markTimeMillis = startTimeMillis; isMeasuring = !isMeasuring; memory.clear(); } /** * Marks current time for future calculation of lap times. */ public void mark() { checkMeasuringStatusIsOn(); markTimeMillis = System.currentTimeMillis(); } /** * Returns the time elapsed from beginning of the current lap. * * @return the lap time. */ public long lap() { checkMeasuringStatusIsOn(); long now = System.currentTimeMillis(); memory.add(now); long saveMarkTimeMillis = markTimeMillis; markTimeMillis = now; return now - saveMarkTimeMillis; } /** * Returns the entire lap memory. * * @return the list of lap times. */ public long[] recall() { long[] mem = new long[memory.size()]; mem[0] = memory.get(0) - startTimeMillis; for (int i = 1; i &lt; mem.length; i++) { mem[i] = memory.get(i) - memory.get(i - 1); } return mem; } /** * Returns the time of a full previous lap. * * @return the lap time of the previous full lap. */ public long split() { checkMeasuringStatusIsOn(); switch (memory.size()) { case 1: return memory.get(0) - startTimeMillis; default: int index = memory.size() - 2; return memory.get(index + 1) - memory.get(index); } } @Override public String toString() { return String.format( "(isMeasuring=%b, startTimeMillis=%d, markTimeMillis=%d, " + "memory=%s)", isMeasuring, startTimeMillis, markTimeMillis, memory.toString()); } private void checkMeasuringStatus(boolean expecteedMeasuringStatus, String exceptionMessage) { if (isMeasuring != expecteedMeasuringStatus) { throw new IllegalStateException(exceptionMessage); } } private void checkMeasuringStatusIsOn() { checkMeasuringStatus(true, "The stopwatch is not ticking."); } private void checkMeasuringStatusIsOff() { checkMeasuringStatus(false, "The stopwatch is ticking."); } public static void main(String[] args) { StopWatch sw = new StopWatch(); Scanner scanner = new Scanner(System.in); while (true) { System.out.println(sw); String cmd = scanner.next(); switch (cmd) { case "start": sw.start(); break; case "stop": sw.stop(); break; case "recall": System.out.println(Arrays.toString(sw.recall())); break; case "split": System.out.println(sw.split()); break; case "lap": System.out.println(sw.lap()); break; case "mark": sw.mark(); break; case "quit": case "exit": return; } } } } </code></pre> <p>So, am I going into the right direction?</p>
[]
[ { "body": "<p>Typo: <code>expecteedMeasuringStatus</code> the word <code>expected</code> is spelled with only one consecutive <code>e</code>.</p>\n\n<h3>Measuring time:</h3>\n\n<p>Imagine that some user would start your application, start measuring the time, then <strong>change the system time</strong>, then at some point later stop the measuring. What happens? Your time measuring will be inaccurate. Solution: Use <code>System.nanoTime()</code> and not <code>System.currentTimeMillis()</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T11:40:37.040", "Id": "412605", "Score": "0", "body": "True. Citing, _This method can only be used to measure elapsed time_" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T11:18:29.703", "Id": "213298", "ParentId": "213297", "Score": "1" } } ]
{ "AcceptedAnswerId": "213298", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T11:05:52.603", "Id": "213297", "Score": "1", "Tags": [ "java", "timer", "benchmarking" ], "Title": "A simple Java class for implementing code stop watches - follow-up" }
213297
<p>So I've run into a few occasions where I'd want to sort a list according to a criteria, then for all loosely sorted sublists (a sequence of equal elements), I'd want to sort those sublists according to another criteria. I previously did something like this (assuming there are <code>m</code> criteria.</p> <pre class="lang-py prettyprint-override"><code>sorted(sorted(sorted...(sorted(lst, key = keys[m]), key = keys[m-1]), ..., key = keys[1]), key = keys[0]). </code></pre> <p>Generally, I had around two sorting criteria so it wasn't an issue. Working on a problem that required sorting according to 3 criteria led me to generalise my method, which led me to noticing that it had atrocious resource usage (best case time complexity is <code>O(m*s)</code> (where <code>s</code> is the time complexity of <code>sorted()</code>, and best case space complexity is <code>O(m*n)</code> (where <code>n</code> is the length of the list). This prompted me to seek more efficient ways of doing this, and after some thought, discussion and feedback from others, here's what I have: </p> <h2>ChainedSort.py</h2> <pre class="lang-py prettyprint-override"><code>from collections import deque """ * Finds all sublists that have equal elements (according to a provided function) in a given sorted list. * Params: * `lst`: The sorted list to be searched. * `f`: The function that is used to compare the items in the list. * Return: * A list containing 2 tuples of the form `(start, stop)` where `start` and `stop` give the slice of equal values in the list. If no elements in the list are equal this is empty. """ def checkSort(lst, f = lambda x: x): #Finds all sublists that have equal elements in a given sorted list. i, slices, ln = 0, [], len(lst) while i &lt; ln-1: if f(lst[i]) == f(lst[i+1]): j = i+1 while f(lst[i]) == f(lst[j]): if j+1 == ln: break j += 1 slices.append((i, j)) #The slice can be directly accessed using `lst[tpl[0]:tpl[1]]` where `tpl` is the tuple denoting the slice. i = j continue #`i` should not be further increased. i += 1 #Increment `i` normally if `i+1` != `i`. return slices """ * Returns a sorted list whose elements are drawn from a given iterable, according to a list of provided keys. * It is equivalent to a lazily evaluated form of `sorted(lst, key = lambda x: (key1(x), key2(x), key3(x) [,..., keym(x)]))`. The lazy evaluation provides the same `O(s)` (where `s` is the time complexity of `sorted()`) best case as a simple `sorted()` with only one key. On the other hand, the best case of the above (due to its strict evaluation) is `O(m*s)` where `m` is the number of supplied keys. This function would be very useful in cases where some of the key functions are expensive to evaluate. The process can be described as: * Elements are ordered according to criterion 1. * Elements equal by criterion 1 are ordered according to criterion 2. * ... * ... * ... * Elements equal by criterion i are ordered according to criterion i+1. * ... * ... * ... * Elements equal by criterion n-1 are ordered according to criterion n. * This process is being referred to as "Chained Sort". * Algorithm for Chained Sort: * Step 1: lst := sorted(itr, keys[i]), ln := len(keys) * Step 2: i := i+1 * Step 3: If i &lt; ln and some elements in the list are equal according to criterion i: * Step 4: while there exist elements equal according to criterion i: * Step 5: Find the slices of all elements equal according to criterion i. * Step 6: Sort those slices according to criterion i. * Step 7: i := i+1 * [End of Step 4 while loop.] * [End of Step 3 if block.] * Step 8: Return lst. * Params: * `itr`: The iterable to be sorted. * `keys`: A deque containing all the sorting keys, in the order in which they are to be evaluated. * Return: * `lst`: The sorted contents of `itr`, after applying the chained sort. """ def chainedSort(itr, keys = deque([lambda x: x])): lst = sorted(itr, key = keys.popleft()) check = [] if not keys else checkSort(lst, keys.popleft()) while keys and check: k = keys.popleft() for tpl in check: #Sort all equal slices with the current key. i, j = tpl[0], tpl[1] lst[i:j] = sorted(lst[i:j], key = k) if keys: k, tmp = keys.popleft(), [] """ * We only need to check those slices of the list that were not strictly sorted under the previous key. Slices of the list that were strictly sorted under a previous key should not be sorted under the next key. As such, rather than iterating through the list every time to find the loosely sorted elements, we only need to search among the loosely sorted elements under the previous key, as the set of loosely sorted elements cannot increase upon successive sorts. """ for tpl in check: i, j = tpl[0], tpl[1] tmp.extend(checkSort(lst[i:j], k)) check = tmp else: check = [] return lst </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T14:44:08.720", "Id": "412620", "Score": "0", "body": "Can you add some simple example input/output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T01:27:42.807", "Id": "412851", "Score": "0", "body": "Sorry. I haven't actually encountered a use case for the program. It was more an academic exercise to generalise sorting. I would try developing a use case later on I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T09:33:43.167", "Id": "413120", "Score": "0", "body": "You still know what you expect an input/output to look like. E.g., let's say you want to sort inner lists in ascending order, and outer lists by descending order of first element. ``input = [[0, -1, 1], [1, 2, 3]]``, and ``output = [[1, 2, 3], [-1, 0, 1]]``." } ]
[ { "body": "<p>I don't see any good reason to require that the keys are put in a deque. It feels like clobbering the calling site. Instead I’d use variable number of arguments to ease usage:</p>\n\n<pre><code>def chained_sort(iterable, *keys):\n if not keys:\n keys = deque([lambda x: x])\n else:\n keys = deque(keys)\n # etc\n</code></pre>\n\n<p>Also note:</p>\n\n<ol>\n<li>that using a mutable default argument <a href=\"https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument\">is prone to errors</a>;</li>\n<li>the use of <code>snake_case</code> for the function name to conform to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>;</li>\n<li>it would be a good idea to add a <code>reverse</code> argument to mimic the <code>sorted</code> signature.</li>\n</ol>\n\n<hr>\n\n<p>Now I have the feeling that the sorting behaviour of Python already does what you want. No need to extend it. In fact, sorting tuples in Python already uses multiple stages in that it sort on the first element first, then on the second element, then on the third, if any, and so on:</p>\n\n<pre><code>&gt;&gt;&gt; sorted([(1, 2, 3), (4, 5, 6), (1, 1, 1), (2, 2, 2), (4, 4, 4), (2, 1, 2), (2, 1, 0)])\n[(1, 1, 1), (1, 2, 3), (2, 1, 0), (2, 1, 2), (2, 2, 2), (4, 4, 4), (4, 5, 6)]\n</code></pre>\n\n<p>So you can leverage this behaviour to implement yours: just have the key argument of <code>sorted</code> return a tuple of all the keys for each item, and let Python sort those tuples:</p>\n\n<pre><code>def chained_sort(iterable, *keys, reverse=False):\n if not keys:\n key = None\n else:\n def key(item):\n return tuple(f(item) for f in keys)\n return sorted(iterable, key=key, reverse=reverse)\n</code></pre>\n\n<p>Usage being</p>\n\n<pre><code>&gt;&gt;&gt; import operator\n&gt;&gt;&gt; a = [{'one': 'foo', 'two': 42}, {'one': 'bar', 'two': 1337}, {'one': 'baz', 'two': 1664}, {'one': 'foo', 'two': 1492}, {'one': 'bar', 'two': 2}, {'one': 'baz', 'two': 0}]\n&gt;&gt;&gt; chained_sort(a, operator.itemgetter('one'), lambda x: x['two'] &lt; 1000)\n[{'one': 'bar', 'two': 1337}, {'one': 'bar', 'two': 2}, {'one': 'baz', 'two': 1664}, {'one': 'baz', 'two': 0}, {'one': 'foo', 'two': 1492}, {'one': 'foo', 'two': 42}]\n</code></pre>\n\n<hr>\n\n<p>Lastly docstrings should come just after the function declaration, not before. Read <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP257</a> for indsights.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T13:55:00.830", "Id": "412617", "Score": "0", "body": "As far as I'm aware, Python's inbuilt `sorted()` doesn't have lazy evaluation, which means that all key functions are evaluated for each item in the iterable? If I'm wrong about this please correct me. I'll add a `reverse` parameter, and look into replacing the `deque()`. I am somewhat unclear on camel case, since that's how I learned to code, and the code in my book (\"Automate the Boring Stuff with Python\") uses it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T13:59:05.693", "Id": "412618", "Score": "1", "body": "Right, you’ll have to call each key on each item and then sort according to the resulting list of tuples. But as far as I can tell, your code eventually does call each key on each item as well; just not necessarily in the same order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T01:26:13.203", "Id": "412850", "Score": "0", "body": "It doesn't call each key on each item if it's not needed. It evaluates the key function lazily. If items are sorted according to the 1st key, it stops there. They both have the same worst case, but as written, my code would perform better on average (and especially better if the last key functions are costly to evaluate)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T13:31:45.490", "Id": "213303", "ParentId": "213299", "Score": "3" } }, { "body": "<p>This algorithm does not sort anything. In fact, it is broken in at least two ways. Let's illustrate that with a simple example:</p>\n\n<pre><code>import operator, itertools\narray = list(zip(range(10), itertools.repeat(5), reversed(range(10))))\n\nkeys = deque(map(operator.itemgetter, range(3)))\nprint(chainedSort(array, keys))\nprint(keys)\n</code></pre>\n\n<p>Here we are contructing a list of 3-tuples that are already sorted, and we are asking to sort it according to their first element first, then their second one and then the third one. Since their first element is sorted, the principles behind your algorithm should make it so that the second and third comparison function are never executed (since there is no repeating elements according to the first comparison function). However the results are very deceptive:</p>\n\n<pre><code>[(8, 5, 1), (7, 5, 2), (6, 5, 3), (5, 5, 4), (4, 5, 5), (3, 5, 6), (2, 5, 7), (1, 5, 8), (0, 5, 9), (9, 5, 0)]\ndeque([])\n</code></pre>\n\n<p>Not only is it not sorted in any meaningful way, but the keys have been completely depleted; meaning that all 3 functions have been called. This is something that was meant to be avoided. Also note that the <code>keys</code> passed to this function are modified in-place, which is an unexpected side-effect that should at least be documented, at best avoided. Using variable number of arguments is prefered here to simplify the calling site:</p>\n\n<pre><code>def chained_sort(iterable, *keys):\n if not keys:\n return sorted(iterable)\n\n keys = deque(keys)\n # rest of the code\n</code></pre>\n\n<p>Now about that \"sorting\" behaviour, I see at least 3 issues:</p>\n\n<ol>\n<li>you check for item equality with the next key function instead of the same that you just used to sort; this is not desirable as you are trying to find groups of elements that compare equal according to the actual sort so you can sort them with the following function: you must use the same key function that you used to sort; this is why in my example the result is mostly reversed, the second key function find the whole list equal so your algorithm end up sorting it according to the third key function;</li>\n<li>your index management is a mess in <code>checkSort</code> and mainly lead to skipping the last element in your slices;</li>\n<li>you call <code>checkSort</code> on sub-lists but apply the resulting slices on the original list, meaning you won't sort sub-lists but random bit of the original list.</li>\n</ol>\n\n<p>Fixing the second point is easy enough as you really don't need to special case for <code>i+1</code> before assigning to <code>j</code>. Just use a simpler loop and then find out if the slice <code>[i:j]</code> represents more than one element to add it to <code>slices</code>. A simple substraction tells you how many items are in the slice. Two other points worth noting: you should cache the value of <code>f(lst[i])</code> instead of recomputing it for all elements that compare equal, and you can use a <code>slice</code> object instead of storing these weird tuples:</p>\n\n<pre><code>&gt;&gt;&gt; a = 'just a testing string'\n&gt;&gt;&gt; s = slice(7, 14)\n&gt;&gt;&gt; a[s]\n'testing'\n&gt;&gt;&gt; a[7:14]\n'testing'\n</code></pre>\n\n<p>Also transforming this function into a generator can simplify its writting:</p>\n\n<pre><code>def check_sort(array, cmp_function):\n i, ln = 0, len(array)\n while i &lt; ln-1:\n key = cmp_function(array[i])\n j = i + 1\n while j != ln and key == cmp_function(array[j]): \n j += 1\n if j - i &gt; 1: # Keep only slices of more than 1 elements\n yield slice(i, j)\n i = j\n</code></pre>\n\n<p>But while loops feels weird so I’d rather write it like:</p>\n\n<pre><code>def check_sort(array, cmp_function):\n i = None\n key = None\n for j, item in enumerate(array):\n if i is None:\n i = j\n key = cmp_function(item)\n continue\n\n keyed = cmp_function(item)\n if keyed != key:\n if j - i &gt; 1:\n yield slice(i, j)\n i = j\n key = keyed\n\n if i is not None and i != j:\n # Special case of the last slice as it can't be\n # generated from the loop. Be sure to check that\n # 1) it exists and 2) it is more than 1 element.\n yield slice(i, j + 1)\n</code></pre>\n\n<p>But, all in all, we’re still left with 2 issues.</p>\n\n<p>So, what you really need is a way to group elements by the same key you used to sort them. Fortunately, this is exactly what <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a> is for. Once your groups are formed, just check their length to know if you must apply the next key function on this very same group or if you are done for this path. The simplest implementation uses recursion:</p>\n\n<pre><code>import itertools\n\n\ndef check_sorted(iterable, key, next_keys=(), reverse=False):\n for _, group in itertools.groupby(iterable, key=key):\n grouped = list(group)\n if len(grouped) &gt; 1:\n yield chained_sort(grouped, *next_keys, reverse=reverse)\n else:\n yield grouped\n\n\n\ndef chained_sort(iterable, *keys, reverse=False):\n if not keys:\n return sorted(iterable, reverse=reverse)\n\n keys = iter(keys)\n key = next(keys)\n result = sorted(iterable, key=key, reverse=reverse)\n return list(itertools.chain.from_iterable(check_sorted(result, key, keys, reverse)))\n</code></pre>\n\n<p>Since recursion is limited in Python, you’ll have to write a looping version if you plan on supporting more than 500 key functions at once.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-15T13:42:43.290", "Id": "213519", "ParentId": "213299", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T11:57:04.043", "Id": "213299", "Score": "2", "Tags": [ "python", "performance", "beginner", "algorithm", "sorting" ], "Title": "Chained Sort Python Implementation" }
213299
<p>The idea originaes from the <a href="http://codekata.com/kata/kata19-word-chains/" rel="nofollow noreferrer">CodeKata19</a>, find a word chain for two words of a <a href="http://codekata.com/data/wordlist.txt" rel="nofollow noreferrer">wordlist</a></p> <p>example 1 turning <code>lead</code> into <code>gold</code>:</p> <pre><code>lead load goad gold </code></pre> <p>example 2 turning <code>code</code> into <code>ruby</code>:</p> <pre><code>code rode robe rube ruby </code></pre> <h2>Note</h2> <p>it would be also valid if you had found this chain even though it is not an optimal solution (because it's depth 6 not 5). It should only demonstrate that the start/end-letter is not always identical to the start/destiny word</p> <pre><code>code rode rods robs rubs ruby </code></pre> <p>can you inspect my code on principals of CleanCode OOP and maybe some hints on performance/algorithm?</p> <h2>Main class</h2> <pre><code>public static void main( String[] args ) { WordChainBuilder wordChainBuilder = new WordChainBuilder("src/main/resources/words.txt"); List&lt;String&gt; goldChain = wordChainBuilder.build("gold", "lead"); System.out.println("chain: "+goldChain); List&lt;String&gt; rubyChain = wordChainBuilder.build("ruby", "code"); System.out.println("chain: "+rubyChain); } </code></pre> <h2>Node class</h2> <pre><code>class Node { private Node predecessor; private final String word; Node(String word) { this.word= word; } String getWord() { return word; } void setPredecessor(Node node){ predecessor = node; } Node getPredecessor() { return predecessor; } } </code></pre> <h2>WordChainBuilder class</h2> <pre><code>class WordChainBuilder { private final String wordListFilename; WordChainBuilder(String wordListFilename) { this.wordListFilename = wordListFilename; } List&lt;String&gt; build(String startWord, String destinyWord) { if (startWord == null || destinyWord == null || startWord.length() != destinyWord.length()) { throw new IllegalArgumentException(); } List&lt;String&gt; words = readAllWordsWithLength(startWord.length()); List&lt;Node&gt; currentDepth = new ArrayList&lt;&gt;(); currentDepth.add(new Node(startWord)); while (!currentDepth.isEmpty()) { List&lt;Node&gt; nextDepth = new ArrayList&lt;&gt;(); for (Node node : currentDepth) { List&lt;Node&gt; derivedNodes = findDerivedNodes(node, words); Node destinyNode = findDestinyNode(derivedNodes, destinyWord); if (destinyNode != null){ return buildChain(destinyNode); } nextDepth.addAll(derivedNodes); } removeWordsAlreadyUsed(words, nextDepth); currentDepth = nextDepth; } return Collections.emptyList(); } private void removeWordsAlreadyUsed(List&lt;String&gt; words, List&lt;Node&gt; nodes) { words.removeAll(nodes.stream().map(Node::getWord). collect(Collectors.toList())); } private Node findDestinyNode(List&lt;Node&gt; nodes, String destinyWord) { return nodes.stream().filter(node -&gt; node.getWord().equals(destinyWord)).findAny().orElse(null); } private List&lt;Node&gt; findDerivedNodes(Node node, List&lt;String&gt; words) { List&lt;Node&gt; derivedNodes = new ArrayList&lt;&gt;(); for (String derivedWord : findDerivedWords(node.getWord(), words)) { Node derivedNode = new Node(derivedWord); derivedNode.setPredecessor(node); derivedNodes.add(derivedNode); } return derivedNodes; } private List&lt;String&gt; buildChain(Node node) { List&lt;String&gt; chain = new ArrayList&lt;&gt;(); while (node.getPredecessor() != null) { chain.add(node.getWord()); node = node.getPredecessor(); } chain.add(node.getWord()); Collections.reverse(chain); return chain; } private List&lt;String&gt; findDerivedWords(String word, List&lt;String&gt; candidates) { return candidates.stream().filter(w -&gt; derivesByOne(word, w)).collect(Collectors.toList()); } private static boolean derivesByOne(String word, String candidate) { int difference = 0; for (int i = 0; i &lt; word.length(); i++) { if (word.charAt(i) != candidate.charAt(i)) { difference = difference + 1; if (difference &gt; 1){ return false; } } } return difference == 1; } private List&lt;String&gt; readAllWordsWithLength(final int length) { try (Stream&lt;String&gt; lines = Files.lines(Paths.get(wordListFilename), Charset.defaultCharset())) { return lines.filter(line -&gt; line.length() == length).collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } return Collections.emptyList(); } } </code></pre> <p>again i'm totally lost in finding proper objects or any idea on how to better split my code into seperate concerns :-( help!</p> <p>thanks for the help so far, i opened <a href="https://codereview.stackexchange.com/questions/213361/word-chain-implementation-follow-up">a followup question</a> on that topic...</p>
[]
[ { "body": "<h1>Responsibilities</h1>\n\n<p>A class should have only one <a href=\"http://principles-wiki.net/principles:single_responsibility_principle\" rel=\"nofollow noreferrer\">responsibility</a>. Robert C. Martin describes it with <em>\"There should never be more than one reason for a class to change\"</em>.</p>\n\n<p>The class <code>WordChainBuilder</code> has more than one responsibilities. An indicator for this is that it has <em>many private methods</em>. I saw a video (I will provide a reference to it) in which <a href=\"https://www.sandimetz.com/\" rel=\"nofollow noreferrer\">Sandi Metz</a> said she generally avoids private methods. </p>\n\n<p>I think you can not always avoid private methods, but if you have too many, your class definitely has more than one responsibility.</p>\n\n<p>Responsibilities of <code>WordChainBuilder</code>:</p>\n\n<ul>\n<li>build the word chain</li>\n<li>read from the file system</li>\n<li>do operations on list</li>\n<li>do operations on strings</li>\n</ul>\n\n<h1><a href=\"https://blog.codinghorror.com/code-smells/\" rel=\"nofollow noreferrer\">Type Embedded in Name</a></h1>\n\n<blockquote>\n <p>Avoid placing types in method names; it's not only redundant, but it forces you to change the name if the type changes.</p>\n</blockquote>\n\n<p>Because of the multiple responsibilities, there are several hidden abstractions in a class. So you have to name your variables and methods somehow.</p>\n\n<p>Some type embedded names are:</p>\n\n<ul>\n<li><code>startWord</code> &amp; <code>destinyWord</code></li>\n<li><code>findDerivedNodes</code> &amp; <code>findDestinyNode</code></li>\n<li><code>findDerivedWords</code></li>\n<li><code>destinyNode</code> &amp; <code>derivedNodes</code></li>\n</ul>\n\n<h1><a href=\"http://wiki.c2.com/?PrimitiveObsession\" rel=\"nofollow noreferrer\">Primitive Obsession</a></h1>\n\n<blockquote>\n <p>Primitive Obsession is using primitive data types to represent domain ideas. For example, we use a String to represent a message [...]</p>\n</blockquote>\n\n<p>I see some variables with the name <code>startWord</code>, <code>destinyWord</code> and <code>words</code>, a method <code>derivesByOne</code> that interacts with to words, but I can't find a data type <code>Word</code>.</p>\n\n<p>We can created it and copy/paste the method <code>derivesByOne</code> into it. After that we can rename the variable names <code>startWord</code> and <code>destinyWord</code> to <code>start</code> and <code>destiny</code> to avoid the code small <a href=\"https://blog.codinghorror.com/code-smells/\" rel=\"nofollow noreferrer\">Type Embedded in Name</a>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Word {\n\n private String value;\n\n public Word(String word) {/*..*/}\n\n public boolean isDerivedByOne() {/*..*/}\n\n // equals &amp; hashcode\n}\n</code></pre>\n\n<h1>First Class Collection</h1>\n\n<p>The First Class Collection [FCC] is an idea of the <a href=\"https://www.cs.helsinki.fi/u/luontola/tdd-2009/ext/ObjectCalisthenics.pdf\" rel=\"nofollow noreferrer\">Object Calisthenics</a>.</p>\n\n<blockquote>\n <p>Any class that contains a collection should contain no other member variables. Each collection gets wrapped in its own class, so now behaviors related to the collection have a home. </p>\n</blockquote>\n\n<p>With an FCC you can extract the methods <code>findDerivedNodes</code> and<code>findDestinyNode</code> into their own class. Normally a collection of <code>Nodes</code>s is a graph - so the new class might have the name<code>Graph</code> or <code>NodeCollection</code>. In addition, the <code>removeWordsAlreadyUsed</code> and<code>findDerivedWords</code> methods can be in their own class called <code>Dictionary</code> or<code>WordCollection</code>.</p>\n\n<h1><a href=\"http://wiki.c2.com/?LawOfDemeter\" rel=\"nofollow noreferrer\">Law Of Demeter</a></h1>\n\n<blockquote>\n <p>Only talk to your immediate friends.\" E.g. one never calls a method on an object you got from another call </p>\n</blockquote>\n\n<p>The line <code>node.getWord().equals(destinyWord)</code> doesn't follow the Law of Demeter. <code>Note</code> should have a method <code>contains</code> and than the line can be replaced with <code>node.contains(destinyWord)</code></p>\n\n<h1><a href=\"https://en.wikipedia.org/wiki/Null_object_pattern\" rel=\"nofollow noreferrer\">Null Object Pattern</a> And New Methods</h1>\n\n<p>Because you return in the default case in <code>findDestinyNode</code> a <code>null</code> you have to check on two places if a <code>Node</code> is <code>null</code> (<code>node.getPredecessor() != null)</code>\n and <code>destinyNode != null</code>)</p>\n\n<p>We can get ride of the checks by using the Null Object Pattern. For this you have to return in <code>findDestinyNode</code> as default a <em>null object</em> <code>EmptyNode</code> which we have to implement. This object shares the same interface with <code>Node</code> so they implement the same methods.</p>\n\n<p>When we create for <code>destinyNode != null</code> a method <code>isEmpty</code>, the \"normal <code>Node</code>\" will return <code>false</code> and the <code>EmptyNode</code> <code>true</code>. For <code>node.getPredecessor() != null</code> we can write a method <code>hasPredecessor</code> where the \"normal <code>Node</code>\" returns <code>true</code> and the <code>EmptyNode</code> <code>false</code>.</p>\n\n<h1>Better Data Structure</h1>\n\n<p>The method <code>buildChain</code> uses an<code>ArrayList</code> to add all predecessors. Since they are appended to the end of the list, it is reversed with <code>Collections.reverse (chain)</code>.</p>\n\n<p>The time performance of this method is something like <span class=\"math-container\">\\$O(n²)\\$</span>, where the first <span class=\"math-container\">\\$n\\$</span> is the number of <code>predecessor</code> and the second <span class=\"math-container\">\\$n\\$</span> the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#reverse(java.util.List)\" rel=\"nofollow noreferrer\">time complexity of Collections.reverse</a></p>\n\n<p>The interface <code>List</code> provides a method <code>add(index, element)</code> which we can use. If we add all elements to the first position we don't have to reverse it. But <code>ArrayList</code> has <span class=\"math-container\">\\$O(n)\\$</span> for adding 1 element to the first index. Instead of the <code>ArrayList</code> we can use a <code>LinkedList</code> which has for the same operation <span class=\"math-container\">\\$O(1)\\$</span> and the hole method would have a time complexity of <span class=\"math-container\">\\$O(n)\\$</span></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private List&lt;String&gt; buildChain(Node node) {\n List&lt;String&gt; chain = new LinkedList&lt;&gt;();\n while (node.getPredecessor() != null) {\n chain.add(0, node.getWord());\n node = node.getPredecessor();\n }\n chain.add(node.getWord());\n return chain;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T05:17:49.807", "Id": "412702", "Score": "2", "body": "oh wow thank you so much... i really had struggeled with my code, even though it's working and it's an proper algorithm (in my humble opinion) i had a lot of problems with my implementation!!! this answer is not good it's really great!!! i'll try to implement your very handy hints and show them to you!!! thank you very much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T07:02:24.757", "Id": "412708", "Score": "1", "body": "no problem @MartinFrank :] It makes me very happy that I could help you. And yes - it is a very cleaver idea to use the Breadth-First-Search for this problem! :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T07:17:42.770", "Id": "413942", "Score": "0", "body": "Code Review should have a common dictionaries like this for Java, OOP etc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T18:17:00.047", "Id": "213320", "ParentId": "213301", "Score": "3" } } ]
{ "AcceptedAnswerId": "213320", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T12:49:53.043", "Id": "213301", "Score": "3", "Tags": [ "java", "algorithm", "object-oriented" ], "Title": "Word Chain Implementation" }
213301
<p>The task:</p> <blockquote> <p>Given two strings A and B, return whether or not A can be shifted some number of times to get B.</p> <p>For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false.</p> </blockquote> <p>Solution 1:</p> <pre><code>const haveSameLength = (a, b) =&gt; a.length === b.length; const isSame = (a, b) =&gt; a === b; const isFullyShifted = a =&gt; a === 0; const shiftStringBy = i =&gt; a =&gt; `${a.substring(i)}${a.substring(0, i)}`; const isSameAfterShifting = (strA, strB, items) =&gt; { if (strA.length === 0 || strB.length ===0) { return false } if (!haveSameLength(strA, strB)) { return false } if (isSame(strA, strB)) { return true } if (isFullyShifted(items)) { return false } return isSameAfterShifting(strA, shiftStringBy(1)(strB), --items) } const str1 = 'abcde'; const str2 = 'cdeab'; console.log(isSameAfterShifting(str1, str2, str2.length)); </code></pre> <p>Solution 2</p> <pre><code>const isSameAfterShifting2 = (strA, strB) =&gt; { if (strA.length === 0 || strB.length ===0) { return false } if (!haveSameLength(strA, strB)) { return false } const arrB = strB.split(''); const firstLetterA = strA.substring(0, 1); let shiftIndex = arrB.indexOf(firstLetterA); if (shiftIndex === -1) { return false } while (shiftIndex &lt; arrB.length) { const strBShifted = `${strB.substring(shiftIndex)}${strB.substring(0, shiftIndex)}`; if (strA === strBShifted) { return true } shiftIndex++; } return false; } console.log(isSameAfterShifting2('abc', 'acb')); </code></pre> <p>Which one is more readable and easier to understand for you?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:15:27.560", "Id": "412662", "Score": "0", "body": "I think this needs only a one liner `const isShifted = (a, b) => a.length === b.length && a === b || (a + a).includes(b);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T17:55:13.827", "Id": "412948", "Score": "0", "body": "This is quite genius. Lol" } ]
[ { "body": "<p>You can check if the <code>String</code> is empty with <code>!str</code> instead of <code>strA.length === 0</code>, </p>\n\n<p><code>console.log(''); // false</code></p>\n\n<p>i think <code>haveSameLength</code> and <code>isSame</code> are extras, you can write <code>srtA.length === strB.length</code> and it would still be readable,</p>\n\n<p>you can get the first letter with a simpler <code>strA[0]</code> instead of <code>strA.substring(0, 1);</code></p>\n\n<blockquote>\n <p>Which one is more readable and easier to understand for you?</p>\n</blockquote>\n\n<p>a loop is easier to read and understand than a recursive function, </p>\n\n<p>But the hole approach seems like it can be simpler using a <code>for</code> loop, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\">Array.some()</a> , here's what i would suggest : </p>\n\n<p>You can generate an array of combinations moving the letters one index at a time,\nfor a string <code>abc</code> you would have <code>['abc, bca', 'cba']</code>, see if one of the resulting array entries euqals the second string :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const isSameAfterShifting = (str1, str2) =&gt; {\n // check if the strings are empty or has different lengths\n if (!str1 || !str2 || str1.length !== str2.length) return false;\n\n // check if the strings are the same\n if (str1 === str2) return true;\n\n // generate the array \n let combos = [];\n for (let i = 0; i &lt; str1.length; i++) {\n let c = str1.slice(i) + str1.slice(0, i);\n combos.push(c);\n }\n\n // for a string 'abc'\n // combos = ['abc', bca', 'cab']\n\n // check if the array has one of its entries equal to the second string \n return combos.some(s =&gt; s === str2);\n}\n\nconsole.log( isSameAfterShifting('abc', 'cab') );\nconsole.log( isSameAfterShifting('abc', 'cabaaa') );\nconsole.log( isSameAfterShifting('abc', 'bac') );</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>you can replace the <code>for</code> loop with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"nofollow noreferrer\">Array.from()</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const isSameAfterShifting = (str1, str2) =&gt; {\n // check if the strings are empty or has different lengths\n if (!str1 || !str2 || str1.length !== str2.length) return false;\n\n // check if the strings are the same\n if (str1 === str2) return true;\n\n // generate the array\n let combos = Array.from({\n length: str1.length\n }, (_, i) =&gt; str1.slice(i) + str1.slice(0, i));\n\n // for a string 'abc'\n // combos = ['abc', bca', 'cab']\n\n // check if the array has one of its entries equal to the second string\n return combos.some(s =&gt; s === str2);\n};\n\nconsole.log(isSameAfterShifting(\"abc\", \"cab\"));\nconsole.log(isSameAfterShifting(\"abc\", \"cabaaa\"));\nconsole.log(isSameAfterShifting(\"abc\", \"bac\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T15:05:35.620", "Id": "213309", "ParentId": "213302", "Score": "1" } } ]
{ "AcceptedAnswerId": "213309", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T13:19:36.817", "Id": "213302", "Score": "1", "Tags": [ "javascript", "algorithm", "strings", "functional-programming", "comparative-review" ], "Title": "Find out whether string A can be shifted to get string B" }
213302
<p>I'm new to C, just started reading K&amp;R C book, and am working through exercises. This is my solution to 1-21, and as far as I tested it works. Anything that I'm doing wrong, or that it's not idiomatic C? What can be improved ?</p> <blockquote> <p>Exercise 1-21. Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab. When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?</p> </blockquote> <pre><code>#include &lt;stdio.h&gt; #define TAB_SIZE 4 int main_entab() { int c; int character_count = 0; int whitespace_count = 0; while ((c = getchar()) != EOF) { if (c == ' ') { // A _ B _ | _ C _ _ | int numberOfCharsToReachTabStop = (TAB_SIZE - ((character_count + whitespace_count) % TAB_SIZE)); whitespace_count++; if (numberOfCharsToReachTabStop == 1 &amp;&amp; whitespace_count &gt; 0) { putchar('\t'); //advance count by how many whitespaces we are replacing, so next tab stop calculation is correct character_count = character_count + whitespace_count; whitespace_count = 0; } } else { //we encountered a non-whitespace char. Print all 'saved' whitespaces. while (whitespace_count &gt; 0) { putchar(' '); whitespace_count--; character_count++; } //print the non-whitespace char character_count++; putchar(c); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-15T00:53:37.990", "Id": "412967", "Score": "0", "body": "the tab size on a printer or terminal will be 8 characters, not 4 characters, so the posted code will fail to perform as desired" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-15T00:55:03.700", "Id": "412969", "Score": "0", "body": "the `main()` function name is not optional. It must be 'main' not 'main_entab'" } ]
[ { "body": "<p>After <code>whitespace_count++</code>, the condition <code>&amp;&amp; whitespace_count &gt; 0</code> will always be <code>true</code>, so can be removed. </p>\n\n<p>Bug: if the file ends in space characters, these can be lost. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T13:39:28.003", "Id": "412750", "Score": "0", "body": "Unless `INT32_MAX == whitespace_count`. I would NOT advice to remove the condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T14:13:59.620", "Id": "412759", "Score": "2", "body": "@Nicolas `whitespace_count` is always non-negative. It could only overflow if `TABSIZE == INT_MAX+1` which is already an overflow." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T15:17:38.730", "Id": "213310", "ParentId": "213304", "Score": "3" } }, { "body": "<h3>Constants</h3>\n\n<blockquote>\n<pre><code>#define TAB_SIZE 4\n</code></pre>\n</blockquote>\n\n<p>This is the old way of doing things. Modernly C uses the same syntax as C++: </p>\n\n<pre><code>const int TAB_SIZE = 4;\n</code></pre>\n\n<p>While both will still function, this has the added benefit of offering type safety. The <code>#define</code> is just a search and replace used by the preprocessor. I.e. it replaces <code>TAB_SIZE</code> with the character 4 in an intermediate copy of the file. The <code>const</code> variable will be managed by the compiler. </p>\n\n<h3>Update assignments</h3>\n\n<blockquote>\n<pre><code> character_count = character_count + whitespace_count;\n</code></pre>\n</blockquote>\n\n<p>This is more idiomatically written </p>\n\n<pre><code> character_count += whitespace_count;\n</code></pre>\n\n<p>That form is exactly the same as the longer form. It evaluates the left-hand side of the assignment, adds it to the right-hand side, and stores the result in the left-hand side. But it is shorter and more easily recognizable. </p>\n\n<h3>Simplifying logic</h3>\n\n<p>However, I wouldn't do either of these. Instead, on each iteration of the loop, just increment <code>character_count</code>. Then you never have to add <code>character_count</code> and <code>whitespace_count</code>. This will work in your program because you never use <code>character_count</code> separately from <code>whitespace_count</code>. So make this change and replace <code>character_count + whitespace_count</code> with just <code>character_count</code>. </p>\n\n<h3>Yoda conditions</h3>\n\n<blockquote>\n<pre><code> if (c == ' ') {\n</code></pre>\n</blockquote>\n\n<p>This is often written as </p>\n\n<pre><code> if (' ' == c) {\n</code></pre>\n\n<p>The reason is that if you accidentally leave off an equals sign <code>' ' = c</code> will generate a compiler error. Meanwhile, <code>c = ' '</code> will silently do the wrong thing. It wouldn't be so bad here, as it will be immediately obvious in the display. But in a different kind of program, assigning to <code>c</code> might make a much more subtle bug. </p>\n\n<h3>Correct naming</h3>\n\n<blockquote>\n<pre><code> //we encountered a non-whitespace char. Print all 'saved' whitespaces.\n</code></pre>\n</blockquote>\n\n<p>This is incorrect. A whitespace is any character that can produce indent. It specifically includes tabs (and new lines). But what you check is non-space characters. This is easy enough to fix, just remove \"white\" both times here and rename <code>whitespace_count</code> to <code>space_count</code>. </p>\n\n<h3>Consistent naming style</h3>\n\n<p>You have the camelCased <code>numberOfCharsToReachTabStop</code> and snake_cased <code>character_count</code> and <code>whitespace_count</code>. Please pick one kind of casing per identifier type and stick to it. If local variables are snake_cased, then <code>number_of_chars_to_reach_tab_stop</code>. Or change them all to camelCase. I personally prefer snake_case, which is easier for non-native English speakers, as it doesn't rely on an ability to differentiate between capital and lowercase letters. But the most important thing is to be consistent so that people can see snake_case and realize that it is a local variable or one of the other things that use snake_case. </p>\n\n<p><code>TAB_SIZE</code> is a constant, so it is appropriate to use a different casing style (e.g. ALL_CAPS) for it. </p>\n\n<h3>Bugs</h3>\n\n<p>As already noted, you don't print spaces at the end of a line. But there is a more serious bug. You treat tabs as single characters in the character count. You should not. Instead, tabs are <code>TAB_SIZE</code> characters. Don't forget to adjust for the tab stop. I.e. if you are currently one character past the tab stop, you'd only add three characters for the tab. So if you adopt my previous suggestion of incrementing <code>character_count</code> on every iteration, you need something like </p>\n\n<pre><code>if ('\\t' == c) {\n /* update character_count appropriately */\n} else {\n character_count++;\n}\n</code></pre>\n\n<p>I'll leave the actual update to you, as that's the exercise that you're exploring. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:33:37.410", "Id": "412684", "Score": "0", "body": "Thank you so much for the detailed answer :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T15:59:47.593", "Id": "213312", "ParentId": "213304", "Score": "8" } }, { "body": "<p>the tab size on a printer or terminal will be 8 characters, not 4 characters, so the posted code will fail to perform as desired </p>\n\n<p>the main() function name is not optional. It must be 'main' not 'main_entab' </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-15T09:57:26.967", "Id": "412995", "Score": "0", "body": "Tab size I think is configurable. It's 4 on my machine. My guess is there should be a way to get the current size.\n\nYes, I know about the main, I was calling the main_entab() from another file that has the main function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-15T01:00:35.743", "Id": "213485", "ParentId": "213304", "Score": "1" } } ]
{ "AcceptedAnswerId": "213312", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T13:33:45.377", "Id": "213304", "Score": "5", "Tags": [ "beginner", "c", "formatting", "io" ], "Title": "K&R C book, Exercise 1-21: Replace tabs with spaces" }
213304
<p>Suppose You have two kind of response like one for success and one for failure </p> <p>Success response model will looks like </p> <pre><code>struct UserLogin: Codable { let status: Bool? let accessToken: String? let data: [UserLoginData]? .... } </code></pre> <p>Failure Model will looks like </p> <pre><code>struct FailedResponse: Codable { let status: Bool? let error: ErrorResponse? } </code></pre> <p>How I handle this two responses </p> <pre><code>struct FailableResponse &lt;T:Codable,E:Codable&gt; : Codable { var success:T? var failure:E? public init(from decoder:Decoder) throws { let singleValue = try decoder.singleValueContainer() success = try singleValue.decode(T.self) failure = try singleValue.decode(E.self) } } </code></pre> <p>And How I use <code>FailableResponse</code></p> <pre><code> APIClient.login(userName: self.loginViewModel.userName, password: self.loginViewModel.password) { (response:FailableResponse&lt;UserLogin,FailedResponse&gt;? , error) in } // METHOD OF API CLIENT // API CALLING static func login&lt;T:Codable&gt;(userName:String,password:String,completion:@escaping completionResponse&lt;T&gt;) { self.performRequest(request: APIRouterUserModule.login(email: userName, password: password)) {(model) in self.handleResponseCallCompletion(result: model, completion: completion) } } // Parsing private static func handleResponseCallCompletion&lt;T:Codable&gt;(result:Result&lt;Any&gt;,completion:@escaping completionResponse&lt;T&gt;) { let object = CodableHelper&lt;T&gt;().decode(json: result) completion(object.object,object.error) } </code></pre> <p>I think It can be more better </p> <p>Any suggestion Please :)</p>
[]
[ { "body": "<p>There are two approaches</p>\n\n<ol>\n<li><p>For the sake of completeness, I’ll describe the typical, simple solution:</p>\n\n<pre><code>struct UserLoginResponse: Codable {\n let status: Bool\n let error: ErrorResponse?\n let accessToken: String?\n let data: [UserLoginData]?\n}\n</code></pre>\n\n<p>The <code>status</code> is not optional (because it’s presumably there regardless). But you can just decode this <code>struct</code>:</p>\n\n<pre><code>do {\n let responseObject = try decoder.decode(UserLoginResponse.self, from: data)\n switch responseObject.status {\n case true:\n guard let accessToken = responseObject.accessToken, let userLoginData = responseObject.data else {\n throw ParsingError.requiredFieldMissing\n }\n\n // use accessToken and userLoginData here\n\n case false:\n guard let errorObject = responseObject.error else {\n throw ParsingError.requiredFieldMissing\n }\n\n // use errorObject here\n }\n} catch {\n print(error)\n}\n</code></pre></li>\n<li><p>If you really want to do this generic, wrapper approach, I’d suggest a slight refinement. Notably, the code in your question returns an object for which both the success and error objects are optionals. (There seem like there are a lot of <code>?</code> thrown in there quite liberally, whereas most API dictate “if success, <em>x</em> and <em>y</em> will be present, if failure, <em>z</em> will be present”.)</p>\n\n<p>I’d suggest, instead, a pattern that captures the fact that the response will be either success (when <code>status</code> is <code>True</code>) or failure (when <code>status</code> is <code>False</code>), and rather than returning both success and failure objects as optionals, use the <code>Result&lt;Success, Failure&gt;</code> enumeration with associated values, which is included in Swift 5. Or, if you’re using an earlier version of Swift, you can define it yourself:</p>\n\n<pre><code>enum Result&lt;Success, Failure&gt; {\n case success(Success)\n case failure(Failure)\n}\n</code></pre>\n\n<p>Then, the API response wrapper can have a non-optional <code>result</code> property of type <code>Result&lt;T, E&gt;</code>, where:</p>\n\n<ul>\n<li>If <code>status</code> is <code>True</code>, parse the success object as a non-optional associated value which is the <code>Success</code> type;</li>\n<li>If <code>status</code> is <code>False</code>, parse the error object as a non-optional associated value which is the <code>Failure</code> type;<br />&nbsp;</li>\n</ul>\n\n<p>Thus:</p>\n\n<pre><code>struct ApiResponse&lt;T: Codable, E: Codable&gt;: Codable {\n let status: Bool\n var result: Result&lt;T, E&gt;\n var error: E?\n\n enum CodingKeys: String, CodingKey {\n case status, error\n }\n\n init(from decoder: Decoder) throws {\n let values = try decoder.container(keyedBy: CodingKeys.self)\n status = try values.decode(Bool.self, forKey: .status)\n if status {\n let singleValue = try decoder.singleValueContainer()\n result = try .success(singleValue.decode(T.self))\n } else {\n let parsedError = try .failure(values.decode(E.self, forKey: .error))\n error = parsedError\n result = .failure(parsedError)\n }\n }\n}\n</code></pre>\n\n<p>Then you can do:</p>\n\n<pre><code>do {\n let responseObject = try decoder.decode(ApiResponse&lt;UserLoginResponse, ErrorResponse&gt;.self, from: data)\n switch responseObject.result {\n case .success(let object):\n print(object.accessToken, object.data)\n\n case .failure(let error):\n print(error)\n }\n} catch {\n print(error)\n}\n</code></pre>\n\n<p>This would seem to better capture the true nature of the response, that it’s either successful (and you get the non-optional success object) or it’s a failure (and you get the non-optional <code>ErrorResponse</code> object).</p>\n\n<p>By the way, I’d suggest that in this scenario, that <code>UserLoginResponse</code> be updated to reflect which fields are truly optional and which aren’t. For example, if you know that if <code>status</code> is <code>True</code>, that both <code>accessToken</code> and <code>data</code> will be present, then I’d make those non-optional properties:</p>\n\n<pre><code>struct UserLoginResponse: Codable {\n let accessToken: String\n let data: [UserLoginData]\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-29T04:44:15.070", "Id": "423673", "Score": "1", "body": "No one does it better than you :) , Thank for great explanation;" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-28T08:06:34.503", "Id": "219297", "ParentId": "213307", "Score": "3" } } ]
{ "AcceptedAnswerId": "219297", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T14:30:46.003", "Id": "213307", "Score": "3", "Tags": [ "swift", "ios" ], "Title": "Codable Failure Response Handler" }
213307
<p>Round 1: <a href="https://codereview.stackexchange.com/q/213259/73844">Analyzing spoke overlaps during rotation</a></p> <p>I previously posted this question, but I've changed a <em>lot</em> of the code since then.</p> <p>There was a mention of the previous being a bit mixed up, and things being too integrated, so I've abstracted away a lot of that functionality.</p> <p>The purpose of this program is to draw two shapes with given counts of &quot;spokes&quot;, and then analyze the rotation between them and how often the spokes would intersect / overlap / pass each other.</p> <p>To start, I've defined a <code>Shape</code> type that has various components we'll need throughout the program:</p> <h2>Types.fs:</h2> <pre><code>[&lt;AutoOpen&gt;] module Spoke_Analyzer.Types [&lt;Struct&gt;] type Shape = { Spokes : int Angle : float PointSize : int PenWidth : float32 Color : System.Drawing.Color } </code></pre> <p>Next, I moved a couple components to <code>Math.fs</code>, in particular:</p> <ul> <li><code>getXY</code>: this will take the distance and angle and calculate what (X, Y) that is from the origin;</li> <li><code>getOverlaps</code>: this will use the property that the number of total overlaps = the multiple of both spoke counts, then to establish the number of rotations to get all overlaps, it will determine if there are any coincident spokes (<code>large % small = 0</code>) and divide those out;</li> </ul> <p>Additionally, I noticed that there were quite a few edge-cases and miscalculations in the <code>getRotation</code> (though, for the single use-case I needed it worked fine), so I went about it a different route and they seem to have disappeared.</p> <h2>Math.fs:</h2> <pre><code>module Spoke_Analyzer.Math let inline degToRad deg = deg * System.Math.PI / 180. let inline radToDeg rad = rad * 180. / System.Math.PI let inline angleMath distance angle fn = (distance * (angle |&gt; degToRad |&gt; fn)) |&gt; int let inline getXY distance angle = cos |&gt; angleMath distance angle, sin |&gt; angleMath distance angle let inline getOverlaps count1 count2 = let inline calculation smallCount largeCount = let totalOverlaps = (smallCount |&gt; float) * (largeCount |&gt; float) // If the small divides into large evenly, then there are `small` coincident spokes, and we'll divide our total // overlap count by that number. if largeCount % smallCount &lt;&gt; 0 then totalOverlaps else totalOverlaps / (smallCount |&gt; float) if count1 &gt; count2 then calculation count2 count1 else calculation count1 count2 </code></pre> <p>Our <code>Graphics.fs</code> got a <em>major</em> overhaul:</p> <ul> <li><code>drawSpokes</code>: this will draw the spokes for a given shape;</li> <li><code>saveImages</code>: this will draw and save the images, using the <code>drawSpokes</code> function;</li> <li><code>makeGif</code>: this will make the <code>gif</code> file / do the <code>ffmpeg</code> work;</li> </ul> <h2>Graphics.fs:</h2> <pre><code>module Spoke_Analyzer.Graphics open System open System.Drawing open Spoke_Analyzer let drawLine (origin : Point) (g : Graphics) (pen : Pen) (start : Point, stop : Point) = g.DrawLine(pen, Point(start.X + origin.X, start.Y + origin.Y), Point(stop.X + origin.X, stop.Y + origin.Y)) let drawPoint (origin : Point) (g : Graphics) (brush : Brush) width (start : Point) = g.FillEllipse(brush, Rectangle(start.X + origin.X - (width / 2), start.Y + origin.Y - (width / 2), width, width)) let drawSpokes (origin : Point) (g : Graphics) distance (pen : Pen) (brush : Brush) shape offset = let drawLine = drawLine origin g pen let drawPoint = drawPoint origin g brush let drawSpoke num = (Point(0, 0), (shape.Angle * (num |&gt; float) + offset) |&gt; Spoke_Analyzer.Math.getXY distance |&gt; Point) |&gt; drawLine [|0..shape.Spokes|] |&gt; Array.iter (drawSpoke) offset |&gt; Spoke_Analyzer.Math.getXY distance |&gt; Point |&gt; drawPoint shape.PointSize let saveImages imageWidth imageDir shape1 shape2 rotationOffset offset angleDifference totalRotations = let drawImage (bmp : Bitmap) (clearColor : Color) i = use pen1 = new Pen(shape1.Color, shape1.PenWidth) use brush1 = new SolidBrush(shape1.Color) use pen2 = new Pen(shape2.Color, shape2.PenWidth) use brush2 = new SolidBrush(shape2.Color) use g = bmp |&gt; Graphics.FromImage g.SmoothingMode &lt;- Drawing2D.SmoothingMode.AntiAlias g.Clear(clearColor) let drawSpokes = drawSpokes (Point(bmp.Width / 2, bmp.Height / 2)) g (((imageWidth - ((max shape1.PointSize shape2.PointSize) / 2 + 2)) / 2) |&gt; float) drawSpokes pen1 brush1 shape1 rotationOffset drawSpokes pen2 brush2 shape2 (shape2.Angle * offset + rotationOffset + angleDifference * (i |&gt; float)) () let totalRotations = if totalRotations |&gt; Double.IsInfinity then 1 else totalRotations |&gt; int use bmp = new Bitmap(imageWidth, imageWidth) [|0..totalRotations - 1|] |&gt; Array.iter (fun i -&gt; drawImage bmp (Color.FromArgb(255, 32, 32, 32)) i bmp.Save(sprintf &quot;%s/rot_%i.png&quot; imageDir i, Imaging.ImageFormat.Png)) let makeGif fps imageDir : string option -&gt; unit = function | Some ffmpeg -&gt; let ffmpeg = if ffmpeg.EndsWith(&quot;ffmpeg&quot;) = false &amp;&amp; ffmpeg.EndsWith(&quot;ffmpeg.exe&quot;) = false then System.IO.Path.Combine(ffmpeg, &quot;ffmpeg&quot;) else ffmpeg printfn &quot;Running ffmpeg...&quot; System .Diagnostics .Process .Start(ffmpeg, sprintf &quot;-framerate %i -f image2 -i %s/rot_%%d.png -c:v libx264 -crf 0 -r %i -preset ultrafast -tune stillimage %s/temp.avi&quot; fps imageDir fps imageDir) .WaitForExit() System .Diagnostics .Process .Start(ffmpeg, sprintf &quot;-i %s/temp.avi -pix_fmt rgb24 %s/_final.gif&quot; imageDir imageDir) .WaitForExit() printfn &quot;Images converted to gif.&quot; printfn &quot;&quot; | _ -&gt; () </code></pre> <p>The only changes to <code>Input.fs</code> were some formatting:</p> <h2>Input.fs:</h2> <pre><code>module Spoke_Analyzer.Input open System let rec getInput convert validate prompt = printf &quot;%s&quot; prompt let input = () |&gt; Console.ReadLine if input |&gt; validate then input |&gt; convert else printfn &quot;Invalid, please try again.&quot; getInput convert validate prompt let getInputInt = getInput Int32.Parse (Int32.TryParse &gt;&gt; function | true, f when f &gt; 0 -&gt; true | _ -&gt; false) let getInputIntOption = getInput (function | &quot;&quot; -&gt; None | s -&gt; s |&gt; Int32.Parse |&gt; Some) (function | &quot;&quot; -&gt; true | s -&gt; s |&gt; Int32.TryParse |&gt; function | true, f when f &gt; 0 -&gt; true | _ -&gt; false) let getInputDoubleOption = getInput (function | &quot;&quot; -&gt; None | s -&gt; s |&gt; Double.Parse |&gt; Some) (function | &quot;&quot; -&gt; true | s -&gt; s |&gt; Double.TryParse |&gt; function | true, f when f &gt;= 0. &amp;&amp; f &lt;= 1. -&gt; true | _ -&gt; false) let getInputDouble = getInput Double.Parse (Double.TryParse &gt;&gt; function | true, f when f &gt;= 0. &amp;&amp; f &lt;= 1. -&gt; true | _ -&gt; false) let getInputFileOption (file : string) = getInput (function | &quot;&quot; -&gt; None | s -&gt; Some s) (function | &quot;&quot; -&gt; true | s -&gt; if Uri.IsWellFormedUriString(sprintf &quot;file:///%s&quot; (s.Replace('\\', '/')), UriKind.RelativeOrAbsolute) then let test = if s.EndsWith(file) = false &amp;&amp; s.EndsWith(sprintf &quot;%s.exe&quot; file) = false then let t = System.IO.Path.Combine(s, file) if System.IO.File.Exists(t) then t else System.IO.Path.Combine(s, sprintf &quot;%s.exe&quot; file) else s if System.IO.File.Exists(test) then true else false else false) </code></pre> <p>We also added an <code>IO.fs</code> to separate directory concerns out:</p> <h2>IO.fs:</h2> <pre><code>module Spoke_Analyzer.IO let createDirIfNotExists dir = if dir |&gt; System.IO.Directory.Exists then dir |&gt; System.IO.DirectoryInfo else dir |&gt; System.IO.Directory.CreateDirectory let clearDir = System.IO.Directory.GetFiles &gt;&gt; Array.iter System.IO.File.Delete </code></pre> <p>And finally, our <code>Program.fs</code> got a lot tighter:</p> <h2>Program.fs:</h2> <pre><code>open System open System.Drawing open Spoke_Analyzer open Spoke_Analyzer [&lt;Literal&gt;] let FULL_CIRCLE = 360. [&lt;Literal&gt;] let ROTATION_OFFSET = -90. // -FULL_CIRCLE / 4. [&lt;Literal&gt;] let IMAGE_DIR = &quot;temp/images&quot; [&lt;EntryPoint&gt;] let main argv = let getShape pointSize penWidth color i = let spokes = i |&gt; sprintf &quot;Enter the number of spokes for shape %i (whole number &gt; 0): &quot; |&gt; Input.getInputInt { Spokes = spokes; Angle = FULL_CIRCLE / (spokes |&gt; float); PointSize = pointSize; PenWidth = penWidth; Color = color } let imageWidth = Input.getInputIntOption &quot;Enter the image dimension (whole number &gt; 0) [160]: &quot; |&gt; Option.defaultValue 160 let shape1 = getShape 8 2.5f (Color.FromArgb(255, 224, 32, 32)) 1 let shape2 = getShape 6 1.5f (Color.FromArgb(255, 32, 224, 32)) 2 let offset = Input.getInputDoubleOption &quot;Enter the radial offset in percentage (0.0 - 1.0) [0]: &quot; |&gt; Option.defaultValue 0. let ffmpeg = Input.getInputFileOption &quot;ffmpeg&quot; &quot;Enter the location of ffmpeg (if available) []: &quot; let fps = ffmpeg |&gt; Option.bind (fun s -&gt; Input.getInputIntOption &quot;Enter the fps of the output (whole number &gt; 0) [24]: &quot;) |&gt; Option.defaultValue 24 printfn &quot;&quot; let totalRotations = Spoke_Analyzer.Math.getOverlaps shape1.Spokes shape2.Spokes let angleDifference = FULL_CIRCLE / totalRotations IMAGE_DIR |&gt; Spoke_Analyzer.IO.createDirIfNotExists |&gt; ignore IMAGE_DIR |&gt; Spoke_Analyzer.IO.clearDir |&gt; ignore Graphics.saveImages imageWidth IMAGE_DIR shape1 shape2 ROTATION_OFFSET offset angleDifference totalRotations printfn &quot;Images saved.&quot; Graphics.makeGif fps IMAGE_DIR ffmpeg printfn &quot;Shape 1 Angle (%i spokes): %f° / %f rads&quot; shape1.Spokes shape1.Angle (shape1.Angle |&gt; Spoke_Analyzer.Math.degToRad) printfn &quot;Shape 2 Angle (%i spokes): %f° / %f rads&quot; shape2.Spokes shape2.Angle (shape2.Angle |&gt; Spoke_Analyzer.Math.degToRad) printfn &quot;Overlap Angle Difference: %f° / %f rads (%f rotations)&quot; angleDifference (angleDifference |&gt; Spoke_Analyzer.Math.degToRad) (angleDifference / FULL_CIRCLE) printfn &quot;Overlaps per Rotation: %f&quot; totalRotations 0 </code></pre> <p>I've no idea if LoC went down or not, nor do I really care, because this feels like a much more maintainable version.</p> <p>As always, all suggestions welcome.</p> <p>The project is on GitHub: <a href="https://github.com/EBrown8534/Spoke_Analyzer" rel="nofollow noreferrer">https://github.com/EBrown8534/Spoke_Analyzer</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T15:00:08.030", "Id": "413404", "Score": "0", "body": "@HenrikHansen Possibly, that would make for a fair answer." } ]
[ { "body": "<p>In <code>getOverlaps</code> I think you should find the <code>gcd(small, large)</code> and divide with that instead of testing for <code>large % small &lt;&gt; 0</code> (if I understand the project right).</p>\n\n<p>E.g.: <code>spokes 12 and 15 -&gt; gcd = 3 -&gt; 180 / 3 = 60 rotations -&gt; rotation angle: 360 / 60 = 6</code></p>\n\n<hr>\n\n<p>IMO you overdo the use of the <code>|&gt;</code> operator a little:</p>\n\n<blockquote>\n<pre><code>let input = () |&gt; Console.ReadLine\nif input |&gt; validate then\n</code></pre>\n</blockquote>\n\n<p>To me it is more clear and straight forward to write:</p>\n\n<pre><code>let input = Console.ReadLine()\nif validate input then\n ...\n</code></pre>\n\n<hr>\n\n<p>All in all it's definitely better and cleaner than the first version, but I still think it could be more stringent in the workflow.</p>\n\n<p>For instance:</p>\n\n<p>The <code>main</code> function could be be split into:</p>\n\n<pre><code>let processInfo = promptForInput()\n\nprepareOutputDirectory processInfo.OutputPath\nprocessRotations processInfo\n</code></pre>\n\n<p>All the exiting stuff are hidden in <code>Graphics.saveImages</code>. I think I would \"revert\" the process/workflow, so that it is more clear what the algorithm and what the output are - for instance:</p>\n\n<pre><code>let processRotations processInfo =\n let rec processRotation info =\n if info.RotationIndex &lt; info.Rotations then\n createImage info\n processRotation (rotate info)\n else\n postProcess info // create gif, print info etc...\n\n processRotation processInfo\n</code></pre>\n\n<p>The function <code>rotate info</code> handles the rotation of one of the shapes and returns a new instance of processInfo that holds that new state state plus all the other (input) information</p>\n\n<p>I hope this skeleton makes any sense...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-18T17:05:59.353", "Id": "213737", "ParentId": "213308", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T14:32:20.750", "Id": "213308", "Score": "4", "Tags": [ ".net", "image", "animation", "f#", "graphics" ], "Title": "Analyzing spoke overlaps during rotation: Round 2" }
213308
<p>I made a brute force password cracker with Python, but it's extremely slow. How can I make it faster?</p> <pre><code>import itertools import string import time def guess_password(real): chars = string.ascii_uppercase + string.digits password_length = 23 start = time.perf_counter() for guess in itertools.product(chars, repeat=password_length): guess = ''.join(guess) t = list(guess) t[5] = '-' t[11] = '-' t[17] = '-' tg = ''.join(t) if tg == real: return 'Scan complete. Code: \'{}\'. Time elapsed: {}'.format(tg, (time.perf_counter() - start)) print(guess_password('E45E7-BYXJM-7STEY-K5H7L')) </code></pre> <p>As I said, it's extremely slow. It takes at least 9 days to find a single password.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T16:27:04.280", "Id": "412625", "Score": "6", "body": "For a start you could change `password_length` to 20, you are needlessly duplicating your searches (each of your proposal passwords is constructed 36^3 different times)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T16:40:27.580", "Id": "412627", "Score": "0", "body": "@RussHyde thanks for your comment. I compared my old code and your code with `AAAAA-AAAAA-AAAAA-FORTN` but my old code is faster than yours with 5 seconds. My old code got 25 seconds but your one got 30 seconds. Why? I thought it was going to make it faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T16:59:34.487", "Id": "412631", "Score": "2", "body": "Do it a thousand times, and post the mean and std-dev" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:14:03.770", "Id": "412633", "Score": "0", "body": "You could also strip the \"-\" from a single copy of the real password, rather than mutating every guess" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:36:18.673", "Id": "412691", "Score": "0", "body": "This is almost a hypothetical question, as you would never have the real password to test against, but some encrypted/hashed version of it. If you had it available for a more direct string comparison somehow, it would make sense to either guess character by character, or group by group." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T01:34:23.120", "Id": "412697", "Score": "1", "body": "@AkınOktayATALAY Try Russ Hyde's suggested change with a password that extends past the first dash and you'll see the difference much more clearly: `AAAAA-AAAAA-AAAAB-AAAAA`." } ]
[ { "body": "<p>You should exploit the structure of the password, if it has any. Here you have a 20 character password separated into four blocks of five characters each, joined with a <code>-</code>. So don't go on generating all combinations of length 23, only to throw most of them away.</p>\n\n<p>You also <code>str.join</code> the guess, then convert it to a <code>list</code>, then replace the values and <code>str.join</code> it again. You could have saved yourself the first <code>str.join</code> entirely by directly converting to <code>list</code>.</p>\n\n<p>You know the length of the password, so no need to hardcode it. Just get it from the real password (or, in a more realistic cracker, pass the length as a parameter).</p>\n\n<p>With these small changes your code would become:</p>\n\n<pre><code>def guess_password(real):\n chars = string.ascii_uppercase + string.digits\n password_format = \"-\".join([\"{}\"*5] * 4)\n password_length = len(real) - 3\n for guess in itertools.product(chars, repeat=password_length):\n guess = password_format.format(*guess)\n if guess == real:\n return guess\n</code></pre>\n\n<p>Here I used some string formatting to get the right format.</p>\n\n<p>Note also that the timing and output string are not in there. Instead make the former a <a href=\"https://realpython.com/primer-on-python-decorators/\" rel=\"noreferrer\">decorator</a> and the latter part of the calling code, which should be protected by a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow you to import from this script without running the brute force cracker:</p>\n\n<pre><code>from time import perf_counter\nfrom functools import wraps\n\ndef timeit(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = perf_counter()\n ret = func(*args, **kwargs)\n print(f\"Time elapsed: {perf_counter() - start}\")\n return ret\n return wrapper\n\n@timeit\ndef guess_password(real):\n ...\n\nif __name__ == \"__main__\":\n real_password = 'E45E7-BYXJM-7STEY-K5H7L'\n if guess_password(real_password):\n print(f\"Scan completed: {real_password}\")\n</code></pre>\n\n<p>On my machine this takes 9.96 s ± 250 ms, whereas your code takes 12.3 s ± 2.87 s for the input string <code>\"AAAAA-AAAAA-AAAAA-FORTN\"</code>.</p>\n\n<p>But in the end you will always be limited by the fact that there are a <em>lot</em> of twenty character strings consisting of upper case letters and digits. Namely, there are <span class=\"math-container\">\\$36^{20} = 13,367,494,538,843,734,067,838,845,976,576\\$</span> different passwords that need to be checked (well, statistically you only need to check half of them, on average, until you find your real password, but you might get unlucky). Not even writing your loop in Assembler is this going to run in less than days.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:23:11.800", "Id": "412635", "Score": "0", "body": "I got output `guess = password_format.format(*guess)\n\nIndexError: tuple index out of range`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:26:19.770", "Id": "412638", "Score": "0", "body": "@AkınOktayATALAY: In that case you gave it a password of a different format (or used a previous revision, I had a typo in the password length). It works with the two given strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:27:24.510", "Id": "412639", "Score": "0", "body": "I think I should change `password_length = len(real) - 5` to `password_length = len(real) - 3`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:31:06.003", "Id": "412640", "Score": "0", "body": "@AkınOktayATALAY: Yes, I already did that (about a minute after posting the answer for the first time), just update the page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:31:16.517", "Id": "412641", "Score": "0", "body": "Yeah it reduced 5 seconds. I will mark as working in at least a hour. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:32:11.670", "Id": "412642", "Score": "1", "body": "@AkınOktayATALAY: Take your time. It is usually not a bad idea to wait at least 24 hours, so everybody on the globe had a chance to see the question and think about answering. Maybe I missed something." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T17:15:33.390", "Id": "213319", "ParentId": "213313", "Score": "8" } }, { "body": "<p>There are other ways beyond improving the code itself.</p>\n\n<ol>\n<li>Beyond changes which reduce allocations a lot, like:</li>\n</ol>\n\n<pre><code>t = list(guess)\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>guess = ''.join(guess)\nt = list(guess)\n</code></pre>\n\n<p>Reduces the runtime 11s -> 6.7s.</p>\n\n<ol start=\"2\">\n<li>You can use a different runtime which will speed up almost any code:</li>\n</ol>\n\n<pre><code>➜ /tmp python3 foo.py\nScan complete. Code: 'AAAAA-AAAAA-AAAAA-FORTN'. Time elapsed: 6.716003532\n➜ /tmp pypy3 foo.py\nScan complete. Code: 'AAAAA-AAAAA-AAAAA-FORTN'. Time elapsed: 3.135087580012623\n</code></pre>\n\n<ol start=\"3\">\n<li>Or precompile the existing code into a module which you can load again in your standard python code:</li>\n</ol>\n\n<pre><code># cythonize -3 -i foo.py\nCompiling /private/tmp/foo.py because it changed.\n[1/1] Cythonizing /private/tmp/foo.py\nrunning build_ext\nbuilding 'foo' extension\n...\n\n# ipython3\n\nIn [1]: import foo\nScan complete. Code: 'AAAAA-AAAAA-AAAAA-FORTN'. Time elapsed: 3.846977077\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T14:43:03.153", "Id": "412762", "Score": "0", "body": "thanks the `cythonize` worked but the PyPy is 3x slow for me. Do you know why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T22:56:10.367", "Id": "412846", "Score": "0", "body": "`¯\\_(ツ)_/¯` sorry" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:21:28.140", "Id": "213345", "ParentId": "213313", "Score": "4" } } ]
{ "AcceptedAnswerId": "213319", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T16:21:51.023", "Id": "213313", "Score": "6", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Brute force password cracker in Python" }
213313
<p>I'm calling an API to request token, and making sure i'm not leaving any corners for errors and handle the result appropriately. </p> <p>It's a web service POST call in general, The code gets credentials, formats them in the URL and parses the result.</p> <p>The objective here is I'm looking if code overall is good when it comes to REST call, if any corner I'm missing for an error somewhere.</p> <pre><code>function Authentication() { } Authentication.prototype.requestToken = function(credentials) { var self = this; return new Promise(function(resolve, reject){ https.request({ method: 'POST', hostname: 'hostname.com', path: '/path-to-api' + '&amp;client_id=' + credentials.clientId + '&amp;client_secret=' + credentials.clientSecret + '&amp;device_id=' + credentials.deviceId + '&amp;device_token=' + credentials.deviceToken, headers: { 'accept': 'application/json;charset=UTF-8', 'content-type': 'application/x-www-form-urlencoded' } }, function(response) { var buffers = []; response.on('data', buffers.push.bind(buffers)); response.on('end', function(){ try { self.token = JSON.parse(Buffer.concat(buffers).toString()); response.statusCode == 200 ? resolve(self.token) : reject(self.token); } catch (error) { reject(error); } }); }).on('error', reject).end(); }); }; Authentication.prototype.token; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T20:54:10.373", "Id": "412657", "Score": "1", "body": "Please tell us more about what your code does and why you wrote it. Code lives in a context and a good review takes this context into account." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:34:12.013", "Id": "412685", "Score": "0", "body": "@Mast I've added some details, hope it helps. The idea is to know if the http call is comprehensive covering all corners of errors and results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T14:44:51.187", "Id": "412763", "Score": "0", "body": "Much better already." } ]
[ { "body": "<p>A few minor quibbles:</p>\n\n<ul>\n<li>You should always have a try-catch inside a new Promise, otherwise exceptions are swallowed. </li>\n<li>Query parameters should be escaped</li>\n<li>\"new Promise\" should be a rare sight. Never use it directly. Always wrap the thing you want to use with a promise interface (in this case, it's the https library)</li>\n</ul>\n\n<p>And a major quibble:</p>\n\n<ul>\n<li>This code is stuck in the past. You can simplify greatly if you embrace newer versions of javascript, and maybe add a couple of packages</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>const rp = require('request-promise')\n\nclass Authentication{\n constructor(){\n this.token = null\n }\n\n async requestToken(credentials){\n const token = await rp({\n method: 'POST',\n uri: 'https://hostname.com/path-to-api',\n json: true,\n qs: {\n client_id: credentials.clientId,\n client_secret: credentials.clientSecret,\n device_id: credentials.deviceId,\n device_token: credentials.deviceToken,\n },\n headers: {\n 'accept': 'application/json;charset=UTF-8',\n 'content-type': 'application/x-www-form-urlencoded'\n }\n })\n\n this.token = token\n return token\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T19:51:13.377", "Id": "413177", "Score": "0", "body": "thanks but I don't see any error handlings, it's never a smooth ride, what if things goes wrong? my code was around all possibilites of errors, from json parsing, to http errors and returning it to the caller" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T19:51:33.287", "Id": "413178", "Score": "0", "body": "I didn't get you on `You should always have a try-catch inside a new Promise, otherwise exceptions are swallowed.` please explain more. I think my code try catch is inside." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T06:28:04.260", "Id": "413201", "Score": "1", "body": "Your code didn't handle any errors, it just turned them into rejections. My version also does this. About try catch inside a new promise. Anything you don't reject yourself will be swallowed. For example, if credentials is null, you will get a swallowed exception." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-17T18:42:59.957", "Id": "413278", "Score": "1", "body": "in your version, I'll have a try catch outside or catch expression at the caller level of requestToken, appreciate if you can add that part just for a comprehensive deal." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T11:22:52.657", "Id": "213578", "ParentId": "213317", "Score": "1" } } ]
{ "AcceptedAnswerId": "213578", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T16:39:33.273", "Id": "213317", "Score": "1", "Tags": [ "javascript", "node.js" ], "Title": "Calling token API" }
213317
<p>I recently started learning C++ and have made a very simple Console-based Snake Game, I would like to have some feedback on improvements.</p> <p>You might notice the obvious delay in clearing and printing of the screen, as I did not use <code>system("cls")</code> since it was stated as 'evil' and 'bad'.<br> I printed a bunch of newlines instead as suggested <a href="http://www.cplusplus.com/forum/articles/10515/" rel="noreferrer">in a forum that I had read</a>.<br> (Didn't use NCurses since it was an overkill for my simple snake game)</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;limits&gt; #include &lt;conio.h&gt; #include &lt;thread&gt; #include &lt;chrono&gt; enum Direction2D { UNDEFINED = 0, LEFT, RIGHT, UP, DOWN }; bool IsOppositeOf(const Direction2D&amp; first, const Direction2D&amp; second) { // Feedback for a more elegant approach, thanks. bool isOpposite = false; if (first == LEFT &amp;&amp; second == RIGHT) { isOpposite = true; } else if (first == RIGHT &amp;&amp; second == LEFT) { isOpposite = true; } else if (first == UP &amp;&amp; second == DOWN) { isOpposite = true; } else if (first == DOWN &amp;&amp; second == UP) { isOpposite = true; } return isOpposite; } struct Vector2D { int x; int y; }; // Since we are printing downwards, 'up' would technically be down. Vector2D const Up = { 0, -1 }; Vector2D const Down = { 0, 1 }; Vector2D const Left = { -1, 0 }; Vector2D const Right = { 1, 0 }; Vector2D const Zero = { 0, 0 }; #pragma region Vector2D_Operators bool operator ==(const Vector2D&amp; first, const Vector2D&amp; second) { return (first.x == second.x) &amp;&amp; (first.y == second.y); } Vector2D operator +(const Vector2D&amp; first, const Vector2D&amp; second) { return { (first.x + second.x), (first.y + second.y) }; } Vector2D operator -(const Vector2D&amp; first, const Vector2D&amp; second) { return { (first.x - second.x), (first.y - second.y) }; } #pragma endregion bool gameOver; int playerScore; int width; int height; Vector2D snakeHeadPosition; Vector2D currentFruitPosition; Direction2D currentSnakeMovingDirection; // I'm assuming the length of the tail doesn't go beyond 256. // Accepting feedback on how I could do this more elegantly. Vector2D tailPositions[256]; int tailLength; #pragma region Util void ClearCinInput() { std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); } template &lt;typename T&gt; void RequestForValidInputValue(T &amp;receivingArg, std::string errorMsg) { // Ask for input while the input is not of the correct type. while (!(std::cin &gt;&gt; receivingArg)) { std::cout &lt;&lt; errorMsg &lt;&lt; std::endl; ClearCinInput(); } } #pragma region Request_For_YesNo void PrintRespectiveYesNoTextByFirstRun(bool firstRun) { if (firstRun) { std::cout &lt;&lt; "(Y/N)" &lt;&lt; std::endl; } else { std::cout &lt;&lt; "Please input either 'Y' or 'N'." &lt;&lt; std::endl; } } bool CheckIfValidYesNoInput(std::string input) { return (input == "Y" || input == "N"); } bool AskUserForYesNo() { std::string userInput = ""; bool loopFirstRun = true; // Ask for input again while the input was not a confirmation. do { PrintRespectiveYesNoTextByFirstRun(loopFirstRun); RequestForValidInputValue(userInput, "ERROR: Please input 'Y' or 'N' "); loopFirstRun = false; } while (!CheckIfValidYesNoInput(userInput)); return userInput == "Y"; } #pragma endregion void ClearScreen() { // SLOW std::cout &lt;&lt; std::string(100, '\n'); } void PlaceFruitRandomlyInPlayingField() { currentFruitPosition = { rand() % width, rand() % height }; } #pragma endregion void HandleFruitEating() { ++tailLength; ++playerScore; PlaceFruitRandomlyInPlayingField(); } bool SnakeEatingFruit() { return snakeHeadPosition == currentFruitPosition; } bool SnakeHeadTouchedTail() { bool touchedTail = false; for (int i = 0; i &lt; tailLength; ++i) { if (tailPositions[i] == snakeHeadPosition) { touchedTail = true; break; } } return touchedTail; } bool SnakeHeadTouchedBorder() { int x = snakeHeadPosition.x; int y = snakeHeadPosition.y; return (x &gt; width || x &lt; 0 || y &gt; height || y &lt; 0); } void UpdateSnakePositionByCurrentMoveDirection() { switch (currentSnakeMovingDirection) { case LEFT: snakeHeadPosition = snakeHeadPosition + Left; break; case RIGHT: snakeHeadPosition = snakeHeadPosition + Right; break; case UP: snakeHeadPosition = snakeHeadPosition + Up; break; case DOWN: snakeHeadPosition = snakeHeadPosition + Down; break; default: break; } } void UpdateSnakeTailPositions() { Vector2D prevPosition = tailPositions[0]; Vector2D temp; tailPositions[0] = snakeHeadPosition; for (int i = 1; i &lt; tailLength; ++i) { temp = tailPositions[i]; tailPositions[i] = prevPosition; prevPosition = temp; } } void UpdateGameLogic() { UpdateSnakeTailPositions(); UpdateSnakePositionByCurrentMoveDirection(); if (SnakeHeadTouchedBorder() || SnakeHeadTouchedTail()) { gameOver = true; } else if (SnakeEatingFruit()) { HandleFruitEating(); } } #pragma region Handling_Inputs void MoveSnakeIfValid(Direction2D newDirection) { if (tailLength &gt; 0) { // To prevent suicidal acts by moving backwards into a tail. if (!IsOppositeOf(newDirection, currentSnakeMovingDirection)) { currentSnakeMovingDirection = newDirection; } } else { currentSnakeMovingDirection = newDirection; } } void MoveSnakeByUserInput(char inputValue) { Direction2D newMoveDirection; switch (inputValue) { case 'a': newMoveDirection = LEFT; break; case 'd': newMoveDirection = RIGHT; break; case 'w': newMoveDirection = UP; break; case 's': newMoveDirection = DOWN; break; default: newMoveDirection = UNDEFINED; break; } if (newMoveDirection != UNDEFINED) { MoveSnakeIfValid(newMoveDirection); } } bool GetKeyPressInputIfExists(char &amp;keyPressValue) { if (_kbhit()) { keyPressValue = _getch(); return true; } else { return false; } } #pragma endregion void HandleInput() { char keyPressValue; if (GetKeyPressInputIfExists(keyPressValue)) { MoveSnakeByUserInput(keyPressValue); } } #pragma region Drawing_PlayField bool PrintTailOnPositionIfNeeded(Vector2D position) { bool tailPrinted = false; for (int i = 0; i &lt; tailLength; ++i) { if (position == tailPositions[i]) { std::cout &lt;&lt; "o"; tailPrinted = true; break; } } return tailPrinted; } void PrintFruitOrSnakeOrEmptyByPosition(Vector2D position) { if (snakeHeadPosition == position) { std::cout &lt;&lt; "O"; } else if (currentFruitPosition == position) { std::cout &lt;&lt; "X"; } else if (!PrintTailOnPositionIfNeeded(position)) { std::cout &lt;&lt; " "; } } void DrawHorizontalBorderByWidth() { for (int i = 0; i &lt; width + 2; ++i) { std::cout &lt;&lt; "#"; } std::cout &lt;&lt; std::endl; } void DrawMiddleSection() { for (int i = 0; i &lt; height; ++i) { for (int j = 0; j &lt; width; ++j) { if (j == 0) { std::cout &lt;&lt; "#"; } PrintFruitOrSnakeOrEmptyByPosition({ j, i }); if (j == width - 1) { std::cout &lt;&lt; "#"; } } std::cout &lt;&lt; std::endl; } } #pragma endregion void DrawPlayingField() { // system("cls"); ClearScreen(); // Top DrawHorizontalBorderByWidth(); DrawMiddleSection(); // Bottom DrawHorizontalBorderByWidth(); } void UpdateGame() { DrawPlayingField(); HandleInput(); UpdateGameLogic(); } #pragma region Request_PlayField_Width_And_Height_From_User #pragma region Request_For_Valid_Play_Field_Size bool PlayingFieldSizeIsValid() { return (width &gt;= 10) &amp;&amp; (height &gt;= 10); } void RequestForValidPlayingFieldSize() { bool loopFirstRun = true; // Keep asking for width and height while the given playing field is not of valid size. do { if (!loopFirstRun) { std::cout &lt;&lt; "The width and height of the playing field must be at least 10 or more!"; } std::cout &lt;&lt; "Enter the gamearea's width: " &lt;&lt; std::endl; RequestForValidInputValue(width, "ERROR: width must be an integer!"); std::cout &lt;&lt; "Enter the gamearea's height: " &lt;&lt; std::endl; RequestForValidInputValue(height, "ERROR: Height must be an integer!"); loopFirstRun = false; } while (!PlayingFieldSizeIsValid()); } #pragma endregion void RequestForPlayingFieldSize() { bool confirmed = false; do { RequestForValidPlayingFieldSize(); std::cout &lt;&lt; "Your game area will be (" &lt;&lt; width &lt;&lt; ", " &lt;&lt; height &lt;&lt; "), Confirm?" &lt;&lt; std::endl; confirmed = AskUserForYesNo(); } while (!confirmed); } #pragma endregion void ClearAndInitalizeVariables() { tailLength = 0; playerScore = 0; gameOver = false; currentSnakeMovingDirection = UNDEFINED; } void InitializeGame() { ClearScreen(); ClearAndInitalizeVariables(); RequestForPlayingFieldSize(); // Start in the center snakeHeadPosition = { (width / 2), (height / 2) }; tailPositions[0] = snakeHeadPosition; PlaceFruitRandomlyInPlayingField(); } int main() { // Play the game while the user wants to play again. do { InitializeGame(); while (!gameOver) { UpdateGame(); std::this_thread::sleep_for(std::chrono::milliseconds(400)); } std::cout &lt;&lt; "GAMEOVER, Your Score: " &lt;&lt; playerScore &lt;&lt; std::endl; std::cout &lt;&lt; "Play again? "; } while (AskUserForYesNo()); return 0; } </code></pre> <p>Also, would anyone give me any directions on how to properly overload and make a <code>+=</code> operator for <code>Vector2D</code>?<br> Currently I'm doing addition as <code>Vector1 = Vector1 + Vector2</code>, as I tried to do a <code>+=</code> operator but the implementation I did had issues.</p>
[]
[ { "body": "<h3>Small Bug Fix</h3>\n<p>Noticed a small bug in my game, where the fruit might have a chance to spawn inside the snake.<br>\nDid a quick fix for it:</p>\n<p>Renamed <code>PlaceFruitRandomlyInPlayingField</code> into <code>PlaceFruitInPlayingField</code>, added and changed codes:</p>\n<pre><code>bool ValidPositionForFruit(Vector2D position) {\n bool isValidPosForFruit = true;\n\n if (position == snakeHeadPosition) {\n isValidPosForFruit = false;\n }\n else if (PositionIsTouchingTail(position)) {\n isValidPosForFruit = false;\n }\n\n return isValidPosForFruit;\n}\n\nvoid PlaceFruitInPlayingField() {\n // Change the fruit position while the fruit's current position is not valid.\n do {\n currentFruitPosition = { rand() % width, rand() % height };\n } while (!ValidPositionForFruit(currentFruitPosition));\n}\n</code></pre>\n<p>Finally, I renamed and refactored <code>SnakeHeadTouchedTail</code> into <code>PositionIsTouchingTail(Vector2D)</code> since my I do need to check if my new fruit's position would touch the head, and I didn't want to repeat myself:<br></p>\n<pre><code>bool PositionIsTouchingTail(Vector2D position) {\n bool touchedTail = false;\n\n for (int i = 0; i &lt; tailLength; ++i) {\n if (tailPositions[i] == position) {\n touchedTail = true;\n break;\n }\n }\n return touchedTail;\n}\n</code></pre>\n<p>And I placed inside the <code>#pragma region Util</code> since C++ is picky about function placements.<br>\n(The region should be near the top)</p>\n<p>Also, in <code>UpdateGameLogic()</code> function, as you might have guessed, I'm doing <code>PositionIsTouchingTail(snakeHeadPosition)</code> instead of <code>SnakeHeadTouchedTail()</code> to check if the snake's head had touched the tail.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T19:26:53.190", "Id": "213327", "ParentId": "213324", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T18:56:34.273", "Id": "213324", "Score": "5", "Tags": [ "c++", "game", "console", "snake-game" ], "Title": "Simple Console Snake game C++" }
213324
<p>I am trying to teach myself C++ and using <em>Problem Solving in C++</em> by Walter Savitch. This is a program project from the book that I used to practice using classes/ structs and would like some feedback, please. I included in the notes the question as well as tried to specify my functions for others to try to see my train of thought on each.</p> <p>It's a work in progress and as I said, I'm still learning so I know I can improve certain things or make this more efficient. Some things I noted for myself:</p> <ul> <li>In <code>main</code>, to get each percentage I passed as parameters 20 or 100 then 25 or 50 explicitly there and thought I should make use of global variables to make it more applicable for general use and if those percentages may want to be changed easier, but I did this for now because my focus is practicing using classes/ structs.</li> <li>along with that, I explicitly made the quiz array to hold 2 values (quiz[2]) and am considering making that a dynamic array by which I can ask the user for how many quiz grades there are (but I'll admit, I'm still working on practicing with pointers as well so Like I said, I made this to facilitate my ease of primarily focusing on uses of classes/ structs)</li> <li>to convert the numeric grade to a letter grade, I considered using a <code>switch</code> statement, but opted to use <code>if</code>, <code>else if</code>, <code>else</code>. I could add something in case the numeric grades are out of range when the user inputs it, but left it like this for now as I am inputting valid data when I test it myself.</li> <li>the question states to define and use a structure for the student record, but as I got going I had been using the <code>StudentRecord</code> class and so made the struct <code>Student</code> to be used within the <code>StudentRecord</code> class. I modified it a bit, I guess, but would appreciate alternative ways of going about this.</li> </ul> <pre><code>/* 1. Write a grading program for a class with the following grading policies: a. There are two quizzes, each graded on the basis of 10 points. b. There is one midterm exam and one final exam, each graded on the basis of 100 points. c. The final exam counts for 50 percent of the grade, the midterm counts for 25 percent, and the two quizzes together count for a total of 25 percent. (Do not forget to normalize the quiz scores. They should be converted to a percent before they are averaged in.) Any grade of 90 or more is an A, any grade of 80 or more (but less than 90) is a B, any grade of 70 or more (but less than 80) is a C, any grade of 60 or more (but less than 70) is a D, and any grade below 60 is an F. The program will read in the student’s scores and output the student’s record, which consists of two quiz and two exam scores as well as the student’s average numeric score for the entire course and the final letter grade. Define and use a structure for the student record. */ #include"stdafx.h" #include&lt;iostream&gt; #include&lt;string&gt; using namespace std; struct Student { string name; char finalLetterGrade; }; class StudentRecord { private: Student someStudent; double quiz[2], midterm, finalExam; double finalGrade; char finalLetterGrade; public: void inputQuizzes(); void inputMidtermGrade(); void inputFinalGrade(); double *getQuizzes(); double getMidterm(); double getFinalExam(); double calcPercent(double grade, double outOfTotalPts, double percentOfTotal); // general application for all scores // double setFinalNumericGrade(double newFinalGrade); char setFinalLetterGrade(char newFinalLetterGrade); char calcFinalLetterGrade(double finalGrade); }; // returns ptr to first quiz grade of array // double *StudentRecord::getQuizzes() { double *quizPtr; quizPtr = quiz; return quizPtr; } double StudentRecord::getMidterm() { return midterm; } double StudentRecord::getFinalExam() { return finalExam; } // calculates percent of total final numeric grade // // parameters : grade recieved (numerator), // // max pts could received based on type of test/quiz(denominator), // // percent of final numeric grade (25, 50) // double StudentRecord::calcPercent(double grade, double outOfTotalPts, double percentOfTotal) { double totalPercent = (grade / outOfTotalPts) * percentOfTotal; return totalPercent; } /////////////////////////////////////////////////////////////////// double StudentRecord::setFinalNumericGrade(double newFinalGrade) { return finalGrade = newFinalGrade; } // takes final numeric grade as parameter // // returns letter grade as char // char StudentRecord::calcFinalLetterGrade(double finalGrade) { /* Any grade of 90 or more is an A, any grade of 80 or more (but less than 90) is a B, any grade of 70 or more (but less than 80) is a C, any grade of 60 or more (but less than 70) is a D, and any grade below 60 is an F. */ if (finalGrade &gt;= 90) return 'A'; else if (finalGrade &gt;= 80 &amp;&amp; finalGrade &lt; 90) return 'B'; else if (finalGrade &gt;= 70 &amp;&amp; finalGrade &lt; 80) return 'C'; else if (finalGrade &gt;= 60 &amp;&amp; finalGrade &lt; 70) return 'D'; else return 'F'; } /////////////////////////////////////////////////////////////////////////// char StudentRecord::setFinalLetterGrade(char newFinalLetterGrade) { return finalLetterGrade = newFinalLetterGrade; } // user inputs grades // void StudentRecord::inputQuizzes() { cout &lt;&lt; "Enter quiz grades : "; for (int i = 0; i &lt; 2; i++) { cin &gt;&gt; quiz[i]; } } void StudentRecord::inputMidtermGrade() { cout &lt;&lt; "Enter midterm grade : "; cin &gt;&gt; midterm; } void StudentRecord::inputFinalGrade() { cout &lt;&lt; "Enter final grade : "; cin &gt;&gt; finalExam; } ///////////////////////////////////////////////////////////////////////// int main() { Student someStudent; cout &lt;&lt; "Enter name : "; cin &gt;&gt; someStudent.name; StudentRecord student; student.inputQuizzes(); student.inputMidtermGrade(); student.inputFinalGrade(); double *ptr; ptr = student.getQuizzes(); for (int i = 0; i &lt; 2; i++) cout &lt;&lt; "Quiz "&lt;&lt; i+1 &lt;&lt;": "&lt;&lt; ptr[i] &lt;&lt; endl; cout &lt;&lt; "Midterm : " &lt;&lt; student.getMidterm() &lt;&lt; endl; cout &lt;&lt; "Final Exam : " &lt;&lt; student.getFinalExam() &lt;&lt; endl; // calculations // double quizSum = 0; for (int i = 0; i &lt; 2; i++) quizSum += ptr[i]; double quizPercent = student.calcPercent(quizSum, 20, 25); double midtermPercent = student.calcPercent(student.getMidterm(), 100, 25); double finalPercent = student.calcPercent(student.getFinalExam(), 100, 50); double finalNumGrade = quizPercent + midtermPercent + finalPercent; student.setFinalNumericGrade(finalNumGrade); char letterGrade = student.calcFinalLetterGrade(finalNumGrade); student.setFinalLetterGrade(letterGrade); someStudent.finalLetterGrade = letterGrade; cout &lt;&lt; "Name : " &lt;&lt; someStudent.name &lt;&lt; endl; cout &lt;&lt; "Final Grade : " &lt;&lt; someStudent.finalLetterGrade &lt;&lt; endl; return 0; } </code></pre>
[]
[ { "body": "<p>Welcome to CodeReview StackExchange. I'm new here too, so I would try my best to review your code and give you an explanation about it. Take in consideration that all of this is my opinion.</p>\n\n<p>First of all your code should explain itself. You do not need to put comments about everything that you do in your code. It's a good practice to comment your code. But, you should comment stuff that maybe hard to understand at first glance, that maybe for you or anyone else reading your code. Try to put yourself as an outsider. You would know what a piece of code is doing just by looking at it or if you come back in a year you would know what it does?</p>\n\n<p>Secondly, you should not put comment to separate blocks of code (in your case multiple slashes). This would make your code a little but unreadable and extensive. When you read code, you want to scroll as little as possible to understand the code in question. And most of IDE and Editor now include a feature to collapse regions of code.</p>\n\n<p>Third, You should use the correct <a href=\"https://en.cppreference.com/w/cpp/language/expressions#Literals\" rel=\"nofollow noreferrer\">C ++ Literals</a> for your code. All of your double statement where declared like int <code>double i = 20</code>. You should declare them like <code>double i = 20.0</code>.</p>\n\n<p>Fourth, Try to use the <a href=\"https://en.cppreference.com/w/cpp/header\" rel=\"nofollow noreferrer\">C ++ STL</a> whenever possible. It offers the best C ++ feature and implementation of trivial stuff almost bug free. So you do not have the hassle of dealing with trivial and non-trivial problem.</p>\n\n<p>I don't know If I have missed something, maybe someone else may point it out. If you have any question, just ask. I would gladly answer you with the best of my ability. This is the source code with the same functionality and some comments explaining the changes</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\n// I don't like to use `using namespace`. It help me read the code better and see where all the methods are comming from.\n\n// Use global constants to avoid errors.\n// And if you want to change it later you change the value once throughout your code base\nconstexpr std::size_t QUIZZES_COUNT = 2;\n\n/*\n * Try to consolidate all your struct. You were having a struct named Student with fields\n * that can be included in a student record. Hence the elmination.\n*/\n\nclass StudentRecord {\npublic:\n std::string name;\n char finalLetterGrade;\n\nprivate:\n // Try to use standard containers where posible\n std::array&lt;double, QUIZZES_COUNT&gt; quiz;\n double midterm, finalExam;\n double finalGrade;\n\npublic:\n void inputQuizzes();\n void inputMidtermGrade();\n void inputFinalGrade();\n\n double* getQuizzes();\n double getMidterm();\n double getFinalExam();\n\n // If a method doesn't access a field of the class, that method could be static.\n static double calcPercent(double grade, double outOfTotalPts, double percentOfTotal);\n static char calcFinalLetterGrade(double finalGrade);\n\n // Since this method are only setters there is no need for them to return the value\n void setFinalNumericGrade(double newFinalGrade);\n void setFinalLetterGrade(char newFinalLetterGrade);\n};\n\ndouble* StudentRecord::getQuizzes() {\n /*\n C style arrays are basically pointer to memory too. So you could have done something like this\n\n double data[2];\n return data;\n\n This would have returned a pointer of data. Without the necesity to create an extra variable\n */\n return quiz.data();\n}\n\ndouble StudentRecord::getMidterm() { return midterm; }\ndouble StudentRecord::getFinalExam() { return finalExam; }\n\ndouble StudentRecord::calcPercent(double grade, double outOfTotalPts, double percentOfTotal) {\n return (grade / outOfTotalPts) * percentOfTotal;\n}\n\nvoid StudentRecord::setFinalNumericGrade(double newFinalGrade) {\n // Since this method are only setters there is no need for them to return the value\n finalGrade = newFinalGrade;\n}\n\n// This method is static because doesn't access any of the member of StudentRecord\nchar StudentRecord::calcFinalLetterGrade(double finalGrade) {\n if (finalGrade &gt;= 90.0)\n return 'A';\n // You don't need to prove `finalGrade &lt; 90` since it would automatically be qualified for the above if clause.\n else if (finalGrade &gt;= 80.0) \n return 'B';\n else if (finalGrade &gt;= 70.0)\n return 'C';\n else if (finalGrade &gt;= 60.0)\n return 'D';\n else\n return 'F';\n}\n\nvoid StudentRecord::setFinalLetterGrade(char newFinalLetterGrade) {\n // Since this method are only setters there is no need for them to return the value\n finalLetterGrade = newFinalLetterGrade;\n}\n\nvoid StudentRecord::inputQuizzes() {\n // This method is unnecessary since they are only called once. Their code could be putted where they are called\n std::cout &lt;&lt; \"Enter quiz grades : \";\n for (int i = 0; i &lt; QUIZZES_COUNT; i++) {\n std::cin &gt;&gt; quiz[i];\n }\n}\n\nvoid StudentRecord::inputMidtermGrade() {\n // This method is unnecessary since they are only called once. Their code could be putted where they are called\n std::cout &lt;&lt; \"Enter midterm grade : \";\n std::cin &gt;&gt; midterm;\n}\n\nvoid StudentRecord::inputFinalGrade() {\n // This methods is unnecessary since they are only called once. Their code could be putted where they are called\n std::cout &lt;&lt; \"Enter final grade : \";\n std::cin &gt;&gt; finalExam;\n}\n\nint main() {\n StudentRecord student;\n\n std::cout &lt;&lt; \"Enter name : \";\n std::cin &gt;&gt; student.name;\n\n student.inputQuizzes();\n student.inputMidtermGrade();\n student.inputFinalGrade();\n\n // General iostream tip: Don't use std::endl since it flush the stream buffer. That have performance impact\n // Source: Video by Jason Turner https://www.youtube.com/watch?v=GMqQOEZYVJQ\n\n double* ptr = student.getQuizzes();\n for (int i = 0; i &lt; QUIZZES_COUNT; i++)\n std::cout &lt;&lt; \"Quiz \" &lt;&lt; i + 1 &lt;&lt; \": \" &lt;&lt; ptr[i] &lt;&lt; '\\n';\n\n\n std::cout &lt;&lt; \"Midterm : \" &lt;&lt; student.getMidterm() &lt;&lt; '\\n';\n\n std::cout &lt;&lt; \"Final Exam : \" &lt;&lt; student.getFinalExam() &lt;&lt; '\\n';\n\n // calculations //\n\n double quizSum = 0.0;\n for (int i = 0; i &lt; QUIZZES_COUNT; i++)\n quizSum += ptr[i];\n\n // All of this \"random\" numbers (20.0, 25.0, 50.0, 100.0) can be made into constant to make the code reader aware of their significance\n double quizPercent = StudentRecord::calcPercent(quizSum, 20.0, 25.0);\n double midtermPercent = StudentRecord::calcPercent(student.getMidterm(), 100.0, 25.0);\n double finalPercent = StudentRecord::calcPercent(student.getFinalExam(), 100.0, 50.0);\n\n double finalNumGrade = quizPercent + midtermPercent + finalPercent;\n\n student.setFinalNumericGrade(finalNumGrade);\n\n char letterGrade = StudentRecord::calcFinalLetterGrade(finalNumGrade);\n\n student.setFinalLetterGrade(letterGrade);\n\n std::cout &lt;&lt; \"Name : \" &lt;&lt; student.name &lt;&lt; '\\n';\n std::cout &lt;&lt; \"Final Grade : \" &lt;&lt; student.finalLetterGrade &lt;&lt; '\\n';\n\n return 0;\n}\n<span class=\"math-container\">```</span>cpp\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:34:39.410", "Id": "412690", "Score": "0", "body": "I appreciate the feedback. This was the first post I added so I wasn't sure and did the //////////// and extra comments to perhaps make it easier to break down for others seeing it, but I guess I did the opposite haha\nI see what you're saying about the ints and doubles. Also, I'll check out the C++ STL more, but can you give me specific examples if you had thought of any?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:01:08.497", "Id": "213335", "ParentId": "213326", "Score": "3" } }, { "body": "<p>Using 'using namespace std;' is considered bad practice, 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>.\nIf another unit declares a function or variable that has the same name, the compiler might choose the wrong one and create difficult to debug bugs.</p>\n\n<p>You could consider validating the input of calcFinalLetterGrade(), a value higher than 100 or lower than 0 should probably give some error/warning. Although you are the only one that will call this function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:33:03.743", "Id": "412688", "Score": "0", "body": "Thanks for the tip. I had seen people comment in forums, posts, etc that it's bad practice to use using namespace std; but I hadn't looked into the reasoning so thanks for the link and I'll look at that. I had used it because that's how the book I'm using has been implementing things. \nI like the idea of adding a validation function. Would a do-while loop be a good method, you suggest? That way I'd do something like do (cin input) while (data >=0 && <=100 and if data is invalid to give error and call the input function again)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T10:54:01.757", "Id": "413126", "Score": "0", "body": "If you pass the function an array of grades and expect a char output, a loop could work. However, I would rather split the 'aggregate' and 'convert' functionalities into two functions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:21:23.967", "Id": "213338", "ParentId": "213326", "Score": "2" } }, { "body": "<p>Some shorter points:</p>\n\n<ul>\n<li>You don't need <code>#include \"stdafx.h\"</code>. It's usually used to consolidate includes in Windows projects. That's not applicable here.</li>\n<li>Don't use <code>using namespace std;</code>. Instead refer to things in <code>std</code> with the <code>std::</code> prefix. C++ (name resolution) is <strike>needlessly</strike> complicated and as a result you can get bitten by some strange bugs if names collide. You avoid all of this by not doing <code>using namespace std;</code>.</li>\n<li>Instead of <code>double quiz[2]</code>, use <code>std::array</code> (<code>std::array&lt;double, 2&gt; quizzes</code>). This is preferable to passing around pointers for many reasons, the primary one being that the length of the array is encoded in the type. With a pointer (<code>*double</code>), doing <code>quizzes[3]</code> is a really easy way to introduce undefined behavior. This is bad. (Another benefit is if you change the size, you don't have to change all the usage iteration sites; with your existing code you'd have to change the loops in <code>inputQuizzes()</code>, <code>main()</code>, etc.) If you want to accept a variable number of quizzes, use <code>std::vector</code> instead.</li>\n<li>We usually prefix members with <code>m_</code> to differentiate between local variables. Ex. <code>finalGrade</code> should be <code>m_finalGrade</code></li>\n<li>Separate implementation from interface. All of the foreward declarations should be in a <code>student.h</code> file (that begins with <code>#pragma once</code>) and the implementation should be in a <code>student.cpp</code> file (that has <code>#include \"student.h\"</code>)</li>\n<li>Usually we write comments <code>// comment</code> instead of <code>// comment //</code>. Also dividers like <code>///////////</code> are rarely used. Your usage of them indicates that you probably want to split things up into different files.</li>\n<li>You have a lot of information duplicates (ex. <code>Student</code> and <code>StudentRecord</code> has a <code>finalLetterGrade</code> with different access methods (ex. directly by <code>student.finalLetterGrade</code> and through a setter by <code>studentRecord.setFinalLetterGrade('A')</code>). You're conflating the getter/setter pattern. You probably want to pick just one approach. But also, this information should only live in one place. Any duplication is an opportunity for things to accidentally go out of sync (Think if somewhere else you changed the final letter grade for the <code>Student</code> but not the <code>StudentRecord</code>. Now how do you know which <code>finalLetterGrade</code> is correct?).</li>\n<li>Some of your methods on <code>StudentRecord</code> don't really belong. For example, <code>calcFinalLetterGrade</code> (and <code>calcPercent</code>) doesn't perform an action on a specific student. It doesn't use any of the <code>private</code> member variables. It could just (and probably should) be a <code>static</code> function.</li>\n<li><code>getQuizzes()</code> has a strange body. You can just <code>return quiz</code> as arrays decay to pointers (although as I argue above, relying on this is generally bad and you should be using <code>std::array</code>).</li>\n<li>Be careful with <code>double</code>. There are some numbers that cannot be represented with it. In particular, you shouldn't use floating point numbers to encode currency (because small imprecisions can lead to lost money). I'm dubious as to whether you could make the same case for grades. It is possible that with the right series of divisions you could produce a number that in a pure math class would be > 90 but wouldn't be representable and would instead be represented as closer to an 89. Since it's easier to use <code>double</code>, I'll stick with it, but keep this in mind.</li>\n<li><code>cin</code> can fail. You also don't handle the case of an invalid grade. What if the user inputs a negative midterm grade?</li>\n<li>Representation is up to you, of course, but often we'll represent 0-100% as the range 0-1 (like you would in math) instead of 1-100 (I'll stick with your convention, but keep this in mind).</li>\n<li>Keep your indentation consistent. Indent blocks surrounded by <code>{}</code>. This makes code much easier to follow.</li>\n</ul>\n\n<p>Overall, this is a good first attempt, but it could use some work. My main observation is that there is a lot of code (with lots of methods and several objects) for relatively little logic. This is often a sign that you can refactor to simplify things. Shorter, simpler code will almost always be easier to understand.</p>\n\n<p>The first thing we'll try is eliminating all of the indirection and doing everything inside of <code>main</code>. You're already almost doing this. <code>calcPercent</code> and <code>calcFinalLetterGrade</code> is the only real logic done outside of it (sans the input). The only thing you've really pulled out is where the grades and student information are stored (encapsulated in an object, instead of local variables).</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;iostream&gt;\n#include &lt;numeric&gt;\n#include &lt;string&gt;\n\nint main() {\n std::string studentName;\n std::array&lt;double, 2&gt; quizGrades;\n double midtermGrade;\n double finalExamGrade;\n\n std::cout &lt;&lt; \"Enter student name: \";\n std::cin &gt;&gt; studentName;\n\n // Read in grades\n for (size_t i = 0; i &lt; quizGrades.size(); i++) {\n std::cout &lt;&lt; \"Enter quiz \" &lt;&lt; (i + 1) &lt;&lt; \" grade: \";\n std::cin &gt;&gt; quizGrades[i];\n }\n\n std::cout &lt;&lt; \"Enter midterm grade: \";\n std::cin &gt;&gt; midtermGrade;\n\n std::cout &lt;&lt; \"Enter final exam grade: \";\n std::cin &gt;&gt; finalExamGrade;\n\n // Compute final grade\n double finalGrade =\n 25 * (std::accumulate(quizGrades.begin(), quizGrades.end(), 0) / (10 * quizGrades.size())) +\n 25 * (midtermGrade / 100) +\n 50 * (finalExamGrade / 100);\n\n char finalLetterGrade = (finalGrade &gt;= 90) ? 'A' :\n (finalGrade &gt;= 80) ? 'B' :\n (finalGrade &gt;= 70) ? 'C' :\n (finalGrade &gt;= 60) ? 'D' : 'F';\n\n std::cout &lt;&lt; studentName &lt;&lt; \" got an \" &lt;&lt; finalLetterGrade &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Some things to note with this approach:</p>\n\n<ul>\n<li>The use of <code>std::accumulate</code> to sum an arbitrary length collection.</li>\n<li>I'm a little dubious about the ternary (because the precedence is abused a bit here), but it seems clear enough</li>\n<li>It should illustrate just how simple the business logic of your program is. There's no need to complicate it much beyond this.</li>\n<li>It doesn't handle invalid input (<code>cin</code> failing, negative grades). We'll get to this in a second</li>\n</ul>\n\n<p>With the exception of the last point, I'd argue for this scenario, there isn't a good reason to complicate the code any further than the above. But it looks like you want to learn how to properly OOP-ify a problem, so we'll tackle this as an example. But first, the validation.</p>\n\n<p>We note that for the first half of our program, we're repeating two actions for each variable we need to fill:</p>\n\n<ol>\n<li>Print a message informing the user that data we are collecting</li>\n<li>Read the grade from stdin</li>\n</ol>\n\n<p>Ideally (2) should also reask the user if they input an invalid grade (say, a negative one).</p>\n\n<p>We could simplify the logic by <em>extracting</em> it into a function.</p>\n\n<pre><code>double readGradeInteractive(std::string name) {\n double grade;\n\n do {\n std::cout &lt;&lt; \"Enter \" &lt;&lt; name &lt;&lt; \" grade: \";\n std::cin &gt;&gt; grade;\n } while (std::cin.fail() || grade &lt; 0);\n\n return grade;\n}\n</code></pre>\n\n<p>Note how this handles errors gracefully. It also allows grades > 100 to allow for extra credit points. We can use this function like so:</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;iostream&gt;\n#include &lt;numeric&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n\nstatic double readGradeInteractive(std::string name) {\n double grade;\n\n do {\n std::cout &lt;&lt; \"Enter \" &lt;&lt; name &lt;&lt; \" grade: \";\n std::cin &gt;&gt; grade;\n } while (std::cin.fail() || grade &lt; 0);\n\n return grade;\n}\n\nint main() {\n std::string studentName;\n std::array&lt;double, 2&gt; quizGrades;\n double midtermGrade;\n double finalExamGrade;\n\n std::cout &lt;&lt; \"Enter student name: \";\n std::cin &gt;&gt; studentName;\n\n // Read in grades\n for (size_t i = 0; i &lt; quizGrades.size(); i++) {\n std::stringstream name;\n name &lt;&lt; \"quiz \" &lt;&lt; (i + 1);\n\n quizGrades[i] = readGradeInteractive(name.str());\n }\n\n midtermGrade = readGradeInteractive(\"midterm\");\n finalExamGrade = readGradeInteractive(\"final exam\");\n\n // Compute final grade\n double finalGrade =\n 25 * (std::accumulate(quizGrades.begin(), quizGrades.end(), 0) / (10 * quizGrades.size())) +\n 25 * (midtermGrade / 100) +\n 50 * (finalExamGrade / 100);\n\n char finalLetterGrade = (finalGrade &gt;= 90) ? 'A' :\n (finalGrade &gt;= 80) ? 'B' :\n (finalGrade &gt;= 70) ? 'C' :\n (finalGrade &gt;= 60) ? 'D' : 'F';\n\n std::cout &lt;&lt; studentName &lt;&lt; \" got an \" &lt;&lt; finalLetterGrade &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Now, you'll note this doesn't save us many lines in <code>main()</code> at first glance, but to handle errors, <code>readGradeInteractive</code> has to be a bit more complicated. So, this is a good refactoring.</p>\n\n<p>I'd argue at this point, this is a fine solution to your problem. You don't really need to introduce OOP here. But, let's say we wanted to allow other programs to use this logic (the grade calculation) in their programs. Then, it may make sense to introduce a <code>Student</code> object, that encapsulates these grades and is capable of computing its final grade (as a number and letter grade). Why no <code>StudentRecord</code>? Think about what's going on here. A <code>Student</code> has grades. And an action you can perform on the student is asking it what its final grade is. There's no need for any intermediary objects. Let's start by redesigning our <code>main</code> to imagine what we need <code>Student</code> to be able to do.</p>\n\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n\n#include \"student.h\"\n\n\nint main() {\n auto student = Student::readInteractive();\n\n std::cout &lt;&lt; student.name() &lt;&lt; \" got an \" &lt;&lt; student.finalGrade() &lt;&lt; std::endl;\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Notice how much simpler this is! <code>main</code> no longer has any logic. It delegates reading the student name and grades in from stdin to a static method on <code>Student</code>. And it delegates computing the final (&amp; letter) grade to the student object.</p>\n\n<p>Let's start by writing <code>student.h</code>. All we need to do is look at the API we want <code>Student</code> to expose (namely <code>static Student readInteractive()</code>, <code>char finalGrade()</code>, <code>std::string name()</code>) and consult our original code to recall the member variables that student needs to encapsulate:</p>\n\n<pre><code>#pragma once\n\n#include &lt;array&gt;\n#include &lt;string&gt;\n\n\nclass Student {\npublic:\n static Student readInteractive();\n std::string name() const;\n char finalGrade() const;\n\nprivate:\n std::string m_name;\n std::array&lt;double, 2&gt; m_quizGrades;\n double m_midtermGrade;\n double m_finalExamGrade;\n};\n</code></pre>\n\n<p>Now, all that's left is to implement it in <code>student.cpp</code>:</p>\n\n<pre><code>#include \"student.h\"\n\n#include &lt;iostream&gt;\n#include &lt;numeric&gt;\n#include &lt;sstream&gt;\n\n\nstatic double readGradeInteractive(std::string name) {\n double grade;\n\n do {\n std::cout &lt;&lt; \"Enter \" &lt;&lt; name &lt;&lt; \" grade: \";\n std::cin &gt;&gt; grade;\n } while (std::cin.fail() || grade &lt; 0);\n\n return grade;\n}\n\nStudent Student::readInteractive() {\n Student student;\n\n std::cout &lt;&lt; \"Enter student name: \";\n std::cin &gt;&gt; student.m_name;\n\n for (size_t i = 0; i &lt; student.m_quizGrades.size(); i++) {\n std::stringstream name;\n name &lt;&lt; \"quiz \" &lt;&lt; (i + 1);\n\n student.m_quizGrades[i] = readGradeInteractive(name.str());\n }\n\n student.m_midtermGrade = readGradeInteractive(\"midterm\");\n student.m_finalExamGrade = readGradeInteractive(\"final exam\");\n\n return student;\n}\n\nstd::string Student::name() const { return m_name; }\n\nchar Student::finalGrade() const {\n double finalGrade =\n 25 * (std::accumulate(m_quizGrades.begin(), m_quizGrades.end(), 0) / (10 * m_quizGrades.size())) +\n 25 * (m_midtermGrade / 100) +\n 50 * (m_finalExamGrade / 100);\n\n return (finalGrade &gt;= 90) ? 'A' :\n (finalGrade &gt;= 80) ? 'B' :\n (finalGrade &gt;= 70) ? 'C' :\n (finalGrade &gt;= 60) ? 'D' : 'F';\n}\n</code></pre>\n\n<p>Note how we largely just copied the logic from our original program (changing the local variables to member variables where appropriate).</p>\n\n<p>I'd wager this is a fairly reasonable application of OOP. You could take this one step further by examining the grade. Often, we like our type signatures to be very informative about the things they take and return. In the case of <code>char finalGrade()</code>, it may not immediately be clear that <code>char</code> is a letter grade. Additionally, the type <code>char</code> doesn't restrict the things that can be returned to just <code>ABCDEF</code>. An <code>H</code> could be returned. What would that mean? Additionally, there are other grade-like states like Incomplete, Withdrawn, etc. that you may want to encode here. But we wouldn't want to just use magic letters for them (lest we accidentally return a grade with them due to a bug). Another concern with the above approach is that it combines two concerns intot <code>finalGrade</code>: (1) computing the final grade as a number and (2) converting that numeric grade to a letter grade.</p>\n\n<p>So, we could solve both of these by using an <code>enum class</code> to represent grades and make that enum responsible for converting from a numeric grade to a letter. I'll leave this as an exercise for you :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T20:36:42.370", "Id": "412837", "Score": "0", "body": "Wow a lengthier response than I anticipated from anyone. I won't acknowledge everything specifically, but thanks. I appreciate the responses because it's teaching me a lot and I am reading them thoroughly.\nFor example, user2966394 commented about validation. I responded with a do-while loop as a solution. Then you put that so it's good to see critiques, think of solutions, myself, and see comments reaffirming I'm learning more as I go.\nIt's also beneficial to see some \"conventions,\" like m_ for member functions. Until, I'm exposed to it, I wouldn't know, but now it seems so obviously simple." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T20:05:07.150", "Id": "213404", "ParentId": "213326", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T19:08:40.757", "Id": "213326", "Score": "6", "Tags": [ "c++", "beginner", "object-oriented" ], "Title": "Student grade calculator using classes/ structs in C++" }
213326
<p>For practice, I solved Leetcode <a href="https://leetcode.com/problems/3sum/" rel="nofollow noreferrer">15. 3Sum</a> question:</p> <blockquote> <p>Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.</p> </blockquote> <p>My code pass all testcases from my location but get Time Limit Exceeded from leetcode. Can anyone suggest me how to improve my code?</p> <pre><code>def threeSum(nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) &lt; 3: return [] len_n, res, n_map, target = len(nums), set(), dict(), 0 nums.sort() for i, n in enumerate(nums): for j, c in enumerate(nums[i + 1:], i + 1): s = n + c n_map[s] = n_map.get(s, []) + [(i, j)] for i, n in enumerate(nums): s = target - n for k in n_map.get(s, []): if i &gt; k[1]: res.add((nums[i], nums[k[0]], nums[k[1]])) return list(map(list, res)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:03:23.383", "Id": "412679", "Score": "1", "body": "You currently have a small error? typo? in your code: `len_n, res, n_map. target = len(nums), set(), dict(), ` is not actually ok. I am not sure how this is supposed to look like, so please just correct it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T01:21:25.060", "Id": "412696", "Score": "0", "body": "thank you. updated already..it is typo when i post the code.." } ]
[ { "body": "<p>I think the current way of solving this problem seems an acceptable, albeit naive, way to solve it, but there are some tweaks that can enhance the readability.</p>\n\n<h1>variables</h1>\n\n<pre><code>len_n, res, n_map, target = len(nums), set(), dict(), 0\n</code></pre>\n\n<p>is both unclear and unnecessary.</p>\n\n<p><code>len_n</code> is never used, <code>res</code> is only used far further in the code</p>\n\n<h1><code>collections.defaultdict</code></h1>\n\n<p>You do a lot of <code>n_map.get(s, [])</code>. Simpler would be to define <code>n_map</code> as a <code>collectcions.defaultdict(list)</code>, and then for example just do <code>n_map[s].append((i, j))</code></p>\n\n<h1>indices</h1>\n\n<p>You add <code>(i, j)</code> to <code>n_map</code>, only to later retrieve them as tuple <code>k</code>. It would be easier to use tuple unpacking:</p>\n\n<pre><code>for k, n in enumerate(nums): # i is used\n s = target - n\n for i, j in n_map[s]:\n if k &gt; j:\n res.add((nums[k], nums[i], nums[j]))\n</code></pre>\n\n<p>Since you only use <code>i</code> and <code>j</code> here to retrieve <code>a</code> and <code>b</code>, why not save them in <code>n_map</code> in the first place?</p>\n\n<pre><code>n_map = defaultdict(list)\nfor i, a in enumerate(nums):\n for j, b in enumerate(nums[i + 1 :], i + 1):\n n_map[a + b].append((j, a, b))\nres = set()\nfor k, c in enumerate(nums):\n for j, a, b in n_map[target - c]:\n result = c, a, b\n if k &gt; j:\n ...\n</code></pre>\n\n<h1><code>res</code> and <code>yield</code></h1>\n\n<p>Defining <code>res</code> as a set is a good choice. I think it is easier to only add the tuple to <code>res</code> if it is not present yet, and <code>yield</code> it at the same time, instead of returning <code>list(map(list, res))</code> at the end</p>\n\n<p>In total this gives:</p>\n\n<pre><code>def three_sum_maarten(nums, target=0):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]In total this gives\n \"\"\"\n if len(nums) &lt; 3:\n return []\n n_map = defaultdict(list)\n nums = sorted(nums)\n for i, a in enumerate(nums):\n for j, b in enumerate(nums[i + 1 :], i + 1):\n n_map[a + b].append((j, a, b))\n res = set()\n for k, c in enumerate(nums):\n for j, a, b in n_map[target - c]:\n result = c, a, b\n if k &gt; j and result not in res:\n yield [c, a, b]\n res.add(result)\n</code></pre>\n\n<p>With this leetcode boilerplate:</p>\n\n<pre><code>class Solution:\n def threeSum(self, nums: 'List[int]') -&gt; 'List[List[int]]':\n return list(three_sum_maarten(nums))\n</code></pre>\n\n<p>This passes all but one scenario. The scenario it fails is <code>nums = [0] * 3000</code></p>\n\n<p>To tackle this scenario, you can filter all numbers so only maximum 3 of each are present in <code>nums</code>. I do this with the help of a <code>collections.Counter</code>:</p>\n\n<pre><code>def prepare_nums(nums):\n counter = Counter(nums)\n\n for n, c in sorted(counter.items()):\n yield from [n] * min(c, 3)\n</code></pre>\n\n<p>and then <code>nums = list(prepare_nums(nums))</code> instead of <code>nums = sorted(nums)</code></p>\n\n<hr>\n\n<h1>Alternative approach</h1>\n\n<p>You make about half of all combinations of 2 numbers in <code>nums</code>. One extra bit of knowledge you can use to reduce this is to take into account that at least 1 negative and 1 positive number need to be present in each triplet.</p>\n\n<pre><code>counter = Counter(nums)\npositives = [i for i in counter if i &gt; 0]\nnegatives = [i for i in counter if i &lt; 0]\n\nfor a, b in product(positives, negatives):\n c = -(a + b)\n if c not in counter:\n continue\n result = a, b, c\n</code></pre>\n\n<p>and then only yield the correct, unique results</p>\n\n<pre><code> result = a, b, c\n if c == a:\n if counter[a] &gt;= 2:\n yield result\n elif c == b:\n if counter[b] &gt;= 2:\n yield result\n elif a &gt; c &gt; b:\n yield result\n</code></pre>\n\n<p>and yield 1 <code>(0, 0, 0)</code> triplet if there are 3 or more <code>0</code>s present</p>\n\n<pre><code>if counter[0] &gt;= 3:\n yield (0, 0, 0)\n</code></pre>\n\n<p>This solution is about 10 times faster, and uses 30 times less memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T16:11:01.887", "Id": "412785", "Score": "0", "body": "thank you. the review make so much sense now. However, couple of question for line ` for j, a, b in n_map[target - c]:` what if no key can found on n_map? and can you explain a littit bit about why it is good choice to use yield `yield [c, a, b]` here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T16:28:06.973", "Id": "412791", "Score": "0", "body": "If there is no element with key `target-c` in `n_map`, this `defaultdict` returns an empty list. The `for`-loop starts iterating over it, but since it's empty, there are no iterations. On your second question, the order of `c, a, b` has no effect" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T16:30:37.303", "Id": "412793", "Score": "0", "body": "understand, thank you.. great solution for your alternative approach as well" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T15:46:29.810", "Id": "213384", "ParentId": "213328", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T20:19:11.147", "Id": "213328", "Score": "2", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded", "k-sum" ], "Title": "Leetcode 3Sum problem using hashmap in Python" }
213328
<p>I just wrote an echo server that responds to curl requests with the method used and the data sent. Sticking to GET and POST for now, but I would like to know if there's something I can do to improve my RESTful API.</p> <p>I'm supposed to:</p> <ol> <li>Only be able to call the <code>/data</code> endpoint</li> <li>Only allow JSON parameters </li> <li>Use best practices of coding a RESTful API</li> </ol> <p>Expected JSON response:</p> <pre><code>{ "method": &lt;HTTP METHOD REQUESTED&gt;, "data": &lt;HTTP PARAMETERS SENT IN THE REQUEST&gt; } </code></pre> <p>Here is my current code:</p> <pre><code>from bottle import run, post, request, response, get, route, put, delete from json import dumps import json @get('/data') def data(): #if headers are not specified we can check if body is a json the following way #postdata = request.body.read() postdata = request.json try: #rv = {"method": request.method, "data": json.loads(postdata.decode('utf-8'))} rv = {"method": request.method, "data": postdata} except: raise ValueError response.content_type = 'application/json' return dumps(rv) @post('/data') def data(): #postdata = request.body.read() postdata = request.json try: #rv = {"method": request.method, "data": json.loads(postdata.decode('utf-8'))} rv = {"method": request.method, "data": postdata} except: raise ValueError response.content_type = 'application/json' return dumps(rv) </code></pre> <p>Everything seems to work fine for now. I'm looking to improve my code so any feedback is appreciated.</p>
[]
[ { "body": "<p>The code looks a bit incomplete, e.g. shouldn't there be a main method\nsomewhere?</p>\n\n<p>I added the following to get it to run for now:</p>\n\n<pre><code>if __name__ == \"__main__\":\n run()\n</code></pre>\n\n<p>It's good practice to have the <code>__name__</code> check in there instead of just\nexecuting, because then you're still able to import the file elsewhere\nwithout it automatically executing code.</p>\n\n<hr>\n\n<p>Okay, so with that out of the way, there's commented out code that\nshould be there: Either it's correct, then it should replace the\nuncommented code, or it's not, then it should be deleted. To me,\nreading that just confuses me what the purpose is, or was.</p>\n\n<p>And then there's two functions, which are identical ... why is that? I\nsuppose that's a feature of the framework that allows you to have both\nfunctions because of the annotations, but generally <em>do not do that</em> and\ngive them separate names, at least something like\n<code>data_get</code>/<code>data_post</code>.</p>\n\n<p>The specification is pretty vague, <em>what</em> are you supposed to echo, the\nPOST body, or the URL parameters? Because then I don't get what the\n<code>GET</code> one is supposed to be doing. With that in mind I'd delete it.</p>\n\n<p>So, then, trying it out:</p>\n\n<pre><code>&gt; curl -d '{\"data\": 1}' -H \"Content-Type: application/json\" -v http://localhost:8080/data\n{\"method\": \"POST\", \"data\": {\"data\": 1}}%\n</code></pre>\n\n<p>Seems to work.</p>\n\n<p>(Also, since there's a single endpoint that echoes data ... there's\nlittle REST here. I'm not sure what other best practices are meant to\nbe followed for this exercise.)</p>\n\n<p>I've no idea how you'd get an exception in there, but in any case,\n<code>raise ValueError</code> isn't super helpful, it says exactly nothing about\nwhat went wrong. Consider adding some information like <code>raise\nValueError(\"Couldn't format data.\")</code>. Note that in this particular\nsituation there's little that adds information, maybe don't catch the\nexception then.</p>\n\n<p>At that point it might look like this:</p>\n\n<pre><code>@post(\"/data\")\ndef data():\n response.content_type = \"application/json\"\n return dumps({\"method\": request.method, \"data\": request.json})\n</code></pre>\n\n<hr>\n\n<p>However, then I was thinking, maybe this framework does the JSON\nformatting for us. And it does:</p>\n\n<pre><code>@post(\"/data\")\ndef data():\n return {\"method\": request.method, \"data\": request.json}\n</code></pre>\n\n<p>Probably can't get it much smaller than that actually. And then you can\ndelete a lot of imports too:</p>\n\n<pre><code>from bottle import run, request, post\nfrom json import dumps\n</code></pre>\n\n<hr>\n\n<p>Hope that helps. In general it's good to let readers know all you can,\nlike \"which dependencies do I need\" and \"how do I run this\", including\nexample invocations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:09:30.957", "Id": "213344", "ParentId": "213329", "Score": "1" } } ]
{ "AcceptedAnswerId": "213344", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T20:56:41.917", "Id": "213329", "Score": "2", "Tags": [ "python", "python-3.x", "json", "api", "rest" ], "Title": "RESTful API echo server using Python bottles" }
213329
<p>I've got a class with few fields:</p> <pre><code>public class Helper { String first; String second; String third; String fourth; String fifth; String sixth; } </code></pre> <p>And helper service with method which I try to refactor.</p> <pre><code>public class HelperService { public Helper toRefactor(String[] attributes) { Helper testObject = new Helper(); if (attributes.length &gt; 0) { testObject.first = attributes[0]; if (attributes.length &gt; 1) { testObject.second = attributes[1]; } if (attributes.length &gt; 2) { testObject.third = attributes[2]; } if (attributes.length &gt; 3) { testObject.fourth = attributes[3]; } if (attributes.length &gt; 4) { testObject.fifth = attributes[4]; } if (attributes.length &gt; 5) { testObject.sixth = attributes[5]; } } return testObject; } } </code></pre> <p>My ideal solution would've look like:</p> <pre><code> for (int i = 0; i &gt; attributes.length; i++) { testObject.array[i] = attributes[i]; } </code></pre> <p>But this gnerates syntax error on <code>testObject.array[i]</code> part</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:14:27.360", "Id": "412661", "Score": "0", "body": "Are you sure `first`, `second`, `third`... should be separate fields? Are you sure `attributes` should be an array of unknown length? Translating data from an ordered sequence to an object with named fields will likely require bulk. It may be better to look at why things are set up the way they are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:27:28.777", "Id": "412666", "Score": "0", "body": "What do you mean by \"Translating data from an ordered sequence to an object with named fields will likely require bulk.\"? And yeah, I'm sure that they need to be separated fields. I will try to investigate why attributes are unknown array length..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:37:00.720", "Id": "412669", "Score": "0", "body": "I mean you are moving data between two structures that are holding data differently. Somewhere, you need to have code that says `attributes[0]` should be stored in `first` and so on. If you can guarantee `attributes` will always have 5 elements, you could give the class a constructor and do `new Helper(attributes[0], attributes[1], attributes[2], attributes[3], attributes[4], attributes[5])` or something similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:41:50.210", "Id": "412670", "Score": "0", "body": "Yeah, but I don't know how many attributes there will be, so constructor isn't the way :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:43:59.570", "Id": "412671", "Score": "0", "body": "Will this code be run super often, or only occasionally?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:44:35.833", "Id": "412672", "Score": "0", "body": "Is there any difference? I guess kinda often." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:49:41.953", "Id": "412673", "Score": "0", "body": "If the code isn't run in a performance sensitive place, you could just copy the array using `Arrays.copyOf(attributes, 5)` to standardize the length. Copying an array 5 elements long take next to no time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:55:52.030", "Id": "412675", "Score": "0", "body": "Ohh you mean falsely create a 5 element array to be able to use the constructor which will be filled with nulls if element not exist" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:58:37.063", "Id": "412676", "Score": "0", "body": "It would at least eliminate the length checks. Even just doing that would improve your constructorless way that you have now. And in your current setup, the fields will be left uninitialized anyways, so there shouldn't be much difference in that regard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:00:05.977", "Id": "412677", "Score": "0", "body": "Yeah your right with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:01:45.283", "Id": "412678", "Score": "0", "body": "And I just timed it using a proper benchmarking library, and copying a 5 element array takes between 17-36 nanoseconds. I'm not sure how long your strings are, but I don't think it would go much beyond that. I'm also on a slow computer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:09:43.007", "Id": "412680", "Score": "0", "body": "I think it will be a good entry point to start refactoring." } ]
[ { "body": "<p>Your <code>HelperService.toRefactor()</code> doesn't seem to be accessing any data in its own <code>HelperService</code> instance, so it probably should be a <code>static</code> method.</p>\n\n<p>Your \"ideal\" solution would not work well, since <code>i &gt; attributes.length</code> would never be true; the loop would never start.</p>\n\n<pre><code> for (int i = 0; i &gt; attributes.length; i++) {\n testObject.array[i] = attributes[i];\n }\n</code></pre>\n\n<p>Perhaps you meant <code>i &lt; attributes.length</code>.</p>\n\n<hr>\n\n<p>Reflection may be useful here. It is close to your 'ideal' solution.</p>\n\n<pre><code>private final static String[] fields = { \"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\" };\n\npublic static Helper toRefactor(String[] attributes) {\n Helper testObject = new Helper();\n\n for (int i=0; i&lt;attributes.length; i++) {\n Field field = Helper.class.getDeclaredField(fields[i]);\n field.setAccessible(true);\n field.set(testObject, attributes[i]);\n }\n\n return testObject;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:14:45.387", "Id": "213337", "ParentId": "213330", "Score": "1" } }, { "body": "<p>I'm not sure how much neater you consider this (if at all), but a <code>switch</code> could be used here:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static Helper toRefactor2(String[] attributes) {\n Helper testObject = new Helper();\n\n switch(attributes.length) {\n case 6: testObject.sixth = attributes[5];\n case 5: testObject.fifth = attributes[4];\n case 4: testObject.fourth = attributes[3];\n case 3: testObject.third = attributes[2];\n case 2: testObject.second = attributes[1];\n case 1: testObject.first = attributes[0];\n case 0: break\n\n default: throw new IllegalArgumentException(\"Invalid array of length \" + attributes.length)\n }\n\n return testObject;\n}\n</code></pre>\n\n<p>This takes advantage of the fall-through.</p>\n\n<p>Thanks to @AJ for rubustness suggestions. </p>\n\n<hr>\n\n<p>You could also standardize the length of the array by making a copy of it. This does away with the need for length checks if you can't guarantee the length ahead of time:</p>\n\n<pre><code>public static Helper toRefactor3(String[] attributes) {\n Helper testObject = new Helper();\n\n String[] std = Arrays.&lt;String&gt;copyOf(attributes, 5);\n\n testObject.first = std[0];\n testObject.second = std[1];\n testObject.third = std[2];\n testObject.fourth = std[3];\n testObject.fifth = std[4];\n testObject.sixth = std[5];\n\n return testObject;\n}\n</code></pre>\n\n<p>I'm not sure how people would feel about this though. It's quite fast at least. I benchmarked copying an array that small using Criterium (in Clojure, but that shouldn't matter much). It's basically instantaneous:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(let [arr (to-array [\"ABCDEFG\"\n \"HIJKLMNOP\"\n \"QRSTUVWXYZ\"\n \"QWERTYUIOP\"\n \"ASDFGHJKL\"])]\n\n (cc/bench\n (Arrays/copyOf arr 5)))\n\nEvaluation count : 2908877280 in 60 samples of 48481288 calls.\n Execution time mean : 17.184167 ns\n Execution time std-deviation : 1.008121 ns\n Execution time lower quantile : 15.294929 ns ( 2.5%)\n Execution time upper quantile : 19.609513 ns (97.5%)\n Overhead used : 3.609363 ns\n\nFound 5 outliers in 60 samples (8.3333 %)\n low-severe 1 (1.6667 %)\n low-mild 4 (6.6667 %)\n Variance from outliers : 43.4678 % Variance is moderately inflated by outliers\n</code></pre>\n\n<hr>\n\n<p>And I agree with @AJ. In the current context, that method should be static. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:34:32.920", "Id": "412689", "Score": "0", "body": "I like the `switch` statement approach. Fast & type safe. And no unnecessary reflection, so using an IDE to rename a field won’t break the code by missing a string that happens to contain the field name. The only fragile part is if you pass in an array of 7 or more items, nothing will get copied. So, I’d add a `case 0: break;` followed by `default: throw new IllegalArgumentException();` just to be safe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:51:57.443", "Id": "412693", "Score": "0", "body": "@AJNeufeld Oh, good point. Sec." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:37:58.020", "Id": "213340", "ParentId": "213330", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:01:16.497", "Id": "213330", "Score": "-2", "Tags": [ "java" ], "Title": "Refactor multiple if statements while creating object" }
213330
<p>i created this console application ( it's actually a Mastermind) and i would like to know what can i improve as a beginner. Thanks !</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;time.h&gt; std::string colorsRandomizer(); int verif(char couleur); std::string transform(char couleur); int main() { std::srand(time(0)); //Declaration des variables std::string color_1; std::string color_2; std::string color_3; std::string color_4; std::string combination; char color_1_User; char color_2_User; char color_3_User; char color_4_User; std::string color_1_trial; std::string color_2_trial; std::string color_3_trial; std::string color_4_trial; std::string combinationUser; short chances = 0; short s = 0; //Compteur pour le boucle du choix utilisateur short good; short near; //Creation aleatoire de la combinaison color_1 = colorsRandomizer(); color_2 = colorsRandomizer(); color_3 = colorsRandomizer(); color_4 = colorsRandomizer(); combination = color_1 + color_2 + color_3 + color_4; std::cout &lt;&lt; "Bienvenue dans MasterMind ! Le jeu qui va vous soulever le cerveau !" &lt;&lt; std::endl; std::cout &lt;&lt; "Le bot a choisi sa combinaison. A vous d'essayer de la trouver. J pour jaune, R pour rouge, B pour Bleu, V pour violet, G pour vert, O pour orange." &lt;&lt; std::endl; while(chances &lt;= 10){ ++chances; do{ std::cout &lt;&lt; "Couleur une:" &lt;&lt; std::endl; std::cin &gt;&gt; color_1_User; std::cin.ignore(999, '\n'); s=verif(color_1_User); }while(s!=1); color_1_trial= transform(color_1_User); do{ s=0; std::cout &lt;&lt; "Couleur deux:" &lt;&lt; std::endl; std::cin &gt;&gt; color_2_User; std::cin.ignore(999, '\n'); s=verif(color_2_User); }while(s!=1); color_2_trial= transform(color_2_User); do{ s=0; std::cout &lt;&lt; "Couleur trois:" &lt;&lt; std::endl; std::cin &gt;&gt; color_3_User; std::cin.ignore(999, '\n'); s=verif(color_3_User); }while(s!=1); color_3_trial= transform(color_3_User); do{ s=0; std::cout &lt;&lt; "Couleur quatre:" &lt;&lt; std::endl; std::cin &gt;&gt; color_4_User; std::cin.ignore(999, '\n'); s=verif(color_4_User); }while(s!=1); color_4_trial= transform(color_4_User); s=0; combinationUser = color_1_trial + color_2_trial + color_3_trial + color_4_trial; std::cout &lt;&lt; combinationUser &lt;&lt; std::endl; good = 0; near = 0; //Test de la première couleur proposée if(color_1_trial == color_1){ ++good; } else if(color_1_trial == color_2 &amp;&amp; good&lt;1){ ++near; } else if(color_1_trial == color_3 &amp;&amp; near &lt;1 &amp;&amp; good&lt;1){ ++near; } else if (color_1_trial == color_4&amp;&amp; near &lt;1 &amp;&amp; good&lt;1){ ++near; } //Test de la deuxième couleur proposée if(color_2_trial == color_2){ ++good; } else if(color_2_trial == color_1 &amp;&amp; good&lt;2){ ++near; } else if(color_2_trial == color_3 &amp;&amp; near &lt;2 &amp;&amp; good&lt;2){ ++near; } else if (color_2_trial == color_4 &amp;&amp; near &lt;2 &amp;&amp; good&lt;2){ ++near; } //Test de la troisième couleur proposée if(color_3_trial == color_3){ ++good; } else if(color_3_trial == color_1 &amp;&amp; good&lt;3){ ++near; } else if(color_3_trial == color_2 &amp;&amp; near &lt;3 &amp;&amp; good&lt;3){ ++near; } else if (color_3_trial == color_4 &amp;&amp; near &lt;3 &amp;&amp; good&lt;3){ ++near; } //Test de la quatrième couleur proposée if (color_4_trial == color_4){ ++good; } else if(color_4_trial == color_1 &amp;&amp; good&lt;4){ ++near; } else if(color_4_trial == color_2 &amp;&amp; near &lt;4 &amp;&amp; good&lt;4){ ++near; } else if(color_4_trial == color_3 &amp;&amp; near &lt;4 &amp;&amp; good&lt;4){ ++near; } if(near==0){ std::cout &lt;&lt; "Il n'y a aucune couleur dans la combinaison." &lt;&lt; std::endl; } if(near&gt;0){ std::cout &lt;&lt; "Il y a " &lt;&lt; near &lt;&lt; " couleur(s) qui sont dans la combi, mais pas a la bonne place." &lt;&lt; std::endl; } if(good==0){ std::cout &lt;&lt; "Il n'y a aucune bonne couleur lo. " &lt;&lt; std::endl; } if(good&gt;0){ std::cout &lt;&lt; "Il y a " &lt;&lt; good &lt;&lt; " couleur(s) justes." &lt;&lt; std::endl; } if(good == 4){ std::cout &lt;&lt; "Bien joué le jo, tu as battu le bot ! J'espere que tu es fier de toi !!!!!!!!!!!!!!!!! \a"; system("PAUSE"); return 0; } } std::cout &lt;&lt; " PAS DE BOL, tu as perdu ! La combinaison etait " &lt;&lt; combination &lt;&lt; std::endl; system("PAUSE"); return 0; } int verif(char couleur){ short s = 0; //Initialisation de la variable de sortie de boucle. switch(couleur){ case 'J': case 'j': std::cout &lt;&lt; " Vous avez choisi la couleur jaune." &lt;&lt; std::endl; s++; break; case 'B': case 'b': std::cout &lt;&lt; "Vous avez choisi la couleur bleue." &lt;&lt; std::endl; s++; break; case 'G': case 'g': std::cout &lt;&lt; "Vous avez choisi la couleur verte." &lt;&lt; std::endl; s++; break; case 'R': case 'r': std::cout &lt;&lt; "Vous avez choisi la couleur rouge." &lt;&lt; std::endl; s++; break; case 'V': case 'v': std::cout &lt;&lt; "Vous avez choisi la couleur violette." &lt;&lt; std::endl; s++; break; case 'O': case 'o': std::cout &lt;&lt; "Vous avez choisi la couleur orange." &lt;&lt; std::endl; s++; break; default: std::cout &lt;&lt; "Veuillez respecter le code couleur." &lt;&lt; std::endl; } return s; } std::string transform(char couleur){ std::string coul; switch(couleur){ case 'J': case 'j': coul="yellow"; break; case 'B': case 'b': coul="blue"; break; case 'G': case 'g': coul="green"; break; case 'R': case 'r': coul="red"; break; case 'V': case 'v': coul="violet"; break; case 'O': case 'o': coul="orange"; break; default: std::cout &lt;&lt; "ho" &lt;&lt; std::endl; } return coul; } std::string colorsRandomizer(){ short x; std::string color; x = rand() % 6; switch(x){ case 0: color = "red"; break; case 1: color = "blue"; break; case 2: color = "yellow"; break; case 3: color = "violet"; break; case 4: color = "green"; break; case 5: color = "orange"; break; } return color; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T01:46:14.627", "Id": "412698", "Score": "1", "body": "It might be better to define an `enum` for colors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T10:45:50.387", "Id": "412729", "Score": "0", "body": "Okay i'll keep that in a corner of my head. thanks !" } ]
[ { "body": "<p>There's a lot of things you can improve upon, but let me offer at least a reasonable start.</p>\n\n<p>First, look into arrays (particularly, <code>std::vector</code>). If you have bunch of variables (like color_1 through color_4) that are intimately connected, they should be somehow logically connected. One natural way is to put them into a vector. </p>\n\n<p>Also, does it make sense a color is represented as a string? The answer is no: you are expecting it to be something like \"r\" or \"R\" to designate red. So consider switching the type into something that conveys the correct meaning and protects the user from unintentional mistakes, so make it a <code>char</code> or your own color-enum.</p>\n\n<p>Your transform and colorRandomizer should be implemented in terms of a data structure as well. For example, consider:</p>\n\n<pre><code>const std::vector&lt;std::string&gt; cols = { \"red\", \"blue\", \"yellow\", \"violet\", \"green\", \"orange\" };\n\nstd::string colorsRandomizer()\n{\n int x = rand() % 6;\n return cols.at(x);\n}\n</code></pre>\n\n<p>For the above, you need to include <code>&lt;string&gt;</code> and <code>&lt;vector&gt;</code>. Notice how much more simpler this is for maintenance: you can easily change color names and/or add more colors.</p>\n\n<p>A similar idea extends to transform:</p>\n\n<pre><code>const std::map&lt;char, std::string&gt; col_map = \n{\n { 'j', \"yellow\" },\n { 'b', \"blue\" },\n { 'g', \"green\" },\n { 'r', \"red\" },\n { 'v', \"violet\" },\n { 'o', \"orange\" },\n};\n\nstd::string transform(char couleur)\n{\n return col_map[std::tolower(couleur)];\n}\n</code></pre>\n\n<p>For this, you will need to include <code>&lt;map&gt;</code> and <code>&lt;cctype&gt;</code>. So again this approach decreases your maintenance burden and makes the code more readable. You could also ensure that the argument is actually in the map, and then fail gracefully in case it is not, but I'm skipping that you focus on the idea.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T16:34:33.667", "Id": "213899", "ParentId": "213331", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T21:12:53.057", "Id": "213331", "Score": "2", "Tags": [ "c++", "beginner" ], "Title": "Simple Mastermind in c++" }
213331
<p>This is my database connection class in order to handle multiple connections with the use of context managers. Brief explanation:</p> <ul> <li>The <code>__init__</code> method reads database configurations from an INI file in order to call the connection and set two dictionaries, one for connections and one for cursors.</li> <li>The <code>__enter__</code> method takes the specified database connection and cursor returning at the end the cursor to execute queries.</li> <li>The <code>__exit__</code> method commits the query and close the cursor if no exception has been identified.</li> </ul> <p>I'm using <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow noreferrer">PyMySQL</a> as MySQL module but I think that the code can be generalized for all MySQL modules, the functions are always those.</p> <p>Any advice is welcome, I'm new with Python!</p> <pre><code>import os.path import configparser import pymysql.cursors class Database: def __init__(self): config = configparser.ConfigParser() dbConfigFile = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'dbconfig.ini')) config.read(dbConfigFile) # Connections (database:connection method) self.connections = { 'db1': self.connection(dict(config.items('db1info'))), 'db2': self.connection(dict(config.items('db2info'))) } # Cursors list (database:cursor method) self.cursors = { 'db1': self.cursor(self.connections['db1']), 'db2': self.cursor(self.connections['db2']) } def connection(self, config): return pymysql.connect(**config) def cursor(self, connection): return connection.cursor def __call__(self, database): self.database = database return self def __enter__(self): self.db = self.connections[self.database] self.cursor = self.cursors[self.database](pymysql.cursors.SSDictCursor) return self.cursor def __exit__(self, exc_type, exc_value, tb): if not exc_type: self.db.commit() self.cursor.close() </code></pre> <p>Usage:</p> <pre><code>db = Database() with db('db1') as cursor: cursor.execute("SELECT 1 FROM table_name") </code></pre>
[]
[ { "body": "<p>Neat idea! Some suggestions:</p>\n\n<ul>\n<li><code>__exit__</code> should <code>try</code> to commit or roll back based on whether there is an unhandled exception, should then close the cursor, and should <code>finally</code> unconditionally close the connection. This is one of the main reasons for using a context manager - it is expected to always clean up after itself, leaving the relevant parts of the system in the same state as before using it.</li>\n<li>I would reuse the configuration section name as the keys in the <code>dict</code>. That way you don't need to maintain a mapping in your head or the code - what's in the configuration is what you get when you use the context manager.</li>\n<li>Rather than opening all connections and then using only one of them, it should open the connection and the cursor with the name passed in. Otherwise you're wasting resources.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T03:02:15.113", "Id": "213351", "ParentId": "213332", "Score": "3" } } ]
{ "AcceptedAnswerId": "213351", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:11:56.613", "Id": "213332", "Score": "2", "Tags": [ "python", "mysql" ], "Title": "Multiple database connections class" }
213332
<p>The task:</p> <blockquote> <p>We're given a hashmap associating each courseId key with a list of courseIds values, which represents that the prerequisites of courseId are courseIds. Return a sorted ordering of courses such that we can finish all courses.</p> <p>Return null if there is no such ordering.</p> <p>For example, given <code>{'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}</code>, should return <code>['CSC100', 'CSC200', 'CSCS300']</code>.</p> </blockquote> <p>My solution:</p> <pre><code>const isEveryCourseCovered = courses =&gt; courses.every(c =&gt; !Boolean(c)); const getCourseOrder = courses =&gt; { const courseSubjects = Object.keys(courses); const courseRequirements = Object.values(courses); const courseOrder = []; do { courseSubjects.map((subject, i) =&gt; { if (subject) { courseRequirements[i].map((requirement, idx) =&gt; { if (courseOrder.includes(requirement)) { courseRequirements[i].splice(idx, 1); } }); if (!courseRequirements[i].length) { courseOrder.push(subject); delete courseSubjects[i]; } } }); } while(!isEveryCourseCovered(courseSubjects)); return courseOrder; }; const coursesObj = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}; console.log("result ", getCourseOrder(coursesObj)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T01:01:47.133", "Id": "412694", "Score": "0", "body": "Should the values be sorted by (alpha-) numeric order? e.g. if the input was `{'CSC400': ['CSC200'], 'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []};` then should the output be `[ \"CSC100\", \"CSC200\", \"CSC300\", \"CSC400\"]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T01:05:45.470", "Id": "412695", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ following the pattern of the post, i assume `CSC400` would have an array of courses required to get to it, `'CSC400': ['CSC100', 'CSC200', 'CSC300'],`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T02:32:20.927", "Id": "412699", "Score": "0", "body": "@Taki you can’t assume CS300 would be a pre-requisite of CS400. Some institutions *might* not have such a pattern- e.g. if both are elective courses like graphics and networking" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T03:24:06.597", "Id": "412701", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ oh didn't know that, fair enough, but again, it's just an assumption following the pattern in the post." } ]
[ { "body": "<p><a href=\"https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference\">Objects are passed by \"copy of a reference\".</a></p>\n\n<p>Notice that the <code>coursesObj</code> after the function call has empty values ( see snippet below )</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const isEveryCourseCovered = courses =&gt; courses.every(c =&gt; !Boolean(c));\nconst getCourseOrder = courses =&gt; {\n const courseSubjects = Object.keys(courses);\n const courseRequirements = Object.values(courses);\n const courseOrder = [];\n\n do {\n courseSubjects.map((subject, i) =&gt; {\n if (subject) {\n courseRequirements[i].map((requirement, idx) =&gt; {\n if (courseOrder.includes(requirement)) {\n courseRequirements[i].splice(idx, 1);\n }\n });\n if (!courseRequirements[i].length) {\n courseOrder.push(subject);\n delete courseSubjects[i];\n }\n }\n });\n } while (!isEveryCourseCovered(courseSubjects));\n\n return courseOrder;\n};\n\nconst coursesObj = {\n 'CSC300': ['CSC100', 'CSC200'],\n 'CSC200': ['CSC100'],\n 'CSC100': []\n};\nconsole.log(\"result \", getCourseOrder(coursesObj));\n\nconsole.log(\"Courses Object : \", coursesObj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You should create a copy of the passed object, a quick way ( <a href=\"https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object\">one of many ways</a> ) of doing that is <code>JSON.parse(JSON.stringify(c));</code>\n( see snippet below ):</p>\n\n<pre><code>const getCourseOrder = c =&gt; {\n // make a copy of the input object\n const courses = JSON.parse(JSON.stringify(c));\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const isEveryCourseCovered = courses =&gt; courses.every(c =&gt; !Boolean(c));\nconst getCourseOrder = c =&gt; {\n // make a copy of the input object\n const courses = JSON.parse(JSON.stringify(c));\n\n const courseSubjects = Object.keys(courses);\n const courseRequirements = Object.values(courses);\n const courseOrder = [];\n\n do {\n courseSubjects.map((subject, i) =&gt; {\n if (subject) {\n courseRequirements[i].map((requirement, idx) =&gt; {\n if (courseOrder.includes(requirement)) {\n courseRequirements[i].splice(idx, 1);\n }\n });\n if (!courseRequirements[i].length) {\n courseOrder.push(subject);\n delete courseSubjects[i];\n }\n }\n });\n } while (!isEveryCourseCovered(courseSubjects));\n\n return courseOrder;\n};\n\nconst coursesObj = {\n 'CSC300': ['CSC100', 'CSC200'],\n 'CSC200': ['CSC100'],\n 'CSC100': []\n};\nconsole.log(\"result \", getCourseOrder(coursesObj));\n\nconsole.log(\"Courses Object : \", coursesObj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I didn't test the performance but i would guess it wouldn't be that efficient since it has 5 nested loops (<code>do while</code>, <code>.map</code>, <code>.map</code>, <code>.includes</code>) and <code>.every</code> that's called on every iteration of the <code>while</code> loop and 3 <code>if</code>s </p>\n\n<p>Reading the requirement : </p>\n\n<blockquote>\n <p>Return a <strong>sorted</strong> ordering of courses </p>\n</blockquote>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\">Array.sort()</a> was the first thing to come to my mind, my suggested approach would be simply sorting the <code>Object.keys</code> of the <code>coursesObj</code> based on the length of the value ( array of required courses) corresponding to that key, like so :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const coursesObj = {\n 'CSC300': ['CSC100', 'CSC200'],\n 'CSC400': ['CSC100', 'CSC200', 'CSC300'],\n 'CSC200': ['CSC100'],\n 'CSC100': []\n};\n\nconst result = Object.keys(coursesObj).sort((a, b) =&gt;\n coursesObj[a].length - coursesObj[b].length\n);\n\nconsole.log(result)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>PS : i added the <code>CSC400</code> key in the middle just for the demo.</p>\n\n<p><strong>EDIT :</strong></p>\n\n<p>If you have an Object like : </p>\n\n<pre><code>const coursesObj = \n { \n c1: ['c2', 'c3', 'c4'], \n c5: ['c1'], \n c4: [], \n c2: [], \n c3: ['c4']\n }\n</code></pre>\n\n<p>you can transform it to add the prerequisites of the courses in its prerequisites \n array so it becomes :</p>\n\n<pre><code>const detailed = \n { \n c1: [ 'c2', 'c3', 'c4' ],​​​​​\n c5: [ 'c1', 'c2', 'c3', 'c4' ],​​​​​ // c5 now has c1 and the prerequisites of c1\n ​​​​​ c4: [],​​​​​\n​​​​​ c2: [],​​​​​\n ​​​​​ c3: [ 'c4' ] \n }​​​​​\n</code></pre>\n\n<p>then apply the same sort function above :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const coursesObj = { c1: [\"c2\", \"c3\", \"c4\"], c5: [\"c1\"], c4: [], c2: [], c3: [\"c4\"] };\n\nconst detailedObj = Object.entries(coursesObj).reduce((accumulator, [courseId, requirements]) =&gt; {\n accumulator[courseId] = requirements.slice(0); // original courses required.\n\n requirements.forEach(course =&gt; {\n accumulator[courseId].push(...coursesObj[course]); // add the required courses for each required course .\n });\n\n // remove the duplicates\n accumulator[courseId] = [...new Set(accumulator[courseId])];\n\n return accumulator;\n}, {});\n\n// sort by the number of prerequisites \nconst result = Object.keys(detailedObj).sort((a, b) =&gt;\n detailedObj[a].length - detailedObj[b].length\n);\n\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T05:48:15.067", "Id": "412706", "Score": "0", "body": "Thanks for the input. There are something I definitely will take into account. But I'm not sure, whether the solution you presented is correct. The sorting can't be done by the length of the array alone but has to be in relation to the required courses. E.g. `const coursesObj = {\n 'c1': ['c2', 'c3', 'c4'],\n 'c5': ['c1'],\n 'c4': [],\n 'c2': [],\n 'c3': ['c4'],\n};` should return this order `{c4, c2, c3, c1, c5}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T17:04:01.970", "Id": "412801", "Score": "0", "body": "@thadeuszlay i updated the answer for the input you provided," } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T01:04:09.447", "Id": "213347", "ParentId": "213333", "Score": "2" } } ]
{ "AcceptedAnswerId": "213347", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:19:45.993", "Id": "213333", "Score": "0", "Tags": [ "javascript", "algorithm", "functional-programming" ], "Title": "Return a sorted ordering of courses such that we can finish all courses" }
213333
<p>This is a python game that I am working on. It is a grid based treasure hunt game in which you collect coins from specific tiles (some tiles ask you questions in which you need to answer correctly in order to get coins), and after a number of moves the coins that you end up with are recorded and put in a file. At the moment I haven't fully implemented everything to the final game but I am using SQlite3 for the backend database of storing questions/answers and for the front end Tkinter and Pygame. Any advice on how to improve my code, organise it, make it more efficient or anything else would be good to know. Thanks.</p> <pre><code>import pygame, sys import random from pygame.locals import * from tkinter import ttk import tkinter from tkinter import messagebox import sqlite3 conn = sqlite3.connect('games.db') c = conn.cursor() #creates table #c.execute("""CREATE TABLE game ( # questionID integer PRIMARY KEY AUTOINCREMENT, # question text, # answer text # )""") #execute only once #SQL QUESTION ADD/REMOVE/GET def insert_question(emp): c.execute("INSERT INTO game VALUES (?, ?, ?)", (emp)) conn.commit() def get_question(): c.execute("SELECT * FROM game") return c.fetchall() def remove_question(emp): c.execute("DELETE from game WHERE question = ?", [emp]) conn.commit() #Tkinter window = tkinter.Tk() window.title("Treasure Hunt Game!") labelOne = ttk.Label(window, text = """ ~~~~~~~~~~~~~ MENU ~~~~~~~~~~~~~ """)#label displays instruction labelOne.grid(row = 0, column = 0)#places label in a grid def showInstructions(): messagebox.showinfo("Instructions", "shows instructions")#messagebox used for more simple functions (showing messages) btn = ttk.Button(window, text = "View instructions", command = showInstructions) btn.grid(row = 1, column = 0)#places button in a grid def showLeaderboard(): messagebox.showinfo("Leaderboard", "shows leaderboard") window.destroy() btn = ttk.Button(window, text = "View leaderboard", command = showLeaderboard) btn.grid(row = 2, column = 0) def showQuestions(): emps = get_question() messagebox.showinfo("List of questions/answers", emps) btn = ttk.Button(window, text = "View all questions", command = showQuestions) btn.grid(row = 3, column = 0) btn = ttk.Button(window, text = "Continue", command = showLeaderboard) btn.grid(row = 4, column = 0) labelTwo = ttk.Label(window, text = "Enter a math question:") labelTwo.grid(row = 5, column = 0) mathquestion = tkinter.StringVar()#value type is classified as a string userEntryQ = ttk.Entry(window, width = 30, textvariable = mathquestion) userEntryQ.grid(row = 6, column = 0) labelTwo = ttk.Label(window, text = "Enter the answer to this question:") labelTwo.grid(row = 7, column = 0) mathanswer = tkinter.StringVar() userEntryQ = ttk.Entry(window, width = 30, textvariable = mathanswer) userEntryQ.grid(row = 8, column = 0) def answer(): mathquestion1 = mathquestion.get() mathanswer1 = mathanswer.get() emp_1 = (None, mathquestion1, mathanswer1) insert_question(emp_1) emps = get_question() print(emps) btn = ttk.Button(window, text = "Submit", command = answer) btn.grid(row = 8, column = 1) labelTwo = ttk.Label(window, text = "Enter question to remove:") labelTwo.grid(row = 9, column = 0) removequestion = tkinter.StringVar() userEntryQ = ttk.Entry(window, width = 30, textvariable = removequestion) userEntryQ.grid(row = 10, column = 0) def remove(): removequestion1 = removequestion.get() remove_question(removequestion1) btn = ttk.Button(window, text = "Submit", command = remove) btn.grid(row = 10, column = 1) window.mainloop() #MAIN GAME #colours black = (0, 0, 0) white = (255, 255, 255) brown = (153, 76, 0) blue = (0, 0, 255) grey = (192,192,192) #game dimensions tilesize = 20 mapwidth = 30 mapheight = 20 coins = 0 ship = 1 water = 2 rock = 3 movesMade = 4 #dictionary for texture of the map textures = { #the transform function scales the photo to the tile size ship : pygame.transform.smoothscale(pygame.image.load('ship.png'), (tilesize, tilesize)), water: pygame.transform.smoothscale(pygame.image.load('water.png'), (tilesize, tilesize)), rock: pygame.transform.smoothscale(pygame.image.load('rock.png'), (tilesize, tilesize)), coins: pygame.transform.smoothscale(pygame.image.load('chest.png'), (tilesize, tilesize)), movesMade: pygame.transform.smoothscale(pygame.image.load('player.png'), (tilesize, tilesize)) } inventory = { coins: 0, movesMade: 0 } #image that will represent player PLAYER = pygame.transform.smoothscale(pygame.image.load('player.png'), (tilesize, tilesize)) #position of the player playerPos = [0,0] resources = [coins, movesMade] #utilise list comprehension to create grid tilemap = [[water for w in range(mapwidth)] for h in range(mapheight)] pygame.init() #set up display displaysurf = pygame.display.set_mode((mapwidth*tilesize,mapheight*tilesize + 60)) invfont = pygame.font.Font('FreeSansBold.ttf', 18) #loops through each row for rw in range(mapheight): for cl in range(mapwidth): randomnumber = random.randint(0,15) if randomnumber == 0 or randomnumber == 1: tile = rock elif randomnumber == 2 or randomnumber == 3 : tile = ship else: tile = water #sets position in the grid tilemap[rw][cl] = tile visit = {} while True: displaysurf.fill(black) #background color #user events for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: if event.key == K_RIGHT and playerPos[0] &lt; mapwidth - 1: playerPos[0] += 1 if event.key == K_LEFT and playerPos[0] &gt; 0: playerPos[0] -= 1 if event.key == K_UP and playerPos[1] &gt; 0: playerPos[1] -= 1 if event.key == K_DOWN and playerPos[1] &lt; mapheight -1: playerPos[1] += 1 if event.key == K_SPACE: pos = (playerPos[1], playerPos[0]) if not pos in visit: # checks whether a tile has been used visit[pos] = True currentTile = tilemap[playerPos[1]][playerPos[0]] if currentTile == rock: inventory[movesMade] += 1 percent = 30 # coins are kept with a probability of 30 percent and will be lost by 70 percent ran1 = random.randint(0,100) # random value in [0, 99] if ran1 &gt;= percent: inventory[coins] = 0 else: inventory[coins] += 100 elif currentTile == ship: inventory[coins] += 20 inventory[movesMade] += 1 #loops through each row for row in range(mapheight): #loops through each column in row for column in range(mapwidth): displaysurf.blit(textures[tilemap[row][column]], (column*tilesize,row*tilesize)) displaysurf.blit(PLAYER,(playerPos[0]*tilesize,playerPos[1]*tilesize)) placePosition = 10 for item in resources: displaysurf.blit(textures[item],(placePosition, mapheight*tilesize + 20)) placePosition += 30 #text displays amount of coin textObj = invfont.render(str(inventory[item]), True, white, black) displaysurf.blit(textObj,(placePosition, mapheight*tilesize + 20)) placePosition += 50 #if inventory[coins] &gt; 100: # break pygame.display.update() </code></pre>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>There is very little structure. A game like this would typically have at least <code>Game</code>, <code>Question</code>, <code>Answer</code>, <code>Storage</code> and <code>Window</code> classes and a <code>main</code> method which just creates a <code>Game</code> and runs it.</li>\n<li>Pull out fields or constants (as appropriate) for magic values such as strings and numbers, so a reader can know at a glance <em>what</em> they are, rather than just their value.</li>\n<li>Run the code through <code>flake8</code> and <code>pycodestyle</code> to get hints about non-pythonic code such as the variable names.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T02:45:30.107", "Id": "213350", "ParentId": "213334", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T22:34:19.080", "Id": "213334", "Score": "4", "Tags": [ "python", "pygame" ], "Title": "Python Pygame treasure hunt game" }
213334
<p>I'm looking to parse a reduced subset of the Valve Data Format (VDF). It is similar to JSON, allowing representation of key-value collections (maps) with arbitrary recursion. As a small example:</p> <pre><code>"root" { "key1" "value1" "key2" "value2" "key3" { ... } } </code></pre> <p>I'm taking on only a subset of the language (no comments; all keys and values enclosed in quotation marks; no escape sequences). Below is the code I've written to tokenize and iterate over input of the above form:</p> <pre><code>import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.UncheckedIOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Iterator; class TokenIterator implements Iterator&lt;String&gt;, Iterable&lt;String&gt;, AutoCloseable { private static final int EOF = -1; private static final int BUFFER_SZ = 4 * 1024 * 1024; private static final String LPAREN = "{"; private static final String RPAREN = "}"; private final Reader reader; private final StringBuilder sb; private int ch; private TokenIterator(Reader reader, StringBuilder sb, int ch) { this.reader = reader; this.sb = sb; this.ch = ch; } static TokenIterator forPath(Path path) { try { Reader reader = new BufferedReader(new FileReader(path.toFile()), BUFFER_SZ); StringBuilder sb = new StringBuilder(); return new TokenIterator(reader, sb, reader.read()); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public boolean hasNext() { try { while ((ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ')) { ch = reader.read(); } } catch (IOException e) { throw new UncheckedIOException(e); } return ch != EOF; } @Override public String next() { try { String result; switch (ch) { case '"': done: do { ch = reader.read(); switch (ch) { case EOF: throw new IllegalArgumentException("Reached EOF while reading quoted string"); case '"': ch = reader.read(); result = sb.toString(); sb.setLength(0); break done; default: sb.append(ch); } } while (true); break; case '{': result = LPAREN; break; case '}': result = RPAREN; break; default: String message = String.format("Unexpected char '%x' at beginning of token", ch); throw new IllegalArgumentException(message); } ch = reader.read(); return result; } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public void close() throws Exception { reader.close(); } @Override public Iterator&lt;String&gt; iterator() { return this; } public static void main(String[] args) { TokenIterator it = forPath(Paths.get("items_game.txt")); long start = System.currentTimeMillis(); for (String s : it) {} System.out.printf("Token iteration time: %d", System.currentTimeMillis() - start); } } </code></pre> <p>All constructive comments are welcome, but I'm most interested in improving performance. It's taking around 70ms to iterate through a 3.66MB, ~131k line file of this type on my machine (i7-7700HQ 2.8GHz processor, 16GB system memory), which I find disappointing.</p>
[]
[ { "body": "<p>You are using the older, legacy <code>java.io.File</code> and <code>java.io.FileReader</code> classes for opening a newer <code>java.nio.file.Path</code> object. The <code>nio</code> stands for \"new IO\", and can make use of high-efficiency byte-buffers and operating system calls for file reading and writing. You may (or may not) see an improvement if you use the newer <a href=\"https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html#newBufferedReader(java.nio.file.Path)\" rel=\"nofollow noreferrer\"><code>Files.newBufferedReader(Path)</code></a> method from <code>java.nio.file</code> to open the file.</p>\n\n<p>(You cannot specify the buffer size using the <code>newBufferedReader()</code> method, but your 4MB buffer was likely not helping you since the operating system would limit itself to transferring the drive's block-size memory chunks anyway.)</p>\n\n<p>The <code>TokenIterator</code> constructor is <code>private</code>, and only called from <code>forPath(...)</code>. The <code>forPath(...)</code> method does preparatory work for the constructor, creating a <code>BufferedReader</code>, <code>StringBuilder</code> and reading one character from the reader to prime the <code>TokenIterator</code>. These are all internal details which could be hidden completely inside the constructor:</p>\n\n<pre><code>private final StringBuilder sb = new StringBuilder();\n\npublic TokenIterator(Path path) {\n try {\n reader = Files.newBufferedReader(path);\n ch = reader.read();\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n}\n</code></pre>\n\n<p><code>TokenIterator</code> is declared as an <code>AutoCloseable</code> resource, but you are not taking advantage of that in your <code>main</code> function, so possibly leaking a resource:</p>\n\n<pre><code>public static void main(String[] args) {\n\n try (TokenIterator it = new TokenIterator(Paths.get(\"item_games.txt\"))) {\n long start = System.currentTimeMillis();\n\n for (String s : it) { /* no-op */ }\n\n System.out.printf(\"Token iteration time: %d\", System.currentTimeMillis() - start);\n } // TokenIterator is auto-closed here.\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T02:18:04.443", "Id": "213349", "ParentId": "213341", "Score": "0" } } ]
{ "AcceptedAnswerId": "213349", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:40:28.187", "Id": "213341", "Score": "1", "Tags": [ "java", "parsing" ], "Title": "Token generator for Valve Data Format parser in Java" }
213341
<p>Mostly as a learning exercise, and partly as I thought it might be useful, I have written an implementation of AVL trees ( <a href="https://en.wikipedia.org/wiki/AVL_tree" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/AVL_tree</a> ). </p> <blockquote> <p>An AVL tree is a height-balanced binary search tree, where if the height difference of the left and right sub-trees becomes more than one a "rotate" operation is applied to re-balance the tree, which keeps the tree nodes in the same order, but promoting a child node upwards, with the unbalanced node being demoted.</p> </blockquote> <p>Implementing C# iterators was totally new to me, so that has been a learning exercise, and I'm not quite sure if my style on that is quite right.</p> <p>There are two main classes, a key-only tree <code>AvlTree</code>, and a key/value dictionary <code>AvlDict</code>. </p> <p>I tend to stick to <a href="https://en.wikipedia.org/wiki/C_Sharp_2.0" rel="nofollow noreferrer"><strong>C# version 2</strong></a>, for reasons I won't go into, and I do not generally use <code>_</code> for private fields, please don't comment on that - all other comments and reviews welcome. The way I have implemented dictionary assignment is perhaps a little questionable, but I wanted to separate out the key/value pair logic from the AVL tree. Is there a better way to do that?</p> <p>Here is the code, starting with a usage example:</p> <pre><code>using Collections = System.Collections; using Generic = System.Collections.Generic; using Console = System.Console; // For example usage. class AvlExample { public static void Usage() { AvlTree&lt;long&gt; tree = new AvlTree&lt;long&gt;(); int testSize = 5 * 1000 * 1000; // Insert keys 0, 10, 20 ... into the tree. for ( int i = 0; i &lt; testSize; i += 10 ) tree.Insert( i ); Console.WriteLine( "Should print 50,60..100" ); foreach ( long x in tree.Range( 50, 100 ) ) Console.WriteLine( x ); // Remove 4/5 of the keys to test Remove. for ( int i = 0; i &lt; testSize; i += 10 ) if ( i % 50 != 0 ) tree.Remove( i ); Console.WriteLine( "Should print 50,100..250" ); foreach ( long x in tree.Range( 50, 250 ) ) Console.WriteLine( x ); AvlDict&lt;int,string&gt; dict = new AvlDict&lt;int,string&gt;( "" ); dict[ 100 ] = "There"; dict[ 50 ] = "Hello"; dict[ 100 ] = "there"; foreach ( int i in dict ) Console.WriteLine( dict[ i ] ); } } class AvlTree&lt;T&gt; : Generic.IEnumerable&lt;T&gt; { public delegate int DComparer( T key1, T key2 ); public AvlTree() // Initialise with default compare. { Compare = Generic.Comparer&lt;T&gt;.Default.Compare; } public AvlTree( DComparer compare ) // Initialise with specific compare function. { Compare = compare; } public void Insert( T key ) // Insert key into the tree. If key is already in tree, Found is called. { bool heightIncreased; Root = Insert( Root, key, out heightIncreased ); } public bool Contains( T key ) { return Lookup( key ) != null; } public void Remove( T key ) // Remove key from the tree. If key is not present, has no effect. { bool heightIncreased; Root = Remove( Root, key, out heightIncreased ); } public Generic.IEnumerator&lt;T&gt; GetEnumerator() { if ( Root != null ) foreach( T key in Root ) yield return key; } Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public Generic.IEnumerable&lt;T&gt; Range( T start, T end ) { if ( Root != null ) foreach( T key in Root.Range( start, end, Compare ) ) yield return key; } protected virtual Node NewNode( T key ) { // Called by Insert if key not found. return new Node( key ); } protected virtual void Found( Node x ) { // Called by Insert when an existing key is found. } protected virtual void FreeNode( Node x ) { // Called by Remove when a Node is removed. } protected Node Lookup( T key ) { Node x = Root; while ( x != null ) { int cf = Compare( key, x.Key ); if ( cf &lt; 0 ) x = x.Left; else if ( cf &gt; 0 ) x = x.Right; else return x; } return null; } protected class Node : Generic.IEnumerable&lt;T&gt; { public Node Left, Right; public readonly T Key; public sbyte Balance; public Node( T key ) { Key = key; } public Generic.IEnumerator&lt;T&gt; GetEnumerator() { if ( Left != null ) foreach ( T key in Left ) yield return key; yield return Key; if ( Right != null ) foreach ( T key in Right ) yield return key; } Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public Generic.IEnumerable&lt;T&gt; Range( T start, T end, DComparer compare ) { int cstart = compare( start, Key ); int cend = compare( end, Key ); if ( cstart &lt; 0 &amp;&amp; Left != null ) { foreach ( T key in Left.Range( start, end, compare ) ) yield return key; } if ( cstart &lt;= 0 &amp;&amp; cend &gt;= 0 ) yield return Key; if ( cend &gt; 0 &amp;&amp; Right != null ) { foreach ( T key in Right.Range( start, end, compare ) ) yield return key; } } } // Node // Fields. private readonly DComparer Compare; private Node Root; // Constant values for Node.Balance. private const int LeftHigher = -1, Balanced = 0, RightHigher = 1; // Private methods. private Node Insert( Node x, T key, out bool heightIncreased ) { if ( x == null ) { x = NewNode( key ); heightIncreased = true; } else { int compare = Compare( key, x.Key ); if ( compare &lt; 0 ) { x.Left = Insert( x.Left, key, out heightIncreased ); if ( heightIncreased ) { if ( x.Balance == Balanced ) { x.Balance = LeftHigher; } else { heightIncreased = false; if ( x.Balance == LeftHigher ) { bool heightDecreased; return RotateRight( x, out heightDecreased ); } x.Balance = Balanced; } } } else if ( compare &gt; 0 ) { x.Right = Insert( x.Right, key, out heightIncreased ); if ( heightIncreased ) { if ( x.Balance == Balanced ) { x.Balance = RightHigher; } else { heightIncreased = false; if ( x.Balance == RightHigher ) { bool heightDecreased; return RotateLeft( x, out heightDecreased ); } x.Balance = Balanced; } } } else // compare == 0 { Found( x ); heightIncreased = false; } } return x; } private Node Remove( Node x, T key, out bool heightDecreased ) { if ( x == null ) // key not found. { heightDecreased = false; return x; } int compare = Compare( key, x.Key ); if ( compare == 0 ) { Node deleted = x; if ( x.Left == null ) { heightDecreased = true; x = x.Right; } else if ( x.Right == null ) { heightDecreased = true; x = x.Left; } else { // Remove the smallest element in the right sub-tree and substitute it for x. Node right = RemoveLeast( deleted.Right, out x, out heightDecreased ); x.Left = deleted.Left; x.Right = right; x.Balance = deleted.Balance; if ( heightDecreased ) { if ( x.Balance == LeftHigher ) { x = RotateRight( x, out heightDecreased ); } else if ( x.Balance == RightHigher ) { x.Balance = Balanced; } else { x.Balance = LeftHigher; heightDecreased = false; } } } FreeNode( deleted ); } else if ( compare &lt; 0 ) { x.Left = Remove( x.Left, key, out heightDecreased ); if ( heightDecreased ) { if ( x.Balance == RightHigher ) { return RotateLeft( x, out heightDecreased ); } if ( x.Balance == LeftHigher ) { x.Balance = Balanced; } else { x.Balance = RightHigher; heightDecreased = false; } } } else { x.Right = Remove( x.Right, key, out heightDecreased ); if ( heightDecreased ) { if ( x.Balance == LeftHigher ) { return RotateRight( x, out heightDecreased ); } if ( x.Balance == RightHigher ) { x.Balance = Balanced; } else { x.Balance = LeftHigher; heightDecreased = false; } } } return x; } private static Node RemoveLeast( Node x, out Node least, out bool heightDecreased ) { if ( x.Left == null ) { heightDecreased = true; least = x; return x.Right; } else { x.Left = RemoveLeast( x.Left, out least, out heightDecreased ); if ( heightDecreased ) { if ( x.Balance == RightHigher ) { return RotateLeft( x, out heightDecreased ); } if ( x.Balance == LeftHigher ) { x.Balance = Balanced; } else { x.Balance = RightHigher; heightDecreased = false; } } return x; } } private static Node RotateRight( Node x, out bool heightDecreased ) { // Left is 2 levels higher than Right. heightDecreased = true; Node z = x.Left; Node y = z.Right; if ( z.Balance != RightHigher ) // Single rotation. { z.Right = x; x.Left = y; if ( z.Balance == Balanced ) // Can only occur when deleting values. { x.Balance = LeftHigher; z.Balance = RightHigher; heightDecreased = false; } else // z.Balance = LeftHigher { x.Balance = Balanced; z.Balance = Balanced; } return z; } else // Double rotation. { x.Left = y.Right; z.Right = y.Left; y.Right = x; y.Left = z; if ( y.Balance == LeftHigher ) { x.Balance = RightHigher; z.Balance = Balanced; } else if ( y.Balance == Balanced ) { x.Balance = Balanced; z.Balance = Balanced; } else // y.Balance == RightHigher { x.Balance = Balanced; z.Balance = LeftHigher; } y.Balance = Balanced; return y; } } private static Node RotateLeft( Node x, out bool heightDecreased ) { // Right is 2 levels higher than Left. heightDecreased = true; Node z = x.Right; Node y = z.Left; if ( z.Balance != LeftHigher ) // Single rotation. { z.Left = x; x.Right = y; if ( z.Balance == Balanced ) // Can only occur when deleting values. { x.Balance = RightHigher; z.Balance = LeftHigher; heightDecreased = false; } else // z.Balance = RightHigher { x.Balance = Balanced; z.Balance = Balanced; } return z; } else // Double rotation { x.Right = y.Left; z.Left = y.Right; y.Left = x; y.Right = z; if ( y.Balance == RightHigher ) { x.Balance = LeftHigher; z.Balance = Balanced; } else if ( y.Balance == Balanced ) { x.Balance = Balanced; z.Balance = Balanced; } else // y.Balance == LeftHigher { x.Balance = Balanced; z.Balance = RightHigher; } y.Balance = Balanced; return y; } } } class AvlDict&lt;TKey,TValue&gt; : AvlTree&lt;TKey&gt; { public AvlDict( TValue def ) : base() { Default = def; } public AvlDict( TValue def, DComparer compare ) : base( compare ) { Default = def; } public TValue this [ TKey key ] { get { Pair p = (Pair) Lookup( key ); return p != null ? p.Value : Default; } set { Value = value; Insert( key ); } } private readonly TValue Default; private TValue Value; private class Pair : AvlTree&lt;TKey&gt;.Node { public TValue Value; public Pair( TKey key, TValue value ) : base( key ) { Value = value; } } protected override Node NewNode( TKey key ) { return new Pair( key, Value ); } protected override void Found( Node x ) { Pair p = (Pair) x; p.Value = Value; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T15:11:34.617", "Id": "434881", "Score": "0", "body": "@t3chb0t how are your C# v2 programming skills? :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T15:50:16.827", "Id": "434894", "Score": "1", "body": "@dfhwze wasn't the first version 7.3? ;-P" } ]
[ { "body": "<p>I re-organised my code into a base class <code>AvlTree</code> and two derived classes <code>SortedSet</code> and <code>SortedDictionary</code>. I feel this is an improvement because a <code>SortedDictionary</code> user no longer has access to inappropriate operations in <code>AvlTree</code>, this seems much neater altogether. It's also now on <a href=\"https://github.com/georgebarwood/AvlTree\" rel=\"nofollow noreferrer\">github here</a>.</p>\n\n<p>I have also added set union and intersection operations. Here's the revised code, again starting with the example usage, then the derived classes <code>SortedSet</code> and <code>SortedDictionary</code> and finally the base class <code>AvlTree</code>:</p>\n\n<pre><code>using Collections = System.Collections;\nusing Generic = System.Collections.Generic;\nusing Console = System.Console; // For example usage.\n\nclass AvlExample\n{\n public static void Usage()\n {\n SortedSet&lt;long&gt; set = new SortedSet&lt;long&gt;();\n\n int testSize = 5 * 1000 * 1000;\n\n // Insert elements 0, 10, 20 ... into the set.\n for ( int i = 0; i &lt; testSize; i += 10 ) \n {\n set[ i ] = true; \n }\n\n Console.WriteLine( \"Should print 50,60..100\" );\n foreach ( long x in set.Range( 50, 100 ) ) Console.WriteLine( x );\n\n // Remove 4/5 of the elements from the set.\n for ( int i = 0; i &lt; testSize; i += 10 ) if ( i % 50 != 0 ) \n { \n set[ i ] = false;\n }\n\n Console.WriteLine( \"Should print 50,100..250\" );\n foreach ( long x in set.Range( 50, 250 ) ) Console.WriteLine( x ); \n\n // Test set union and intersection.\n SortedSet&lt;int&gt; s1 = new SortedSet&lt;int&gt;(); \n SortedSet&lt;int&gt; s2 = new SortedSet&lt;int&gt;(); \n s1[ 1 ] = true; s1[ 3 ] = true; s1[ 4 ] = true; s1[ 6 ] = true;\n s2[ 2 ] = true; s2[ 3 ] = true; s2[ 5 ] = true; s2[ 6 ] = true;\n Console.WriteLine( \"Should print 3, 6\" );\n foreach ( int e in s1 &amp; s2 ) Console.WriteLine( e ); \n Console.WriteLine( \"Should print 1..6\" );\n foreach ( int e in s1 | s2 ) Console.WriteLine( e ); \n\n SortedDictionary&lt;int,string&gt; dict = new SortedDictionary&lt;int,string&gt;( \"\" );\n\n dict[ 100 ] = \"There\";\n dict[ 50 ] = \"Hello\";\n dict[ 100 ] = \"there\";\n\n Console.WriteLine( \"Should print Hello there\" );\n foreach ( int i in dict.Keys ) Console.WriteLine( dict[ i ] );\n }\n}\n\n\nclass SortedSet&lt;T&gt; : AvlTree&lt;T&gt;, Generic.IEnumerable&lt;T&gt;\n// Generic sorted set implemented as height-balanced binary search tree. \n{\n public SortedSet() : base() \n // Initialise with default ordering for T.\n { \n } \n\n public SortedSet( DCompare compare ) : base( compare ) \n // Initialise with a specific ordering.\n { \n } \n\n public bool this [ T element ]\n // Include or Remove an element or check whether an element is in the set.\n { \n set\n {\n if ( value ) Insert( element ); else Remove( element );\n }\n get\n {\n return Lookup( element ) != null;\n } \n }\n\n public Generic.IEnumerator&lt;T&gt; GetEnumerator() \n // Iterate over the set elements.\n { \n if ( Root != null ) foreach( T key in Root ) yield return key;\n }\n\n public Generic.IEnumerable&lt;T&gt; Range( T start, T end )\n // Interate over the set elements in the specified range.\n {\n if ( Root != null ) foreach( T key in Root.Range( start, end, Compare ) ) yield return key;\n }\n\n public static SortedSet&lt;T&gt; operator &amp; ( SortedSet&lt;T&gt; a, SortedSet&lt;T&gt; b )\n // Set intersection.\n {\n SortedSet&lt;T&gt; result = new SortedSet&lt;T&gt;( a.Compare );\n Generic.IEnumerator&lt;T&gt; ea = a.GetEnumerator();\n Generic.IEnumerator&lt;T&gt; eb = b.GetEnumerator();\n bool aok = ea.MoveNext();\n bool bok = eb.MoveNext();\n while ( aok &amp;&amp; bok )\n {\n int compare = a.Compare( ea.Current, eb.Current );\n if ( compare == 0 )\n {\n result.Append( ea.Current );\n aok = ea.MoveNext();\n bok = eb.MoveNext();\n }\n else if ( compare &lt; 0 )\n {\n aok = ea.MoveNext();\n }\n else\n {\n bok = eb.MoveNext();\n } \n }\n return result;\n }\n\n public static SortedSet&lt;T&gt; operator | ( SortedSet&lt;T&gt; a, SortedSet&lt;T&gt; b )\n // Set union.\n {\n SortedSet&lt;T&gt; result = new SortedSet&lt;T&gt;( a.Compare );\n Generic.IEnumerator&lt;T&gt; ea = a.GetEnumerator();\n Generic.IEnumerator&lt;T&gt; eb = b.GetEnumerator();\n bool aok = ea.MoveNext();\n bool bok = eb.MoveNext();\n while ( aok &amp;&amp; bok )\n {\n int compare = a.Compare( ea.Current, eb.Current );\n if ( compare == 0 )\n {\n result.Append( ea.Current );\n aok = ea.MoveNext();\n bok = eb.MoveNext();\n }\n else if ( compare &lt; 0 )\n {\n result.Append( ea.Current );\n aok = ea.MoveNext();\n }\n else\n {\n result.Append( eb.Current );\n bok = eb.MoveNext();\n } \n }\n while ( aok )\n {\n result.Append( ea.Current );\n aok = ea.MoveNext();\n }\n while ( bok )\n {\n result.Append( eb.Current );\n bok = eb.MoveNext();\n }\n return result;\n }\n\n Collections.IEnumerator Collections.IEnumerable.GetEnumerator() \n // This is required by IEnumerable&lt;T&gt;. \n { \n return GetEnumerator(); \n }\n\n protected override Node NewNode( T key )\n { \n return new Node( key );\n }\n}\n\n\nclass SortedDictionary&lt;TKey,TValue&gt; : AvlTree&lt;TKey&gt;\n// Generic sorted dictionary implemented as a height-balanced binary search tree.\n{\n public SortedDictionary( TValue defaultValue ) : base() \n // Initialise with default order for TKey.\n // defaultValue is the value returned if an unassigned key is accessed.\n { \n DefaultValue = defaultValue; \n }\n\n public SortedDictionary( DCompare compare, TValue defaultValue ) : base( compare ) \n // Initialise with specific order.\n // defaultValue is the value returned if an unassigned key is accessed.\n { \n DefaultValue = defaultValue; \n }\n\n public TValue this [ TKey key ]\n // Set or get an indexed dictionary value. \n { \n set\n {\n AssignValue = value;\n Insert( key );\n }\n get\n {\n Pair p = (Pair) Lookup( key );\n return p != null ? p.Value : DefaultValue;\n } \n }\n\n public Generic.IEnumerable&lt;TKey&gt; Keys \n // Iterate over all the dictionary keys.\n {\n get\n { \n if ( Root != null ) foreach( TKey key in Root ) yield return key;\n }\n }\n\n public Generic.IEnumerable&lt;TKey&gt; KeyRange( TKey start, TKey end )\n // Iterate over the specified range of dictionary keys.\n {\n if ( Root != null ) foreach( TKey key in Root.Range( start, end, Compare ) ) yield return key;\n }\n\n private readonly TValue DefaultValue;\n\n private TValue AssignValue;\n\n private class Pair : AvlTree&lt;TKey&gt;.Node\n {\n public TValue Value;\n\n public Pair( TKey key, TValue value ) : base( key ) \n { \n Value = value; \n }\n }\n\n protected override Node NewNode( TKey key )\n {\n return new Pair( key, AssignValue );\n }\n\n protected override void Update( Node x )\n {\n Pair p = (Pair) x;\n p.Value = AssignValue;\n }\n}\n\n\nabstract class AvlTree&lt;T&gt; \n// Height-balanced binary search tree.\n{\n public delegate int DCompare( T key1, T key2 );\n\n protected AvlTree() \n // Initialise with default compare function.\n { \n Compare = Generic.Comparer&lt;T&gt;.Default.Compare;\n }\n\n protected AvlTree( DCompare compare ) \n // Initialise with specific compare function.\n { \n Compare = compare;\n }\n\n protected void Insert( T key ) \n // Insert key into the tree. If key is already in tree, Update is called.\n { \n bool heightIncreased;\n Root = Insert( Root, key, out heightIncreased );\n }\n\n protected void Append( T key )\n // Append a key to the tree.\n {\n bool heightIncreased;\n Root = Append( Root, key, out heightIncreased );\n }\n\n protected void Remove( T key ) \n // Remove key from the tree. If key is not present, has no effect. \n {\n bool heightIncreased;\n Root = Remove( Root, key, out heightIncreased );\n }\n\n protected abstract Node NewNode( T key ); \n // Factory method called by Insert if key not found.\n\n protected virtual void Update( Node x )\n // Called by Insert when an existing key is found.\n { \n }\n\n protected virtual void FreeNode( Node x )\n // Called by Remove when a Node is removed.\n { \n }\n\n protected Node Lookup( T key )\n {\n // Search tree for Node with Key equal to key.\n Node x = Root;\n while ( x != null )\n {\n int cf = Compare( key, x.Key );\n if ( cf &lt; 0 ) x = x.Left;\n else if ( cf &gt; 0 ) x = x.Right;\n else return x;\n }\n return null;\n }\n\n protected class Node\n {\n public Node Left, Right;\n public readonly T Key;\n public sbyte Balance;\n public Node( T key ) \n { \n Key = key;\n }\n\n public Generic.IEnumerator&lt;T&gt; GetEnumerator() \n {\n if ( Left != null ) foreach ( T key in Left ) yield return key;\n yield return Key;\n if ( Right != null ) foreach ( T key in Right ) yield return key; \n }\n\n public Generic.IEnumerable&lt;T&gt; Range( T start, T end, DCompare compare )\n {\n int cstart = compare( start, Key );\n int cend = compare( end, Key );\n if ( cstart &lt; 0 &amp;&amp; Left != null )\n {\n foreach ( T key in Left.Range( start, end, compare ) ) yield return key;\n }\n if ( cstart &lt;= 0 &amp;&amp; cend &gt;= 0 ) yield return Key;\n if ( cend &gt; 0 &amp;&amp; Right != null )\n {\n foreach ( T key in Right.Range( start, end, compare ) ) yield return key;\n }\n }\n\n } // Node\n\n // Fields.\n\n protected readonly DCompare Compare;\n protected Node Root;\n\n // Constant values for Node.Balance.\n private const int LeftHigher = -1, Balanced = 0, RightHigher = 1;\n\n // Private methods used to implement key insertion and removal.\n\n private Node Insert( Node x, T key, out bool heightIncreased )\n {\n if ( x == null )\n {\n x = NewNode( key );\n heightIncreased = true;\n }\n else \n {\n int compare = Compare( key, x.Key );\n if ( compare &lt; 0 )\n {\n x.Left = Insert( x.Left, key, out heightIncreased );\n if ( heightIncreased )\n {\n if ( x.Balance == Balanced )\n {\n x.Balance = LeftHigher;\n }\n else\n {\n heightIncreased = false;\n if ( x.Balance == LeftHigher )\n {\n bool heightDecreased;\n return RotateRight( x, out heightDecreased );\n }\n x.Balance = Balanced;\n }\n }\n }\n else if ( compare &gt; 0 )\n {\n x.Right = Insert( x.Right, key, out heightIncreased );\n if ( heightIncreased )\n {\n if ( x.Balance == Balanced )\n {\n x.Balance = RightHigher;\n }\n else\n {\n heightIncreased = false;\n if ( x.Balance == RightHigher )\n {\n bool heightDecreased;\n return RotateLeft( x, out heightDecreased );\n }\n x.Balance = Balanced;\n }\n }\n }\n else // compare == 0\n {\n Update( x );\n heightIncreased = false;\n }\n }\n return x;\n }\n\n private Node Append( Node x, T key, out bool heightIncreased )\n {\n if ( x == null )\n {\n x = NewNode( key );\n heightIncreased = true;\n }\n else \n {\n x.Right = Insert( x.Right, key, out heightIncreased );\n if ( heightIncreased )\n {\n if ( x.Balance == Balanced )\n {\n x.Balance = RightHigher;\n }\n else\n {\n heightIncreased = false;\n if ( x.Balance == RightHigher )\n {\n bool heightDecreased;\n return RotateLeft( x, out heightDecreased );\n }\n x.Balance = Balanced;\n }\n }\n }\n return x;\n }\n\n private Node Remove( Node x, T key, out bool heightDecreased )\n {\n if ( x == null ) // key not found.\n {\n heightDecreased = false;\n return x;\n }\n int compare = Compare( key, x.Key );\n if ( compare == 0 )\n {\n Node deleted = x;\n if ( x.Left == null )\n {\n heightDecreased = true;\n x = x.Right;\n }\n else if ( x.Right == null )\n {\n heightDecreased = true;\n x = x.Left;\n }\n else\n {\n // Remove the smallest element in the right sub-tree and substitute it for x.\n Node right = RemoveLeast( deleted.Right, out x, out heightDecreased );\n x.Left = deleted.Left;\n x.Right = right;\n x.Balance = deleted.Balance;\n if ( heightDecreased )\n {\n if ( x.Balance == LeftHigher )\n {\n x = RotateRight( x, out heightDecreased );\n }\n else if ( x.Balance == RightHigher )\n {\n x.Balance = Balanced;\n }\n else\n {\n x.Balance = LeftHigher;\n heightDecreased = false;\n }\n }\n }\n FreeNode( deleted );\n }\n else if ( compare &lt; 0 )\n {\n x.Left = Remove( x.Left, key, out heightDecreased );\n if ( heightDecreased )\n {\n if ( x.Balance == RightHigher )\n {\n return RotateLeft( x, out heightDecreased );\n }\n if ( x.Balance == LeftHigher )\n {\n x.Balance = Balanced;\n }\n else\n {\n x.Balance = RightHigher;\n heightDecreased = false;\n }\n }\n }\n else\n {\n x.Right = Remove( x.Right, key, out heightDecreased );\n if ( heightDecreased )\n {\n if ( x.Balance == LeftHigher )\n {\n return RotateRight( x, out heightDecreased );\n }\n if ( x.Balance == RightHigher )\n {\n x.Balance = Balanced;\n }\n else\n {\n x.Balance = LeftHigher;\n heightDecreased = false;\n }\n }\n }\n return x;\n }\n\n private static Node RemoveLeast( Node x, out Node least, out bool heightDecreased )\n {\n if ( x.Left == null )\n {\n heightDecreased = true;\n least = x;\n return x.Right;\n }\n else\n {\n x.Left = RemoveLeast( x.Left, out least, out heightDecreased );\n if ( heightDecreased )\n {\n if ( x.Balance == RightHigher )\n {\n return RotateLeft( x, out heightDecreased );\n }\n if ( x.Balance == LeftHigher )\n {\n x.Balance = Balanced;\n }\n else\n {\n x.Balance = RightHigher;\n heightDecreased = false;\n }\n }\n return x;\n }\n }\n\n private static Node RotateRight( Node x, out bool heightDecreased )\n {\n // Left is 2 levels higher than Right.\n heightDecreased = true;\n Node z = x.Left;\n Node y = z.Right;\n if ( z.Balance != RightHigher ) // Single rotation.\n {\n z.Right = x;\n x.Left = y;\n if ( z.Balance == Balanced ) // Can only occur when deleting values.\n {\n x.Balance = LeftHigher;\n z.Balance = RightHigher;\n heightDecreased = false;\n }\n else // z.Balance = LeftHigher\n {\n x.Balance = Balanced;\n z.Balance = Balanced;\n }\n return z;\n }\n else // Double rotation.\n {\n x.Left = y.Right;\n z.Right = y.Left;\n y.Right = x;\n y.Left = z;\n if ( y.Balance == LeftHigher )\n {\n x.Balance = RightHigher;\n z.Balance = Balanced;\n }\n else if ( y.Balance == Balanced )\n {\n x.Balance = Balanced;\n z.Balance = Balanced;\n }\n else // y.Balance == RightHigher\n {\n x.Balance = Balanced;\n z.Balance = LeftHigher;\n }\n y.Balance = Balanced;\n return y;\n }\n }\n\n private static Node RotateLeft( Node x, out bool heightDecreased )\n {\n // Right is 2 levels higher than Left.\n heightDecreased = true;\n Node z = x.Right;\n Node y = z.Left;\n if ( z.Balance != LeftHigher ) // Single rotation.\n {\n z.Left = x;\n x.Right = y;\n if ( z.Balance == Balanced ) // Can only occur when deleting values.\n {\n x.Balance = RightHigher;\n z.Balance = LeftHigher;\n heightDecreased = false;\n }\n else // z.Balance = RightHigher\n {\n x.Balance = Balanced;\n z.Balance = Balanced;\n }\n return z;\n }\n else // Double rotation\n {\n x.Right = y.Left;\n z.Left = y.Right;\n y.Left = x;\n y.Right = z;\n if ( y.Balance == RightHigher )\n {\n x.Balance = LeftHigher;\n z.Balance = Balanced;\n }\n else if ( y.Balance == Balanced )\n {\n x.Balance = Balanced;\n z.Balance = Balanced;\n }\n else // y.Balance == LeftHigher\n {\n x.Balance = Balanced;\n z.Balance = RightHigher;\n }\n y.Balance = Balanced;\n return y;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-15T10:56:12.273", "Id": "413004", "Score": "2", "body": "As long as there are no anwswers yet it's usually a better idea to edit the question and update the code there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T15:05:21.323", "Id": "434880", "Score": "1", "body": "Please merge this answer in your question. It's very confusing for people reviewing your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T15:48:21.327", "Id": "434893", "Score": "0", "body": "At this point in time (5 months down the line) it is pragmatic to leave this answer standing. It is a self-answer, but that's OK. If you want your new solution reviewed, post a new question..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T22:52:45.953", "Id": "213480", "ParentId": "213342", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-12T23:48:33.043", "Id": "213342", "Score": "3", "Tags": [ "c#", "tree", "generics", "binary-search" ], "Title": "AVL height-balanced binary search Tree and Dictionary in C# v2" }
213342
<p>My goal is to create a class that I can call from my webpages like this. Similar to a data access layer?</p> <pre><code>string sql = "SELECT EMPLOYEE_ID, FIRST, LAST, HIRE_DATE " + "FROM EMPLOYEES "; DataTable dtEmployees = SqlConnectionHelpers.TimeManagementDataTable(sql); </code></pre> <p>The class itself looks like this and is working so far (it's in the AppCode, folder on my website), but my boss has me questioning whether it will work in all cases or with a bunch of users accessing the webpages.</p> <pre><code>public static class SqlConnectionHelpers { private static SqlConnection timeManagementCon= new SqlConnection("Data Source=XXX.XXX.XXX.XXX\\TM;Initial Catalog=TimeManagement;User ID=payroll;Password=*****"); #region TimeManagement public static DataTable TimeManagementDataTable(string sql) { DataTable dt = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(sql, SqlConTimeManagement()); adapter.Fill(dt); return dt; } public static string TimeManagementCommand(string sql) { SqlCommand command = new SqlCommand(sql, SqlConTimeManagement()); var result = command.ExecuteScalar(); if (result != null) return result.ToString(); else return "Success"; } private static SqlConnection SqlConTimeManagement() { if (timeManagementCon.State == ConnectionState.Open) return timeManagementCon; else timeManagementCon.Open(); return timeManagementCon; } #endregion } </code></pre> <p>So my questions are</p> <ol> <li><p>Is this thread safe? This is a word that comes up a lot when I was looking into this problem. Say 10 people have this open in 10 different tabs, are they all accessing the same static page? If so does this cause issues with multiple people trying to grab the same connection concurrently?</p></li> <li><p>Does this cost a lot of needless overhead, when I could just code it every time I needed it?</p></li> <li><p>Is this bad practice? If so how can I fix it?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T06:17:28.547", "Id": "412864", "Score": "1", "body": "I suggest not having the static variable for SqlConnection, instead obtain a new SqlConnection each time you need it ( use \"Using\" ) to make sure it's closed/disposed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-30T06:50:07.147", "Id": "423832", "Score": "0", "body": "You can remove static keyword from class and method. And create an object of the class and call method of that class. Also as per @GeorgeBarwood use using keyword so C# will take care of dispose of every object of the class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-30T06:55:06.160", "Id": "423835", "Score": "0", "body": "And one more thing instead of creating a specific method try to create a generic method like instead of TimeManagementDataTable you can change it name to generic GetDataTable to use the same method in every page" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T00:31:45.167", "Id": "213346", "Score": "1", "Tags": [ "c#", "sql", "asp.net", "helper" ], "Title": "Helper class for ASP.net to return data from SQL server" }
213346
<p>This is a select-all checkbox (and checkboxes that it controls), that's usually found in tables/lists.</p> <p>Two things I'm concerned about:</p> <ol> <li><p>I'm returning elements from a React Hook - is that OK to do? As opposed to create a Component (probably a render prop)</p></li> <li><p>I'm calculating <code>master.indeterminate</code> in a <code>useEffect</code>, as opposed to doing it when the checkboxes are clicked. </p></li> </ol> <p>I'm planning on using it in a table that will have 1000s of entries, filtered/paginated upto 100. </p> <p>I realize #2 could be a performance issue since I'm essentially checking all checkboxes to determine whether to set <code>master.indeterminate</code>, but since the table will be filtered I want this to be "reactive" as well.</p> <p>Any other issues I might be overlooking?</p> <p><a href="https://jsfiddle.net/laggingreflex/L1xkzmgb" rel="nofollow noreferrer">Fiddle</a></p> <pre><code>const h = (...args) =&gt; React.createElement(...args) function useSelectAll(existingStateOrSize = []) { const [state, update] = React.useState(existingStateOrSize) const master = React.useRef(null) const children = React.useRef(state.map(() =&gt; null)) function setIndeterminate () { /* Calculate master.indeterminate */ let allChecked for (const child of children.current) { if (!child) continue const checked = Boolean(child.checked) if (allChecked === undefined) { allChecked = checked } else if (allChecked !== checked) { allChecked = null break } } if (typeof allChecked === 'boolean') { master.current.checked = allChecked master.current.indeterminate = false } else { master.current.indeterminate = true } } function onChangeMaster() { children.current.forEach(child =&gt; child.checked = master.current.checked) } function onChangeChild(e) { const i = children.current.indexOf(e.target) const newState = Array.from(state) newState[i] = e.target.checked update(newState) } React.useEffect(setIndeterminate) return [ state, h('input', { type: 'checkbox', ref: master, onChange: onChangeMaster }), state.map((x, i) =&gt; h('input', { type: 'checkbox', ref: r =&gt; children.current[i] = r, checked: existingStateOrSize[i], onChange: onChangeChild })) ] } function Table() { const [state, master, children] = useSelectAll([null,null,null]) return h('table', {}, [ h('tr', {}, h('th', {}, master), h('th', {}, 'Select all')), h('tr', {}, h('td', {}, children[0]), h('td', {}, 'First')), h('tr', {}, h('td', {}, children[1]), h('td', {}, 'Second')), h('tr', {}, h('td', {}, children[2]), h('td', {}, 'Third')), ]) } ReactDOM.render(h(Table), document.getElementById('container')) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T05:07:56.127", "Id": "213353", "Score": "3", "Tags": [ "javascript", "form", "react.js" ], "Title": "React hook \"select all\" checkbox implementation" }
213353