body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>(See also the <a href="https://codereview.stackexchange.com/questions/248274/a-simple-c-winapi-program-for-terminating-processes-via-process-image-names-fo">previous</a> follow-up.)</p> <p>Now, I seem to improve my program partially via the answer in my previous follow-up. It goes like this:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;windows.h&gt; #include &lt;TlHelp32.h&gt; /******************************************************************** * Searches the index of the last occurrence of the input character. * ********************************************************************/ static int get_last_char_index( const char* const arr, const int arr_len, const char c) { for (int i = arr_len - 1; i &gt;= 0; i--) { if (arr[i] == c) { return i; } } return -1; } /************************************************************************ * Searches the index of the last occurrence of the backslash character. * ************************************************************************/ static int get_last_backslash_index( const char* const arr, const int arr_len) { return get_last_char_index(arr, arr_len, '\\'); } /*********************************************** * Returns the base name of this process image. * ***********************************************/ static char* get_base_name(const char* const arg) { size_t arg_len = strlen(arg); int backslash_char_index = get_last_backslash_index(arg, arg_len); size_t return_char_array_len = arg_len - backslash_char_index; char* carr = (char*)calloc(return_char_array_len, sizeof(char)); carr[return_char_array_len - 1] = NULL; memcpy(carr, &amp;arg[backslash_char_index + 1], return_char_array_len); return carr; } int main(int argc, char* argv[]) { if (argc != 2) { char* base_name = get_base_name(argv[0]); fprintf(stderr, &quot;%s PROCESS_NAME\n&quot;, base_name); free(base_name); return EXIT_FAILURE; } PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (snapshot == INVALID_HANDLE_VALUE) { fputs(&quot;Error: could not get the process snapshot.\n&quot;, stderr); return EXIT_FAILURE; } size_t totalProcesses = 0; size_t totalProcessesMatched = 0; size_t totalProcessesTerminated = 0; if (Process32First(snapshot, &amp;entry)) { do { totalProcesses++; if (strcmp(entry.szExeFile, argv[1]) == 0) { totalProcessesMatched++; HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, entry.th32ProcessID); if (hProcess == NULL) { fprintf(stderr, &quot;Error: could not open the process with ID = %d, &quot; &quot;called \&quot;%s\&quot;.\n&quot;, entry.th32ProcessID, entry.szExeFile); } else { BOOL terminated = TerminateProcess(hProcess, 0); if (terminated) { totalProcessesTerminated++; BOOL closed = CloseHandle(hProcess); if (!closed) { fprintf(stderr, &quot;Warning: could not close a handle &quot; &quot;for process ID = %d, called \&quot;%s\&quot;.\n&quot;, entry.th32ProcessID, entry.szExeFile); } printf(&quot;Terminated process ID %d\n&quot;, entry.th32ProcessID); } } } } while (Process32Next(snapshot, &amp;entry)); } BOOL snapshotHandleClosed = CloseHandle(snapshot); if (!snapshotHandleClosed) { fputs(&quot;Warning: could not close the process snapshot.&quot;, stderr); } printf(&quot;Info: total processes: %zu, &quot; &quot;total matching processes: %zu, total terminated: %zu.\n&quot;, totalProcesses, totalProcessesMatched, totalProcessesTerminated); return EXIT_SUCCESS; } </code></pre> <p><em><strong>Critique request</strong></em></p> <p>I am eager to hear any comments whatsoever.</p>
[]
[ { "body": "<p>Some remarks with respect to the <code>get_base_name()</code> function:</p>\n<ul>\n<li><p><code>size_t</code> vs <code>int</code>: You correctly start with</p>\n<pre><code>size_t arg_len = strlen(arg);\n</code></pre>\n<p>but then pass <code>arg_len</code> to <code>get_last_backslash_index()</code> which takes an <code>int</code> argument. Depending on the strictness of your compiler this can cause a “Implicit conversion loses integer precision” warning. I suggest to use <code>size_t</code> consequently for string length.</p>\n</li>\n<li><p>The cast in</p>\n<pre><code>char* carr = (char*)calloc(return_char_array_len, sizeof(char));\n</code></pre>\n<p>is not needed and generally not recommended, see for example <a href=\"https://stackoverflow.com/q/605845/1187415\">Do I cast the result of malloc?</a> on Stack Overflow.</p>\n</li>\n<li><p><code>sizeof(char)</code> is <em>always</em> equal to one, therefore it can be shortened to</p>\n<pre><code>char* carr = malloc(return_char_array_len);\n</code></pre>\n</li>\n<li><p>Here</p>\n<pre><code>carr[return_char_array_len - 1] = NULL;\n</code></pre>\n<p>a <em>pointer</em> value is assigned to <code>char</code> (which is an integral type). The right-hand side should be <code>0</code> or <code>'\\0'</code> to avoid compiler warnings.</p>\n</li>\n<li><p>The implementation can be shortened if you take advantage of Microsoft C runtime library functions like <a href=\"https://docs.microsoft.com/de-de/cpp/c-runtime-library/reference/strrchr-wcsrchr-mbsrchr-mbsrchr-l?view=vs-2019\" rel=\"nofollow noreferrer\"><code>strrchr()</code></a> and <a href=\"https://docs.microsoft.com/de-de/cpp/c-runtime-library/reference/strdup-wcsdup-mbsdup?view=vs-2019\" rel=\"nofollow noreferrer\"><code>_strdup()</code></a>:</p>\n<pre><code>static char* get_base_name(const char* const arg) {\n const char *backslash_char_ptr = strrchr(arg, '\\\\');\n return _strdup(backslash_char_ptr == NULL ? arg : backslash_char_ptr + 1);\n}\n</code></pre>\n</li>\n<li><p>I would perhaps call the function something like <code>copy_base_name()</code> to make it more obvious that the caller is responsible for releasing the memory.</p>\n</li>\n<li><p>As an alternative you can use existing functions from the Microsoft C runtime like <a href=\"https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/splitpath-wsplitpath?view=vs-2019\" rel=\"nofollow noreferrer\"><code>splitpath</code></a>, or <a href=\"https://docs.microsoft.com/en-us/windows/win32/shell/shlwapi-path\" rel=\"nofollow noreferrer\">Shell Path Handling Functions</a> like <code>PathStripPath()</code>.</p>\n</li>\n</ul>\n<p>Some more remarks:</p>\n<ul>\n<li>No error message is printed if terminating a process failed.</li>\n<li>The process handle is closed only if terminating the process succeeded.</li>\n</ul>\n<p>I would perhaps do it like this:</p>\n<pre><code>HANDLE hProcess = OpenProcess(...);\nif (hProcess == NULL) {\n // Print error message\n} else {\n if (TerminateProcess(hProcess, 0)) {\n totalProcessesTerminated++;\n printf(&quot;Terminated process ID %d\\n&quot;, entry.th32ProcessID);\n } else {\n // Print error message\n }\n if (!CloseHandle(hProcess)) {\n // Print error message\n }\n}\n</code></pre>\n<p>In all error situations it would be useful to print the actual reason for the failure (e.g. “access denied”). This can be achieved with <code>GetLastError()</code> and <code>FormatMessage()</code>, see for example <a href=\"https://stackoverflow.com/q/1387064/1187415\">How to get the error message from the error code returned by GetLastError()?</a> on Stack Overflow.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:14:41.227", "Id": "490753", "Score": "0", "body": "Visual Studio C requires `_CRT_SECURE_NO_WARNINGS` to use `strdup()`. They support `_strdup()` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:24:14.427", "Id": "490755", "Score": "1", "body": "@pacmaninbw: You are right (I had compiled this with Clang on a Mac :), thanks for the notice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:33:36.177", "Id": "490758", "Score": "0", "body": "@pacmaninbw: I also wrongly said that `strdup()` is a C standard library function (which is isn't – yet). Apparently that is the reason why Microsoft prepends an underscore to the function name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:36:57.107", "Id": "490760", "Score": "1", "body": "Yes, it has been added to a future standard but not in the current one. See [this SO question](https://stackoverflow.com/questions/63732752/is-this-a-portable-strdup). However, you were correct about `strrchr`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T14:32:06.367", "Id": "250151", "ParentId": "250150", "Score": "3" } } ]
{ "AcceptedAnswerId": "250151", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T12:42:33.980", "Id": "250150", "Score": "5", "Tags": [ "c", "windows", "winapi" ], "Title": "A simple C WinAPI program for terminating processes via process image names - folllow-up 2" }
250150
<p>I have a program which splits a url into host and path:</p> <pre><code> int main(int argc, char** argv){ std::vector&lt;std::string&gt; url = parseUrl(argv[1]); memset(&amp;hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; int MAXDATASIZE = 1024; std::string request = &quot;GET &quot; +url.at(1) + &quot; HTTP/1.1\r\n\r\n&quot;; const char* charRequest = request.c_str(); char buf[MAXDATASIZE]; if((status = getaddrinfo(url.at(0).c_str(), &quot;80&quot;, &amp;hints, &amp;servinfo)) != 0){ std::cout &lt;&lt; &quot;getaddrinfo: &quot; &lt;&lt; gai_strerror(status) &lt;&lt; &quot;\n&quot;; return 2; } else { std::cout &lt;&lt; &quot;Server struct created successfully\n&quot;; } if((sock = socket(servinfo-&gt;ai_family, servinfo-&gt;ai_socktype, servinfo-&gt;ai_protocol)) == -1){ std::cout &lt;&lt; &quot;Error creating socket\n&quot;; return 2; } else { std::cout &lt;&lt; &quot;Successfully created socket\n&quot;; } if(connect(sock, servinfo-&gt;ai_addr, servinfo-&gt;ai_addrlen) == -1){ std::cout &lt;&lt; &quot;Error connecting to host &quot; &lt;&lt; url.at(0) &lt;&lt; &quot; at port &quot; &lt;&lt; &quot;80&quot; &lt;&lt; &quot;\n&quot;; return 2; } else { std::cout &lt;&lt; &quot;Connected successfully to &quot; &lt;&lt; url.at(0) &lt;&lt; &quot;at port &quot; &lt;&lt; &quot;80&quot; &lt;&lt; &quot;\n&quot;; } if((send(sock, charRequest, strlen(charRequest), 0)) == -1){ std::cout &lt;&lt; &quot;Error communicating with website\n&quot;; return 2; } else { std::cout &lt;&lt; &quot;Sent request successfully to &quot; &lt;&lt; url.at(0) &lt;&lt; &quot; at port &quot; &lt;&lt; &quot;80&quot; &lt;&lt; &quot;\n&quot;; } if(recv(sock, buf, MAXDATASIZE, 0) == -1){ std::cout &lt;&lt; &quot;Error recciving data from &quot; &lt;&lt; url.at(0) &lt;&lt; &quot; at port &quot; &lt;&lt; &quot;80&quot; &lt;&lt; &quot;\n&quot;; } else { std::cout &lt;&lt; &quot;Recieved data successfully from &quot; &lt;&lt; url.at(0) &lt;&lt; &quot; at port &quot; &lt;&lt; &quot;80&quot; &lt;&lt; &quot;\n&quot;; } std::ofstream file; file.open(argv[2]); file &lt;&lt; buf; file.close(); close(sock); freeaddrinfo(servinfo); } // Returns vector with host as first argument and path as second std::vector&lt;std::string&gt; parseUrl(std::string url){ std::vector&lt;std::string&gt; ret; size_t dotPos = url.find('.'); size_t slashPos = url.find('/', dotPos); std::string host = url.substr(0, slashPos); std::string path = url.substr(slashPos, url.length()); ret.push_back(host); ret.push_back(path); return ret; } </code></pre> <p>Does anyone have suggestions for improvement. Especially about the clunky vector return?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T16:03:34.783", "Id": "490726", "Score": "0", "body": "The returning of a vector is not that clunky. Because of move semantics the vector will be `moved` back avoiding any copies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T16:06:55.987", "Id": "490727", "Score": "2", "body": "Your URL parsing is not very accurate and would break on any real url. The host section does is not required to have a `dot` in it. See: https://en.wikipedia.org/wiki/URL. This image I find particularly helpful: https://en.wikipedia.org/wiki/File:URI_syntax_diagram.svg but the full definition is here: https://tools.ietf.org/html/rfc3986" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T16:08:58.827", "Id": "490728", "Score": "3", "body": "Personally I would split a url into: `schema`, `user`, `host`, `port`, `path`, `query`, fragment` (removing the dividers). Not in the wild a lot of URL are mall formed most browser take this into account. The worst offenders is not having the `?` before the query." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T16:35:15.250", "Id": "490730", "Score": "0", "body": "What does the next function look like that will handle the returned vector?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T16:42:07.897", "Id": "490731", "Score": "0", "body": "I've posted the next function @Mast" } ]
[ { "body": "<p>Rather than using a <code>std::vector</code> and using the indices to specify the host and path, we can create a little struct and refer to the members by name:</p>\n<pre><code>struct URL\n{\n std::string host;\n std::string path;\n};\n</code></pre>\n<p>So we can refer to <code>url.host</code> instead of <code>url.at(0)</code>.</p>\n<hr />\n<p>As pointed out in the comments, the parsing method could be more accurate and comprehensive. It's fine to only support a small subset of the url syntax, but we should at least check that we got what we expected in the string.</p>\n<p>In this case, I think we should:</p>\n<ul>\n<li>Throw an error if we don't find a dot.</li>\n<li>Either throw an error if we don't find a slash, OR set the path part of the url to <code>&quot;/&quot;</code> to ensure that our <code>GET</code> request is valid.</li>\n</ul>\n<hr />\n<pre><code>int MAXDATASIZE = 1024;\n...\nchar buf[MAXDATASIZE];\n</code></pre>\n<p>This doesn't compile for me. <code>MAXDATASIZE</code> must be a constant.</p>\n<p>We can remove the need for a separate constant by using <code>std::array</code>:</p>\n<pre><code>std::array&lt;char, 1024&gt; buf;\n// now we can use buf.size() :)\n</code></pre>\n<hr />\n<p>Even for something small like this, it's probably worth writing our own <code>socket</code> class. This provides some cleanup safety (RAII), as well as making the code in <code>main()</code> a lot simpler and easier to read by removing some of details of the network code. e.g. something like the following:</p>\n<pre><code>struct socket\n{\npublic:\n\n socket();\n explicit socket(struct addrinfo const&amp; address);\n\n socket(socket const&amp;) = delete;\n socket&amp; operator=(socket const&amp;) = delete;\n\n socket(socket&amp;&amp; other);\n socket&amp; operator=(socket&amp;&amp; other);\n\n ~socket();\n\n std::size_t send(char const* data, std::size_t data_size);\n std::size_t receive(char* buffer, std::size_t buffer_size);\n\n bool is_open() const;\n void close();\n\nprivate:\n\n SOCKET m_handle;\n};\n</code></pre>\n<p>We could also move the address lookup out of <code>main()</code> into a separate function, and keep the <code>addrinfo</code> in a unique pointer with a custom deleter that calls <code>freeaddrinfo()</code>. Something like:</p>\n<pre><code>std::unique_ptr&lt;addrinfo, std::function&lt;void(addrinfo*)&gt;&gt; lookup_address(std::string const&amp; node, std::string const&amp; service, int ai_family, int ai_socktype, int ai_protocol, int ai_flags = 0)\n{\n auto ai_hints = addrinfo();\n // ... set up hints!\n\n auto output = (addrinfo*) nullptr;\n auto result = getaddrinfo(node.c_str(), service.c_str(), &amp;ai_hints, &amp;output);\n // ... check errors!\n\n return { output, [] (addrinfo* ai) { freeaddrinfo(ai); } };\n}\n</code></pre>\n<p>So we might end up a main like:</p>\n<pre><code>int main(int argc, char** argv)\n{\n if (argc != 3)\n throw std::runtime_error(&quot;Unexpected argument count!&quot;);\n\n auto url = parse_url(argv[1]);\n auto address = lookup_address(url.host, &quot;80&quot;, AF_UNSPEC, SOCK_STREAM, 0, 0);\n \n if (!address)\n throw std::runtime_error(&quot;Failed address lookup!&quot;);\n\n auto s = socket(*address);\n \n if (!s.is_open())\n throw std::runtime_error(&quot;Failed to connect!&quot;);\n \n auto request = &quot;GET &quot; + url.path + &quot; HTTP/1.1\\r\\n\\r\\n&quot;;\n auto sent = s.send(request.c_str(), request.size() + 1);\n\n if (sent != request.size() + 1)\n throw std::runtime_error(&quot;Failed to send request!&quot;);\n\n auto buffer = std::array&lt;char, 1024&gt;();\n auto received = s.receive(buffer.data(), buffer.size());\n\n if (received == 0)\n throw std::runtime_error(&quot;No data received!&quot;);\n\n std::ofstream(argv[2]).write(buffer.data(), received);\n}\n</code></pre>\n<p>(code not compiled or tested).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T10:46:50.630", "Id": "251203", "ParentId": "250153", "Score": "1" } } ]
{ "AcceptedAnswerId": "251203", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T15:43:47.350", "Id": "250153", "Score": "3", "Tags": [ "c++", "parsing" ], "Title": "Parsing a url into host and path" }
250153
<p>I am just learning about C++ templates and generic types, I decided it would be nice to try to create a generic container class as a challenge and test my knowledge in the process. Here is what I have come up with.</p> <pre><code> #include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;cassert&gt; template &lt;typename __T&gt; class List{ private: struct node{ __T data; node* next; node* prev; }; typedef long long unsigned int c_size; node* head; node* tail; node* current; c_size m_S; public: List() :head{NULL},tail{NULL},current{NULL},m_S{0} {} List(std::initializer_list&lt;__T&gt; __l) :head{NULL},tail{NULL},current{NULL},m_S{0} { for(auto const&amp; elem:__l){ insert_back(elem); } } void insert_front(__T _d){ ++m_S; node* new_node{new node}; new_node-&gt;data = _d; new_node-&gt;next = head; new_node-&gt;prev = NULL; if (head != NULL){ head-&gt;prev = new_node; } else { tail = new_node; } head = new_node; } void print(){ if (m_S == 0) return; node *current = head; while (current-&gt;next != NULL){ std::cout &lt;&lt; current-&gt;data &lt;&lt; &quot;, &quot;; current = current-&gt;next; } std::cout &lt;&lt; current-&gt;data &lt;&lt; '\n'; } void insert_back(__T _d){ ++m_S; node* new_node = new node; new_node-&gt;data = _d; new_node-&gt;next = NULL; node* last = head; if (head == NULL) { new_node-&gt;prev = NULL; head = new_node; tail = new_node; } else{ tail-&gt;next = new_node; new_node-&gt;prev = tail; tail = new_node; } } constexpr __T first(){ assert(head != NULL &amp;&amp; &quot;Calling .front() on an empty list&quot;); return head-&gt;data; } constexpr __T last(){ assert(tail != NULL &amp;&amp; &quot;Calling. last() on an empty list&quot;); return tail-&gt;data; } constexpr c_size size(){return m_S;} void remove_all(){ current = head; while(current-&gt;next != NULL){ current = current-&gt;next; delete current; } head = NULL; tail = NULL; current = NULL; } }; </code></pre> <p>Thanks in advance !</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T19:26:00.590", "Id": "490743", "Score": "7", "body": "_`__T`_ double underscores as prefix for a symbol are reserved for compiler internal implementations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T09:02:12.323", "Id": "490778", "Score": "1", "body": "Hey, if you want some more practice you might want to align the interface of your `List` class with that of the standard `std::list`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T09:05:00.867", "Id": "490779", "Score": "0", "body": "@slepic Hello, can you explain what you mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T10:35:37.900", "Id": "490782", "Score": "0", "body": "I mean to use standard method names (along with their signatures), like push_back, push_front, back, front, pop_back, pop_front, clear, etc. You might also want to implement iterators and generally comply with c++'s container concept... You will get many general algorithms (like sort) for free just by following the interface of all standard containers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T10:41:30.203", "Id": "490783", "Score": "0", "body": "And btw print is usually not part of generic container because it heavily depends on the generic value type T and the application itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T10:50:20.357", "Id": "490784", "Score": "0", "body": "@slepic wow really? I thought it would be a really bad idea to use the ones that are taken. The reason I did not try making the iterator part because I felt that it was a topic of its own . I really appreciate all the information!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T16:12:19.190", "Id": "490926", "Score": "0", "body": "Can you please add a minimal `main` function demonstrating how you believe the class should be used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T18:20:37.257", "Id": "490936", "Score": "0", "body": "@Peter I cannot edit the question now can I? It is again'st the guidelines," } ]
[ { "body": "<p>Identifiers that start with a double underscore, or a single underscore followed by a capital letter, are reserved for use by the implementation. Your use of <code>__T</code> could conflict with this use.</p>\n<p>Spacing is important. The blank line between <code>template &lt;typename __T&gt;</code> and the following <code>class List</code> line makes it harder to recognize the class as a template class.</p>\n<p>What is the purpose of the <code>current</code> member? It is unnecessary.</p>\n<p><code>c_size</code> should probably be <code>std::size_t</code>, not <code>unsigned long long</code>. Because it is a private typedef, users of your class cannot access the type and can only declare a variable to hold the returned value using <code>auto</code>.</p>\n<p>You don't declare the copy constructor, copy assignment operator, move constructor, nor move assignment operators. This will cause problems with assignments of one <code>List</code> object to another.</p>\n<p><code>insert_head</code> and <code>insert_back</code> are very similar functions, but have been written somewhat differently. The implementation for <code>insert_back</code> can be made shorter by making it similar to <code>insert_head</code>. In particular, the assignment to <code>new_node-&gt;prev</code> can be done before the <code>if</code> (using <code>new_node-&gt;prev = tail;</code>, because when <code>head</code> is NULL, <code>tail</code> should also be), while the common <code>tail = new_node;</code> can be done after.</p>\n<p><code>first</code>, <code>last</code>, and <code>size</code> should also have the <code>const</code> modifier (e.g., <code>constexpr c_size size() const</code>.</p>\n<p><code>remove_all</code> will crash because you access <code>current-&gt;next</code> after <code>delete current</code>, nor do you delete the first (head) element.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T00:45:01.637", "Id": "250167", "ParentId": "250158", "Score": "9" } } ]
{ "AcceptedAnswerId": "250167", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T19:02:50.313", "Id": "250158", "Score": "2", "Tags": [ "c++", "linked-list", "template", "collections", "classes" ], "Title": "Generic Doubly Linked-list implementation in C++" }
250158
<p><strong>What is the coin change problem?</strong> The change-making problem addresses the question of finding the minimum number of coins (of certain denominations) that add up to a given amount of money. It is a special case of the integer knapsack problem and has applications wider than just currency. Read more: <a href="https://en.wikipedia.org/wiki/Change-making_problem" rel="nofollow noreferrer">Wiki</a></p> <p><strong>My code:</strong></p> <pre><code>def coin_change(n,coins,known_results): min_coins = n if n in coins: known_results[n] = 1 return 1 elif known_results[n] &gt; 0: return known_results[n] else: for i in [c for c in coins if c&lt;=n]: count = 1 + coin_change(n-i,coins,known_results) if count &lt; min_coins: min_coins = count known_results[n] = min_coins return min_coins coins = [1,2,3] n = 4 known_results = [0]*(n+1) print(coin_change(n,coins,known_results)) </code></pre> <p><strong>Question:</strong> This code works fine and perfectly but can it be done better and more efficiently using python tricks giving it an edge more the other languages? Can it be more efficient and better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T20:26:56.193", "Id": "490748", "Score": "0", "body": "`n` is the amount you have to generate coin change for." } ]
[ { "body": "<p>Welcome to Code Review! Your code looks fine, and is fairly easy to follow. A few points to note though:</p>\n<p>Since your initial if-elif clauses are returning values immediately, no need to wrap an else (and even elif) there:</p>\n<pre><code>if n in coins:\n known_results[n] = 1\n return 1\nif known_results[n] &gt; 0: \n return known_results[n] \nfor i in [c for c in coins if c&lt;=n]:\n .\n .\n</code></pre>\n<p>is achieving the same thing.</p>\n<p>In python, multiple assignments can be done in a single statement:</p>\n<pre><code>known_results[n] = min_coins = count\n</code></pre>\n<p>As an aside, you can make use of type hinting to make the values and parameters more understandable. If I was only reading through the function definition, I'd have no idea what <code>known_results</code> was supposed to be.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T08:11:59.970", "Id": "250174", "ParentId": "250161", "Score": "3" } }, { "body": "<p>When I copy&amp;paste your code into my editor, it immediately greets me with 81(!!!) errors and warnings. To be fair, some of these are duplicates, because I have multiple linters configured. However, about 20 of those are real.</p>\n<h1>PEP8 violations</h1>\n<p>The standard community coding style for the Python community is defined in <a href=\"https://python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python Enhancement Proposal 8 – <em>Style Guide for Python Code</em></a>. You should <em>always</em> follow the guidelines of PEP8. There are plenty of tools available that can flag and even auto-correct violations of PEP8.</p>\n<p>Here's just a couple that my editor flagged (and auto-corrected automatically, so I didn't have to do a single thing):</p>\n<ul>\n<li><em>Space after comma</em>: Pretty much everywhere where you use a comma, you squish everything together without whitespace. You should have a space after the comma.</li>\n<li><em>Space around operators</em>: You should have whitespace on both sides of a binary infix operator. Sometimes you do that, sometimes you don't, e.g. here <code>[c for c in coins if c&lt;=n]</code></li>\n<li><em>Indentation should be 4 spaces</em>. You use 5 spaces for the first level of indentation, then 3 spaces for the second level except in the <code>elif</code> where you use 7.</li>\n<li>You have 2 blank lines before the <code>else:</code>. In general, spacing with a function should only be 1 blank line.</li>\n<li>You have 1 blank line after the function. There should be 2 blank lines after a function or class.</li>\n<li><em>Docstring</em>: Your function should have a docstring explaining its usage. (Note: all the above violations were automatically fixed by my editor, this is the only one that couldn't be auto-corrected.)</li>\n</ul>\n<h1>Consistency</h1>\n<p>It is very important to be consistent. When people read your code, and you do the same thing two different ways, they will automatically assume that you want to tell them something, that the difference is somehow meaningful.</p>\n<p>I mentioned a couple of inconsistencies above, e.g. the fact that you sometimes use whitespace around operators and sometimes don't.</p>\n<p>Even if you don't believe in style guides, you should at least be consistent with yourself.</p>\n<h1>Linter</h1>\n<p>You should use a linter, preferably one with an auto-correct functionality. When I hit &quot;Save&quot; in my editor, of the 81 errors and warnings I mentioned earlier, 78 get fixed automatically, leaving only 3 (of which one is a duplicate, because as I mentioned, I have multiple linters configured).</p>\n<p>As mentioned above, the only PEP8 violation that couldn't be auto-corrected is the missing documentation.</p>\n<p>The other remaining issue is something already mentioned in <a href=\"https://codereview.stackexchange.com/a/250174/1581\">hjpotter92's answer</a>: since you return directly from the <code>if</code>, there is no need for the <code>elif</code>. Once I remove the <code>el</code>, I get a new issue telling me the same thing for the <code>else</code>.</p>\n<h1>Redundant statement</h1>\n<p>In the first <code>if</code>, you assign to <code>known_results[n]</code> but then immediately <code>return 1</code>. Since the <code>return</code> ends the execution of the function, and <code>known_results</code> is local to the function, there is no way that this variable can be used any further, therefore the assignment is unnecessary and can just be removed.</p>\n<h1>Redundant assignment</h1>\n<p>Also, as mentioned in hjpotter92's answer, the two assignments in the <code>if</code> branch inside the <code>for</code> loop can be chained.</p>\n<h1>Truthiness / falsiness</h1>\n<p>In <code>elif</code> condition, you check whether <code>known_results[amount]</code> is greater than <code>0</code>. Since you initialize it with zero, and only ever add to it, what you are <em>semantically</em> doing is basically checking whether you have ever put a value in. In Python, <code>0</code> is a false value, so instead of checking for <code>known_results[amount] &gt; 0</code>, you could simply check for <code>known_results[amount]</code>.</p>\n<h1>Naming</h1>\n<p><code>n</code> and <code>c</code> are not very descriptive names. Try to find names that better reveal the intent of those variables. For example <code>n</code> might be renamed to <code>amount</code> and <code>c</code> to <code>coin</code>.</p>\n<p>In fact, you wrote in <a href=\"https://codereview.stackexchange.com/questions/250161/using-python-tricks-to-find-minimum-coin-change-amazon-interview/250203?noredirect=1#comment490748_250161\">your comment under the question</a>:</p>\n<blockquote>\n<p><code>n</code> is the amount you have to generate coin change for.</p>\n</blockquote>\n<p>If you have to write a comment like this, either in code or in this case under the code, that is a good sign that the name is not good enough. If you have to say something like <code>n</code> is the amount, that is a good indication that <code>n</code> should be called <code>amount</code>, because then you wouldn't have to explain that it is the amount!</p>\n<p><code>i</code> <em>would</em> be acceptable for an index in a loop, but it isn't an index here. It is an element of a collection, not an index into a collection or a loop index. Actually, it could again be called <code>coin</code>, although that might be confusing.</p>\n<p>Thinking about it, maybe <code>coins</code> should be called <code>denominations</code> and <code>c</code> should then be <code>denomination</code>.</p>\n<p>Also, I would expect a function called <code>coin_change</code> to compute the <em>actual</em> coins for the change, not simply the number of coins.</p>\n<h1>Datatypes</h1>\n<p>Since it doesn't make sense to specify the same denomination multiple times, and the order of the denominations doesn't matter, the denominations could be a Set (or even a FrozenSet since it is never mutated) rather than a List.</p>\n<p>Or, does the order matter? It is actually not clear, and could benefit from some documentation if it does indeed matter.</p>\n<p>Likewise, <code>known_results</code> probably makes more sense to be a <code>defaultdict</code>.</p>\n<h1>Type Annotations</h1>\n<p>Python 3 supports (function) type annotations since the very first release in 2008 and variable annotations for a while. In more recent times, the <code>typing</code> module with predefined types has been added. Also, there is the Mypy static type checker for Python.</p>\n<p>It is a good idea to take advanced of these tools, even if just for documentation.</p>\n<h1>API</h1>\n<p><code>known_results</code> is a private internal implementation detail of your (recursive) implementation. It is an accumulator whose only purpose is to keep state in your recursive calls. It shouldn't be part of the public API, you shouldn't force the caller to know what to pass here as an argument.</p>\n<p>At the <em>very least</em>, you should make it an optional parameter with a default argument, so that the caller doesn't <em>have</em> to pass it:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def minimum_number_of_coins_for_change(amount: int, denominations: Set[int]) -&gt; int:\n def minimum_number_of_coins_for_change_rec(\n amount: int, known_results: DefaultDict[int, int]\n ) -&gt; int:\n pass # …\n</code></pre>\n<p>However, the main reason why we pass the accumulator as an argument in a recursive function when we do functional programming is that in functional we are not allowed to mutate state, and thus the arguments on the function call stack are one of the very few places where we can keep state. However, you are mutating <code>known_results</code> anyway, so we don't have to pass it along as an argument, it is enough to define it outside of the recursive function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def def coin_change(amount, denominations, known_results=[0] * (amount + 1)):\n</code></pre>\n<p>But actually, you shouldn't even give the caller a <em>chance</em> to accidentally pass the wrong argument. It is better to remove it from the parameter list completely.</p>\n<p>The standard way of introducing an additional parameter just for purposes of state-keeping during recursion is to introduce a new nested function for the recursion, and call that from the outer function with the correct argument. Something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def minimum_number_of_coins_for_change(amount: int, denominations: Set[int]) -&gt; int:\n known_results: DefaultDict[int, int] = defaultdict(int)\n\n def minimum_number_of_coins_for_change_rec(amount: int) -&gt; int:\n min_coins = amount\n\n if amount in denominations:\n return 1\n\n if known_results[amount]:\n return known_results[amount]\n\n for coin in [\n denomination for denomination in denominations if denomination &lt;= amount\n ]:\n count = 1 + minimum_number_of_coins_for_change_rec(\n amount - coin\n )\n if count &lt; min_coins:\n known_results[amount] = min_coins = count\n\n return min_coins\n\n return minimum_number_of_coins_for_change_rec(amount)\n\n\ndenominations: Set[int] = {1, 2, 3}\namount = 5\n\nprint(minimum_number_of_coins_for_change(amount, denominations))\n</code></pre>\n<p>Unfortunately, there are now still two PEP8 violations in the code: too long lines. I will leave them in here, since there are multiple different ways to tackle this, one of which is better names, which I will leave to you.</p>\n<h1>API, pt. 2</h1>\n<p>It seems to me that the amount you want to compute change for changes much more often than the denominations. So, it could make sense to have a <code>coin_changer</code> object with specific denominations that can then compute change for those denominations multiple times. Something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict\nfrom typing import DefaultDict, Set\n\n\nclass CoinChanger:\n def __init__(self, denominations: Set[int]):\n self.denominations = denominations\n\n def minimum_number_of_coins_for_change(self, amount: int) -&gt; int:\n known_results: DefaultDict[int, int] = defaultdict(int)\n\n def minimum_number_of_coins_for_change_rec(amount: int) -&gt; int:\n min_coins = amount\n\n if amount in self.denominations:\n return 1\n\n if known_results[amount]:\n return known_results[amount]\n\n for coin in [\n denomination\n for denomination in self.denominations\n if denomination &lt;= amount\n ]:\n count = 1 + minimum_number_of_coins_for_change_rec(amount - coin)\n if count &lt; min_coins:\n known_results[amount] = min_coins = count\n\n return min_coins\n\n return minimum_number_of_coins_for_change_rec(amount)\n\n\ndenominations: Set[int] = {1, 2, 3}\namount = 5\n\ncoin_changer = CoinChanger(denominations)\n\nprint(coin_changer.minimum_number_of_coins_for_change(amount))\n</code></pre>\n<p>At the very latest now that we have turned our code into a module containing a class, we should make sure that the test code at the bottom does not accidentally get executed just because someone imported the module. In general, such code should <em>always</em> be wrapped into a <code>__main__</code> guard:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == '__main__':\n denominations: Set[int] = {1, 2, 3}\n amount = 5\n\n coin_changer = CoinChanger(denominations)\n\n print(coin_changer.minimum_number_of_coins_for_change(amount))\n</code></pre>\n<p>Although ideally, it shouldn't be there at all, it should be a proper unit test in a separate test module. (And there should be more tests, including corner cases such as empty denominations, an amount of 0, negative amounts, combinations of amounts and denominations where giving change is impossible, etc.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T22:38:46.953", "Id": "490826", "Score": "0", "body": "Type hints were added in Python 3 and Python 3 was released in 2008. So, alternatively, we could say, type hints (at least for functions) have been part of Python 3 since the beginning. BTW, thanks for reminding me that Python calls them annotations, I believe the \"hint\" terminology crept into my mind from PHP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T22:47:51.680", "Id": "490828", "Score": "0", "body": "Thank you, TIL the date on the PEP and the date it's actually released can be significantly different. :) Sorry I think I've made a mess here! Python has both function annotations (PEP 3107) and type hints (PEP 484). I.e `def foo(bar: \"baz\")` is using function annotations but not type hints, where `def foo(bar: str)` would be using both. I'll leave you be now, just don't want to potentially be the cause for making you say something technically wrong and meet someone's ire." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T22:23:58.420", "Id": "250203", "ParentId": "250161", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T19:32:57.613", "Id": "250161", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Using Python tricks to find Minimum Coin Change (Amazon Interview)" }
250161
<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>function openav() { document.getElementById('sidenav').style.width = '18%'; document.getElementById('open-btn').style.display = 'none'; document.getElementById('main').style.marginRight = '18%'; document.getElementById('hero-header').style.marginRight = '18%'; document.getElementById('footer').style.marginRight = '18%'; } function closenav() { document.getElementById('sidenav').style.width = '0%'; document.getElementById('open-btn').style.display = 'block'; document.getElementById('main').style.marginRight = '0%'; document.getElementById('hero-header').style.marginRight = '0%'; document.getElementById('footer').style.marginRight = '0%'; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html { scroll-behavior: smooth; } body { margin: 0; font-family: 'Montserrat', sans-serif; } header { transition: .5s; } .hero-bg { height: 100vh; width: 100%; background: #232323; color: white; padding-top: 1%; transition: .5s; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; } #open-btn { position: fixed; font-size: 190%; top: 1%; right: 1%; cursor: pointer; } #sidenav { background: #232323; opacity: .95; height: 100%; width: 0; position: fixed; z-index: 1; top: 0; right: 0; overflow-x: hidden; transition: .5s; } #sidenav a { display: block; color: white; text-align: right; text-decoration: none; font-size: 135%; padding: 4%; transition: .3s; } #sidenav a:hover { color: lightgray; font-size: 130%; padding: 4%; } #sidenav .close-btn { text-align: left; top: 0; } main { transition: .5s; } main i { font-size: 190%; } #about { display: flex; flex-direction: row; text-align: center; justify-content: center; padding: 4%; } #services { background: #232323; color: white; text-align: center; display: flex; flex-direction: row; } .service-item { padding: 4%; } #portfolio { display: flex; flex-direction: row; text-align: center; } .portfolio-item { padding: 4%; } #contact { background: #232323; display: flex; flex-direction: row; align-items: center; justify-content: center; } .contact-item { padding: 4%; } .contact-item a { color: white; text-decoration: none; padding: 20%; } .contact-text { text-align: center; color: white; } footer { background: #232323; color: white; text-align: center; padding: 4%; transition: .5s; } .footer-text, a { color: white; display: flex; flex-direction: column; align-items: center; justify-content: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;link rel="icon" href="https://avatar-management--avatars.us-west-2.prod.public.atl-paas.net/initials/BK-0.png"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link href="css/style.css" rel="stylesheet"&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&amp;display=swap" rel="stylesheet"&gt; &lt;script src="https://kit.fontawesome.com/b8c38afa05.js" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="js/script.js"&gt;&lt;/script&gt; &lt;title&gt;Braeden King&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;header id="hero-header"&gt; &lt;div class="hero-bg"&gt; &lt;div class="hero-text"&gt; &lt;h1&gt;Braeden King&lt;/h1&gt; &lt;p&gt;Front End Web Developer&lt;/p&gt; &lt;/div&gt; &lt;div class="hero-button"&gt; &lt;a id="open-btn" onclick="openav()"&gt;&amp;#9776;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;nav id="sidenav"&gt; &lt;a href="javascript:void(0)" onclick="closenav()" class="close-btn"&gt;X&lt;/a&gt; &lt;a href="#"&gt;Home&lt;/a&gt; &lt;a href="#about"&gt;About&lt;/a&gt; &lt;a href="#portfolio"&gt;Portfolio&lt;/a&gt; &lt;a href="#contact"&gt;Contact&lt;/a&gt; &lt;/nav&gt; &lt;/header&gt; &lt;main id="main"&gt; &lt;section id="about"&gt; &lt;div class="about-item"&gt; &lt;article&gt; &lt;h1&gt;Hi There! I'm Braeden King.&lt;/h1&gt; &lt;p&gt;I am a Front End Web Developer &lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;/section&gt; &lt;section id="services"&gt; &lt;div class="service-item"&gt; &lt;article&gt; &lt;h2&gt;Web Design&lt;/h2&gt; &lt;i class="fas fa-pen-fancy"&gt;&lt;/i&gt; &lt;hr&gt; &lt;p&gt;Lorem ipsum dolor, sit amet consectetur adipisicing elit. In placeat ipsa, labore eaque inventore, ullam molestiae nesciunt tempore quis corrupti sequi explicabo accusamus sed, recusandae eum veniam eius qui est.&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;div class="service-item"&gt; &lt;article&gt; &lt;h2&gt;Web Development&lt;/h2&gt; &lt;i class="fas fa-code"&gt;&lt;/i&gt; &lt;hr&gt; &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Enim, autem obcaecati pariatur consequatur corrupti commodi eaque nostrum quo iusto numquam nisi dolorem voluptatem omnis repellat tempora eligendi quis suscipit laborum.&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;div class="service-item"&gt; &lt;article&gt; &lt;h2&gt;UI / UX Design&lt;/h2&gt; &lt;i class="fas fa-puzzle-piece"&gt;&lt;/i&gt; &lt;hr&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis corrupti dicta maiores ab ex facilis iure tempora, maxime amet nesciunt labore vel odit architecto delectus soluta repellat rerum, mollitia placeat!&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;/section&gt; &lt;section id="portfolio"&gt; &lt;div class="portfolio-item"&gt; &lt;article&gt; &lt;h2&gt;Tip Calculator&lt;/h2&gt; &lt;a href="#"&gt;&lt;/a&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore dolores asperiores ad culpa sapiente quisquam dolorum quia dolor maxime nam ipsam accusantium, ducimus deleniti, voluptatem quod! Ut nobis eum voluptates.&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;div class="portfolio-item"&gt; &lt;article&gt; &lt;h2&gt;Project&lt;/h2&gt; &lt;a href=""&gt;&lt;/a&gt; &lt;p&gt;Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ipsa totam sed pariatur consequatur mollitia nobis maxime? Iste, perspiciatis rem? Dolorem molestiae quibusdam sequi ipsum consectetur, commodi accusamus iure veritatis aspernatur.&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;div class="portfolio-item"&gt; &lt;article&gt; &lt;h2&gt;Project&lt;/h2&gt; &lt;a href="#"&gt;&lt;/a&gt; &lt;p&gt;Lorem, ipsum dolor sit amet consectetur adipisicing elit. Tempora modi numquam provident molestiae impedit, eius fuga aliquam ratione vitae deserunt ad saepe placeat rem consequatur laboriosam doloribus? Enim, quis non.&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;/section&gt; &lt;section id="contact"&gt; &lt;div class="contact-item"&gt; &lt;a href="#"&gt;&lt;i class="fab fa-linkedin"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;i class="fab fa-facebook"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;i class="fab fa-dribbble"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;i class="fab fa-twitter"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="contact-item"&gt; &lt;div class="contact-text"&gt; &lt;article&gt; &lt;h2&gt;Contact Me!&lt;/h2&gt; &lt;p&gt;I'm always looking for new opportunities to gain experience.&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="contact-item"&gt; &lt;a href="mailto: "&gt;&lt;i class="fas fa-envelope"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="tel:"&gt;&lt;i class="fas fa-phone"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;i class="fas fa-file-alt"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;i class="fas fa-address-card"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;/section&gt; &lt;/main&gt; &lt;footer id="footer"&gt; &lt;hr&gt; &lt;div class="footer-text"&gt; &lt;article&gt; &lt;h3&gt;Braeden King&lt;/h3&gt; &lt;a href="mailto:"&gt;example@example.com&lt;/a&gt; &lt;a href="tel:"&gt;+1 (800) 429-6666 &lt;a&gt; &lt;p&gt;Copyright &lt;i class="fas fa-copyright"&gt;&lt;/i&gt; 2020 by Braeden King&lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;/footer&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Just wondering if anyone could give me tips/pointers/feedback on the code i have written here for a personal portfolio. Thanks (im new to this site so take it easy on me lol) :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:28:02.240", "Id": "490757", "Score": "4", "body": "When you vote to close or down vote, please leave a comment if there are no comments about why you so voted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:34:01.570", "Id": "490759", "Score": "0", "body": "Can you please add a description of what the code does, a sentence or 2 after the title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:51:43.963", "Id": "490762", "Score": "0", "body": "@pacmaninbw the HTML and CSS is just the layout and styles of my portfolio the javascript controls the sidenav and how the page moves in relation to the sidenav being opened. Sorry for not stating that in the title. I'm new to stack exchange." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T14:08:00.197", "Id": "490790", "Score": "0", "body": "@pacmaninbw It's a bit thin on description, but considering it's a portfolio page, not much description is required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T14:08:44.957", "Id": "490791", "Score": "0", "body": "It looks unfinished though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T15:25:48.250", "Id": "490795", "Score": "0", "body": "@Mast I've retracted my VTC, that is the best I can do. Neither down vote is mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T15:04:36.347", "Id": "491040", "Score": "0", "body": "@Mast sorry for the late response. But it is a little bit unfinished but this is just me trying to get tips for what I should maybe add or get rid of before actually finishing up the project" } ]
[ { "body": "<p>The JavaScript unnecessarily contains information that belongs in the style sheet. It would be much easier to have the JavaScript simply set/remove a class (for example, on the body) and put the styles into the style sheet.</p>\n<pre><code>function openav() {\n document.body.classList.add(&quot;open-nav&quot;);\n}\n\nfunction closenav() {\n document.body.classList.remove(&quot;open-nav&quot;);\n}\n</code></pre>\n<pre><code>.open-nav #sidenav {\n width: 18%;\n}\n\n.open-nav #open-btn {\n display: none;\n}\n\n.open-nav #main, .open-nav #hero-header, .open-nav #footer {\n margin-right: 18%;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-15T11:12:48.373", "Id": "250700", "ParentId": "250162", "Score": "4" } } ]
{ "AcceptedAnswerId": "250700", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T20:05:54.157", "Id": "250162", "Score": "-1", "Tags": [ "javascript", "css", "html5" ], "Title": "Personal Portfolio - Layout and basic functionality" }
250162
<p>Stock analysis takes a lot of time to filter and find the right one for a long-term investment. So I thought I could speed up the process by calculating a few basic values and write them all into one report file. Now I'd like to simplify everything as I'm sure there are a lot of redundant and repeating parts in it.</p> <p>My code:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/python3 import locale from time import strftime print(&quot;-------------------------&quot;) print(&quot; Stock analysis &quot;) print(&quot;-------------------------&quot;) # Declare base variables locale.setlocale(locale.LC_ALL, '') date = strftime(&quot;%Y-%m-%d&quot;) time = strftime(&quot; %H:%M:%S&quot;) partners = &quot;none&quot; trends = &quot;none&quot; assets_increase = &quot;y&quot; liabilities_increase = &quot;n&quot; income_increase = &quot;y&quot; age = &quot;y&quot; forecast = &quot;y&quot; commodity_reliance = &quot;y&quot; # Start the dialogue print(&quot;Let's start with some basic values...&quot;) print(&quot;You can get the required information using Onvista or Yahoo Finance&quot;) print(&quot;\n\nPlease note: This program uses the american number writing style. If you want to write decimal numbers, &quot; &quot;please use a point instead of a comma to separate the digits (e.g. 1.1 instead of 1,1).\n\n&quot;) name = input(&quot;Name of the company: &quot;) file = open(&quot;%s-report.txt&quot; % name, &quot;a&quot;) wkn = input(&quot;WKN: &quot;) symbol = input(&quot;Symbol: &quot;) isin = input(&quot;ISIN: &quot;) sector = input(&quot;Sector: &quot;) # Check initial numbers while True: try: current_price = float(input(&quot;Current price: &quot;)) eps = float(input(&quot;EPS: &quot;)) pe = float(input(&quot;PE: &quot;)) market_cap = float(input(&quot;Market capitalization: &quot;)) break except ValueError: print(&quot;please enter only numbers without comma and use . for decimals (e.g. 5.55 instead of 5,55&quot;) continue # Check next variables with failsafe so the program doesn't crash when the user enters wrong values def check_partners_trends(): # Check Partners global partners, trends while True: partner_check = input(&quot;Does it have big partners? (y/n): &quot;) if not partner_check.isalpha(): print(&quot;Please only enter y or n&quot;) continue if partner_check == &quot;y&quot;: partners = input(&quot;Who? &quot;) break elif partner_check == &quot;n&quot;: partners = &quot;none&quot; break else: print(&quot;Please only enter y or n&quot;) continue # Check Trend while True: trend_check = input(&quot;Is it participating in any current trends? (y/n): &quot;) if not trend_check.isalpha(): print(&quot;Please only enter y or n&quot;) continue if trend_check == &quot;y&quot;: trends = input(&quot;Which? &quot;) break elif trend_check == &quot;n&quot;: trends = &quot;none&quot; break else: print(&quot;Please only enter y or n&quot;) continue return partners, trends check_partners_trends() # Write to the report file file.write(&quot;Report for company: &quot; + name) file.write(&quot;\nWKN: %s\tSymbol: %s\nISIN: %s\tSector: %s&quot; % (wkn, symbol, isin, sector)) file.write(&quot;\n\nEvaluated: %s\nAt: %s\n\n\n&quot; % (date, time)) # first \n for new line, second \n for one blank line file.write(name + &quot; is currently trading at: &quot; + locale.currency(current_price, grouping=True)) file.write(&quot;\nEPS: %s\n\t--&gt; The higher the better\nP/E: %s\nMarket capitalization: %s&quot; % (eps, pe, locale.currency(market_cap, grouping=True))) file.write(&quot;\n\nIt has the following partners: %s\nAnd is participating in the trend: %s&quot; % (partners, trends)) print(&quot;\n__________&quot;) print(&quot;Income Statement Analysis&quot;) print(&quot;__________\n&quot;) # Check income numbers while True: try: total_revenue = float(input(&quot;Total Revenue: &quot;)) gross_profit = float(input(&quot;Gross profit: &quot;)) operating_expenses = float(input(&quot;Operating expenses: &quot;)) cost_of_revenue = float(input(&quot;Cost of revenue: &quot;)) net_income = float(input(&quot;Net income: &quot;)) ebit = float(input(&quot;EBIT: &quot;)) ebitda = float(input(&quot;EBITDA: &quot;)) break except ValueError: print(&quot;please enter only numbers without comma and use . for decimals (e.g. 5.55 instead of 5,55&quot;) continue income_red_flags = 0 ### Start writing to the report ### file.write(&quot;\n\n\n_____________\n\nIncome Statement Analysis\n_____________\n&quot;) file.write( &quot;\nTotal revenue: %s\nGross profit: %s\nOperating expenses: %s\nNet income: %s\nCost of revenue: %s\nEBIT: %s\n --&gt; analyzes the performance of core operations\nEBITDA: %s\n --&gt; earnings before interest, taxes, depreciation and amortization --&gt; analyzes performance and projects earnings potential&quot; % ( locale.currency(total_revenue, grouping=True), locale.currency(gross_profit, grouping=True), locale.currency(operating_expenses, grouping=True), locale.currency(net_income, grouping=True), locale.currency(cost_of_revenue, grouping=True), locale.currency(ebit, grouping=True), locale.currency(ebitda, grouping=True))) def analyze_income(): &quot;&quot;&quot;Analyze some of the given values and write them to the report&quot;&quot;&quot; global income_red_flags, gross_profit, total_revenue, operating_expenses, cost_of_revenue gross_margin = '{0:.2f}%'.format((gross_profit / total_revenue * 100)) # Return this value as percentage operating_income = gross_profit - operating_expenses file.write(&quot;\n\n\n[--&gt;] Analyzing income...\n&quot;) file.write( &quot;\nGross margin: {}\n --&gt; Portion of each dollar of revenue that the company retains as profit (35% = 0,35 cent/dollar)\n&quot;.format( gross_margin)) if operating_income &lt; 0: income_red_flags += 1 file.write( &quot;\n[!] Operating expenses are negative: %s\n --&gt; Company is generating a loss.&quot; % locale.currency( operating_income, grouping=True)) # company is generating loss if operating_expenses &gt; total_revenue: income_red_flags += 1 file.write( &quot;\n[!] Operating expenses are higher than the revenue --&gt; The company is spending more money than it is receiving.&quot;) # company is spending more than it's receiving if cost_of_revenue &gt; gross_profit: income_red_flags += 1 file.write(&quot;\n[!] Cost of revenue is higher than gross profits --&gt; The product costs more than it pays.&quot;) # the product costs more than it gives you file.write(&quot;\n[!] Income red flags: %s&quot; % income_red_flags) return gross_margin, operating_income, income_red_flags analyze_income() print(&quot;\n__________&quot;) print(&quot;Balance Sheet Analysis&quot;) print(&quot;__________\n&quot;) # Check Balance numbers while True: try: # Can be liquidated within 1 year total_assets = float(input(&quot;Total assets: &quot;)) current_assets = float(input(&quot;Current Assets: &quot;)) cash = float(input(&quot;Cash and cash equivalents: &quot;)) inventory = float(input(&quot;Inventory: &quot;)) # Total non-current assets -&gt; can't be liquidated within 1 year net_ppe = float(input(&quot;Net PPE: &quot;)) # Check how that property is divided depreciation = float(input(&quot;Depreciation: &quot;)) intangible_assets = float(input(&quot;Intangible Assets: &quot;)) # Liabilities total_liabilities = float(input(&quot;Total Liabilities: &quot;)) current_liabilities = float(input(&quot;Current Liabilities: &quot;)) # total non current liabilities long_term_debt = float(input(&quot;Long term debt: &quot;)) stockholders_equity = float(input(&quot;Stockholders' Equity: &quot;)) total_debt = float(input(&quot;Total Debt: &quot;)) break except ValueError: print(&quot;please enter only numbers without comma and use . for decimals (e.g. 5.55 instead of 5,55&quot;) continue # Check asset increase def check_assets_liabilities(): global assets_increase, liabilities_increase, receivable_increase # Check assets while True: assets_increase_check = input(&quot;Have the total assets increased year over year? (y/n): &quot;) if not assets_increase_check.isalpha(): print(&quot;Please only enter y or n&quot;) continue if assets_increase_check == &quot;y&quot;: assets_increase = &quot;y&quot; break elif assets_increase_check == &quot;n&quot;: assets_increase = &quot;n&quot; break else: print(&quot;Please only enter y or n&quot;) continue # Check liabilities while True: liabilities_increase_check = input(&quot;Have the total liabilities decreased year over year? (y/n): &quot;) if not liabilities_increase_check.isalpha(): print(&quot;Please only enter y or n&quot;) continue if liabilities_increase_check == &quot;y&quot;: liabilities_increase = &quot;y&quot; break elif liabilities_increase_check == &quot;n&quot;: liabilities_increase = &quot;n&quot; break else: print(&quot;Please only enter y or n&quot;) continue return assets_increase, liabilities_increase check_assets_liabilities() balance_red_flags = 0 ### Start writing to the report ### file.write(&quot;\n\n\n_____________\n\nBalance Sheet Analysis\n_____________\n&quot;) # Liquidatable assets file.write(&quot;\n\n--- Assets that can be liquidated within 1 year ---\n&quot;) file.write(&quot;\nTotal assets: %s\nCurrent assets: %s&quot; % ( locale.currency(total_assets, grouping=True), locale.currency(current_assets, grouping=True))) file.write(&quot;\nCash and cash equivalents: %s\nInventory value: %s&quot; % ( locale.currency(cash, grouping=True), locale.currency(inventory, grouping=True))) # Non-liquidatable assets file.write(&quot;\n\n--- Non-current assets which can't be liquidated within 1 year ---\n&quot;) file.write( &quot;\nNet PPE (property, plant and equipment): %s\n --&gt; These are long term assets important for business operations.\nDepreciation: %s&quot; % ( locale.currency(net_ppe, grouping=True), locale.currency(depreciation, grouping=True))) file.write(&quot;\nIntangible Assets: %s --&gt; Brand recognition, brand names, etc. How well the company is known.&quot; % locale.currency(intangible_assets, grouping=True)) # Liabilities file.write(&quot;\n\n--- Liabilities ---\n&quot;) file.write( &quot;\nTotal Liabilities: %s\nCurrent Liabilities: %s\nLong term debt: %s\n[!] Stockholders Equity: %s\nTotal debt: %s&quot; % ( locale.currency(total_liabilities, grouping=True), locale.currency(current_liabilities, grouping=True), locale.currency(long_term_debt, grouping=True), locale.currency(stockholders_equity, grouping=True), locale.currency(total_debt, grouping=True))) def analyze_balance(): &quot;&quot;&quot;Analyze the Balance sheet and write the results to the report&quot;&quot;&quot; global balance_red_flags, assets_increase, liabilities_increase, stockholders_equity file.write(&quot;\n\n\n[--&gt;] Analyzing balance...\n&quot;) if assets_increase == &quot;n&quot;: balance_red_flags += 1 file.write(&quot;\n[!] Assets are _not_ increasing.&quot;) if liabilities_increase == &quot;y&quot;: balance_red_flags += 1 file.write(&quot;\n[!] Liabilities are increasing -&gt; more debt is being accumulated.&quot;) if stockholders_equity &lt; 0: balance_red_flags += 1 file.write(&quot;\n[!] Stockholders equity is negative. Liabilities are growing faster than assets.&quot;) file.write(&quot;\n[!] Balance red flags: %s&quot; % balance_red_flags) return balance_red_flags analyze_balance() print(&quot;\n__________&quot;) print(&quot;Cash Flow Analysis&quot;) print(&quot;__________\n&quot;) # Check balance numbers while True: try: operating_cash_flow = float(input(&quot;Operating Cash Flow: &quot;)) investing_cash_flow = float(input(&quot;Investing Cash Flow: &quot;)) financing_cash_flow = float(input(&quot;Financing Cash Flow: &quot;)) stock_compensation = float(input(&quot;Stock based compensation: &quot;)) break except ValueError: print(&quot;please enter only numbers without comma and use . for decimals (e.g. 5.55 instead of 5,55&quot;) continue # Check income increase def check_income(): global income_increase while True: income_increase_check = input(&quot;Is the company's net income increasing year over year? (y/n): &quot;) if not income_increase_check.isalpha(): print(&quot;Please only enter y or n&quot;) continue if income_increase_check == &quot;y&quot;: income_increase = &quot;y&quot; break elif income_increase_check == &quot;n&quot;: income_increase = &quot;n&quot; break else: print(&quot;Please only enter y or n&quot;) continue return income_increase check_income() cash_red_flags = 0 ### Start writing the report ### file.write(&quot;\n\n\n_____________\n\nCash Flow Analysis\n_____________\n&quot;) file.write( &quot;\nOperating cash flow: %s\nInvesting cash flow: %s\nFinancing cash flow: %s\nStock based compensation: %s&quot; % ( locale.currency(operating_cash_flow, grouping=True), locale.currency(investing_cash_flow, grouping=True), locale.currency(financing_cash_flow, grouping=True), locale.currency(stock_compensation, grouping=True))) def analyze_cash(): global cash_red_flags, current_assets, current_liabilities, operating_cash_flow, investing_cash_flow, financing_cash_flow, income_increase, operating_cash_flow file.write(&quot;\n\n\n[--&gt;] Analyzing Cash-flow...\n&quot;) working_capital = current_assets - current_liabilities net_change_cash = operating_cash_flow - investing_cash_flow - financing_cash_flow if income_increase == &quot;n&quot;: cash_red_flags += 1 file.write(&quot;\n[!] Income is not increasing each year -&gt; take a look at the company's files to figure out why.&quot;) if working_capital &lt; 0: cash_red_flags += 1 file.write( &quot;\n[!] Working capital negative: %s\n\t--&gt; Company took on more debt or sold something to generate more money&quot; % locale.currency( working_capital, grouping=True)) if net_change_cash &lt; 0: cash_red_flags += 1 file.write( &quot;\n[!] Negative Net cash: %s\n\t--&gt; Find out why and if it was warranted&quot; % locale.currency(net_change_cash, grouping=True)) if operating_cash_flow &lt; 0: cash_red_flags += 1 file.write( &quot;\nCash flow from financing activities is negative: %s\n\t--&gt; Why? Where's the company's money coming from if they're not producing income?&quot; % locale.currency( operating_cash_flow, grouping=True)) return cash_red_flags, working_capital, net_change_cash analyze_cash() print(&quot;\n__________&quot;) print(&quot;Intrinsic value analysis&quot;) print(&quot;__________\n&quot;) def check_age_forecast_commodity(): global age, forecast, commodity_reliance # Check age while True: age_check = input(&quot;Is the company older than 10 years? (y/n): &quot;) if not age_check.isalpha(): print(&quot;Please only enter y or n&quot;) continue if age_check == &quot;y&quot;: age = &quot;y&quot; break elif age_check == &quot;n&quot;: age = &quot;n&quot; break else: print(&quot;Please only enter y or n&quot;) continue # Check forecast while True: forecast_check = input(&quot;Do you still see it around in 10 years? (y/n): &quot;) if not forecast_check.isalpha(): print(&quot;Please only enter y or n&quot;) continue if forecast_check == &quot;y&quot;: forecast = &quot;y&quot; break elif forecast_check == &quot;n&quot;: forecast = &quot;n&quot; break else: print(&quot;Please only enter y or n&quot;) continue # Check commodity reliance while True: commodity_check = input(&quot;Is the company distinguishable from others/ Does it have an economic moat? (y/n): &quot;) if not commodity_check.isalpha(): print(&quot;Please only enter y or n&quot;) continue if commodity_check == &quot;y&quot;: commodity_reliance = &quot;y&quot; break elif commodity_check == &quot;n&quot;: commodity_reliance = &quot;n&quot; break else: print(&quot;Please only enter y or n&quot;) continue return age, forecast, commodity_reliance check_age_forecast_commodity() intrinsic_score = 0 def intrinsic_value(): global total_assets, total_liabilities, total_debt, current_price, net_income, stockholders_equity, income_red_flags, balance_red_flags, cash_red_flags, ebit, current_price, intrinsic_score file.write( &quot;\n\n\n________________________________________\n\nIntrinsic value analysis\n\n________________________________________&quot;) book_value = total_assets - total_liabilities pbv = current_price / book_value roe = '{0:.2f}%'.format((net_income / stockholders_equity * 100)) debt_to_equity_ratio = total_liabilities / stockholders_equity rcoe = ebit / (total_assets - current_liabilities) rcoe_to_price = rcoe * current_price total_red_flags = income_red_flags + balance_red_flags + cash_red_flags # Write to the report file.write( &quot;\n\n\nBook value: %s --&gt; Should be &gt; 1. If the business went out of business now, how many times could it pay off all its debt.\nPrice to book value (P/BV): %s\n\t--&gt; Should be &gt; 1.5.&quot; % (locale.currency(book_value, grouping=True), pbv)) file.write( &quot;\nDebt to equity ratio: %s\n\t--&gt; How much the company is financing its operations through debt.&quot; % debt_to_equity_ratio) file.write( &quot;\nReturn on Equity (ROE): {}\n\t--&gt; Should be &gt; 10%. How effectively the management is using a company's assets to create profits.&quot;.format( roe)) file.write( &quot;\nReturn on capital employed (RCOE): %s\n\ŧ--&gt; Amount of profit a company is generating per 1$ employed -&gt; good for peer comparison.&quot; % rcoe) file.write( &quot;\nRCOE in comparison to price per share: %s\n\t--&gt; Amount of money the company is generating per one share at the current price.&quot; % locale.currency( rcoe_to_price, grouping=True)) # Calculate Score if age == &quot;y&quot; or &quot;Y&quot;: intrinsic_score += 1 if forecast == &quot;y&quot; or &quot;Y&quot;: intrinsic_score += 1 if commodity_reliance == &quot;y&quot; or &quot;Y&quot;: intrinsic_score += 1 if book_value &gt; 0: intrinsic_score += 1 if pbv &lt; 1.5: intrinsic_score += 1 if roe &gt; 0.1: intrinsic_score += 1 if debt_to_equity_ratio &lt; 1: intrinsic_score += 1 if total_red_flags &lt; 1: intrinsic_score += 1 file.write( &quot;\n\n_________________________________\nFINAL INTRINSIC VALUE\n_________________________________\n\nIntrinsic value score: %s/8&quot; % intrinsic_score) if intrinsic_score &lt;= 3: file.write(&quot;\n\n[--&gt;] Analysis: High risk!\n\t\t[&gt;] Be careful investing into this companyand make sure to check the financial statements and company story again properly. Further research recommended!&quot;) elif intrinsic_score == 4 or 5 or 6: file.write(&quot;\n\n[--&gt;] Analysis: Medium risk.\n\t\t[&gt;] This company could be turning a profit but for safety reasons, please check the financial statements, red flags and other facts again, to be sure that nothing is inadvertently overlooked&quot;) elif intrinsic_score == 7 or 8: file.write(&quot;\n\n[--&gt;] Analysis: Low risk.\n\t\t[&gt;] It's unlikely that the company will go bankrupt in the foreseeable future.&quot;) return book_value, pbv, roe, debt_to_equity_ratio, rcoe, total_red_flags, intrinsic_score intrinsic_value() print(&quot;\n\nDone.\n&quot;) print(&quot;The intrinsic value score is: &quot; + str(intrinsic_score) + &quot;/8\n&quot;) print( &quot;A report has been generated. Please check the same directory this program is located in\nThank you for using the Stock analysis tool.&quot;) file.close() </code></pre> <p>Thank you for taking the time to read until here :)</p>
[]
[ { "body": "<h1>Don't repeat yourself</h1>\n<p>Whenever you see that you are doing the same thing twice or more often in your program, find some way to avoid repeating yourself. For example, you have many instances of a <code>while</code>-loop that just checks if someone entered a <code>y</code> or <code>n</code>. You can make a function for that:</p>\n<pre><code>def ask_yes_no(prompt):\n while True:\n answer = input(prompt + &quot; (y/n): &quot;)\n\n if answer == &quot;y&quot;:\n return True\n elif answer == &quot;n&quot;:\n return False\n\n print(&quot;Please only enter y or n.&quot;)\n</code></pre>\n<p>And then you can use it like so:</p>\n<pre><code>def check_partner_trends():\n ...\n if ask_yes_no(&quot;Does it have big partners?&quot;):\n partners = input(&quot;Who? &quot;)\n\n if ask_yes_no(&quot;Is it participating in any current trends?&quot;):\n trends = input(&quot;Which? &quot;)\n ...\n</code></pre>\n<h1>Avoid global variables</h1>\n<p>It is OK to have global variables if there is no better way to put them, but a major problem in your code is that your functions read from and write to those global variables, instead of getting the variables passed as function arguments and just returning them as return values. This prevents your functions from being reusable.</p>\n<p>For example, in <code>check_partner_trends()</code>, don't use <code>global</code> variables <code>partners</code> and <code>trends</code>, only use local ones. You already return those, which is good. The caller can then decide in which variables to put those results. For example, it can just do:</p>\n<pre><code>partners, trends = check_partner_trends()\n</code></pre>\n<p>In the function <code>analyze_income()</code>, pass the variables as parameters:</p>\n<pre><code>def analyze_income(gross_profit, total_revenue, operating_expenses, cost_of_revenue):\n gross_margin = gross_profit / total_revenue\n ...\n return gross_margin, operating_income, income_red_flags\n\ngross_margin, operating_income, income_red_flags = analyze_income(gross_profit, total_revenue, operating_expenses, cost_of_revenue)\n</code></pre>\n<h1>Separate logic from input/output</h1>\n<p>Many of your functions do not only implement the logic and calculations, but also read input and write to files. Try to separate these things, it will make the code more readable, and makes it much easier to reuse functions. For example, <code>intrinsic_value()</code> not only calculates the intrinsic score, but it also writes it to <code>file</code>. Create one function to calculate the value, and another to write out the results. In this case, you probably should avoid writing out anything until you have read all the input and processed it, and then have a single <code>create_report()</code> function which itself opens the output file and prints the results to it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T22:39:43.310", "Id": "490827", "Score": "0", "body": "Thank you very much, especially all the while loops gave me a headache, but I just couldn't get my head around how else to do it.\n\nI like the idea of the create_report() function, but how could I implement it, so that it writes everything in the right order, without being partly redundant itself, as it would mirror parts of functions like analyze_income (i.e. the red flag count)?\n\n@Peilonrayz I left the parts he was commenting in the old way, so as to prevent confusion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T07:18:23.087", "Id": "490855", "Score": "0", "body": "You could have `analyze_income()` build a list of strings, where each string is a description of the red flag. Then you ensure `create_report()` gets this list, and then it can use `len()` on the list to get the number of red flags, and use a `for`-loop to print a list of all the red flags encountered." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T10:59:52.877", "Id": "490886", "Score": "0", "body": "So something like [this](https://pastebin.com/uz6mxWVK)? There are some redundancies in the analyzing parts again, but I couldn't get it printing the numbers with a list + for loop as you suggested (e.g. ` file.write(\"\\n[!] Balance red flags: %s\" % balance_red_flags)`)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T16:00:54.273", "Id": "250189", "ParentId": "250164", "Score": "5" } } ]
{ "AcceptedAnswerId": "250189", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:53:42.030", "Id": "250164", "Score": "3", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Stock analysis tool using Python" }
250164
<p>Apologies if this question doesn't fit the format here, seemed more appropriate here than SO due to the more nebulous nature of the question.</p> <p>Think mini tinyURL clone: POST to service to save the url + hash, then look up the mapping when visiting <code>/anything</code>. It's been a while since I've touched Ruby, and the resulting code snippet is not easy on the eyes:</p> <pre><code>require 'sinatra' require 'mongoid' require 'digest' class MinifiedUrl include Mongoid::Document field :code, type: String field :original_url, type: String end # Redirect to the actual url, like tinyurl.com/abcdefg get '/:code' do link = MinifiedUrl.where(:code =&gt; params[:code]).first # .first is falsy if there is no mapping if link puts &quot;Found minified link&quot; redirect link[:original_url], 302 else puts &quot;No minified link&quot; redirect '/404', 404 end end # Create a mapping from a POST request like { url: 'https://google.com/ '} post '/' do incoming_url = params[:url] link = MinifiedUrl.where(:code =&gt; params[:code]).first # Reassign link if link is falsy link = MinifiedUrl.create(:target_url =&gt; incoming_url, :code =&gt; Digest::MD5.hexdigest(incoming_url)[0..5]) unless link link[:slug] end </code></pre> <p>Is there an obvious way to make the code more idiomatic? My concern is multiple calls to <code>MinifiedUrl</code> model / reassigning value of <code>link</code>. I can't put my finger on it, but it doesn't feel ruby-like.</p>
[]
[ { "body": "<p>I agree that re-assigning variables is not great. The most 'obvious' way to improve this is to extract a helper method like</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def fetch_link\n if (existing_link = MinifiedUrl.where(:code =&gt; params[:code]).first)\n existing_link\n else\n MinifiedUrl.create(:target_url =&gt; params[:url], :code =&gt; generate_code)\nend\n\ndef generate_code\n Digest::MD5.hexdigest(incoming_url)[0..5]\nend\n</code></pre>\n<p>or if you prefer or memoization</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def fetch_link\n return existing_link if existing_link.present?\n \n MinifiedUrl.create(:target_url =&gt; params[:url], :code =&gt; generate_code)\nend\n\ndef existing_link\n @existing_link ||= MinifiedUrl.where(:code =&gt; params[:code]).first\nend\n\ndef generate_code\n Digest::MD5.hexdigest(incoming_url)[0..5]\nend\n</code></pre>\n<p>Another approach could be to implement a class method on your model which does it for you like</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class MinifiedUrl\n def self.find_or_create_by(original_url:, code:)\n if (existing_link = MinifiedUrl.where(:code =&gt; code).first)\n existing_link\n else\n MinifiedUrl.create(:target_url =&gt; original_url, :code =&gt; generate_code)\n end\n end\nend\n\npost '/' do\n incoming_url = params[:url]\n\n link = MinifiedUrl.find_or_create_by(url: incoming_url, code: params[:code])\n\n link[:slug]\nend\n</code></pre>\n<p>## Edit</p>\n<p>Adding some more thoughts about error handling here.</p>\n<h3>URL</h3>\n<p>There are several things which can go wrong with the URL like invalid or already taken.</p>\n<p>The invalid case I would cover with a validation but there is not much what you can validate here to be honest except the format. Mongoid comes with ActiveSupport validations so you could do something like this.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class MinifiedUrl\n validates_format_of :original_url, with: /regex/\nend\n\nMinifiedUrl.create(url: 'invalid').valid?\n# false\n</code></pre>\n<p>It can be that your URL is already taken, e.g. somebody else already added this URL. What do you want to do in this case? Give an error or allow it? I think it's a valid use case to allow the same URL twice with a different code (you don't want to have the same code as e.g. you want to have a visit counter as well). If you want to allow the same URL twice, your approach with the MD5 hash does not work anymore as it would be the same obviously so in this case you should use something more random.</p>\n<p>The hex digest is anyway a problem in case of collisions you would fail at the moment. I think a better approach is to just generate a random code in a loop.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def generate_code\n 100.times do\n code = SecureRandom.hex\n break code unless MinifiedUrl.find_by(code: code)\n end\nend\n</code></pre>\n<p>I'm also wondering why your <code>POST</code> does accept a <code>code</code> parameter but I don't know your user interface, I just found it a bit confusing.</p>\n<p>I wouldn't be too concerned about DB not available and would not put any code handling this in my application to be honest. If you need this safety you should have DB replicas which can handle if a node goes away.</p>\n<p>I would also calculate if a 5 digit code is big enough for your use case.</p>\n<p>I'm also wondering why you chose to use to Mongoid? I don't think a document store is a good data storage here? I think a key/value store like Redis would be a better alternative here because you basically just do key lookup and you can store everything in a hash. But again, I don't know the requirements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T23:22:52.633", "Id": "490829", "Score": "0", "body": "Thanks! What are the implications of error handling with each of these approaches? I'm partial to the fat model. Cheers!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T21:01:09.290", "Id": "490967", "Score": "0", "body": "That really depends which kind of errors you would expect? You could add errors to your model (https://docs.mongodb.com/mongoid/7.1/tutorials/mongoid-validation/index.html), throw an exception, return a result object. There are several different way but it depends really on your use case. Can you give some examples?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T21:33:01.777", "Id": "490973", "Score": "0", "body": "Let me rephrase... this is for a sort of a quiz. Say you were looking at a proof of concept applet that did this, what would you expect to see to tick the box \"This guy has thought about idiomatic error handling in this demo app\"? I know how to handle errors, just rusty with ruby. What does an app with two routes look like in terms of idiomatic erro handling? I imagine there should be some safeguards like \"db not available\" or \"malformed incoming url\" (helper for that to be added I suppose)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:16:14.257", "Id": "491268", "Score": "0", "body": "Added some more comments to the original answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T10:19:29.753", "Id": "250176", "ParentId": "250169", "Score": "2" } } ]
{ "AcceptedAnswerId": "250176", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-03T21:19:11.557", "Id": "250169", "Score": "2", "Tags": [ "ruby", "sinatra" ], "Title": "Idiomatic Ruby if/else in a Sinatra route" }
250169
<p>This is my first attempt at using asyncio, I don't believe I am using it properly and would like assistance using it to maximize efficiency. The current run time is between 20-22 seconds. I would like to reduce this as much as possible, thank you!</p> <pre><code>import asyncio import aiosnow from snow import snowCommands #import login import subprocess import os from pathlib import Path import sys import wmi import requests import time import datetime import winreg import sys import time from formatting.formatter import Formatter import logging from snow.ComputerSupport import CompSup from snow.computer import Computer from snow.user import User import wmi import traceback import re #Settings _version = &quot;0.1.1&quot; # Current Version _filePath = os.path.splitext(__file__)[0]+'.exe' # returns PATH/TO/script.exe _scriptname = Path(__file__).stem+'.exe' # returns script.exe creator = &quot;dmcanady&quot; # Creator contributors = [] # add anyone who assisted with the script async def main(): start_time = time.time() logging.basicConfig(filename='example.log',level=logging.DEBUG) welcome = Formatter(_scriptname,_version,creator,contributors) welcome.header() username = &quot;&quot; while True: #username,password = login.login() username = input(&quot;Username: &quot;) password = input(&quot;Password: &quot;) if &quot;@&quot; in username: print(&quot;Usernames cannot be an email&quot;) else: break __instance__ = 'libertydev.service-now.com' # URL for service now serviceNow = aiosnow.Client(__instance__, basic_auth=(username,password)) # creates serviceNow session for creds provided ticket = await genTicket(serviceNow) await userAccept(username,ticket) ticketTypes = {&quot;Assignment&quot;:__assignment__,&quot;Return&quot;:__return__,&quot;Repair&quot;:__repair__,&quot;Life Cycle Management&quot;:__LCM__} await ticketTypes[ticket[&quot;CS&quot;].cat_item](ticket) print(time.time()-start_time) welcome.footer() async def genTicket(serviceNow:object): # Validates CS Number # valid = False while valid == False: print(&quot;CS Format: CSXXXXXXX&quot;) CSNumber = input(&quot;CSNumber: &quot;) valid = bool(re.match(&quot;^CS[0-9]{7}&quot;,CSNumber)) # Attempts to get ticket # try: CS = await CompSup(serviceNow,CSNumber) # Validates that the ticket is available # if((CS.state).key == 1 and CS.assigned_to == None and CS.u_wi_primary_tech == None): while True: accept = input(&quot;Do you want to accept this ticket (y/n): &quot;) if accept == &quot;y&quot;: Comp = await Computer(serviceNow,CS.u_asset) assigned = await User(serviceNow,CS.assigned_to) if CS.assigned_to == CS.u_wi_primary_tech: tech = assigned else: tech = await User(serviceNow,CS.u_wi_primary_tech) customer = await User(serviceNow,CS.requested_for) LCMComp = await Computer(serviceNow,CS.u_asset_returned) # Returns ticket information if available # return {&quot;CS&quot;:CS,&quot;computer&quot;:Comp,&quot;assigned&quot;:assigned,&quot;technician&quot;:tech,&quot;Customer&quot;:customer,&quot;LCM computer&quot;: LCMComp} elif accept == &quot;n&quot;: print(&quot;You have declined the ticket, please restart when you want one.&quot;) # if ticket is unavailable else: print(&quot;Ticket is not available (not in open or is already assigned). Please selected another ticket.&quot;) sys.exit(0) except Exception as e: logging.getLogger().exception(e) async def userAccept(username,computerInfo): await computerInfo[&quot;CS&quot;].updateCS([&quot;assigned_to&quot;,&quot;u_wi_primary_tech&quot;],[username,username]) await computerInfo[&quot;assigned&quot;].__init__(computerInfo[&quot;CS&quot;].serviceNow,computerInfo[&quot;CS&quot;].assigned_to) await computerInfo[&quot;technician&quot;].__init__(computerInfo[&quot;CS&quot;].serviceNow,computerInfo[&quot;CS&quot;].u_wi_primary_tech) await computerInfo[&quot;CS&quot;].updateCS([&quot;state&quot;,&quot;u_substate&quot;],[2,&quot; &quot;]) print(&quot;Ticket Type 1:&quot;,computerInfo[&quot;CS&quot;].cat_item) #Will be used to verify the correct computer is being used. print(&quot;verifying device's serial&quot;) c = wmi.WMI() if computerInfo[&quot;computer&quot;].sys_id != None: try: serial = computerInfo[&quot;computer&quot;].serial_number print(&quot;Ticket Type:&quot;,computerInfo[&quot;CS&quot;].cat_item) except: serial = computerInfo[&quot;computer&quot;].u_asset print(&quot;Ticket Type:&quot;,computerInfo[&quot;CS&quot;].cat_item) elif computerInfo[&quot;computer&quot;].sys_id == None: try: serial = computerInfo[&quot;computer&quot;].serial_number print(&quot;Ticket Type:&quot;,computerInfo[&quot;CS&quot;].cat_item) except: serial = computerInfo[&quot;computer&quot;].u_asset print(&quot;Ticket Type:&quot;,computerInfo[&quot;CS&quot;].cat_item) cSerial = c.Win32_ComputerSystem()[0].Name print(&quot;Ticket Type:&quot;,computerInfo[&quot;CS&quot;].cat_item) if(serial != cSerial): print(&quot;Please run me on {0}.&quot;.format(serial)) print(&quot;Exiting...&quot;) input(&quot;Press any key to continue&quot;) print(&quot;Ticket Type:&quot;,computerInfo[&quot;CS&quot;].cat_item) #sys.exit(0) # opens programs and features for tech def uninstallApp(ticketType): print('----') # if ticket is a repair, it looks for non standard applications if ticketType == &quot;repair&quot;: message = ' Please uninstall any applications not standard.' proType = 'non-standard' # if ticket is a return it looks for licensed applications elif ticketType == &quot;return&quot;: message = ' Please uninstall any licensed applications.' proType = 'licensed' print(message) time.sleep(1) os.system('cmd /c appwiz.cpl') # opens programs and features while True: # Verifies with tech that changes have been made removed = input(&quot;have all {0} programs been removed (y/n): &quot;.format(proType)) if removed == &quot;y&quot;: return True elif removed == &quot;n&quot;: print(&quot;I will open the window for you...&quot;) time.sleep(1) os.system('cmd /c appwiz.cpl') # opens programs and features else: print(&quot;Please respond y or n.&quot;) # Checks to see if computer needs to have an IPU ran async def reimage(): global _OSVersion key = r&quot;SOFTWARE\Microsoft\Windows NT\CurrentVersion&quot; val = r&quot;ReleaseID&quot; with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key) as key: _OSVersion = int(winreg.QueryValueEx(key,val)[0]) if _OSVersion &lt; 1909: print(&quot;Please run IPUInstaller.exe to update to newest version.&quot;) elif _OSVersion &gt;=1909: print(&quot;This computer is 1909 or newer!&quot;) # Restarts device async def restart(): for i in reversed(range(11)): print(&quot;This device will restart in: {:02}&quot;.format(i)) time.sleep(1) print(&quot;Restarting for reimaging...&quot;) time.sleep(1) os.system(&quot;shutdown /r /t 10&quot;) # set to restart computer after 10 seconds async def setState(computerInfo,state,__sysid__ = &quot;&quot;): if __sysid__ == &quot;&quot;: __sysid__ = computerInfo[&quot;computer&quot;].sys_id states = { &quot;In Use&quot; : {&quot;install_status&quot;:1,&quot;substatus&quot;:&quot;&quot;,&quot;assigned_to&quot;:computerInfo[&quot;CS&quot;].requested_for}, &quot;Return&quot; : {&quot;install_status&quot;:16,&quot;substatus&quot;:&quot;&quot;,&quot;stockroom&quot;:&quot;IT Helpdesk Walkin Support&quot;}, &quot;LCMed&quot; : {&quot;install_status&quot;:6,&quot;substatus&quot;:&quot;pending_transfer&quot;,&quot;stockroom&quot;:&quot;IT Helpdesk Walkin Support&quot;} } if state == &quot;In Use&quot;: # Assigns customer as assigned to await computerInfo[&quot;computer&quot;].updateHardware(__sysid__,[&quot;assigned_to&quot;], [states[state][&quot;assigned_to&quot;]]) else: await computerInfo[&quot;computer&quot;].updateHardware(__sysid__,[&quot;stockroom&quot;],[states[state][&quot;stockroom&quot;]]) # changes status to in use await computerInfo[&quot;computer&quot;].updateHardware(__sysid__,[&quot;install_status&quot;,&quot;substatus&quot;],[states[state][&quot;install_status&quot;],states[state][&quot;substatus&quot;]]) # checks if warranty is expired or not. async def warrantyCheck(computerInfo): if computerInfo[&quot;computer&quot;].sys_id == None: print(&quot;This device is a personal device.&quot;) expire_raw = None check = computerInfo[&quot;CS&quot;].u_manufacturer.value elif computerInfo[&quot;computer&quot;].sys_id != None: today = datetime.datetime.now() expire_raw = computerInfo[&quot;computer&quot;].warranty_expiration check = computerInfo[&quot;computer&quot;].display_name if expire_raw == None: if &quot;Dell&quot; in check: site = &quot;https://www.dell.com/support/home/en-us?app=warranty&quot; elif &quot;HP&quot; in check: site = &quot;https://support.hp.com/us-en/checkwarranty&quot; elif &quot;Lenovo&quot; in check: site = &quot;https://pcsupport.lenovo.com/us/en/warrantylookup#/&quot; elif &quot;Microsoft&quot; in check: site = &quot;https://mybusinessservice.surface.com/en-US/CheckWarranty/CheckWarranty&quot; else: site = &quot;your manufacture's site&quot; print(&quot;No warranty information avaliable&quot;) print(&quot;Please go to {0} to check current warranty info!&quot;.format(site)) # Connection for warranty API to check current warranty information else: exp = datetime.datetime.strptime(expire_raw, &quot;%Y-%m-%d&quot;) if exp &gt; today: print(&quot;device's warranty expires %s&quot; % exp) elif exp == today: print(&quot;device's warranty expires today&quot;) elif exp &lt; today: print(&quot;device's warranty expired %s&quot; % exp) #Processes by ticket type async def __assignment__(computerInfo): print(&quot;I am an assignment&quot;) await setState(computerInfo = computerInfo,state = &quot;In Use&quot;) # Requested steps to take after print(&quot;Please run auto-assign&quot;) print(&quot;Check to make sure drivers have been updated.&quot;) async def __return__(computerInfo): print(&quot;I am a return&quot;) await setState(computerInfo = computerInfo,state = &quot;Return&quot;) # Returns true if tech states they uninstalled all licensed programs if uninstallApp(&quot;return&quot;): assoc = input(&quot;Is there an associated assignment Ticket (y/n): &quot;) # if there is an associated assignment, reboots with intent of reimage if assoc == &quot;y&quot;: await computerInfo[&quot;CS&quot;].updateCS(&quot;work_notes&quot;,&quot;System checked for licensed applications.&quot;) print(&quot;Please ensure an ethernet cable is securely connected before proceeding.&quot;) await computerInfo[&quot;CS&quot;].updateCS(&quot;work_notes&quot;,&quot;begin Win 10 1909 Fac/Staff imaging process via IPv4 PXE&quot;) # Otherwise reboots with intent to erase all data print(&quot;Computer will restart shortly to erase data.&quot;) decide = input(&quot;continue (y/n): &quot;) if decide == &quot;y&quot;: await restart() else: pass async def __repair__(computerInfo): print(&quot;I am a repair&quot;) await reimage() # Checks current OS await warrantyCheck(computerInfo) # Checks warranty status # Checks for unauthorized programs if uninstallApp(&quot;repair&quot;): await computerInfo[&quot;CS&quot;].updateCS(&quot;work_notes&quot;,&quot;System checked for nonstandard applications.&quot;) print(&quot;Check to make sure drivers have been updated.&quot;) async def __LCM__(computerInfo): print(&quot;I am an LCM&quot;) print(computerInfo[&quot;computer&quot;].install_status.key) if computerInfo[&quot;computer&quot;].install_status.key != 1: await setState(computerInfo = computerInfo,__sysid__ = computerInfo[&quot;computer&quot;].sys_id,state = &quot;In Use&quot;) else: print(&quot;It appears the device is already in use...&quot;) print(&quot;Let me check who&quot;) if computerInfo[&quot;computer&quot;].assigned_to == computerInfo[&quot;CS&quot;].requested_for: pass else: print(&quot;Oh no, looks like someone else is currently assigned...&quot;) print(&quot;Let me correct that!&quot;) user = computerInfo[&quot;CS&quot;].requested_for await computerInfo[&quot;computer&quot;].updateHardware(computerInfo[&quot;computer&quot;].sys_id,[&quot;assigned_to&quot;],[user]) print(&quot;Awesome! Looks like the proper user is assigned.&quot;) print(&quot;Let me check on the return device.&quot;) while True: resp = input(&quot;Do you have the original device (y/n): &quot;) if resp == &quot;y&quot;: await setState(computerInfo = computerInfo,__sysid__ = computerInfo[&quot;LCM computer&quot;].sys_id,state = &quot;LCMed&quot;) break elif resp == &quot;n&quot;: print(&quot;Please restart when you have the device...&quot;) await computerInfo[&quot;CS&quot;].updateCS(&quot;work_notes&quot;,&quot;Awaiting returned device.&quot;) break # Starts loop asyncio.run(main()) </code></pre>
[]
[ { "body": "<h2>Pathlib</h2>\n<pre><code>_filePath = os.path.splitext(__file__)[0]+'.exe'\n</code></pre>\n<p>is better expressed as</p>\n<pre><code>from pathlib import Path\n\nFILE_PATH = Path(__file__).with_suffix('.exe')\n</code></pre>\n<p>Note that since it's a global constant, it should be capitalized.</p>\n<h2>Pre-declaration?</h2>\n<p>Delete <code>username = &quot;&quot;</code>.</p>\n<h2>Password security</h2>\n<p>Do <em>not</em> use <code>input</code> to capture a password. It's visible to onlookers. Use <a href=\"https://docs.python.org/3/library/getpass.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/getpass.html</a> instead.</p>\n<h2>Parens and comparisons</h2>\n<pre><code>if((CS.state).key == 1 and CS.assigned_to == None and CS.u_wi_primary_tech == None):\n</code></pre>\n<p>has a few issues:</p>\n<ul>\n<li>Don't use outer parens. This isn't Java.</li>\n<li>Use <code>is None</code> instead of <code>== None</code> since <code>None</code> is a singleton in Python.</li>\n<li>Don't use parens around <code>(CS.state)</code>, either.</li>\n</ul>\n<h2>Mystery hangs</h2>\n<p>Why does <code>uninstallApp</code> (which should be <code>uninstall_app</code>) do this?</p>\n<pre><code>time.sleep(1)\n</code></pre>\n<p>Don't make your user wait pointlessly.</p>\n<h2>External processes</h2>\n<p>Don't use <code>os.system</code>. Use <a href=\"https://docs.python.org/3/library/subprocess.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/subprocess.html</a> instead.</p>\n<h2>More extraneous code</h2>\n<pre><code> else:\n pass\n</code></pre>\n<p>can be deleted.</p>\n<h2>Expression negation</h2>\n<pre><code> if computerInfo[&quot;computer&quot;].assigned_to == computerInfo[&quot;CS&quot;].requested_for:\n pass\n else:\n</code></pre>\n<p>should just be</p>\n<pre><code>if computerInfo[&quot;computer&quot;].assigned_to != computerInfo[&quot;CS&quot;].requested_for:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T22:29:20.297", "Id": "250452", "ParentId": "250170", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T02:48:45.320", "Id": "250170", "Score": "2", "Tags": [ "python", "python-3.x", "web-services" ], "Title": "A program designed to update fields in Service Now depending on type" }
250170
<p>First Question: <a href="https://codereview.stackexchange.com/questions/250149/simple-c-hash-function-library">Simple C++ Hash function library</a></p> <blockquote> <p>I had created hash function library (<code>MD5</code>, <code>MD4</code>, <code>SHA256</code>, <code>SHA384</code>, <code>SHA512</code>, <code>RipeMD128</code>, <code>RipeMD160</code>, <code>CRC16</code>, <code>CRC32</code>, <code>CRC64</code>), written in C++. Everything working well and My library produces exactly the same output compared to the PHP output. (Except for CRC series) The individual algorithmic abstraction layers consist of the chash::IAlgorithm interface and chash::IDigest. But I'd like to refine IDigest more elegantly. How can I do it? Full code: <a href="https://github.com/whoamiho1006/chash" rel="nofollow noreferrer">https://github.com/whoamiho1006/chash</a></p> </blockquote> <p>I had modified following <code>G. Sliepen</code>'s opinion.</p> <ol> <li>Removal of IDigest interface.</li> <li>Forwarded <code>std::vector&lt;uint8_t&gt;</code> to <code>CDigest</code>.</li> </ol> <p>And then, the question arose about the need for the TAlgorithm template class. I was explicitly intent on making that interface can be deleted by the C++ <code>delete</code> keyword. However, there is a strong feeling of something awkward and a little heavy.</p> <p>The reason for designing this class was to make the implementation of the IAlgorithm interface short and reliable, but it feels like something is out of focus. Should I keep this class? Or should it be removed and redesigned?</p> <p><strong>Modified IAlgorithm class</strong></p> <pre><code>#pragma once #include &quot;Macros.hpp&quot; #include &lt;vector&gt; namespace chash { enum class EAlgorithm { Unknown = 0x0000, CRC16 = 0x1000, // --&gt; IBM Poly-Nomial. CRC32 = 0x1001, // --&gt; IEEE 802.3 CRC64 = 0x1002, // --&gt; ISO Poly-Nomial. SHA256 = 0x2000, SHA384 = 0x2001, SHA512 = 0x2002, MD5 = 0x3000, MD4 = 0x3001, RipeMD128 = 0x4000, RipeMD160 = 0x4001, }; enum class EAlgorithmErrno { Succeed = 0, InvalidAlgorithm, InvalidState, //InvalidDigest }; typedef std::vector&lt;uint8_t&gt; CDigest; class IAlgorithm { public: IAlgorithm(EAlgorithm type) : _type(type), _errno(EAlgorithmErrno::Succeed) { } virtual ~IAlgorithm() { } private: EAlgorithm _type; EAlgorithmErrno _errno; protected: inline void setError(EAlgorithmErrno _errno) { this-&gt;_errno = _errno; } public: /* get algorithm type. */ inline EAlgorithm type() const { return _type; } /* get algorithm state. */ inline EAlgorithmErrno error() const { return _errno; } /* initiate the algorithm. */ virtual bool init() = 0; /* update the algorithm state by given bytes. */ virtual bool update(const uint8_t* inBytes, size_t inSize) = 0; /* finalize the algorithm and digest. */ virtual bool finalize(CDigest&amp; outDigest) = 0; /* compute hash with digest. */ virtual EAlgorithmErrno compute(CDigest&amp; outDigest, const uint8_t* inBytes, size_t inSize) { if (init()) { update(inBytes, inSize); finalize(outDigest); } return error(); } }; /* Digest to hex. */ inline std::string toHex(const CDigest&amp; inDigest) { std::string outHex; outHex.reserve(inDigest.size() &lt;&lt; 1); for(uint8_t b : inDigest) { int32_t fr = b / 16; int32_t bk = b % 16; if (fr &lt; 10) outHex.push_back('0' + fr); else outHex.push_back('a' + (fr - 10)); if (bk &lt; 10) outHex.push_back('0' + bk); else outHex.push_back('a' + (bk - 10)); } return outHex; } /* Comparator between two CDigests. */ inline bool operator ==(const CDigest&amp; left, const CDigest&amp; right) { if (left.size() == right.size()) { return !::memcmp(&amp;left[0], &amp;right[0], left.size()); } return false; } /* Comparator between two CDigests. */ inline bool operator !=(const CDigest&amp; left, const CDigest&amp; right) { if (left.size() == right.size()) { return ::memcmp(&amp;left[0], &amp;right[0], left.size()); } return true; } } </code></pre> <p>Belows are example implementation:</p> <p><strong>CMD5.hpp</strong></p> <pre><code>#pragma once #include &quot;chash/IAlgorithm.hpp&quot; namespace chash { class CMD5 : public IAlgorithm { private: static const uint8_t PADDING[64]; public: CMD5(); ~CMD5() { } private: bool _init; uint32_t _state[4]; uint64_t _count; uint8_t _buffer[64]; public: bool init() override; bool update(const uint8_t* inBytes, size_t inSize) override; bool finalize(CDigest&amp; outDigest) override; private: void updateFinal(); void flush(); void transform(const uint32_t* data); }; } </code></pre> <p><strong>CMD5.cpp</strong></p> <pre><code>#include &quot;CMD5.hpp&quot; #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 #define F(x, y, z) (((x) &amp; (y)) | ((~x) &amp; (z))) #define G(x, y, z) (((x) &amp; (z)) | ((y) &amp; (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) #define ROTATE_LEFT(x, n) (((x) &lt;&lt; (n)) | ((x) &gt;&gt; (32-(n)))) #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define GG(a, b, c, d, x, s, ac) { \ (a) += G ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define HH(a, b, c, d, x, s, ac) { \ (a) += H ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define II(a, b, c, d, x, s, ac) { \ (a) += I ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } namespace chash { const uint8_t CMD5::PADDING[64] = { 0x80, 0, }; CMD5::CMD5() : IAlgorithm(EAlgorithm::MD5), _init(false), _count(0) { } bool CMD5::init() { if (_init) { setError(EAlgorithmErrno::InvalidState); return false; } _init = true; _state[0] = 0x67452301; _state[1] = 0xefcdab89; _state[2] = 0x98badcfe; _state[3] = 0x10325476; _count = 0; setError(EAlgorithmErrno::Succeed); return true; } bool CMD5::update(const uint8_t* inBytes, size_t inSize) { if (!_init) { setError(EAlgorithmErrno::InvalidState); return false; } uint32_t pos = uint32_t(_count) &amp; 0x3f; while (inSize) { _buffer[pos++] = *inBytes++; _count++; inSize--; if (pos &gt;= 64) { pos = 0; flush(); } } setError(EAlgorithmErrno::Succeed); return true; } bool CMD5::finalize(CDigest&amp; outDigest) { if (!_init) { setError(EAlgorithmErrno::InvalidState); return false; } updateFinal(); outDigest.reserve(16); for (int32_t i = 0, j = 0; j &lt; 16; ++i, j += 4) { outDigest.push_back(uint8_t(_state[i])); outDigest.push_back(uint8_t(_state[i] &gt;&gt; 8)); outDigest.push_back(uint8_t(_state[i] &gt;&gt; 16)); outDigest.push_back(uint8_t(_state[i] &gt;&gt; 24)); } _init = false; setError(EAlgorithmErrno::Succeed); return true; } void CMD5::updateFinal() { uint8_t lenBits[8]; uint64_t length = _count &lt;&lt; 3; uint32_t index = uint32_t(_count &amp; 0x3f), pads = index &lt; 56 ? 56 - index : 120 - index; lenBits[0] = uint8_t(length); lenBits[1] = uint8_t(length &gt;&gt; 8); lenBits[2] = uint8_t(length &gt;&gt; 16); lenBits[3] = uint8_t(length &gt;&gt; 24); lenBits[4] = uint8_t(length &gt;&gt; 32); lenBits[5] = uint8_t(length &gt;&gt; 40); lenBits[6] = uint8_t(length &gt;&gt; 48); lenBits[7] = uint8_t(length &gt;&gt; 56); update(PADDING, pads); update(lenBits, 8); } void CMD5::flush() { uint32_t block[16]; for (int32_t i = 0; i &lt; 16; ++i) { block[i] = (uint32_t(_buffer[i * 4 + 3]) &lt;&lt; 24) | (uint32_t(_buffer[i * 4 + 2]) &lt;&lt; 16) | (uint32_t(_buffer[i * 4 + 1]) &lt;&lt; 8) | (uint32_t(_buffer[i * 4 + 0])); } transform(block); } void CMD5::transform(const uint32_t* data) { uint32_t a = _state[0], b = _state[1], c = _state[2], d = _state[3]; /* Round 1 */ FF(a, b, c, d, data[0], S11, 0xd76aa478); /* 1 */ FF(d, a, b, c, data[1], S12, 0xe8c7b756); /* 2 */ FF(c, d, a, b, data[2], S13, 0x242070db); /* 3 */ FF(b, c, d, a, data[3], S14, 0xc1bdceee); /* 4 */ FF(a, b, c, d, data[4], S11, 0xf57c0faf); /* 5 */ FF(d, a, b, c, data[5], S12, 0x4787c62a); /* 6 */ FF(c, d, a, b, data[6], S13, 0xa8304613); /* 7 */ FF(b, c, d, a, data[7], S14, 0xfd469501); /* 8 */ FF(a, b, c, d, data[8], S11, 0x698098d8); /* 9 */ FF(d, a, b, c, data[9], S12, 0x8b44f7af); /* 10 */ FF(c, d, a, b, data[10], S13, 0xffff5bb1); /* 11 */ FF(b, c, d, a, data[11], S14, 0x895cd7be); /* 12 */ FF(a, b, c, d, data[12], S11, 0x6b901122); /* 13 */ FF(d, a, b, c, data[13], S12, 0xfd987193); /* 14 */ FF(c, d, a, b, data[14], S13, 0xa679438e); /* 15 */ FF(b, c, d, a, data[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG(a, b, c, d, data[1], S21, 0xf61e2562); /* 17 */ GG(d, a, b, c, data[6], S22, 0xc040b340); /* 18 */ GG(c, d, a, b, data[11], S23, 0x265e5a51); /* 19 */ GG(b, c, d, a, data[0], S24, 0xe9b6c7aa); /* 20 */ GG(a, b, c, d, data[5], S21, 0xd62f105d); /* 21 */ GG(d, a, b, c, data[10], S22, 0x2441453); /* 22 */ GG(c, d, a, b, data[15], S23, 0xd8a1e681); /* 23 */ GG(b, c, d, a, data[4], S24, 0xe7d3fbc8); /* 24 */ GG(a, b, c, d, data[9], S21, 0x21e1cde6); /* 25 */ GG(d, a, b, c, data[14], S22, 0xc33707d6); /* 26 */ GG(c, d, a, b, data[3], S23, 0xf4d50d87); /* 27 */ GG(b, c, d, a, data[8], S24, 0x455a14ed); /* 28 */ GG(a, b, c, d, data[13], S21, 0xa9e3e905); /* 29 */ GG(d, a, b, c, data[2], S22, 0xfcefa3f8); /* 30 */ GG(c, d, a, b, data[7], S23, 0x676f02d9); /* 31 */ GG(b, c, d, a, data[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH(a, b, c, d, data[5], S31, 0xfffa3942); /* 33 */ HH(d, a, b, c, data[8], S32, 0x8771f681); /* 34 */ HH(c, d, a, b, data[11], S33, 0x6d9d6122); /* 35 */ HH(b, c, d, a, data[14], S34, 0xfde5380c); /* 36 */ HH(a, b, c, d, data[1], S31, 0xa4beea44); /* 37 */ HH(d, a, b, c, data[4], S32, 0x4bdecfa9); /* 38 */ HH(c, d, a, b, data[7], S33, 0xf6bb4b60); /* 39 */ HH(b, c, d, a, data[10], S34, 0xbebfbc70); /* 40 */ HH(a, b, c, d, data[13], S31, 0x289b7ec6); /* 41 */ HH(d, a, b, c, data[0], S32, 0xeaa127fa); /* 42 */ HH(c, d, a, b, data[3], S33, 0xd4ef3085); /* 43 */ HH(b, c, d, a, data[6], S34, 0x4881d05); /* 44 */ HH(a, b, c, d, data[9], S31, 0xd9d4d039); /* 45 */ HH(d, a, b, c, data[12], S32, 0xe6db99e5); /* 46 */ HH(c, d, a, b, data[15], S33, 0x1fa27cf8); /* 47 */ HH(b, c, d, a, data[2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II(a, b, c, d, data[0], S41, 0xf4292244); /* 49 */ II(d, a, b, c, data[7], S42, 0x432aff97); /* 50 */ II(c, d, a, b, data[14], S43, 0xab9423a7); /* 51 */ II(b, c, d, a, data[5], S44, 0xfc93a039); /* 52 */ II(a, b, c, d, data[12], S41, 0x655b59c3); /* 53 */ II(d, a, b, c, data[3], S42, 0x8f0ccc92); /* 54 */ II(c, d, a, b, data[10], S43, 0xffeff47d); /* 55 */ II(b, c, d, a, data[1], S44, 0x85845dd1); /* 56 */ II(a, b, c, d, data[8], S41, 0x6fa87e4f); /* 57 */ II(d, a, b, c, data[15], S42, 0xfe2ce6e0); /* 58 */ II(c, d, a, b, data[6], S43, 0xa3014314); /* 59 */ II(b, c, d, a, data[13], S44, 0x4e0811a1); /* 60 */ II(a, b, c, d, data[4], S41, 0xf7537e82); /* 61 */ II(d, a, b, c, data[11], S42, 0xbd3af235); /* 62 */ II(c, d, a, b, data[2], S43, 0x2ad7d2bb); /* 63 */ II(b, c, d, a, data[9], S44, 0xeb86d391); /* 64 */ _state[0] += a; _state[1] += b; _state[2] += c; _state[3] += d; } } </code></pre> <p><strong>chash.hpp</strong></p> <pre><code>#pragma once #include &quot;chash/IAlgorithm.hpp&quot; #if defined(_WIN32) || defined(_WIN64) #ifdef __CHASH_EXPORTS__ #define CHASH_API __declspec(dllexport) #else #define CHASH_API __declspec(dllimport) #endif #else #define CHASH_API #endif namespace chash { CHASH_API IAlgorithm* createAlgorithm(EAlgorithm algorithm); template&lt;EAlgorithm Algo&gt; class TAlgorithm : public IAlgorithm { public: TAlgorithm() : IAlgorithm(EAlgorithm::Unknown) { algorithm = createAlgorithm(Algo); setType(Algo); } TAlgorithm(const TAlgorithm&lt;Algo&gt;&amp;) = delete; TAlgorithm(TAlgorithm&lt;Algo&gt;&amp;&amp; other) : algorithm(other.algorithm) { } ~TAlgorithm() { if (algorithm) { delete algorithm; } } private: IAlgorithm* algorithm; public: inline operator bool() const { return algorithm; } inline bool operator !() const { return !algorithm; } inline TAlgorithm&lt;Algo&gt;&amp; operator =(const TAlgorithm&lt;Algo&gt;&amp;) = delete; inline TAlgorithm&lt;Algo&gt;&amp; operator =(TAlgorithm&lt;Algo&gt;&amp;&amp; other) { if (this != &amp;other) std::swap(algorithm, other.algorithm); return *this; } public: /* initiate the algorithm. */ virtual bool init() override { if (algorithm) { bool retVal = algorithm-&gt;init(); setError(algorithm-&gt;error()); return retVal; } setError(EAlgorithmErrno::InvalidAlgorithm); return false; } /* update the algorithm state by given bytes. */ virtual bool update(const uint8_t* inBytes, size_t inSize) override { if (algorithm) { bool retVal = algorithm-&gt;update(inBytes, inSize); setError(algorithm-&gt;error()); return retVal; } setError(EAlgorithmErrno::InvalidAlgorithm); return false; } /* finalize the algorithm and digest. */ virtual bool finalize(CDigest&amp; outDigest) override { if (algorithm) { bool retVal = algorithm-&gt;finalize(outDigest); setError(algorithm-&gt;error()); return retVal; } setError(EAlgorithmErrno::InvalidAlgorithm); return false; } }; } </code></pre> <p><strong>chash.cpp</strong></p> <pre><code>#include &quot;chash.hpp&quot; #include &quot;crc/CCRC16.hpp&quot; #include &quot;crc/CCRC32.hpp&quot; #include &quot;crc/CCRC64.hpp&quot; #include &quot;md/CMD5.hpp&quot; #include &quot;md/CMD4.hpp&quot; #include &quot;sha/CSHA256.hpp&quot; #include &quot;sha/CSHA384.hpp&quot; #include &quot;sha/CSHA512.hpp&quot; #include &quot;ripemd/CRipeMD128.hpp&quot; #include &quot;ripemd/CRipeMD160.hpp&quot; namespace chash { CHASH_API IAlgorithm* createAlgorithm(EAlgorithm algorithm) { switch (algorithm) { case EAlgorithm::CRC16: return new CCRC16(); case EAlgorithm::CRC32: return new CCRC32(); case EAlgorithm::CRC64: return new CCRC64(); case EAlgorithm::SHA256: return new CSHA256(); case EAlgorithm::SHA384: return new CSHA384(); case EAlgorithm::SHA512: return new CSHA512(); case EAlgorithm::MD5: return new CMD5(); case EAlgorithm::MD4: return new CMD4(); case EAlgorithm::RipeMD128: return new CRipeMD128(); case EAlgorithm::RipeMD160: return new CRipeMD160(); } return nullptr; } } </code></pre> <p>Usage:</p> <pre><code>int main() { TAlgorithm&lt;EAlgorithm::MD4&gt; MD4; CDigest Digest; if (MD4.init()) { MD4.update((uint8_t*)&quot;abcd&quot;, 4); MD4.finalize(Digest); printf(&quot;MD4(abcd): %s\n&quot;, toHex(Digest).c_str()); return 0; } return -1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T21:37:43.817", "Id": "491178", "Score": "0", "body": "I don't have much to add to the fine reviews, but I'd make sure that your comparators are time-constant. This is a security requirement for some usages of hash algorithms and certainly HMAC." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:24:22.150", "Id": "491339", "Score": "0", "body": "@MaartenBodewes I have implemented HMAC and pushed through github now." } ]
[ { "body": "<h2>General Observations</h2>\n<p>Nice job. I think it was a good decision to create the <code>chash</code> namespace, although I might have used <code>CHash</code> instead of <code>chash</code>.</p>\n<p>A lot of this code looks a lot more like the C programming language that the C++ programming language. Prefer <code>std::cout</code> instead of <code>printf()</code>. When using standard C header files, instead of <code>#include &lt;stdint.h&gt;</code> use <code>#include &lt;cstdint&gt;</code>, all of the standard C header files are prefaced with <code>c</code> in C++.</p>\n<h2>Example Usage</h2>\n<p>The <code>main()</code> function provided does not include any <code>#include</code> statements or <code>using namespace chash;</code> statements, however, in Visual Studio 2019 professional it doesn't compile without these.</p>\n<p>For the <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">same reason that <code>using namespace std;</code></a> is discouraged a <code>using namespace ...;</code> statement should be discouraged. It is much more helpful for people performing maintenance on the code if they know where a class, method, function or variable is coming from. I therefore recommend that the example be re-written as:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cstdlib&gt;\n#include &quot;chash.hpp&quot;\n\nint main()\n{\n chash::TAlgorithm&lt;chash::EAlgorithm::MD4&gt; MD4;\n\n chash::CDigest Digest;\n\n if (MD4.init()) {\n MD4.update((uint8_t*)&quot;abcd&quot;, 4);\n MD4.finalize(Digest);\n\n std::cout &lt;&lt; &quot;MD4(abcd): &quot; &lt;&lt; chash::toHex(Digest) &lt;&lt; &quot;\\n&quot;;\n return EXIT_SUCCESS;\n }\n\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>In most C++ compilers on most operating systems <code>main()</code> should return 0 for success or 1 for failure, this example is using <code>-1</code> for failure. Rather than hard code numbers use the system defined symbolic constants <a href=\"https://stackoverflow.com/questions/8867871/should-i-return-exit-success-or-0-from-main\">EXIT_SUCCESS and EXIT_FAILURE</a> that are supplied in the C standard header file <code>cstdlib</code> (stdlib.h).</p>\n<p><em>Note, by replacing printf() with std::cout the statement is simplified because std::string::c_str does not need to be access, std::string has an override for the operator <code>&lt;&lt;</code>.</em></p>\n<h2>Macros.h</h2>\n<p>This header file is essentially a wrapper for <code>stdint.h</code>, it would be better to just <code>#include &lt;cstdint&gt;</code> anywhere that Macros.h is currently included.</p>\n<h2>Obsolete Usage</h2>\n<p>For modern C++ compilers the keyword <code>inline</code> provides only a recommendation to the compiler to inline the function, thus rendering the keyword <code>inline</code> obsolete. When C++ is compiled with the optimization flag -O3 the compiler itself will decided whether a function should be in lined or not based on several factors.</p>\n<h2>Prefer C++ Constants, Lambda Functions and Member Functions Over <code>#define</code> Macros</h2>\n<p>The use of C type macros is discouraged in C++, one of the reasons being that macros are not type safe, another is that multi-line macros are very hard to debug. There are several C++ constructs to replace macros, the original was the <code>inline</code> function, however, Lambda Functions or Expressions, regular functions and C++ style constants have all been created to replace the C style macro definition in C++, and these are all type safe.</p>\n<p>In the file <code>CMD5.cpp</code> the first 46 lines of code contains more than 40 lines of macro definitions, these should be replaced with more modern C++ constructs.</p>\n<pre><code>static const int S11 = 7; // or unsigned, size_t, uint8_t etc. rather than int. \n</code></pre>\n<p>The macro ROTATE_LEFT could be defined as a private function in the class <code>CMD5</code>.</p>\n<p>It isn't clear what the macros <code>F()</code>, <code>G()</code>, <code>H()</code>, and <code>I()</code> are doing so meaningful names might be better, the same could possibly be said for the macros <code>FF()</code>, <code>GG()</code>, <code>HH()</code> and <code>II()</code>.</p>\n<h2>Common Programming Conventions</h2>\n<p>This isn't a rule, but it is generally followed, since most code is written by teams of developers, in class declarations put public variables and methods at the top so that they can be easily found by other members of the team using the code. It is better to have one public block and one private block (at least in C++).</p>\n<h2>One Variable Declaration Per Line with Initialization</h2>\n<p>In both the C programming language and the C++ programming language it is best to initialize local variables when they are declared. To ease modification (maintain the code) each declaration and initialization should be on one line.</p>\n<p>Let's say that I need to modify the second line of this code from <code>CMD5.cpp</code>:</p>\n<pre><code> void CMD5::transform(const uint32_t* data) {\n uint32_t a = _state[0], b = _state[1], c = _state[2], d = _state[3];\n</code></pre>\n<p>It is going to be more difficult to add or remove a declaration than if the code looked like this:</p>\n<pre><code> void CMD5::transform(const uint32_t* data) {\n uint32_t a = _state[0];\n uint32_t b = _state[1];\n uint32_t c = _state[2];\n uint32_t d = _state[3];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T15:21:56.370", "Id": "250187", "ParentId": "250172", "Score": "5" } }, { "body": "<h1>Keep it simple</h1>\n<p>I think you are focusing too much on creating a generic framework, and you lost sight of how you actually want to use your hash functions. As a <em>user</em> of your library, I just want to calculate the hash of some blob of data, I don't want to be bothered with what kind of class hierarchy you use. I don't want to write this line:</p>\n<pre><code>TAlgorithm&lt;EAlgorithm::MD4&gt; MD4;\n</code></pre>\n<p>Instead I want to write this line:</p>\n<pre><code>CMD4 MD4;\n</code></pre>\n<p>It gives me exactly what I want, with less typing and without the overhead of dynamically allocation. There is no reason at all to use the template <code>TAlgorithm</code>.</p>\n<h1>Run-time algorithm selection</h1>\n<p>In most cases, you know which hash function you need, so you can immediately use the class that actually implements it. And in this case, you don't need those classes to inherit from <code>IAlgorithm</code> at all. The only time it is necessary is if you don't know at compile-time what algorithm to use, but when that is something you only know at run-time. In the latter case, I need a function to instantiate an object of the right type for me, and then I would want to write something like:</p>\n<pre><code>EAlgorithm algo = ...; // determined at run-time\nauto hash = createAlgorithm(algo_name);\n\nhash.update(...);\nauto digest = hash.finalize();\n</code></pre>\n<h1>Use <code>std::unique_ptr</code> to manage resources</h1>\n<p>Avoid raw <code>new</code> and <code>delete</code> in your code, and prefer to use some type that makes resource management automatic, like <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a>. For example, <code>createAlgorithm()</code> should return a <code>std::unique_ptr&lt;IAlgorithm&gt;</code>.</p>\n<h1>Don't overload operators for <code>std::vector</code></h1>\n<p>The class <code>CDigest</code> is now just an alias for <code>std::vector&lt;uint8_t&gt;</code>. The latter already has <a href=\"https://en.cppreference.com/w/cpp/container/vector/operator_cmp\" rel=\"nofollow noreferrer\">operator overloads</a> that do exactly what you want, so don't reimplement them.</p>\n<h1>Prevent being able to instantiate an invalid <code>IAlgorithm</code></h1>\n<p>Your constructor for <code>TAlgorithm()</code> allows creating an instance with an &quot;Unknown&quot; algorithm:</p>\n<pre><code>TAlgorithm() : IAlgorithm(EAlgorithm::Unknown) {\n algorithm = createAlgorithm(Algo);\n setType(Algo);\n}\n</code></pre>\n<p>If <code>createAlgorithm()</code> fails, it returns a <code>nullptr</code>. Now all the public functions have to check whether <code>algorithm</code> is a valid pointer, and propagate an error if it is <code>nullptr</code>.</p>\n<p>It is much better to report errors as early as possible. I would just <code>throw</code> a <a href=\"https://en.cppreference.com/w/cpp/error/runtime_error\" rel=\"nofollow noreferrer\"><code>std::runtime_error</code></a> inside <code>createAlgorithm()</code>, instead of returning a <code>nullptr</code>. This in turn will cause the constructor of <code>TAlgorithm</code> to throw an error. This way, you always know that if you have an instance of <code>TAlgorithm</code>, its member variable <code>algorithm</code> is pointing to a valid algorithm, and you no longer need the error checking in the other member functions.</p>\n<p>Also, once you have that in place, you will note that there is no way <code>init()</code>, <code>update()</code> and <code>finalize()</code> can fail, so there is no need to return a <code>bool</code> indicating an error, and in fact you can have <code>finalize()</code> just <code>return</code> a <code>CDigest</code> instead of taking a reference to it as an output parameter.</p>\n<h1>Use the constructor to initialize instead of an <code>init()</code> function</h1>\n<p>In C++ it is custom to use the constructor to ensure an object is properly initialized. This avoids the need to manually call an <code>init()</code> function. If you do want to have a separate <code>init()</code> function, then at least make sure you call this function from the constructor. In <code>class CMD5</code> for example, you don't, so the following code:</p>\n<pre><code>CMD5 hash;\nhash.update(&quot;test&quot;, 4);\nauto digest = hash.finalize();\n</code></pre>\n<p>Will result in a different digest than if you do:</p>\n<pre><code>CMD5 hash;\nhash.init();\nhash.update(&quot;test&quot;, 4);\nauto digest = hash.finalize(digest);\n</code></pre>\n<p>But it's hard to spot the mistake; there is no compile-time or run-time error generated, and C++ programmers typically expect objects that have just been constructed to be in a good state.</p>\n<h1>Avoid using pre-processor macros</h1>\n<p>You are using pre-processor macros in <code>CMD5.cpp</code>. Perhaps you copied the code from an open source C implementation? If so, ensure there is proper attribution and that the license is in fact compatible with your project. In this case, there is an argument to be made for leaving the code as it is, however if you wrote this code yourself, then I would try to replace the macros with proper functions. For example, instead of:</p>\n<pre><code>#define ROTATE_LEFT(x, n) (((x) &lt;&lt; (n)) | ((x) &gt;&gt; (32-(n))))\n</code></pre>\n<p>Write:</p>\n<pre><code>static uint32_t ROTATE_LEFT(uint32_t x, uint32_t n) {\n return (x &lt;&lt; n) | (x &gt;&gt; (32 - n));\n}\n</code></pre>\n<p>Once you converted all the macros to functions and verified everything still works OK, you can search and replace all the function names with their lower case equivalents to signal that these are no longer macros.</p>\n<h1>Use default member initialization if possible</h1>\n<p>See <a href=\"https://stackoverflow.com/questions/36600187/whats-the-differences-between-member-initializer-list-and-default-member-initia\">this question</a> for more details. But in short, using this often avoids the need to write a constructor, and it especially helps if you have multiple constructors for a class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T07:31:29.213", "Id": "490856", "Score": "0", "body": "Thank you so much, and I've modified following your review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T07:55:26.557", "Id": "490857", "Score": "0", "body": "You're welcome. Feel free to create a new Code Review post with your modified code!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T15:32:23.053", "Id": "250188", "ParentId": "250172", "Score": "7" } } ]
{ "AcceptedAnswerId": "250188", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T03:55:49.207", "Id": "250172", "Score": "4", "Tags": [ "c++" ], "Title": "Simple C++ Hash library and its abstraction, Design that seems out of focus?" }
250172
<p>Input:</p> <pre><code> Enter a decimal number: 101 </code></pre> <p>Output:</p> <pre><code> The binary number is : 1100101 </code></pre> <p>I have solved this way-&gt;</p> <pre><code>#include &lt;stdio.h&gt; int main(void){ int input=get_input(); long long complete_integer=binary_conversion(input); reverse_digits(complete_integer); } int get_input() { int number = 0; printf(&quot;Enter a decimal number: &quot;); scanf(&quot;%d&quot;,&amp;number); return number; } int binary_conversion(int number) { long long complete_integer = 0; int base=2; while (number != 0) { //Take the last digit from the integer and push the digit back of complete integer complete_integer = complete_integer * 10 + number%base; number /= base; } printf(&quot;Completed integer number : %d\n&quot;,complete_integer); return complete_integer; } int reverse_digits(long long complete_integer) { int binary = complete_integer; int last_digit = 0; while(binary != 0) { last_digit = last_digit * 10 + binary % 10; binary /= 10; } printf(&quot;The binary number is: %d&quot;,last_digit); } </code></pre> <p>I am here for: What about my comments and indentations? Will I face any problem for some conditions? Would you propose a better simplification by using my program?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T14:22:37.170", "Id": "490792", "Score": "0", "body": "You can check it now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T04:07:04.107", "Id": "490843", "Score": "0", "body": "You should indent your code, it makes it much more readable and emphasizes its structure. Unindented code can quickly become unmaintainble." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:24:59.800", "Id": "490859", "Score": "0", "body": "I understand. Thank you sir." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T09:08:58.687", "Id": "490869", "Score": "0", "body": "I am sorry for making a reply delay in all your answer." } ]
[ { "body": "<p>There is no indentation except in the function <code>revers_digits()</code>. The indentation within that function is fine, you should correct the rest of the program because it is basically unreadable.</p>\n<p>While this may compile in a free online compiler, the code is broken for 2 reasons. The first is that in a one file program such as this one for the C programming language <code>main()</code> should be the last function in the file so that all of the other functions are defined previously. There is a workaround for this using function prototypes.</p>\n<p>The second reason the code is broken is that <code>binary_conversion(int number,int value)</code> is declared with 2 variables, but is only called with one (remove value since it doesn't seem to be necessary).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:42:38.717", "Id": "490863", "Score": "0", "body": "(remove value since it doesn't seem to be necessary). I removed it. Thank you for your help to get the wrong of mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:43:52.037", "Id": "490864", "Score": "0", "body": "main() should be the last function in the file so that all of the other functions are defined previously Why?. Whatever I did in my program. It works fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T09:21:28.200", "Id": "490873", "Score": "0", "body": "Thank you for your established information. Keep up the good work." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T12:31:31.857", "Id": "250181", "ParentId": "250175", "Score": "6" } }, { "body": "<p><strong>Repeating short comings</strong></p>\n<p><a href=\"https://codereview.stackexchange.com/a/249956/29485\">The indentation of your post is very bad (and others)</a> of previous post with scant improvement here.</p>\n<p><strong>Omitting #1 productivity step</strong></p>\n<p>Turn on all warnings.</p>\n<p>Below code suffers from mis-match of specifier and type. A good well enabled compile will warn. My compiler provided about 10 warnings. Example:</p>\n<pre><code>long long complete_integer = 0;\n...\nprintf(&quot;Completed integer number : %d\\n&quot;,complete_integer);\n// warning: format '%d' expects argument of type 'int', but argument 2 has type 'long long int' [-Wformat=]\n</code></pre>\n<p><strong>Omitting #2 productivity step</strong></p>\n<p>Use auto-format to format code.</p>\n<p><strong>Not full range solutions</strong></p>\n<p>Both <code>binary_conversion()</code> and <code>reverse_digits()</code> fail to handle large <code>int </code> values. Code architecture needs a new approach. I recommend forming the result in a <em>string</em> or array.</p>\n<p>Code should detail expected results when <code>n</code> is negative.</p>\n<p><strong>Missing check</strong></p>\n<p>Robust code would check the result of <code>scanf(&quot;%d&quot;,&amp;number)</code> and only convert when <code>1</code>.</p>\n<p><strong>Strange output</strong></p>\n<p>Reported output is &quot;The binary number is : 1100101&quot;. I get 2 lines of output. Post true output.</p>\n<p><code>printf(&quot;Completed integer number : %d\\n&quot;,complete_integer);</code> makes more sense as the &quot;binary&quot;</p>\n<p><code>printf(&quot;The binary number is: %d&quot;,last_digit);</code> makes more sense as the\n&quot;reversed number&quot;.</p>\n<hr />\n<p>To print non-negatives in binary, a candidate simplification:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid print_binary(int n) {\n if (n &gt; 1) print_binary(n/2);\n printf(&quot;%d&quot;, n % 2);\n}\n \nint main(void) {\n print_binary(101);\n puts(&quot;&quot;);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:31:38.710", "Id": "490860", "Score": "0", "body": "I run my program on the code blocks. The compiler gives me a total of three warnings. You told me that your compiler gives a total of ten warnings. Why warning varies compiler to compiler?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:35:13.227", "Id": "490861", "Score": "0", "body": "Use auto-format to format code.\n\nI think this is not a good strategy to follow. If I can write good coding styles and formats by practicing then it would be better for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:38:02.293", "Id": "490862", "Score": "0", "body": "Reported output is \"The binary number is : 1100101\". I get 2 lines of output. Sorry for this inconvenience. I was trying to appear the first output called complete_integer for the checking purposes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T09:21:55.643", "Id": "490874", "Score": "0", "body": "Thank you for your established guidelines and information. Thank you so much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T09:10:51.200", "Id": "491317", "Score": "0", "body": "@AshifulIslamPrince \"Why warning varies compiler to compiler?\" C does not require all compilers to warn in the same way or amount. Also consider enabling more warnings. e.g. gcc: '-Wpedantic' '-Wall' '-Wextra' '-Wconversion'" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T13:12:37.057", "Id": "250183", "ParentId": "250175", "Score": "5" } }, { "body": "<h3>Indent your code!</h3>\n<p>Most of your code is completely unindented, which makes it very hard to read.</p>\n<p>While the compiler can easily scan your code and count <code>{</code> and <code>}</code> signs to tell where each function and code block begins and ends, for humans this is much more difficult and prone to mistakes. That's why it's a good idea to indent the lines inside each function and block, so that the structure of the code is apparent to a human eye.</p>\n<p>Does your code really look like something you'd want to read in six months, after you've forgotten what it looks like? If not, please make it cleaner. (If you think it is, please actually try this experiment!)</p>\n<h3>Turn on compiler warnings!</h3>\n<p><a href=\"https://tio.run/##dVPRTsIwFH3fV1xnMENBwBcT5nwx/oGJLyaktGVr6DrSdhhC@HVne9cNROhD0557zr235250TCVRedPcCkVlzTi8GMtE9Vi8RkJZKIlQybYSbLiPEBBqU9ss53aBp2SYRrJSOeBGq3IjueUuZnnOdbYUiujdglZqy7URlUpQ5USae4QvmMiFNcm50jEOWO@kEuwRUXW55BoymKbRRjtklcTvTqWBAONUlEQGzhxil8dQohxlwOLRXYtjeVtrFXhdrUvddvVG/rglsua@j@tPbvvCbMTw7CmNou9CSA5J6PvGEXyKyeSDrDnYgoMkxgIaAStdlYh16YhisKlNgWDLWRK6hmrVl@640YVe/kH3MJvCQ3jUwPeYRqGzSQbt/dD7@hbkrO8ncOcwYF8qHl2YW7D2POLToi9nk79upXcJ3DqO5sKD0p7iXWyTtjPAAHqfBHVnPUb8@iM5uQSTgmzgbmmvCaAzq0MPuHeWfbg5BU7wShjvVjw6FsCvu2lm09kPXUmSm2Y8dr9dRmfPzfjT@7OzhVD5Lw\" rel=\"nofollow noreferrer\" title=\"C (clang) – Try It Online\">Compiling your code with warnings enabled</a> (Clang with <code>-Weverything</code> and <a href=\"https://stackoverflow.com/questions/47529854/what-is-c17-and-what-changes-have-been-made-to-the-language\"><code>--std=c17</code></a>) would alert you to several serious issues in it that you should fix. These include:</p>\n<ul>\n<li>the lack of <a href=\"https://en.wikipedia.org/wiki/Function_prototype\" rel=\"nofollow noreferrer\">prototypes</a> for your helper functions,</li>\n<li>the unused <code>value</code> parameter to <code>binary_conversion</code>,</li>\n<li>the incorrect use of the <code>%d</code> format specifier instead of <code>%lld</code> for printing a <code>long long int</code> value,</li>\n<li>the fact that the return value of <code>binary_conversion</code> is truncated from a <code>long long int</code> to an <code>int</code>, and</li>\n<li>the fact that <code>reverse_digits</code> is defined to return an <code>int</code> even though it actually doesn't.</li>\n</ul>\n<p>Actually, it's quite surprising that your code even compiles and (sort of) works with all these bugs in it.</p>\n<h3>Incorrect output:</h3>\n<p>You left in the line:</p>\n<pre><code>printf(&quot;Completed integer number : %d\\n&quot;,complete_integer);\n</code></pre>\n<p>that causes your code to print something that it's not supposed to. A simple and minor issue, really, but possibly enough to fail your assignment.</p>\n<p>A bigger problem is that, because you forgot to change the return type of <code>binary_conversion</code> to <code>long long int</code>, your code will produce incorrect output for inputs larger than 1023 (= 1111111111 in binary). For example, the input 1025 causes your code to <a href=\"https://tio.run/##dVPLTsMwELznK5agohRa@pAQEiFcEH@AxAWpcm0nsXCcynaKEOqvE@yNk5bS@mDZszO769mETqkkqmjbS6GobBiHR2OZqG/Lp0goCxURKtnWgo2/IwSE2jQ2K7hd4SkZp5GsVQG40braSG65i1lecJ2thSL6a0VrteXaiFolqHIizT3CV0wUwprkWOkYO6x3UAm@EVFNteYaMpin0UY7JE/iF6fSQIBxKioiA@cBYpfHUKIcZcTiyVWHY3nbaBV4fa1T3fb1Jv64JbLhvo/zT@76wmzE8GyZRtFnKSSHJPR94Qg@xWz2Sj442JKDJMYCGgG5rivE@nREMdg0pkSw46wJ/YA6H0r33OhEL/@ga1jM4SY8auR7TKPQ2SyD7r4bfH0Ocjb0E7gPMGLvKp6cmFuw9jji06IvR5M/b6V3Cdzaj@bEg9KB4l3sknYzwAB6nwR1bz1G/PojObgEk4Js5G7poAmgM6tHd7j3lr26OQVO8EoY71Y82RfAr7ttF/Pl3Q/NJSlMO526/y6ji/t2@uYN@rKlUMUv\" rel=\"nofollow noreferrer\" title=\"C (clang) – Try It Online\">generate the nonsense output</a>:</p>\n<pre><code>The binary number is: 455665549\n</code></pre>\n<p>(Even if you did fix this bug, your code would still fail for inputs larger than about 2<sup>19</sup> − 1, since a 64-bit signed <code>long long int</code> cannot store a decimal number with more than 19 digits.)</p>\n<p>An <em>even</em> bigger problem is that your algorithm doesn't work for even numbers <em>at all!</em> For example, the input 1024 (or indeed any other power of 2) <a href=\"https://tio.run/##dVPLTsMwELznK5agohRa@hASEiFcEH@AxAWpcm0nsXCcynaKEOqvE@yNk5bS@mDZszO769mETqkkqmjbS6GobBiHR2OZqG/Lp0goCxURKtnWgo2/IwSE2jQ2K7hd4SkZp5GsVQG40braSG65i1lecJ2thSL6a0VrteXaiFolqHIizT3CV0wUwprkWOkYO6x3UAm@EVFNteYaMpin0UY7JE/iF6fSQIBxKioiA@cBYpfHUKIcZcTiyVWHY3nbaBV4fa1T3fb1Jv64JbLhvo/zT@76wmzE8GyZRtFnKSSHJPR94Qg@xWz2Sj442JKDJMYCGgG5rivE@nREMdg0pkSw46wJ/YA6H0r33OhEL/@ga1jM4SY8auR7TKPQ2SyD7r4bfH0Ocjb0E7gPMGLvKp6cmFuw9jji06IvR5M/b6V3Cdzaj@bEg9KB4l3sknYzwAB6nwR1bz1G/PojObgEk4Js5G7poAmgM6tHd7j3lr26OQVO8EoY71Y82RfAr7ttF/Pl3Q/NJSlMO526/y6ji/t2@uYN@rKlUMUv\" rel=\"nofollow noreferrer\" title=\"C (clang) – Try It Online\">causes your program to print</a>:</p>\n<pre><code>The binary number is: 1\n</code></pre>\n<p>Honestly, did you even test the code at all?</p>\n<h3>A better solution:</h3>\n<p>The computer already stores the input number read by <code>scanf</code> in binary. Instead of converting that binary number to a decimal number that <em>looks</em> the same when printed with <code>printf</code> (and reversing its decimal digits twice in the process), you should instead try to find some way of printing the bits of the binary number one by one directly.</p>\n<p>Here's a quick sketch of something that <a href=\"https://tio.run/##jVJNT8JAEL3vrxgx0DahQuFghBbjwYMHOWH0YEKWdttuLLuku8Wg4a9bp9@gHtxT@@bte29mx7f9hIoozy@58JMsYOAqHXB5FS/IOSR0gZHRCHap1FIfdgwChrdTqrkUakb2kgdYROZ6wwVND2aG39PJWoPIthuWWnNCEIEt5cIs2BZ8EsBTgBUFPBjPS6wUCs3evdAI08KLb2lS82bQsyqe8qlAWj/oDWHQ@ZSyIZi17AJ1YTAAMxOKR4IFhadVF10Pnh6WK0z6ePfSZDrNsIoZVC01MbnqErTMpu22b6tr/Kfkq2iuH4Eliv3huqys@phVgcw0yBBSfCx2gZeH59JHciT/eIDapYU3XOPEu7wOuC5MnXp@7zFPGJgFadE0jjOs/p3TQRXQyIPJHAAXRL3xHSSM4tJE8MFSqeqMv0THZ9POtB/TtCwNGr9bMBwDZmCMjZMptn5t83l@05wvP0xopHLbxr31fOc6t5/ZnqUHHWOgbw\" rel=\"nofollow noreferrer\" title=\"C (clang) – Try It Online\">should work</a>:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n\nvoid print_binary(uint32_t number) {\n uint32_t bit = (uint32_t)1 &lt;&lt; 31;\n\n while (bit &gt; number &amp;&amp; bit &gt; 1) {\n bit /= 2; // skip leading zeros\n }\n while (bit &gt; 0) {\n putchar(bit &amp; number ? '1' : '0');\n bit /= 2;\n }\n}\n</code></pre>\n<p>(Note the use of the fixed-length unsigned integer type <code>uint32_t</code> to avoid making unnecessary assumptions about the number of bits an <code>int</code> can store — which might be only 16 on some low-end non-POSIX systems — and the user of the <a href=\"https://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work\">bit shift operator</a> <code>&lt;&lt;</code> to easily calculate the constant 2<sup>31</sup>. Also, if you're not familiar with the <a href=\"https://en.wikipedia.org/wiki/Bitwise_operations_in_C#Bitwise_AND_&amp;\" rel=\"nofollow noreferrer\">bitwise AND</a> operator <code>&amp;</code> or the <a href=\"https://en.wikipedia.org/wiki/%3F:\" rel=\"nofollow noreferrer\">ternary conditional operator</a> <code>?</code>…<code>:</code>, this could be a good time learn about them.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:47:16.073", "Id": "490865", "Score": "0", "body": "Does your code really look like something you'd want to read in six months, after you've forgotten what it looks like? If not, please make it cleaner. (If you think it is, please actually try this experiment!). Would you update your answer by providing the proper indentation of my code?." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:53:25.277", "Id": "490866", "Score": "0", "body": "the unused value parameter to binary_conversion, I wrote it by mistake. Thank you for your identification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:57:09.163", "Id": "490867", "Score": "0", "body": "the incorrect use of the %d format specifier instead of %lld for printing a long long int value, I wonder why the compiler named code blocks does not generate a warning for this mistake." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:59:27.203", "Id": "490868", "Score": "0", "body": "You left in the line:\n\nprintf(\"Completed integer number : %d\\n\",complete_integer); I removed this. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T09:11:01.850", "Id": "490870", "Score": "0", "body": "A bigger problem is that, because you forgot to change the return type of binary_conversion to long long int, I keep remain this function type as the same it was. I have changed the format specifier while printing the complete_integer number. But it gives the same output as what you have mentioned above(for the input 1023)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T09:17:42.987", "Id": "490871", "Score": "0", "body": "Honestly, did you even test the code at all?. Ans: Yes Sir, I tested my code and I admitted that my program fails for some conditions as what you have mentioned cases above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T09:20:32.513", "Id": "490872", "Score": "0", "body": "Subsequently, I found a vast of information from your answer. Thank you, sir. May allah bless you. Keep up the good work." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T17:58:03.457", "Id": "250191", "ParentId": "250175", "Score": "4" } } ]
{ "AcceptedAnswerId": "250191", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T09:31:17.160", "Id": "250175", "Score": "6", "Tags": [ "c" ], "Title": "Decimal to binary transformation in c" }
250175
<p>I'm loading my game's sound effects into an array to easily pick a random one and play it. Previously, I used a switch statement to select a random sound but it looks less verbose to just pick an array key.</p> <p>Is it inefficient to use an array to store and play my sound effects? Is there a better way to do this or any improvements I can make to my implementation?</p> <pre><code>let sounds = []; function loadSounds() { const sources = ['sound1.ogg', 'sound2.ogg', 'sound3.ogg', 'sound4.ogg', 'sound5.ogg', 'sound6.ogg']; for (let i = 0; i &lt; sources.length; i++) { sounds[i] = new Audio(sources[i]); } } function playRandomSound() { const randomNumber = Math.floor(Math.random() * 6); sounds[randomNumber].play(); } </code></pre>
[]
[ { "body": "<p>An array is perfectly fine, it's what I'd prefer as well. But there are some improvements you can make:</p>\n<ul>\n<li><p>When you have an array and you want to create a new array by transforming every item of an old array, it's most appropriate to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>Array#map</code></a>:</p>\n<pre><code>// I'd call it `filenames` and `audios`, not `sources` and `sounds`;\n// `audios` is plural of Audio and is a bit more precise\nconst audios = filenames.map(filename =&gt; new Audio(filename));\n</code></pre>\n</li>\n<li><p>If your sound files are really numeric-indexed, it would be even easier to just iterate over the <em>numbers</em> 1 to 4, rather than having to list <code>sound1.ogg</code>, <code>sound2.ogg</code>, etc.</p>\n</li>\n<li><p><a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">Always declare variables with <code>const</code></a> when possible - only use <code>let</code> when you must reassign the variable name. Using <code>const</code> makes code easier to read, when a reader can determine that the variable name won't ever be reassigned at a glance.</p>\n</li>\n<li><p>At the moment, if <code>playRandomSound</code> is called multiple times in a row, multiple sounds may be active at once, which may sound very discordant and not be desirable. In such a case, you may wish to save the <code>randomNumber</code> in a persistent outer variable so that you can call <code>.stop()</code> on the prior <code>Audio</code> before <code>.play()</code>ing another. (Or, if you want to have playing sounds overlap, your current approach is just fine)</p>\n</li>\n<li><p>If your <code>sources</code> array's length changes, you'll also need to change this section: <code>Math.floor(Math.random() * 6);</code> Better to put the array's length there instead of the 6.</p>\n</li>\n</ul>\n<pre><code>const audios = Array.from(\n { length: 6 },\n (_, i) =&gt; new Audio(`sound${i + 1}.ogg`)\n);\nfunction playRandomSound() {\n const randomNumber = Math.floor(Math.random() * audios.length);\n sounds[randomNumber].play();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T20:05:06.423", "Id": "490815", "Score": "0", "body": "Great answer. I didn't realize I could have assigned `sounds` as const in my original example because I assumed constants never change. I learnt a lot, thank you :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T13:08:49.073", "Id": "250182", "ParentId": "250177", "Score": "2" } } ]
{ "AcceptedAnswerId": "250182", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T10:25:37.630", "Id": "250177", "Score": "0", "Tags": [ "javascript" ], "Title": "Loading sound effects into an array" }
250177
<p><strong>Context.</strong> I was looking for some simple implementation of SVM with the SMO algorithm that can be used as an in-class problem together with a simple mathematical explanation of how it works. The problem is, that even simplest modifications of SMO I was able to find, e.g. <a href="http://cs229.stanford.edu/materials/smo.pdf" rel="nofollow noreferrer">Simplified SMO from Stanford CS course</a>, are still complicated enough. Moreover, mathematical formulas behind it, e.g. <a href="http://fourier.eng.hmc.edu/e176/lectures/ch9/node9.html" rel="nofollow noreferrer">this random notes on the internet</a>, are lengthy and it's easy to make an error during derivation. At the end of the day I decided to write my own implementation with my own formulas.</p> <p><strong>What help am I seeking for.</strong> Since this implementation was made from scratch with formulas derived from scratch I'm not sure if I didn't break SMO during all the simplifications. Or maybe there are some problems with all this derivation/implementation I just don't see. I have no one to ask for review, so I will highly appreciate any critical remarks/comments from community.</p> <ul> <li>I have posted implementation with some tests on <a href="https://github.com/fbeilstein/simplest_smo_ever" rel="nofollow noreferrer">GitHub</a>, implementation of bare SVM (contains approximately 30 lines of code) provided below</li> </ul> <pre class="lang-py prettyprint-override"><code>class SVM: def __init__(self, kernel='linear', C=10000.0, max_iter=100000, degree=3, gamma=1): self.kernel = {'poly' : lambda x,y: np.dot(x, y.T)**degree, 'rbf' : lambda x,y: np.exp(-gamma*np.sum((y - x[:,np.newaxis])**2, axis=-1)), 'linear': lambda x,y: np.dot(x, y.T)}[kernel] self.C = C self.max_iter = max_iter def restrict_to_square(self, t, v0, u): t = (np.clip(v0 + t*u, 0, self.C) - v0)[1]/u[1] return (np.clip(v0 + t*u, 0, self.C) - v0)[0]/u[0] def fit(self, X, y): self.X = X.copy() self.y = y * 2 - 1 self.lambdas = np.zeros_like(self.y, dtype=float) self.K = self.kernel(self.X, self.X) * self.y[:,np.newaxis] * self.y for _ in range(self.max_iter): for idxM in range(len(self.lambdas)): idxL = np.random.randint(0, len(self.lambdas)) Q = self.K[[[idxM, idxM], [idxL, idxL]], [[idxM, idxL], [idxM, idxL]]] v0 = self.lambdas[[idxM, idxL]] k0 = 1 - np.sum(self.lambdas * self.K[[idxM, idxL]], axis=1) u = np.array([-self.y[idxL], self.y[idxM]]) t_max = np.dot(k0, u) / (np.dot(np.dot(Q, u), u) + 1E-15) self.lambdas[[idxM, idxL]] = v0 + u * self.restrict_to_square(t_max, v0, u) idx, = np.nonzero(self.lambdas &gt; 1E-15) self.b = np.sum((1.0 - np.sum(self.K[idx] * self.lambdas, axis=1)) * self.y[idx]) / len(idx) def decision_function(self, X): return np.sum(self.kernel(X, self.X) * self.y * self.lambdas, axis=1) + self.b </code></pre> <ul> <li><p>It seemingly works at least in simple cases, though I didn't test it extensively <a href="https://i.stack.imgur.com/FTs2O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FTs2O.png" alt="enter image description here" /></a></p> </li> <li><p>My mathematical notes can be found on <a href="https://www.researchgate.net/publication/344460740_Yet_more_simple_SMO_algorithm" rel="nofollow noreferrer">ResearchGate</a>. They contain a detailed explanation, though fitting under two pages. The key idea is writing the dual problem Lagrangian as <span class="math-container">$$ \mathscr{L}^* =\boldsymbol{k}^T_0 \boldsymbol{v}_0 + \frac{1}{2}\boldsymbol{v}^{\,T}_0 \, \boldsymbol{Q} \, \boldsymbol{v}_0 + \text{Const}, $$</span> where <span class="math-container">$$ \begin{align} \boldsymbol{v}_0 &amp;= (\lambda_{\color{red}M}, \lambda_{\color{blue}L})^T,\\ \boldsymbol{k}_0 &amp;= \left(1 - \boldsymbol{\lambda}^T\boldsymbol{K}_{{\color{red}M}}, 1 - \boldsymbol{\lambda}^T\boldsymbol{K}_{{\color{blue}L}}\right)^T,\\ \boldsymbol{Q} &amp;= \begin{pmatrix} K_{{\color{red}M},{\color{red}M}} &amp; K_{{\color{red}M},{\color{blue}L}} \\ K_{{\color{blue}L},{\color{red}M}} &amp; K_{{\color{blue}L},{\color{blue}L}} \\ \end{pmatrix}. \end{align} $$</span></p> </li> </ul> <p><span class="math-container">\$\lambda_{\color{red}M}\$</span> and <span class="math-container">\$\lambda_{\color{blue}L}\$</span> are dual variables we aim to minimize at current iteration of SMO, <span class="math-container">\$\boldsymbol{K}\$</span> is the matrix that comprises information on kernel function <span class="math-container">\$K\$</span> of all possible pairs of datapoints <span class="math-container">\$\boldsymbol{x}_i\$</span> and their classes <span class="math-container">\$y_i = \pm 1\$</span> <span class="math-container">\begin{equation} \boldsymbol{K} = \begin{pmatrix} y_1 y_1 K(\boldsymbol{x}_1; \boldsymbol{x}_1) &amp; \dots &amp; y_1 y_N K(\boldsymbol{x}_1; \boldsymbol{x}_N) \\ \cdots &amp; \cdots &amp; \cdots \\ y_N y_1 K(\boldsymbol{x}_N; \boldsymbol{x}_1) &amp; \dots &amp; y_N y_N K(\boldsymbol{x}_N; \boldsymbol{x}_N) \\ \end{pmatrix}. \end{equation}</span> One index at <span class="math-container">\$\boldsymbol{K}\$</span> means corresponding vector-column, two indices -- single element. Then I represent all possible new lambdas as <span class="math-container">\$\boldsymbol{v}(t) =\boldsymbol{v}_0 + t \boldsymbol{u}\$</span>, where <span class="math-container">\$ \boldsymbol{u} = (-y_{\color{blue}L}, y_{\color{red}M})^T\$</span>. Value of <span class="math-container">\$t\$</span> that maximizes Lagrangian can be found as <span class="math-container">\begin{equation} t_* = \frac{\boldsymbol{k}^T_0 \boldsymbol{u}}{\boldsymbol{u}^{\,T} \boldsymbol{Q} \boldsymbol{u}}. \end{equation}</span> I restrict it so that lambdas fit the rectangle and do update <span class="math-container">\begin{equation} (\lambda_{\color{red}M}^\text{new}, \lambda_{\color{blue}L}^\text{new})^T = \vec{v}_0 + t_*^{\text{restr}} \vec{u}. \end{equation}</span></p> <ul> <li>I will highly appreciate any critique/reviews/suggestions.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T16:04:56.383", "Id": "490798", "Score": "2", "body": "For a review of your formulas, a better place to ask is https://math.stackexchange.com/." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T18:13:07.617", "Id": "490808", "Score": "1", "body": "@G.Sliepen , I'm more concerned about general idea/algorithm than equations. Presumably, errors in formulas would have been manifested during implementation/testing. I'm seeking for someone more experienced in SVM and SMO than I am for a feedback if this is a valid modification of SMO. I would like to use this code as an in-class problem, but I'm afraid to mislead my students." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T11:21:04.797", "Id": "250178", "Score": "4", "Tags": [ "python", "mathematics", "machine-learning" ], "Title": "A Very Simple Support Vector Machine with SMO Algorithm Implementation" }
250178
<p>I wrote the below code to convert a long data frame containing start and end date <em>event spans</em> into a daily df with rows for each day:</p> <p>output:</p> <pre><code> **bene_id, day, death, hha** row 1: abc, 1 ('2018-10-01'), 0,0 row 2: abc, 2 ('2018-10-02'), 0,1 row 3: abc, 3 ('2018-10-03'), 0,0 row 4: abc, 4 ('2018-10-04'), 0,1 </code></pre> <p>I am planning to use the daily output in a Tableau viz. The below code - which does work - heavily uses date comparisons and slicing - is very, very, very slow. Are there particular functions I am using that have faster alternatives? Both the for loop and the functions are slow..</p> <pre><code>from pandas import Timestamp, Series, date_range #creates empty df for input with correct column order long = pd.DataFrame(columns={'bene_id', 'day','date'}) cols_to_order = ['bene_id', 'day','date'] new_columns = cols_to_order + (long.columns.drop(cols_to_order).tolist()) long = long[new_columns] #gets only necessary columns for processing from main data set sample=s[['bene_id','event_type','event_thru_date','look_forward_90_date','service_epi_from_date','service_epi_thru_date']] #creates the long daily table with count 1 to 90, and daily date freq for e in sample.bene_id.drop_duplicates(): temp=sample[sample['bene_id']==e] start =Timestamp(temp[temp['event_type'] =='trigger'][['event_thru_date']].iloc[0][0]) stop= temp[temp['event_type'] =='trigger'][['look_forward_90_date']]+pd.DateOffset(1) stop=Timestamp(stop.iloc[0][0]) for i,j in zip(range(1,91), Series(date_range(start,stop))): long = long.append(pd.Series([e,i,j],index=cols_to_order), ignore_index=True) #create functions to add events to daily df created above &quot;long&quot;; count first day of event span but not last date. def checkdate(row,event): temp=sample[(sample['bene_id']==row['bene_id'])&amp;(sample['event_type']==event)] temp['flag']= np.where((temp['service_epi_from_date']&lt;=row['date']) &amp;(temp['service_epi_thru_date']&gt;row['date']),1,0) daily_status =temp['flag'].sum() return daily_status def checkdeath(row,event): temp=sample[(sample['bene_id']==row['bene_id'])&amp;(sample['event_type']==event)] temp['flag']= np.where(temp['service_epi_from_date']&lt;=row['date'],1,0) daily_status =temp['flag'].sum() return daily_status #apply functions referencing events in original sample df long['death']=long.apply(checkdeath, axis=1, args=('death',)) long['hha']=long.apply(checkdate, axis=1, args=('hha',)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-15T18:35:57.797", "Id": "493161", "Score": "0", "body": "Please [edit] your title so that it *states the purpose of your code** and not what you expect in the review, that belongs in the body." } ]
[ { "body": "<p>There are a few small niceties that you can add.</p>\n<pre><code>long = pd.DataFrame(columns={'bene_id', 'day','date'})\ncols_to_order = ['bene_id', 'day','date']\n</code></pre>\n<p>should reuse the list:</p>\n<pre><code>cols_to_order = ['bene_id', 'day','date']\nlong = pd.DataFrame(columns=set(cols_to_order))\n</code></pre>\n<p>This:</p>\n<pre><code>cols_to_order + (long.columns.drop(cols_to_order).tolist())\n</code></pre>\n<p>can drop the outer parens, since <code>.</code> takes precedence over <code>+</code>.</p>\n<p><code>e</code>, <code>j</code> and <code>temp</code> need better names.</p>\n<p>This:</p>\n<pre><code>for i,j in zip(range(1,91), Series(date_range(start,stop))):\n long = long.append(pd.Series([e,i,j],index=cols_to_order), ignore_index=True)\n</code></pre>\n<p>shouldn't be a loop. There's almost certainly a way for Pandas to vectorize it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-15T18:04:22.173", "Id": "250713", "ParentId": "250184", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T13:20:19.007", "Id": "250184", "Score": "3", "Tags": [ "python", "datetime", "pandas" ], "Title": "ways to code for better speed of processing date comparisions / slicing in python" }
250184
<p>I am using the following script to read search terms from a file and then search those terms in google (each search result in it's own tab).</p> <pre><code>from selenium import webdriver browser = webdriver.Chrome() # first tab browser.get('https://google.com') with open(&quot;google-search-terms.adoc&quot;) as fin: for line_no, line in enumerate(fin): line = line.strip() line = line.replace(' ', '+') line = line.replace('&amp;', '%26') browser.execute_script( &quot;window.open('https://www.google.com/search?q=&quot;+line+&quot;');&quot;) </code></pre> <p>How can I make this code better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T15:19:11.073", "Id": "490794", "Score": "2", "body": "There is not much to improve here since this code is so short. On the last line I would use an F-string. If we could look at the whole program and better understand the general purpose, then maybe we could suggest a better way of doing things. Here you use enumerate but variable line_no does not seem to be used. Either it is used further in the program or it is useless. Without looking at the big picture, hard to tell. Surely, there has to be more than that and you are building a scraping tool of some sort ?" } ]
[ { "body": "<h2>Functions</h2>\n<p>Create individual smaller functions doing a single task.</p>\n<h2>Enumerations</h2>\n<p>The enumeration for file does not make sense. <code>line_no</code> servers no purpose.</p>\n<h2><code>if __name__</code> block</h2>\n<p>For scripts, it is a good practice to put your executable feature inside <a href=\"https://stackoverflow.com/q/419163/1190388\">the <code>if __name__ == &quot;__main__&quot;</code> clause</a>.</p>\n<p>A rewrite of the same code might look like:</p>\n<pre><code>from selenium import webdriver\n\nFILE_NAME = &quot;google-search-terms.adoc&quot;\n\ndef search_google(browser, term: str):\n term = term.replace(' ', '+').replace('&amp;', '%26')\n browser.execute_script(f&quot;window.open('https://www.google.com/search?q={term}');&quot;)\n\n\ndef process_file(filename: str) -&gt; str:\n with open(filename) as fin:\n for line in fin:\n yield line.strip()\n\n\ndef main():\n browser = webdriver.Chrome()\n browser.get('https://google.com')\n for search_term in process_file(FILE_NAME):\n search_google(browser, search_term)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T17:58:19.840", "Id": "250192", "ParentId": "250185", "Score": "3" } }, { "body": "<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>line = line.replace(' ', '+')\nline = line.replace('&amp;', '%26')\nbrowser.execute_script(\n &quot;window.open('https://www.google.com/search?q=&quot;+line+&quot;');&quot;)\n</code></pre>\n</blockquote>\n<p>You can instead use <a href=\"https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode\" rel=\"nofollow noreferrer\"><code>urllib.parse.urlencode</code></a>. This has the benefit of correctly escaping everything, for example you don't escape <code>=</code> to <code>%3D</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import urllib.parse\n\n\ndef search_google(browser, term: str):\n query = urllib.parse.urlencode({'q': term})\n browser.execute_script(f&quot;window.open('https://www.google.com/search?{query}');&quot;)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; import urllib.parse\n&gt;&gt;&gt; urllib.parse.urlencode({'q': 'hello world &amp;=#$!?'})\n'q=hello+world+%26%3D%23%24%21%3F'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T18:16:31.157", "Id": "250193", "ParentId": "250185", "Score": "3" } } ]
{ "AcceptedAnswerId": "250192", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T13:36:51.390", "Id": "250185", "Score": "0", "Tags": [ "python", "python-3.x", "selenium" ], "Title": "open multiple tabs using selenium" }
250185
<p>The function filterList recieves an array of objects and filters the list, checking only the properties of the object specified in a 'filterFields' array.</p> <p>It compares the values of those specified properties to a string 'filterTerm' using a comparison function.</p> <p>If the property specified by 'filterFields' is an array or object, it also checks through those and returns the entire top-level object if the specified fields of any child objects are matched with the comparison function.</p> <p>I would like to check to see if this is normal/sensible javascript and whether there is a better way of writing this functionality, performance-wise.</p> <pre><code> //if filterTerm or filterFields are empty, return original list function filterList(list, filterTerm, filterFields) { if(filterTerm &amp;&amp; filterFields.length &gt; 0) { return list.filter(filterCallback(filterFields, filterTerm)); }else{ return list; } } //use closure to pass filterFields and filterTerm to callback function filterCallback(filterFields, filterTerm) { return function(element) { return filterFields.some((filterField)=&gt;{ if(Array.isArray(element[filterField])){ return element[filterField].some(function(childElement){ return filterCallback(childElement); }) }else if(typeof element[filterField] === 'object'){ return filterCallback(element[filterField]); } return comparisonFunction(element[filterField], filterTerm); }) } } //comparisonFunction - field value is populated, and either filterterm contains the fieldValue or visa-versa function comparisonFunction(fieldValue, filterTerm) { return fieldValue &amp;&amp; (String(fieldValue).toLowerCase().indexOf(filterTerm.toLowerCase()) &gt;= 0 || String(filterTerm).toLowerCase().indexOf(fieldValue.toLowerCase()) &gt;= 0); } //EXAMPLE USE: arr = [{name: &quot;a&quot;, job: &quot;b&quot;}, {name:&quot;c&quot;, job:&quot;d&quot;}]; filterList(arr, &quot;a&quot;, [&quot;name&quot;]); // =&gt; [{name: &quot;a&quot;, job:&quot;d&quot;}] arr2 = [{name: &quot;a&quot;, job: &quot;b&quot;, employees: [{name: &quot;d&quot;, job:&quot;e&quot; }]}, {name: &quot;f&quot;, job: &quot;g&quot;}]; filterList(arr2, &quot;d&quot;, [&quot;name&quot;, &quot;employees&quot;]); //=&gt; [{name: &quot;a&quot;, job:&quot;b&quot;, employees: [{name: &quot;d&quot;, job: &quot;e&quot;}]}] <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p><strong>DRY your code</strong> You reference <code>element[filterField]</code> quite a few times in <code>filterCallback</code>. It would be nicer to save the value in a standalone variable first - then you can reference that variable instead of doing object property lookup each time.</p>\n<p><strong>Nested object bug</strong> <code>filterCallback</code> returns a function, but here, if an array or object is found, you're returning a call of <code>filterCallback</code>, which will always be truthy, so the <code>.some</code> will pass, even when it shouldn't:</p>\n<pre><code>return filterFields.some((filterField) =&gt; {\n if (Array.isArray(element[filterField])) {\n return element[filterField].some(function(childElement) {\n return filterCallback(childElement); // &lt;--- always truthy\n })\n } else if (typeof element[filterField] === 'object') {\n return filterCallback(element[filterField]); // &lt;--- always truthy\n }\n return comparisonFunction(element[filterField], filterTerm); // &lt;--- OK\n})\n</code></pre>\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>// No items should pass the test, but they do:\n\n\n\n//if filterTerm or filterFields are empty, return original list\nfunction filterList(list, filterTerm, filterFields) {\n if (filterTerm &amp;&amp; filterFields.length &gt; 0) {\n return list.filter(filterCallback(filterFields, filterTerm));\n } else {\n return list;\n }\n}\n\n//use closure to pass filterFields and filterTerm to callback\nfunction filterCallback(filterFields, filterTerm) {\n return function(element) {\n return filterFields.some((filterField) =&gt; {\n if (Array.isArray(element[filterField])) {\n return element[filterField].some(function(childElement) {\n return filterCallback(childElement);\n })\n } else if (typeof element[filterField] === 'object') {\n return filterCallback(element[filterField]);\n }\n return comparisonFunction(element[filterField], filterTerm);\n })\n }\n}\n//comparisonFunction - field value is populated, and either filterterm contains the fieldValue or visa-versa\nfunction comparisonFunction(fieldValue, filterTerm) {\n return fieldValue &amp;&amp;\n (String(fieldValue).toLowerCase().indexOf(filterTerm.toLowerCase()) &gt;= 0 ||\n String(filterTerm).toLowerCase().indexOf(fieldValue.toLowerCase()) &gt;= 0);\n}\n\narr2 = [{\n name: \"a\",\n job: \"b\",\n employees: [{\n name: \"z\",\n job: \"e\"\n }]\n}, {\n name: \"f\",\n job: \"g\"\n}];\nconsole.log(filterList(arr2, \"d\", [\"name\", \"employees\"])); //=&gt; [{name: \"a\", job:\"b\", employees: [{name: \"d\", job: \"e\"}]}]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You need to call <code>filterCallback(filterFields, filterTerm)</code> first to get the filter function, then call the filter function with the value to check, eg:</p>\n<pre><code>return filterFields.some((filterField) =&gt; {\n const value = element[filterField];\n if (Array.isArray(value)) {\n return value.some(function (childElement) {\n return filterCallback(filterFields, filterTerm)(childElement);\n });\n } else if (typeof value === 'object') {\n return filterCallback(filterFields, filterTerm)(value);\n }\n return comparisonFunction(value, filterTerm); // &lt;--- OK\n});\n</code></pre>\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>//if filterTerm or filterFields are empty, return original list\nfunction filterList(list, filterTerm, filterFields) {\n if (filterTerm &amp;&amp; filterFields.length &gt; 0) {\n return list.filter(filterCallback(filterFields, filterTerm));\n } else {\n return list;\n }\n}\n\n//use closure to pass filterFields and filterTerm to callback\nfunction filterCallback(filterFields, filterTerm) {\n return function(element) {\n return filterFields.some((filterField) =&gt; {\n const value = element[filterField];\n if (Array.isArray(value)) {\n return value.some(function (childElement) {\n return filterCallback(filterFields, filterTerm)(childElement);\n });\n } else if (typeof value === 'object') {\n return filterCallback(filterFields, filterTerm)(value);\n }\n return comparisonFunction(value, filterTerm); // &lt;--- OK\n });\n }\n}\n//comparisonFunction - field value is populated, and either filterterm contains the fieldValue or visa-versa\nfunction comparisonFunction(fieldValue, filterTerm) {\n return fieldValue &amp;&amp;\n (String(fieldValue).toLowerCase().indexOf(filterTerm.toLowerCase()) &gt;= 0 ||\n String(filterTerm).toLowerCase().indexOf(fieldValue.toLowerCase()) &gt;= 0);\n}\n\n//EXAMPLE USE:\n\narr = [{\n name: \"a\",\n job: \"b\"\n}, {\n name: \"c\",\n job: \"d\"\n}];\nconsole.log(filterList(arr, \"a\", [\"name\"])); // =&gt; [{name: \"a\", job:\"d\"}]\n\n\narr2 = [{\n name: \"a\",\n job: \"b\",\n employees: [{\n name: \"z\",\n job: \"e\"\n }]\n}, {\n name: \"f\",\n job: \"g\"\n}];\nconsole.log(filterList(arr2, \"d\", [\"name\", \"employees\"])); //=&gt; [{name: \"a\", job:\"b\", employees: [{name: \"d\", job: \"e\"}]}]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Precise variable names</strong> To reduce bugs, best to name variables as precisely as possible - <code>filterCallback</code> isn't actually the callback used in <code>filter</code> or <code>some</code>, but it's a function which <em>creates</em> such a callback. Maybe call it <code>createFilterCallback</code> instead - that probably would've made the problem clearer at a glance.</p>\n<p><strong>Implicit return</strong> Since you're using ES6, you could consider using arrow functions too - their implicit return can make code much more concise. Less code means less surface area for bugs, and can sometimes make it easier to read.</p>\n<p><strong>comparisonFunction</strong> If you want to check whether a string includes another, in ES6, better to use <code>.includes(...)</code> than <code>.indexOf(...) &gt;= 0</code>. You also have a potential bug - you do <code>String(fieldValue).toLowerCase()</code> and <code>String(filterTerm).toLowerCase()</code>, implying that you expect that the value or term may not be a string - but then you do <code>.indexOf(filterTerm.toLowerCase())</code> and <code>.indexOf(fieldValue.toLowerCase())</code>, which will throw if they aren't strings. Make sure to convert them to strings first:</p>\n<pre><code>const comparisonFunction = (fieldValue, filterTerm) =&gt; {\n const value = String(fieldValue).toLowerCase();\n const term = String(filterTerm).toLowerCase();\n return value &amp;&amp; value.includes(term) || term.includes(value);\n};\n</code></pre>\n<p><strong><code>null</code> is an object too</strong>, unfortunately, so:</p>\n<pre><code>}else if(typeof element[filterField] === 'object'){\n return filterCallback(element[filterField]);\n}\n</code></pre>\n<p>will result in a recursive call, even when such a call won't make sense. The code <em>works</em>, but it's confusing flow. Better to only recurse if the value is an object <em>and</em> is not null.</p>\n<p><strong>filterCallback</strong> The whole <code>filterCallback</code> looks a bit ugly IMO. I'd simplify it a bit by not calling the whole function again recursively, but by declaring the function to filter elements by inside the function before returning it. Then, instead of recursing on <code>filterCallback</code>, recurse on that declared function:</p>\n<pre><code>const filterCallback = (filterFields, filterTerm) =&gt; {\n const testElement = element =&gt; filterFields.some((filterField) =&gt; {\n const value = element[filterField];\n if (Array.isArray(value)) {\n return value.some(testElement);\n } else if (value &amp;&amp; typeof value === 'object') {\n return testElement(value);\n } else {\n return value &amp;&amp; comparisonFunction(value, filterTerm);\n }\n });\n return testElement;\n}\n</code></pre>\n<p>In all:</p>\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>//if filterTerm or filterFields are empty, return original list\nfunction filterList(list, filterTerm, filterFields) {\n if (filterTerm &amp;&amp; filterFields.length &gt; 0) {\n return list.filter(filterCallback(filterFields, filterTerm));\n } else {\n return list;\n }\n}\n//use closure to pass filterFields and filterTerm to callback\nconst filterCallback = (filterFields, filterTerm) =&gt; {\n const testElement = element =&gt; filterFields.some((filterField) =&gt; {\n const value = element[filterField];\n if (Array.isArray(value)) {\n return value.some(testElement);\n } else if (value &amp;&amp; typeof value === 'object') {\n return testElement(value);\n } else {\n return value &amp;&amp; comparisonFunction(value, filterTerm);\n }\n });\n return testElement;\n}\n//comparisonFunction - field value is populated, and either filterterm contains the fieldValue or visa-versa\nconst comparisonFunction = (fieldValue, filterTerm) =&gt; {\n const value = String(fieldValue).toLowerCase();\n const term = String(filterTerm).toLowerCase();\n return value.includes(term) || term.includes(value);\n};\n\n//EXAMPLE USE:\narr = [{name: \"a\", job: \"b\"}, {name:\"c\", job:\"d\"}];\nconsole.log(filterList(arr, \"a\", [\"name\"])); // =&gt; [{name: \"a\", job:\"d\"}]\narr2 = [{name: \"a\", job: \"b\", employees: [{name: \"d\", job:\"e\" }]}, {name: \"f\", job: \"g\"}];\nconsole.log(filterList(arr2, \"d\", [\"name\", \"employees\"])); //=&gt; [{name: \"a\", job:\"b\", employees: [{name: \"d\", job: \"e\"}]}]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T19:01:51.560", "Id": "250196", "ParentId": "250186", "Score": "3" } } ]
{ "AcceptedAnswerId": "250196", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T13:43:07.717", "Id": "250186", "Score": "3", "Tags": [ "javascript" ], "Title": "Filter an array of objects, checking only specified properties and child objects" }
250186
<p>Please can I receive suggestions on how to improve my code. I am interested in improvements to the speed, quality and adaptability.</p> <pre><code>import random import time global fs fs = 0 hs = &quot;Heads&quot; ts = &quot;Tails&quot; hs_a_ts = [(hs), (ts)] def coinflip(): while input(&quot;To flip a coin input [Y/N]:&quot;) == &quot;y&quot;: print(random.choice(hs_a_ts)) time.sleep(.5) global fs fs += 1 else: print(&quot;You flipped the coin&quot;,fs,&quot;times.&quot;) print(&quot;Good bye&quot;) if __name__ == &quot;__main__&quot;: coinflip() </code></pre>
[]
[ { "body": "<p>Welcome to code review!</p>\n<h2>Globals</h2>\n<p>Avoid using global declarations as much as possible. This does not mean that constant values need not be global.</p>\n<h2>User input</h2>\n<p>You are asking <strong><code>To flip a coin input [Y/N]:</code></strong> from the user, but verifying that input against only <code>y</code>. If you are showing option as <code>Y</code>, I'd expect it to be valid.</p>\n<h2>Strings in list</h2>\n<p>You do not need variables <code>hs</code> and <code>ts</code> separately, if they do not serve a purpose outside of the list initialization.</p>\n<h2>f-string</h2>\n<p>Putting variables inside a string can be done with f-string in python.</p>\n<hr />\n<p>Combining the above:</p>\n<pre><code>import random\nimport time\n\nheads_and_tails = &quot;Heads&quot;, &quot;Tails&quot;\n\n\ndef ask_user(message):\n while True:\n choice = input(message).lower()\n if choice not in (&quot;y&quot;, &quot;n&quot;):\n print(&quot;Invalid input. Please provide one of y/Y/n/N&quot;)\n continue\n break\n return choice == &quot;y&quot;\n\n\ndef coinflip():\n flips = 0\n while ask_user(&quot;To flip a coin input [Y/N]:&quot;):\n print(random.choice(heads_and_tails))\n time.sleep(.5)\n flips += 1\n else:\n print(f&quot;You flipped the coin {flips} times.\\nGood bye!&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n coinflip()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T22:34:07.873", "Id": "490823", "Score": "1", "body": "I see you also overcame the Great Vowel Shortage Of The 60s, but you didn't mention it in your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T20:19:12.610", "Id": "250199", "ParentId": "250190", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T17:52:20.830", "Id": "250190", "Score": "3", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Beginner coinflip" }
250190
<p>For a project I'm working on, I need to calculate the age of users based on their birthday (which is a DateTime object). with a few requirements:</p> <ol> <li>the output must be in french (the entire project is in french)</li> <li>the output is needed to be all caps</li> <li>the output must follow these rules: <ul> <li>if the person is a newborn (less than 1 month old) return the age in days only</li> <li>else if the person is an young child (less than 3 years old) return the age in years and months</li> <li>else return just the years</li> </ul> </li> </ol> <p>So I wrote this CalculateAge method</p> <p>Here's the code</p> <pre class="lang-csharp prettyprint-override"><code>using System; using System.Linq; using System.Runtime.InteropServices; namespace Project.Common { public static class Utility { private const float YearDays = 365.25f; private const float MonthDays = YearDays / 12f; private const float ChildThresholdDays = MonthDays * 36f; /* ... (Other non-relevant utility methods) */ public static string CalculateAge(DateTime birthday, [Optional] DateTime current) { if (current == null || current == DateTime.MinValue) { current = DateTime.Now; } TimeSpan diff = current.Date.Subtract(birthday.Date); double days = diff.Days; // age less than zero is not accepted if (days &lt; 0) { return &quot;Date incorrecte&quot;; } // age less than 1 month if (days &lt; MonthDays) { return $&quot;{days} JOUR{(days &gt; 1 ? &quot;S&quot; : &quot;&quot;)}&quot;; } // age over 1 month but less than ChildThresholdDays if (days &gt;= MonthDays &amp;&amp; days &lt; ChildThresholdDays) { double years = Math.Floor(days / YearDays); double months = Math.Floor(days % YearDays / MonthDays); string yearsText = $&quot;{years} AN{(years &gt; 1 ? &quot;S&quot; : &quot;&quot;)}&quot;; string monthsText = $&quot;{months} MOIS&quot;; return years &gt;= 1 ? months &gt; 0 ? $&quot;{yearsText} {monthsText}&quot; : yearsText : monthsText; } // age over ChildThresholdDays or unknown (just in case) return days &gt;= ChildThresholdDays ? $&quot;{Math.Round(days / YearDays)} ANS&quot; : &quot;Inconnue&quot;; } } } </code></pre> <p>The code runs and outputs the desired values, but I want to know how can it be improved.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T10:50:30.320", "Id": "490885", "Score": "0", "body": "From what aspect do you want to improve this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T11:14:02.313", "Id": "491118", "Score": "0", "body": "I prefer [this](https://stackoverflow.com/a/1404/12888024) solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T22:50:53.380", "Id": "491183", "Score": "0", "body": "If age is not less than 1 month, why do you test if it is over 1 month? You already know that it is... same for `ChildThresholdDays`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T18:28:22.410", "Id": "250194", "Score": "3", "Tags": [ "c#", "datetime" ], "Title": "Calculate age from birthday in C#" }
250194
<p>I have a personal website that's used primarily for fun. I upload images, videos and text that I want to share. An HTML submission form accepts questions and string submissions from users, which uses a <code>phpmyadmin</code> database table for storage.</p> <p>The below snippet is my current <code>.htaccess</code> file. <a href="https://gtmetrix.com/" rel="nofollow noreferrer">https://gtmetrix.com/</a> notes that redirects are the largest culprit in slowing down my page loads, but I'm unsure of how to streamline them.</p> <pre><code>RewriteEngine On #REDIRECT TO SECURE HTTPS CONNECTION RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] #FORCE WWW TO NON-WWW RewriteCond %{HTTP_HOST} ^www.MYDOMAIN.com [NC] RewriteRule ^(.*)$ https://MYDOMAIN.com/$1 [L,R=301] #URL EXTENSION REMOVAL RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC] RewriteRule ^ /%1 [NC,L,R] RewriteCond %{REQUEST_FILENAME}.html -f RewriteRule ^ %{REQUEST_URI}.html [NC,L] #HOTLINKING PROTECTION #NOTE: having |html| and |htm| included prevented access of the site through browser search, so i removed them. RewriteCond %{HTTP_REFERER} !^https://(www\.)?MYDOMAIN\.com(/.*)*$ [NC] RewriteCond %{HTTP_REFERER} !^$ RewriteRule \.(css|flv|gif|ico|jpe|jpeg|jpg|js|mp3|mp4|php|png|pdf|swf|txt)$ - [F] #CONTENT SECURITY POLICY &lt;FilesMatch &quot;\.(html|php)$&quot;&gt; Header set Content-Security-Policy &quot;default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: 'unsafe-inline'; media-src 'self' data: 'unsafe-inline'; connect-src 'self';&quot; &lt;/FilesMatch&gt; #REDIRECT FOR DATE PAGE Redirect /date /storage/date-202010 #REDIRECT FOR HOME PAGE Redirect /home / #CUSTOM ERROR PAGES ErrorDocument 400 /allerror.php ErrorDocument 401 /allerror.php ErrorDocument 403 /allerror.php ErrorDocument 404 /allerror.php ErrorDocument 405 /allerror.php ErrorDocument 408 /allerror.php ErrorDocument 500 /allerror.php ErrorDocument 502 /allerror.php ErrorDocument 504 /allerror.php #PREVENT DIRECTORY BROWSING Options All -Indexes #FILE CACHING #cache html and htm files for one day &lt;FilesMatch &quot;\.(html|htm)$&quot;&gt; Header set Cache-Control &quot;max-age=43200&quot; &lt;/FilesMatch&gt; #cache css, javascript and text files for one week &lt;FilesMatch &quot;\.(js|css|txt)$&quot;&gt; Header set Cache-Control &quot;max-age=604800&quot; &lt;/FilesMatch&gt; #cache flash and images for one month &lt;FilesMatch &quot;\.(flv|swf|ico|gif|jpg|jpeg|mp4|png)$&quot;&gt; Header set Cache-Control &quot;max-age=2592000&quot; &lt;/FilesMatch&gt; #disable cache for script files &lt;FilesMatch &quot;\.(pl|php|cgi|spl|scgi|fcgi)$&quot;&gt; Header unset Cache-Control &lt;/FilesMatch&gt; #BLOCKS FILE TYPES FOR USERS &lt;FilesMatch &quot;\.(htaccess|htpasswd|ini|log|sh|inc|bak)$&quot;&gt; Order Allow,Deny Deny from all &lt;/FilesMatch&gt; </code></pre> <h2>UPDATE</h2> <p>I have created a new post integrating an HSTS and many of the changes that were recommended by Mr. White. The bounty has been awarded. Please direct any further feedback to the <a href="https://codereview.stackexchange.com/questions/250805/hsts-recommendations-in-htaccess">New Post</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T22:48:10.497", "Id": "491574", "Score": "1", "body": "apache 2.4 or 2.2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T14:09:31.687", "Id": "491629", "Score": "0", "body": "@hjpotter92 2.4" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-15T00:04:34.033", "Id": "493027", "Score": "3", "body": "[so] or [sf], yeah as @Emma commented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-15T15:21:46.090", "Id": "493125", "Score": "1", "body": "@Emma Guess I should have read the choices better...How can I change the bounty type? It doesn't matter to me if the help is coming from an expert or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-15T15:39:07.040", "Id": "493131", "Score": "1", "body": "I understand. I'll make a sister post on Stack Overflow directing people to this one. Thanks guys!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-17T19:01:49.083", "Id": "493425", "Score": "2", "body": "It would be better if you started a follow up question to this one if you want to post your updates. The [rules are that questions shouldn't be modified after an answer has been posted](https://codereview.stackexchange.com/help/someone-answers). You can post a follow up question by creating a new question and linking to this question in the follow up question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-17T19:21:37.050", "Id": "493427", "Score": "2", "body": "@pacmaninbw Done, the new post can be found here: https://codereview.stackexchange.com/questions/250805/hsts-recommendations-in-htaccess" } ]
[ { "body": "<blockquote>\n<p><code>https://gtmetrix.com/</code> notes that redirects are the largest culprit in slowing down my page loads</p>\n</blockquote>\n<p>gtmetrix.com's &quot;suggestion&quot; in this regard is arguably &quot;incorrect&quot; (or rather, not nearly as serious as it implies), assuming you are already consistently linking to the canonical URL<sup><b>*1</b></sup> throughout your site (and you have no other redirects in your application code). These redirects are only likely to affect a &quot;very small fraction&quot; of your site visitors on their very first visit.</p>\n<p><sup>(<b>*1</b> Canonical URL being HTTPS + non-www + no <code>.html</code> extension.)</sup></p>\n<p>You have 3 external redirects in the <code>.htaccess</code> code you posted:</p>\n<blockquote>\n<pre><code>#REDIRECT TO SECURE HTTPS CONNECTION\nRewriteCond %{HTTPS} off\nRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\n#FORCE WWW TO NON-WWW\nRewriteCond %{HTTP_HOST} ^www.example.com [NC]\nRewriteRule ^(.*)$ https://example.com/$1 [L,R=301]\n\n#URL EXTENSION REMOVAL\nRewriteCond %{THE_REQUEST} /([^.]+)\\.html [NC]\nRewriteRule ^ /%1 [NC,L,R]\n</code></pre>\n</blockquote>\n<p>If you have implemented <a href=\"https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\" rel=\"nofollow noreferrer\">HSTS</a> then you need to redirect from HTTP to HTTPS on the same host, before canonicalising the www subdomain - which is what you are doing above in the first rule. This is a requirement of HSTS and the &quot;preload list&quot;. So you cannot avoid having at least 2 redirects (worst case) in this scenario.</p>\n<p>However, if you have no intention of implementing HSTS then you can combine the first two redirects into one. Which you can do by simply reversing the order of the first two rules. For example:</p>\n<pre><code>#FORCE WWW TO NON-WWW\nRewriteCond %{HTTP_HOST} ^www\\.example\\.com [NC]\nRewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]\n\n#REDIRECT TO SECURE HTTPS CONNECTION\nRewriteCond %{HTTPS} off\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n<p>The first rule, that redirects www to non-www, also redirects to HTTPS, so there is never a need to execute the 2nd redirect as well. So, there is only ever 1 redirect to canonicalise HTTPS and non-www.</p>\n<p>I also removed the redundant capturing subpattern (ie. <code>(.*)</code>) in the &quot;HTTP to HTTPS&quot; <code>RewriteRule</code> <em>pattern</em>, since you are using the <code>REQUEST_URI</code> server variable instead. And changed the other &quot;www to non-www&quot; redirect to be consistent. Note that the <code>REQUEST_URI</code> server variable contains the full URL-path, including the slash prefix, whereas the captured backreference omits the slash prefix.</p>\n<p>The above two rules could be combined into a single (marginally more complex) rule, but there is no benefit in doing so.</p>\n<p>The rules could also be made more &quot;generic&quot;, without having to explicitly state the canonical hostname. However, how you implement this and whether this is easily possible is dependent on whether you have other subdomains or not. But again, this serves no &quot;benefit&quot;, other than being more copy/pastable. Generally, it is preferable to be explicit here - less prone to error.</p>\n<blockquote>\n<pre><code>#URL EXTENSION REMOVAL\nRewriteCond %{THE_REQUEST} /([^.]+)\\.html [NC]\nRewriteRule ^ /%1 [NC,L,R]\n</code></pre>\n</blockquote>\n<p>You can also avoid the <code>.html</code> &quot;extension removal redirect&quot; from triggering an <em>additional</em> redirect by including this redirect first (before the above two canonical redirects) and redirecting directly to HTTPS and non-www (the canonical scheme+hostname) as part of the redirect.</p>\n<p><strong>UPDATE:</strong> This should also be a 301 (permanent) redirect, not a 302 (temporary) redirect that it is currently. A 301 redirect is cached by the browser by default, so it avoids unnecessary round trips to the server. When you don't explicitly include the status code with the <code>R</code> flag, it defaults to a 302.</p>\n<p>The <code>NC</code> flag is also not required on the <code>RewriteRule</code> directive, since you are not matching anything here that is case-sensitive.</p>\n<p>This rule to remove the <code>.html</code> extension probably works OK for your URLs, however, it's not necessarily correct and could possibly be made more efficient. The reason for checking against <code>THE_REQUEST</code> server variable, as opposed to the <code>RewriteRule</code> <em>pattern</em> or <code>REQUEST_URI</code> server variable is to avoid a potential redirect loop by preventing rewritten requests from being redirected. This is because <code>THE_REQUEST</code> does not change after the request is rewritten - it contains the first line of the HTTP request headers. However, <code>THE_REQUEST</code> also contains the query string, so it's possible for a legitimate request that contains <code>.html</code> as part of the query string to be incorrectly redirected.</p>\n<p>For example, request <code>example.com/?p1=foo.html&amp;p2=bar</code> (the homepage with a query string and URL parameters containing the value <code>foo.html</code>) and this will be <em>incorrectly</em> redirected to <code>example.com/?p1=foo</code>, truncating the query string.</p>\n<p>The regex <code>/([^.]+)\\.html</code> will also fail to match any URL that contains dots as part of the URL-path in places other than the file extension. eg. A request for <code>/foo.bar.html</code> would not be redirected. Although this may be perfectly OK for the URLs on your site.</p>\n<p>To avoid these &quot;incorrect&quot; redirects you could capture the URL-path from the <code>RewriteRule</code> <em>pattern</em> instead and either use a simpler condition and check against <code>THE_REQUEST</code> (to avoid a loop) or use the <code>REDIRECT_STATUS</code> environment variable instead, which is always empty on direct requests.</p>\n<p>For example:</p>\n<pre><code>#URL EXTENSION REMOVAL\nRewriteCond %{ENV:REDIRECT_STATUS} ^$\nRewriteRule (.+)\\.html$ https://example.com/$1 [NC,R=301,L]\n</code></pre>\n<p>This captures the URL-path <em>before</em> the <code>.html</code> file extension using the <code>RewriteRule</code> <em>pattern</em> (which naturally excludes the query string). The simple condition that checks the <code>REDIRECT_STATUS</code> env var prevents a redirect loop.</p>\n<p>Bringing the above points together we have:</p>\n<pre><code>#URL EXTENSION REMOVAL\nRewriteCond %{ENV:REDIRECT_STATUS} ^$\nRewriteRule (.+)\\.html$ https://example.com/$1 [NC,R=301,L]\n\n#FORCE WWW TO NON-WWW\nRewriteCond %{HTTP_HOST} ^www\\.example\\.com [NC]\nRewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]\n\n#REDIRECT TO SECURE HTTPS CONNECTION\nRewriteCond %{HTTPS} off\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n<p>The <code>NC</code> flag was not required in the &quot;URL extension removal&quot; redirect.</p>\n<p>This now triggers at most 1 redirect regardless of whether a request comes in for HTTP, www or includes the <code>.html</code> extension. However, as noted, this is at the expense of not satisfying the requirements for HSTS.</p>\n<p>And it should be noted, that in real terms, there may not be a perceivable difference between 1, 2 or even 3 redirects here. Particularly since it will not affect the vast majority of visitors anyway.</p>\n<hr />\n<p>Additional:</p>\n<blockquote>\n<pre><code>#REDIRECT FOR DATE PAGE\nRedirect /date /storage/date-202010\n\n#REDIRECT FOR HOME PAGE\nRedirect /home /\n</code></pre>\n</blockquote>\n<p>Generally, you should avoid mixing redirects from both mod_alias (<code>Redirect</code> / <code>RedirectMatch</code>) and mod_rewrite (<code>RewriteRule</code>). The two modules run independently and at different times during the request, despite the apparent order of the directives in the <code>.htaccess</code> file. mod_rewrite runs first. So, you can get unexpected conflicts.</p>\n<p>Note also that <code>Redirect</code> is prefix-matching and everything after the match is appended on to the end of the target URL. eg. <code>/date/foo</code> would get redirected to <code>/storage/date-202010/foo</code> by the first rule. These particular redirects are also 302 (temporary) redirects. It looks like they should be 301 (permanent)?</p>\n<p>However, in this case it probably does not matter whether you use <code>Redirect</code> or <code>RewriteRule</code>, but as a general rule, if you are using mod_rewrite for some redirects, then use mod_rewrite for all redirects. For example:</p>\n<pre><code>#REDIRECT FOR DATE PAGE\nRewriteRule ^date$ /storage/date-202010 [R=301,L]\n\n#REDIRECT FOR HOME PAGE\nRewriteRule ^home$ / [R=301,L]\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>#BLOCKS FILE TYPES FOR USERS\n&lt;FilesMatch &quot;\\.(htaccess|htpasswd|ini|log|sh|inc|bak)$&quot;&gt;\nOrder Allow,Deny\nDeny from all\n&lt;/FilesMatch&gt;\n</code></pre>\n</blockquote>\n<p>You stated in comments that you are using Apache 2.4, however <code>Order</code>, <code>Allow</code> and <code>Deny</code> are Apache 2.2 directives and are formerly deprecated on Apache 2.4. They still work, but for backwards compatibility only and should be updated as soon as.</p>\n<p>Note that you need to update <em>all</em> instances on your system since the newer directives don't necessarily mix well.</p>\n<p>On Apache 2.4 you would use the <code>Require</code> directive instead:</p>\n<pre><code>#BLOCKS FILE TYPES FOR USERS\n&lt;FilesMatch &quot;\\.(ht[ap]|ini|log|sh|inc|bak)$&quot;&gt;\nRequire all denied\n&lt;/FilesMatch&gt;\n</code></pre>\n<p>Note that the Apache server config &quot;should&quot; already be blocking direct access to <code>.htaccess</code> and <code>.htpasswd</code> files, but better to be safe I guess.</p>\n<hr />\n<blockquote>\n<pre><code>ErrorDocument 500 /allerror.php\n</code></pre>\n</blockquote>\n<p>Defining the 500 <code>ErrorDocument</code> <em>late</em> in <code>.htaccess</code> is probably too late to catch most 500 (Internal Server Error) responses (that result from <em>misconfigurations</em>). There's probably not much you can do about this, but it would be preferable to define this <em>earlier</em> in the server config (or <code>&lt;VirtualHost&gt;</code> container) in order to be more &quot;useful&quot;.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-17T00:29:47.280", "Id": "493335", "Score": "2", "body": "Updated my answer to address potential issues/optimisations with the redirect that removes the \".html\" extension. (There are also potential / more serious issues with the _internal rewrite_ that appends the `.html` extension. I'll update my answer again later to address this.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-17T19:15:50.457", "Id": "493426", "Score": "0", "body": "I've created a new post integrating many of your changes and HSTS, and would appreciate any further recommendations you may have being directed to there." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-15T16:17:03.650", "Id": "250710", "ParentId": "250195", "Score": "3" } } ]
{ "AcceptedAnswerId": "250710", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T18:30:37.923", "Id": "250195", "Score": "4", "Tags": [ "security", "error-handling", "cache", ".htaccess", "https" ], "Title": ".htaccess Recommendations" }
250195
<p>I am learning C# and in the process I am trying to implement a multi producer consumer thread safe class. Can you please code review and point me to any mistakes I have made and improvements I can make? I understand there would be libraries and other thread safe queue objects which would provide me the functionality which I am trying to implement, but the very reason I am doing this myself is to learn how threads and thread safe queues are coded and managed. My idea is to achieve maybe an under-optimized but correctly working code.</p> <pre><code>//simple thread safe many producer many consumer class class ProducerConsumer&lt;Task&gt; { public delegate void ConsumerCallback(Task t); protected bool keepRunning = false; protected Queue&lt;Task&gt; taskQueue = null; protected Thread[] consumerThreads = null; protected ConsumerCallback clientConsumerMethodCB = null; public ProducerConsumer(ConsumerCallback clientConsumerMethod, int consumerThreadsCount) { keepRunning = true; consumerThreads = new Thread[consumerThreadsCount]; for (int i = 0; i &lt; consumerThreadsCount; i++) { consumerThreads[i] = new Thread(ConsumerThreadFunction); } for (int i = 0; i &lt; consumerThreadsCount; i++) { consumerThreads[i].Start(); } taskQueue = new Queue&lt;Task&gt;(); clientConsumerMethodCB = clientConsumerMethod; } public void Produce(Task t) { lock (taskQueue) { taskQueue.Enqueue(t); } Monitor.PulseAll(taskQueue); } protected void ConsumerThreadFunction() { Queue&lt;Task&gt; holdTaskQueueItem = new Queue&lt;Task&gt;(); while (keepRunning) { while (taskQueue.Count &lt;= 0) { Monitor.Wait(taskQueue); } lock (taskQueue) { if(taskQueue.Count &gt; 0) { holdTaskQueueItem.Enqueue(taskQueue.Dequeue()); } } if(holdTaskQueueItem.Count &gt; 0) { clientConsumerMethodCB?.Invoke(holdTaskQueueItem.Dequeue()); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:04:51.667", "Id": "491111", "Score": "0", "body": "Why not [`BlockingCollection`](https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.blockingcollection-1?view=netframework-4.8)? What is `ConsumerCallback`, why not `Action<T>`? Also consider TAP - [Asynchronous Programming](https://docs.microsoft.com/en-us/dotnet/csharp/async). Is there some usage example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:10:47.977", "Id": "491112", "Score": "0", "body": "What is `Task`? Consider naming conflict with very popular `System.Threading.Tasks.Task`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:25:06.920", "Id": "491114", "Score": "0", "body": "And finally, the cutting-edge-technology - [`System.Threading.Channels`](https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T17:14:49.690", "Id": "491155", "Score": "0", "body": "@aepot - thanks for your code review comments. I did not use any of the existing libraries or constructs for 2 reasons. I wanted a very simple solution and since I am new to C# wanted to implement simple producer consumer for understanding how such code is written and managed. I mentioned the same reason in my comment above the code. I will change the name Task to something else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T17:18:53.710", "Id": "491156", "Score": "0", "body": "Anyway, consider `BlockingCollection`, it's the easiest way to achieve the same thing but with less lines of code. I can make some example if you need. But can you fix the `Task` first e.g. with `Job`? You may add the fixed code to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T20:57:48.273", "Id": "491469", "Score": "0", "body": "@aepot - Thanks for your comments. I have updated the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T21:53:47.797", "Id": "491475", "Score": "0", "body": "`~ProducerConsumer()` - you need no finalizer here, it's not guaranteed to call by GC. Implement [`IDisposable`](https://docs.microsoft.com/en-us/dotnet/api/system.idisposable?view=netframework-4.8) instead. `false == allTasksDone` replace with `!allTasksDone`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T00:00:11.367", "Id": "491579", "Score": "0", "body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)" } ]
[ { "body": "<p>You have entered in the realm of concurrency. So there will be one or more functions which are competing to be executed. In other words there is no guarantee that your code will run in parallel.</p>\n<p>If there is enough executor (CPU cores) then the runtime might schedule several threads to different cores. If there is not sufficient resource to be utilized then scheduler might use context switching.</p>\n<p>Context switching will execute one portion of T1 and then it suspends T1 in order to avoid thread starvation (a single thread consumes all the available resources, while other threads remain idle). One portion of T2 is executed then it will be suspended. Now scheduler goes back to T1 to resume (hopefully finish) its current function.</p>\n<p>These concepts are crucial to understand because these can cause strange behaviours for those that are used to program in a single threaded environment. Let me share with you a simple example:</p>\n<h3>Example</h3>\n<ol>\n<li>Let's suppose there is one item in the queue</li>\n<li>Also let's assume that there are two consumers (T1 and T2) and they are both checking queue's length before they try to dequeue</li>\n<li>So T1 and T2 are at the same line of where they are checking the queue's length</li>\n<li>Scheduler suspends T1 after it successful checked the queue length</li>\n<li>T2 dequeues the item from the queue</li>\n<li>Scheduler resumes T1, which is in that belief that the queue has an item in it (which is not true, because T2 has already dequeued that)</li>\n<li>T1 tries to dequeue item from the queue but it will fail because it could not get data from an empty queue</li>\n</ol>\n<p>The problem here is that the check and the dequeue functionalities are not treated as atomic. If they were treated as atomic then T1 could not be suspended (by the scheduler or by the GC) between the two queue method calls.</p>\n<hr />\n<p>Back to your code, there are several ways to improve it. (I'll respect your intent to learn so I will not suggest alternatives that are already done this)</p>\n<ol>\n<li>Please do not use <code>Task</code> for the generic parameter name. It is a well-known structure in the .NET world. Please prefer either <code>Job</code> or <code>Computation</code> or what so ever.</li>\n<li>As I can see you would like to use the <code>keepRunning</code> for <a href=\"http://www.albahari.com/threading/part2.aspx\" rel=\"nofollow noreferrer\">signaling</a> (either for cancellation or for completion). Unfortunately it is declared as <code>false</code> then set to <code>true</code> in the initialization phase and then it is never modified.</li>\n<li>For locking the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement#guidelines\" rel=\"nofollow noreferrer\">best practice</a> is to introduce a <code>private static readonly object lockObject = new object();</code> to avoid accidental exposure of your lock object. In your case the queue is protected, which means in a derived class it could be exposed publicly and a consumer of that derived class can add an extra lock for that. In that case the lock is out of your control.</li>\n<li>Please prefer <code>TryDequeue</code> over <code>Count</code> check and <code>Dequeue</code>.</li>\n<li>Please consider to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1\" rel=\"nofollow noreferrer\">ConcurrentQueue</a> or <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.synchronized\" rel=\"nofollow noreferrer\">Synchronized Queue</a> to avoid explicit locking.<br />\n5.1) As always measure implementations with different workloads, <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/when-to-use-a-thread-safe-collection#concurrentqueuet-vs-queuet\" rel=\"nofollow noreferrer\">ConcurrentQueue vs Queue performance</a></li>\n<li>According to my understanding <code>holdTaskQueueItem</code> will hold either one or zero item in it. A single Task or (Job/Computation) variable would be sufficient</li>\n<li>Whenever you allow to your consumer to pass any function (in your case <code>ConcumerCallback</code>) then be very-very careful. What if it runs for minutes? What if it deadlocks because it also contains a lock inside it?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T20:56:58.740", "Id": "491468", "Score": "0", "body": "Thanks for your code review comments. I have implemented some of them and have made changes to my code as well. Please check." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T21:06:59.517", "Id": "491471", "Score": "1", "body": "I believe the problem you described in your sample pseudo code will not happen in code here, since only 1 thread will have access to taskQueue object in one time. In case the thread which owns the lock is suspended, other thread will not be able to access taskQueue as the lock would still be held by first thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T07:00:36.273", "Id": "491597", "Score": "0", "body": "@anands Yes, you are right your code is not exposed to this problem because of explicit locking. I described that because I was not sure (based on the description) that it was a conscious decision or not. Most of the structures that are built to tackle SPMC problem try to use some sort of lock-free mechanism like CAS (compare-and-swap). In .NET world the `Interlocked.CompareExchange` is an example to provide low-level API for CAS." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T07:25:16.487", "Id": "250355", "ParentId": "250197", "Score": "3" } }, { "body": "<p>Not a review but my version of the same as usage example of <code>Task</code>, <code>BlockingCollection</code> and <code>IDisposable</code> implementation. It's thread-safe, thus you may create it and add jobs from multiple threads.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Consumer&lt;T&gt; : IDisposable\n{\n private readonly int _maxConcurrency;\n private readonly Action&lt;T&gt; _action;\n private readonly BlockingCollection&lt;T&gt; _jobs;\n private readonly Task _task;\n\n public Consumer(int maxConcurrency, Action&lt;T&gt; action)\n {\n _maxConcurrency = maxConcurrency;\n _action = action;\n _jobs = new BlockingCollection&lt;T&gt;();\n _task = Task.Run(RunLoop);\n }\n\n public void Enqueue(T job) // BlockingCollection is FIFO collection\n {\n if (disposed) \n throw new ObjectDisposedException(&quot;Can't add new job. Consumer was disposed.&quot;);\n _jobs.Add(job); \n }\n\n private void RunLoop()\n {\n using (SemaphoreSlim semaphore = new SemaphoreSlim(_maxConcurrency))\n {\n List&lt;Task&gt; activeTasks = new List&lt;Task&gt;();\n foreach (T job in _jobs.GetConsumingEnumerable())\n {\n semaphore.Wait();\n lock (activeTasks)\n {\n Task t = null;\n activeTasks.Add(t = Task.Run(() =&gt; \n {\n _action(job);\n lock (activeTasks)\n {\n activeTasks.Remove(t);\n }\n semaphore.Release();\n }));\n }\n }\n Task[] tasks;\n lock (activeTasks)\n {\n tasks = activeTasks.ToArray();\n }\n Task.WaitAll(tasks);\n }\n }\n\n bool disposed;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposed)\n {\n _jobs.CompleteAdding();\n if (disposing) \n {\n _task.GetAwaiter().GetResult();\n }\n disposed = true;\n }\n }\n\n ~Consumer() =&gt; Dispose(false);\n}\n</code></pre>\n<p>Usage</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Program\n{\n static void Main()\n {\n using (Consumer&lt;int&gt; consumer = new Consumer&lt;int&gt;(2, x =&gt; { Thread.Sleep(100); Console.WriteLine(x + &quot; End&quot;); }))\n {\n for (int i = 0; i &lt; 10; i++) // &lt;= Producer\n {\n Console.WriteLine(i + &quot; Start&quot;);\n consumer.Enqueue(i);\n Thread.Sleep(50);\n }\n } // &lt;= here it will synchronously wait until all jobs is done.\n Console.WriteLine(&quot;Done.&quot;);\n }\n}\n</code></pre>\n<p>Output</p>\n<pre class=\"lang-none prettyprint-override\"><code>0 Start\n1 Start\n0 End\n2 Start\n1 End\n3 Start\n2 End\n4 Start\n3 End\n5 Start\n4 End\n6 Start\n5 End\n7 Start\n6 End\n8 Start\n7 End\n9 Start\n8 End\n9 End\nDone.\n</code></pre>\n<p><em>Why there's nothing about producers inside the class?</em></p>\n<p>The application may run multiple threads with code that can add jobs to consume. So it supports any amount of producer threads. On other hand you may implement a producer class that will use the <code>Consumer</code> but here it's not a mandatory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T09:15:00.223", "Id": "532787", "Score": "0", "body": "why the semaphore?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T09:28:33.137", "Id": "532789", "Score": "1", "body": "@esskar that was a year ago. Now I can do a better implementation. But why not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T09:35:57.517", "Id": "532791", "Score": "0", "body": "The semaphore is not needed imho, as the RunLoop Method is just called once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T09:36:59.330", "Id": "532792", "Score": "1", "body": "@esskar semaphore is for inner `foreach` loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T09:38:53.267", "Id": "532793", "Score": "1", "body": "now i see it, thanks." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T00:03:28.800", "Id": "250491", "ParentId": "250197", "Score": "3" } } ]
{ "AcceptedAnswerId": "250355", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T19:27:37.963", "Id": "250197", "Score": "5", "Tags": [ "c#", "multithreading", "locking" ], "Title": "Implementing Multi Producer Multi Consumer Simple Thread Safe Class" }
250197
<p>I just wrote a little Python 3 program to spit out every possible combination of a set of 99 characters. It gets the job done, but I would be very interested in what you think of it.</p> <p>I am just a few days into Python, so I would be grateful for even seemingly obvious advice.</p> <pre><code> import sys # List of 99 characters and a blank string: lib=[&quot;&quot;,&quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;,&quot;I&quot;,&quot;J&quot;,&quot;K&quot;,&quot;L&quot;,&quot;M&quot;,&quot;N&quot;,&quot;O&quot;,&quot;P&quot;,&quot;Q&quot;,&quot;R&quot;,&quot;S&quot;,&quot;T&quot;,&quot;U&quot;,&quot;V&quot;,&quot;W&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;Z&quot;,&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;i&quot;,&quot;j&quot;,&quot;k&quot;,&quot;l&quot;,&quot;m&quot;,&quot;n&quot;,&quot;o&quot;,&quot;p&quot;,&quot;q&quot;,&quot;r&quot;,&quot;s&quot;,&quot;t&quot;,&quot;u&quot;,&quot;v&quot;,&quot;w&quot;,&quot;x&quot;,&quot;y&quot;,&quot;z&quot;,&quot;°&quot;,&quot;!&quot;,&quot;\&quot;&quot;,&quot;§&quot;,&quot;$&quot;,&quot;%&quot;,&quot;&amp;&quot;,&quot;/&quot;,&quot;(&quot;,&quot;)&quot;,&quot;=&quot;,&quot;ß&quot;,&quot;´&quot;,&quot;`&quot;,&quot;+&quot;,&quot;#&quot;,&quot;-&quot;,&quot;.&quot;,&quot;,&quot;,&quot;&gt;&quot;,&quot;&lt;&quot;,&quot;@&quot;,&quot;€&quot;,&quot;|&quot;,&quot;^&quot;,&quot;~&quot;,&quot;–&quot;,&quot;{&quot;,&quot;[&quot;,&quot;]&quot;,&quot;}&quot;,&quot;Ä&quot;,&quot;Ö&quot;,&quot;Ü&quot;,&quot;ä&quot;,&quot;ö&quot;,&quot;ü&quot;] # 10 counters for up to 10-digit-combinations: counter0=-1 counter1=0 counter2=0 counter3=0 counter4=0 counter5=0 counter6=0 counter7=0 counter8=0 counter9=0 # Repetitive if-statements adding to the counters: for i in range(sys.maxsize**99999): counter0+=1 if counter0&gt;99: counter0=counter0*0 counter1+=1 elif counter1&gt;99: counter1=counter1*0 counter2+=1 elif counter2&gt;99: counter2=counter2*0 counter3+=1 elif counter3&gt;99: counter3=counter3*0 counter4+=1 elif counter4&gt;99: counter4=counter4*0 counter5+=1 elif counter5&gt;99: counter5=counter5*0 counter6+=1 elif counter6&gt;99: counter6=counter6*0 counter7+=1 elif counter7&gt;99: counter7=counter7*0 counter8+=1 elif counter8&gt;99: counter8=counter8*0 counter9+=1 elif counter9&gt;99: print(&quot;DONE.&quot;) # Printing the translation from counters to character - and deleting the former output so it stays in one line: else: print(lib[counter0]+lib[counter1]+lib[counter2]+lib[counter3]+lib[counter4]+lib[counter5]+lib[counter6]+lib[counter7]+lib[counter8]+lib[counter9], end=&quot;\r&quot;) sys.stdout.write(&quot;\b&quot;*10+&quot; &quot;*10+&quot;\b&quot;*10) </code></pre>
[]
[ { "body": "<ul>\n<li><p>We can convert a plain string to a list rather than maintain a list for the characters.</p>\n<p>It is far easier to modify and read the following then a list.</p>\n<pre class=\"lang-py prettyprint-override\"><code>lib = [''] + list('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!&quot;§$%&amp;/()=ß´`+#-.,&gt;&lt;@€|^~–{[]}ÄÖÜäöü')\n</code></pre>\n</li>\n<li><p>When we have <code>counter0</code>, <code>counter1</code>, ..., <code>countern</code> it's a hint that we should use a list.</p>\n<pre class=\"lang-py prettyprint-override\"><code>counters = [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n</code></pre>\n<p>We can then use <code>counters[0]</code> as a drop in replacement for <code>counter0</code>.</p>\n</li>\n<li><p>Now that we have <code>counters</code> which is a list we can simplify your print from the following.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>print(lib[counters[0]] + lib[counters[1]] + lib[counters[2]] + lib[counters[3]] + &gt; lib[counters[4]] + lib[counters[5]] + lib[counters[6]] + lib[counters[7]] + lib[counters[8]] + lib[counters[9]], end=&quot;\\r&quot;)\n</code></pre>\n</blockquote>\n<p>We can use a for loop to loop through counters, index <code>lib</code> and print the character. We'll use <code>end=&quot;&quot;</code> to get the same format that you have. Since we've changed from <code>&quot;\\r&quot;</code> to <code>&quot;&quot;</code> we'll need to print that afterwards.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for counter in counters:\n print(lib[counter], end=&quot;&quot;)\nprint(end=&quot;\\r&quot;)\n</code></pre>\n</li>\n<li><p>It would be better to use <code>len(lib)</code> rather than hard coding <code>99</code> in your ifs. If we change the content of <code>lib</code> it's much easier to edit just <code>lib</code> rather than <code>lib</code> and 10 99's.</p>\n</li>\n<li><p>Rather than <code>counter0=counter0*0</code> it would make more sense to remove the multiplication and just set the value to 0.</p>\n<pre class=\"lang-py prettyprint-override\"><code>counter0 = 0\n</code></pre>\n</li>\n<li><p>It's convention in Python to put a space either side of operators. This means <code>a+b</code> should instead be <code>a + b</code>. This is as it makes it easier to see what is and is not an operator and either side of an operator.</p>\n</li>\n<li><p>It's convention in Python to use <code>_</code> as a 'throw away' variable. This means it's normal to use <code>_</code> rather than <code>i</code> in your for loop.</p>\n</li>\n</ul>\n<p>Together this gets:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\n\nlib = [''] + list('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!&quot;§$%&amp;/()=ß´`+#-.,&gt;&lt;@€|^~–{[]}ÄÖÜäöü')\ncounters = [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nfor _ in range(sys.maxsize**99999):\n counters[0] += 1\n if counters[0] &gt;= len(lib):\n counters[0] = 0\n counters[1] += 1\n elif counters[1] &gt;= len(lib):\n counters[1] = 0\n counters[2] += 1\n elif counters[2] &gt;= len(lib):\n counters[2] = 0\n counters[3] += 1\n elif counters[3] &gt;= len(lib):\n counters[3] = 0\n counters[4] += 1\n elif counters[4] &gt;= len(lib):\n counters[4] = 0\n counters[5] += 1\n elif counters[5] &gt;= len(lib):\n counters[5] = 0\n counters[6] += 1\n elif counters[6] &gt;= len(lib):\n counters[6] = 0\n counters[7] += 1\n elif counters[7] &gt;= len(lib):\n counters[7] = 0\n counters[8] += 1\n elif counters[8] &gt;= len(lib):\n counters[8] = 0\n counters[9] += 1\n elif counters[9] &gt;= len(lib):\n print(&quot;DONE.&quot;)\n else:\n for counter in counters:\n print(lib[counter], end=&quot;&quot;)\n print(end=&quot;\\r&quot;)\n sys.stdout.write(&quot;\\b&quot;*10 + &quot; &quot;*10 + &quot;\\b&quot;*10)\n</code></pre>\n<p>There are still some changes that we can make to your code to make it easier to work with.\nThese are a bit more advanced so don't worry if you don't get them straight away.</p>\n<ul>\n<li><p>We can change your big <code>if</code> <code>elif</code> block into a single <code>for</code> loop.<br />\nLets see what we have so far:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>if counters[0] &gt; len(lib):\n counters[0] = 0\n counters[1] += 1\n</code></pre>\n</blockquote>\n<p>We know that this section is repeated each time for each index.\nSo we can make this generic by changing <code>0</code> to <code>index</code> and <code>1</code> to <code>index + 1</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if counters[index] &gt;= len(lib):\n counters[index] = 0\n counters[index + 1] += 1\n</code></pre>\n<p>Now we just need to loop over <code>range(len(counters) - 1)</code> to duplicate the block 9 times.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for index in range(len(counters) - 1):\n if counters[index] &gt;= len(lib):\n counters[index] = 0\n counters[index + 1] += 1\n</code></pre>\n</li>\n<li><p>We can use some Python sugar to make your print for loop 'cleaner'.\nFirstly we can remove all the <code>print</code>s by building a list.</p>\n<pre class=\"lang-py prettyprint-override\"><code>combination = []\nfor counter in counters:\n combination.append(lib[counter])\n</code></pre>\n<p>From here we can join all the strings together with <code>&quot;&quot;.join</code> and pass it to <code>print</code> like you did before. This will join the list by empty strings so it converts it's like manually doing <code>combination[0] + combination[1] + ...</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(&quot;&quot;.join(combination), end=&quot;\\r&quot;)\n</code></pre>\n<p>We can then use a list comprehension to build <code>combination</code> in one line.\nThis is just syntaxtic sugar and is the same as the for loop we used before.\nIt's just different, cleaner, syntax.</p>\n<pre class=\"lang-py prettyprint-override\"><code>combination = [lib[counter] for counter in counters]\n</code></pre>\n</li>\n<li><p>We can use either a <code>while True</code> loop or <code>itertools.count</code> rather than <code>range(sys.maxsize**99999)</code> to loop infinitely.</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n counters[0] += 1\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\nfor _ in range(itertools.count()):\n counters[0] += 1\n</code></pre>\n</li>\n<li><p>We can probably just use <code>print</code> rather than <code>sys.stdout.write</code>.</p>\n<p>To make it so there is no newline we can pass <code>end=&quot;&quot;</code>.\nThis however doesn't flush the stream straight away, and so we need to pass <code>flush=True</code>.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>lib = [''] + list('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!&quot;§$%&amp;/()=ß´`+#-.,&gt;&lt;@€|^~–{[]}ÄÖÜäöü')\ncounters = [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nwhile True:\n counters[0] += 1\n for index in range(len(counters) - 1):\n if counters[index] &gt;= len(lib):\n counters[index] = 0\n counters[index + 1] += 1\n \n if counters[9] &gt;= len(lib):\n print(&quot;DONE.&quot;)\n else:\n print(&quot;&quot;.join([lib[counter] for counter in counters]), end=&quot;\\r&quot;)\n print(&quot;\\b&quot;*10 + &quot; &quot;*10 + &quot;\\b&quot;*10, end=&quot;&quot;, flush=True)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T07:17:48.993", "Id": "490854", "Score": "1", "body": "Very nice answer! One thing I'd add, is that this kind of function seems to be much more useful as a generator. Maybe move the code into a function and a main where the desired amount of data is printed from the generator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T11:47:44.377", "Id": "490890", "Score": "2", "body": "@jaaq Thank you! I would normally agree with you 110% however I feel bringing generator functions into the mix may cause significant confusion for the OP. I know the OP wants the code to run infinitely and figuring out two things at the some time is likely to be harder than just one. (generator functions and making it run infinitely) After the OP has figured out how to make it infinite I think it would make a good follow up question where explaining generator functions would be a reasonable stepping stone in growing the OP's programming abilities. But to be clear, generators would be good here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T14:05:33.413", "Id": "490915", "Score": "1", "body": "Yeah, I agree it'd be a lot at once for someone just starting out. Just wanted to throw it out there; broaden the horizon a bit more you know :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T21:03:08.873", "Id": "490969", "Score": "1", "body": "Why have a list of single character strings, when a string is already a list of characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T21:04:18.490", "Id": "490970", "Score": "1", "body": "@Voo As in change `lib` to `'0123...'`? It's because it won't include `''`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-19T07:17:39.620", "Id": "493542", "Score": "0", "body": "Actually, the python3 [String Module](https://docs.python.org/3/library/string.html) has built-in lists that could be used to create the lib variable in a much less verbose and more maintainable way ;)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T22:24:59.493", "Id": "250204", "ParentId": "250201", "Score": "21" } }, { "body": "<p>It might be useful to know that python has some built-in options for performing combinatorics. In particular, I found the <a href=\"https://docs.python.org/3.6/library/itertools.html\" rel=\"noreferrer\">itertools</a> module very handy for these kind of operations. It might be a bit advanced when still starting with Python, but in time you'll pick up many of these useful things.</p>\n<p>For the case of bruto forcing a password, the <code>product</code> method seems ideal.</p>\n<p>For example, if you want all possible combinations with 5 digits, you can run:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import product\n\nlib = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!&quot;§$%&amp;/()=ß´`+#-.,&gt;&lt;@€|^~–{[]}ÄÖÜäöü'\nfor combination in product(lib, repeat=5):\n attempt=&quot;&quot;.join(combination) # This turns combination (a list of characters) into a string.\n # Use your password attempt here\n</code></pre>\n<p>So if you want to expand this to all number of digits up to 10, you can use:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for length in range(10):\n for combination in product(lib, repeat=length):\n attempt=&quot;&quot;.join(combination)\n # Use your password attempt here\n</code></pre>\n<hr />\n<h2>A note on using generators</h2>\n<p>One advantage of this method is that the methods from <code>itertools</code> don't store all combinations, but instead they generate them on the go. As a result, their memory usage doesn't increase with the number of combinations.</p>\n<p>This is quite important in a scenario like yours, where the amount of possible combinations has a factorial growth. <a href=\"https://realpython.com/introduction-to-python-generators/\" rel=\"noreferrer\">This article</a> gives a good introduction, with some extra use-cases.</p>\n<p>Another nice part of this is, that it's quite easy to let this code keep trying all combinations of increasing length untill something is found.</p>\n<p>This also uses the <code>count()</code> method from itertools, which is a generator that starts from a number and keeps increasing forever.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import product, count\nlib = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!&quot;§$%&amp;/()=ß´`+#-.,&gt;&lt;@€|^~–{[]}ÄÖÜäöü'\n\nfor length in count(0):\n for combination in product(lib, repeat=length):\n attempt=&quot;&quot;.join(combination)\n # Use your password attempt here\n if password_found:\n print(attempt)\n break\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T09:25:14.363", "Id": "250215", "ParentId": "250201", "Score": "10" } }, { "body": "<p>For better usability (will come in very handy in a moment), let's change your code into a generator. That's just a function that yields values one by one when requested (or rather, technically, the generator object it returns does). So the only change is that instead of printing, you <em>yield</em>:</p>\n<pre><code>def combinations():\n\n # List of 99 characters and a blank string:\n\n ...\n\n else:\n yield lib[counter0]+lib[counter1]+lib[counter2]+lib[counter3]+lib[counter4]+lib[counter5]+lib[counter6]+lib[counter7]+lib[counter8]+lib[counter9]\n</code></pre>\n<p>Now we can for example loop over its results and print them:</p>\n<pre><code>for comb in combinations():\n print(comb)\n</code></pre>\n<p>Output:</p>\n<pre><code>\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nA\nB\n...\n</code></pre>\n<p>Or we can take some to build a list:</p>\n<pre><code>from itertools import islice\n\nprint(list(islice(combinations(), 13)))\n</code></pre>\n<p>Output:</p>\n<pre><code>['', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B']\n</code></pre>\n<p>Let's watch it switch from one to two characters:</p>\n<pre><code>&gt;&gt;&gt; list(islice(combinations(), 98, 102))\n['ö', 'ü', '00', '10']\n</code></pre>\n<p>Or from two to three:</p>\n<pre><code>&gt;&gt;&gt; list(islice(combinations(), 99*100-1, 99*100+3))\n['öü', 'üü', '10', '20']\n</code></pre>\n<p>Wait what? Why is <code>'üü'</code> followed by <code>'10'</code>? Shouldn't that have come a lot <em>earlier</em>? Did we produce that twice?</p>\n<pre><code>&gt;&gt;&gt; list(islice(combinations(), 99*100+3)).count('10')\n2\n</code></pre>\n<p>Yeah we did. Oops. So there's some bug in your code. Much harder to notice in your version, btw, with all the combinations just being printed and immediately being overwritten :-)</p>\n<p>Anyway, I don't really want to dig deeper into that but show a simple alternative. Let's start from scratch. While we're at it, let's call it <a href=\"https://en.wikipedia.org/wiki/Formal_language#Words_over_an_alphabet\" rel=\"nofollow noreferrer\"><code>words</code></a> and make the alphabet a parameter. Start simple, only yield the words of lengths 0 and 1:</p>\n<pre><code>def words(alphabet):\n yield ''\n for letter in alphabet:\n yield letter\n</code></pre>\n<p>Demo:</p>\n<pre><code>&gt;&gt;&gt; list(words('abc'))\n['', 'a', 'b', 'c']\n</code></pre>\n<p>Now how to produce the longer words? Let's see what we want:</p>\n<pre><code>'' '' + ''\n'a' '' + 'a'\n'b' '' + 'b'\n'c' '' + 'c'\n'aa' 'a' + 'a'\n'ab' 'a' + 'b'\n'ac' 'a' + 'c'\n'ba' 'b' + 'a'\n'bb' 'b' + 'b'\n'bc' 'b' + 'c'\n'ca' 'c' + 'a'\n'cb' 'c' + 'b'\n'cc' 'c' + 'c'\n'aaa' 'aa' + 'a'\n'aab' 'aa' + 'b'\n'aac' 'aa' + 'c'\n'aba' 'ab' + 'a'\n'abb' 'ab' + 'b'\n ... ...\n</code></pre>\n<p>On the left is the words how we want them, and on the right I split them into prefix and last letter (if any). If we look at the last letter, we can see that it keeps cycling through the alphabet. All letters for each prefix. Let's pretend we had a <code>prefix</code> function that gave us the prefixes. Then we could just write our solution like this:</p>\n<pre><code>def words(alphabet):\n yield ''\n for prefix in prefixes(alphabet):\n for letter in alphabet:\n yield prefix + letter\n</code></pre>\n<p>But wait. The first prefix is <code>''</code>, then <code>'a'</code>, <code>'b'</code>, <code>'c'</code>, <code>'aa'</code>, <code>'ab'</code>, etc. So the prefix just goes through the same sequence of words that we want overall. So... our <code>words</code> function can use <em>itself</em> to produce the prefixes:</p>\n<pre><code>def words(alphabet):\n yield ''\n for prefix in words(alphabet):\n for letter in alphabet:\n yield prefix + letter\n</code></pre>\n<p>That's it. That's the whole solution.</p>\n<p>Demo:</p>\n<pre><code>&gt;&gt;&gt; list(islice(words('abc'), 20))\n['', 'a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca',\n 'cb', 'cc', 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca']\n</code></pre>\n<p>Finally let's try it with your alphabet again and see that switch from two to three letters:</p>\n<pre><code>&gt;&gt;&gt; alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!&quot;§$%&amp;/()=ß´`+#-.,&gt;&lt;@€|^~–{[]}ÄÖÜäöü'\n&gt;&gt;&gt; list(islice(words(alphabet), 99*100-1, 99*100+3))\n['üö', 'üü', '000', '001']\n</code></pre>\n<p>So... we ended up implementing the whole thing with a generator function that has just four simple lines, and it works with an arbitrary alphabet, and as generator it's easy to use in many ways.</p>\n<p>It's probably also a lot faster than yours, although because of your bug, that's not easy to benchmark properly. Peilonrayz' version also has a bug at the moment, but we can compare with Ivo_Merchiers' solution and a few variations.</p>\n<p>First ten million words using your long alphabet of 99 letters:</p>\n<pre><code>same first 9,999,999: True\nsame 10,000,000th: True {'9TT8'}\n\n1.41 1.38 1.38 seconds Stefan_Pochmann\n1.66 1.64 1.63 seconds Stefan_Pochmann_2\n2.45 2.45 2.45 seconds Ivo_Merchiers\n2.19 2.20 2.21 seconds Ivo_Merchiers_2\n1.50 1.49 1.50 seconds Ivo_Merchiers_3\n1.20 1.20 1.20 seconds Ivo_Merchiers_chain\n</code></pre>\n<p>First ten million words using alphabet <code>abc</code>:</p>\n<pre><code>same first 9,999,999: True\nsame 10,000,000th: True {'abcaccbbcccacbc'}\n\n2.49 2.43 2.48 seconds Stefan_Pochmann\n4.16 4.17 4.19 seconds Stefan_Pochmann_2\n3.91 3.91 3.93 seconds Ivo_Merchiers\n3.64 3.66 3.64 seconds Ivo_Merchiers_2\n2.74 2.74 2.75 seconds Ivo_Merchiers_3\n2.45 2.46 2.45 seconds Ivo_Merchiers_chain\n</code></pre>\n<p>Full benchmark code:</p>\n<pre><code>from itertools import product, count, islice, chain\nfrom timeit import repeat\nfrom collections import deque\n\nlib = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!&quot;§$%&amp;/()=ß´`+#-.,&gt;&lt;@€|^~–{[]}ÄÖÜäöü'\n\ndef Stefan_Pochmann(alphabet):\n yield ''\n for prefix in Stefan_Pochmann(alphabet):\n for letter in alphabet:\n yield prefix + letter\n\ndef Stefan_Pochmann_2(alphabet):\n yield ''\n for prefix in Stefan_Pochmann_2(alphabet):\n yield from map(prefix.__add__, alphabet)\n\ndef Ivo_Merchiers(lib):\n for length in count(0):\n for combination in product(lib, repeat=length):\n yield ''.join(combination)\n\ndef Ivo_Merchiers_2(lib):\n join = ''.join\n for length in count(0):\n for combination in product(lib, repeat=length):\n yield join(combination)\n\ndef Ivo_Merchiers_3(lib):\n for length in count(0):\n yield from map(''.join, product(lib, repeat=length))\n\ndef Ivo_Merchiers_chain(lib): # from Peilonrayz\n join = ''.join\n return chain.from_iterable(\n map(join, product(lib, repeat=length))\n for length in count(0)\n )\n\nsolutions = Stefan_Pochmann, Stefan_Pochmann_2, Ivo_Merchiers, Ivo_Merchiers_2, Ivo_Merchiers_3, Ivo_Merchiers_chain\n\nfor alphabet in lib, 'abc':\n print(alphabet)\n\n n = 10**7\n \n # Correctness\n sets = map(set, zip(*(words(alphabet) for words in solutions)))\n print(f'same first {n-1:,}:', all(len(s) == 1 for s in islice(sets, n - 1)))\n s = next(sets)\n print(f'same {n:,}th:', len(s) == 1, s)\n print()\n \n # Speed\n tss = [[] for _ in solutions]\n for _ in range(3):\n for words, ts in zip(solutions, tss):\n t = min(repeat(lambda: deque(islice(words(alphabet), n), 0), number=1))\n ts.append(t)\n for words, ts in zip(solutions, tss):\n print(*('%.2f' % t for t in ts), 'seconds ', words.__name__, sep=' ')\n print()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T18:07:50.220", "Id": "490934", "Score": "1", "body": "@Peilonrayz Ah, I just finished the benchmark, see the update :-). Mine's fastest, as I actually expected because my \"innermost loop\" just adds a prefix and a letter. Faster than Ivo's `join`. I didn't include yours because you have some bug. Not sure it's the same bug you're talking about. I mean that between `ü` and `00` you produce `0` again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T19:28:47.740", "Id": "490948", "Score": "1", "body": "Interesting I'm suprised at how slow `itertools` is. I even moved a lot of Ivo's code into C and it becomes only a smidge faster than yours. [Timings](https://i.stack.imgur.com/UGwNa.png) & [code](https://gist.github.com/Peilonrayz/1a08d69f3c97d7ab245aefc9e09338c6). If you want to add just your two timings here's [another picture](https://i.stack.imgur.com/b2NKE.png)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T20:48:56.853", "Id": "490964", "Score": "1", "body": "@Peilonrayz Updated. Your `chain` version is indeed the fastest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T06:21:59.403", "Id": "491003", "Score": "0", "body": "Interesting analysis, I'm also surprised by how slow the itertools code works. Also surprising to see that chain has such a significant speed impact." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T18:44:07.577", "Id": "491256", "Score": "0", "body": "Nice answer. I wanted to propose another alternative : use 100 chars, pick any number written in base 10 and convert it to base 100, which can be done really fast. Your solution is cleaner and faster." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T17:00:44.770", "Id": "250232", "ParentId": "250201", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T21:19:42.603", "Id": "250201", "Score": "11", "Tags": [ "python", "python-3.x" ], "Title": "Brute Force generator" }
250201
<p>I wrote two microservices in Springboot and tried to follow the best practices. I would appreciate any suggestions about any improvement that I can make on the whole codebase. What are the parts of the code that I can improve on the whole project?</p> <p>Project Link: <a href="https://github.com/forhadmethun/mbank" rel="nofollow noreferrer">https://github.com/forhadmethun/mbank</a></p> <p>Technology used:</p> <pre><code>Java 11+ SpringBoot JPA / Hibernate MyBatis Gradle Postgres RabbitMQ JUnit </code></pre> <p>Thank you very much.</p> <h2>Directory Structure</h2> <pre><code>. ├── main │   ├── java │   │   └── com │   │   └── forhadmethun │   │   └── accountservice │   │   ├── config │   │   │   └── RabbitMQConfiguration.java │   │   ├── controller │   │   │   ├── AccountController.java │   │   │   ├── ExceptionController.java │   │   │   ├── HealthController.java │   │   │   └── TransactionController.java │   │   ├── db │   │   │   ├── entity │   │   │   │   ├── Account.java │   │   │   │   ├── Balance.java │   │   │   │   ├── Customer.java │   │   │   │   └── Transaction.java │   │   │   ├── repository │   │   │   │   ├── AccountCommandRepository.java │   │   │   │   ├── AccountQueryRepository.java │   │   │   │   ├── BalanceCommandRepository.java │   │   │   │   ├── BalanceQueryRepository.java │   │   │   │   ├── CustomerRepository.java │   │   │   │   ├── TransactionQueryRepository.java │   │   │   │   └── TransactionRepository.java │   │   │   └── services │   │   │   ├── AccountService.java │   │   │   ├── BalanceService.java │   │   │   ├── bean │   │   │   │   ├── AccountServiceBean.java │   │   │   │   ├── BalanceServiceBean.java │   │   │   │   ├── CustomerServiceBean.java │   │   │   │   ├── MessageQueueBean.java │   │   │   │   └── TransactionServiceBean.java │   │   │   ├── CustomerService.java │   │   │   ├── MessageQueueService.java │   │   │   └── TransactionService.java │   │   ├── MbankAccountServiceApplication.java │   │   └── utility │   │   ├── constant │   │   │   └── PersistenceConstant.java │   │   ├── CurrencyUtil.java │   │   ├── dto │   │   │   ├── mapper │   │   │   │   ├── AccountMapper.java │   │   │   │   ├── BalanceMapper.java │   │   │   │   ├── CustomerMapper.java │   │   │   │   └── TransactionMapper.java │   │   │   └── model │   │   │   ├── AccountDto.java │   │   │   ├── BalanceDto.java │   │   │   ├── CustomerDto.java │   │   │   ├── DirectionOfTransaction.java │   │   │   ├── mq │   │   │   │   └── BalanceMQDto.java │   │   │   └── TransactionDto.java │   │   ├── exception │   │   │   ├── PersistenceException.java │   │   │   └── RequestException.java │   │   ├── io │   │   │   ├── AccountOperationResponse.java │   │   │   ├── ErrorResponse.java │   │   │   └── mq │   │   │   ├── AccountCreationInfo.java │   │   │   └── TransactionCreationInfo.java │   │   ├── TransactionUtil.java │   │   └── validation │   │   ├── AccountServiceValidation.java │   │   ├── ValidationImpl.java │   │   ├── Validation.java │   │   └── ValidationResult.java │   └── resources │   ├── application.properties │   ├── db │   │   └── migration │   │   └── V1__create_table.sql │   ├── static │   └── templates └── test └── java └── com └── forhadmethun └── accountservice ├── controller │   ├── AccountControllerTest.java │   └── TransactionControllerTest.java └── MbankAccountServiceApplicationTests.java </code></pre> <h2>Some of the Code(Please see the Github repo for all the files)</h2> <p>AccountController.java</p> <pre><code>package com.forhadmethun.accountservice.controller; /** * @author Md Forhad Hossain * @since 01/10/20 */ import com.forhadmethun.accountservice.db.services.AccountService; import com.forhadmethun.accountservice.db.services.CustomerService; import com.forhadmethun.accountservice.utility.CurrencyUtil; import com.forhadmethun.accountservice.utility.dto.model.CustomerDto; import com.forhadmethun.accountservice.utility.exception.PersistenceException; import com.forhadmethun.accountservice.utility.exception.RequestException; import com.forhadmethun.accountservice.utility.io.AccountOperationResponse; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @AllArgsConstructor public class AccountController { private final CustomerService customerService; private final AccountService accountService; @PostMapping(&quot;/accounts&quot;) public ResponseEntity&lt;AccountOperationResponse&gt; createAccount( @RequestBody CustomerDto customerDto ) throws RequestException { CurrencyUtil.checkCurrencyValidity(customerDto.getCurrencies()); AccountOperationResponse accountCreationResponse = customerService.createCustomer(customerDto); return new ResponseEntity&lt;&gt;(accountCreationResponse, HttpStatus.OK); } @GetMapping(&quot;/accounts/{accountId}&quot;) public ResponseEntity&lt;AccountOperationResponse&gt; getAccount( @PathVariable Long accountId ) throws PersistenceException { AccountOperationResponse accountOperationResponse = accountService.findByAccountId(accountId); return new ResponseEntity&lt;&gt;(accountOperationResponse, HttpStatus.OK); } } </code></pre> <p>AccountServiceBean.java</p> <pre><code>package com.forhadmethun.accountservice.db.services.bean; /** * @author Md Forhad Hossain * @since 01/10/20 */ import com.forhadmethun.accountservice.db.entity.Account; import com.forhadmethun.accountservice.db.entity.Balance; import com.forhadmethun.accountservice.db.repository.AccountQueryRepository; import com.forhadmethun.accountservice.db.repository.AccountCommandRepository; import com.forhadmethun.accountservice.db.repository.BalanceQueryRepository; import com.forhadmethun.accountservice.db.services.AccountService; import com.forhadmethun.accountservice.db.services.BalanceService; import com.forhadmethun.accountservice.utility.constant.PersistenceConstant; import com.forhadmethun.accountservice.utility.dto.mapper.BalanceMapper; import com.forhadmethun.accountservice.utility.dto.model.AccountDto; import com.forhadmethun.accountservice.utility.exception.PersistenceException; import com.forhadmethun.accountservice.utility.io.AccountOperationResponse; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; @AllArgsConstructor @Service public class AccountServiceBean implements AccountService { private final AccountCommandRepository accountCommandRepository; private final AccountQueryRepository accountQueryRepository; private final BalanceService balanceService; @Override public Account createAccount(Account account) { return accountCommandRepository.save(account); } @Override public AccountOperationResponse findByAccountId(Long accountId) throws PersistenceException { AccountDto account = accountQueryRepository.findByAccountId(accountId); if (account == null) throw new PersistenceException(PersistenceConstant.ACCOUNT_NOT_FOUND); List&lt;Balance&gt; balances = balanceService.findByAccountId(accountId); AccountOperationResponse accountOperationResponse = AccountOperationResponse.createAccountCreationResponse( account.getAccountId(), account.getCustomerId(), BalanceMapper.toBalanceDtoList(balances) ); return accountOperationResponse; } } </code></pre> <p>AccountControllerTest.java</p> <pre><code>package com.forhadmethun.accountservice.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.forhadmethun.accountservice.db.services.CustomerService; import com.forhadmethun.accountservice.utility.dto.model.CustomerDto; import com.forhadmethun.accountservice.utility.io.AccountOperationResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import java.math.BigDecimal; import java.util.Arrays; import static org.hamcrest.Matchers.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.junit.jupiter.api.Assertions.*; @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc class AccountControllerTest { @Autowired CustomerService customerService; @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; @Test void createAccount() throws Exception { MvcResult mockMvcResult = mockMvc.perform(MockMvcRequestBuilders .post(&quot;/accounts&quot;, 42L) .contentType(&quot;application/json&quot;) .content(objectMapper.writeValueAsString( CustomerDto.builder() .customerId(1L) .country(&quot;Bangladesh&quot;) .currencies(Arrays.asList(&quot;EUR&quot;)) .build() ))) .andExpect(status().isOk()) .andReturn(); String contentAsString = mockMvcResult.getResponse().getContentAsString(); AccountOperationResponse response = objectMapper.readValue(contentAsString, AccountOperationResponse.class); assertEquals(1L, response.getCustomerId()); assertEquals(1, response.getBalances().size()); assertEquals(&quot;EUR&quot;, response.getBalances().get(0).getCurrency()); assertEquals(BigDecimal.ZERO, response.getBalances().get(0).getBalance()); } @Test void getAccount() throws Exception { AccountOperationResponse createdAccountObject = customerService.createCustomer( CustomerDto.builder() .customerId(36L) .country(&quot;Bangladesh&quot;) .currencies(Arrays.asList(&quot;EUR&quot;)) .build() ); MvcResult mockMvcResult = mockMvc.perform(get(&quot;/accounts/&quot; + createdAccountObject.getAccountId())) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath(&quot;$.balances[0].currency&quot;, is(&quot;EUR&quot;)) ).andReturn(); String contentAsString = mockMvcResult.getResponse().getContentAsString(); AccountOperationResponse response = objectMapper.readValue(contentAsString, AccountOperationResponse.class); assertEquals(response.getAccountId(), createdAccountObject.getAccountId()); assertEquals(response.getCustomerId(), createdAccountObject.getCustomerId()); assertEquals(response.getBalances().size(), createdAccountObject.getBalances().size()); assertEquals(&quot;EUR&quot;, response.getBalances().get(0).getCurrency()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T01:25:54.950", "Id": "490836", "Score": "1", "body": "Thanks, @Emma for your valuable comment. Actually, I want the whole project review so it's tough to include all code in the question so shared the GitHub link. Actually, I gave some information about the deployment also in the README.md file of the git. Can you check if you get the idea that how to deploy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:33:41.413", "Id": "490910", "Score": "1", "body": "Thanks, @Emma, I have added a few codes. Hope that I'll get some review." } ]
[ { "body": "<p>Actually I did not reviewed your code as such (as warned by @Emma). But for an &quot;architectural&quot; perspective I see some improvements. However some are more personal guts than real good practices.</p>\n<p>The first reflexion is about your the motivation between those two microservices. Why did you split reporting from anything else. Why did you group <code>Account</code>, <code>Balance</code>, <code>Customer</code> and <code>Transaction</code> in one service instead of creatiing dedicated services ?</p>\n<p>The second one is about the packaging (! Personnal feeling). Are you aware of the package by feature principle ? The idea is to regroup classes by feature instead of layers, so you will have <code>Account</code>, <code>AccountCommandRepository</code>, <code>AccountQuyeryRepository</code>, <code>AccountController</code>, <code>Customer</code>, <code>Balance</code>, <code>AccountDto</code>, ... in the same package.</p>\n<p>Another reflexion is about your choice to create a <em>command</em> and a <em>query</em> repositories. I assume taht your are trying to create a CQRS system. But there are much more behind that than two distinct classes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T13:11:12.490", "Id": "250278", "ParentId": "250202", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T21:28:16.227", "Id": "250202", "Score": "0", "Tags": [ "java", "object-oriented", "spring", "web-services", "spring-mvc" ], "Title": "Microservice in Springboot" }
250202
<p>I'm trying to solve <a href="http://usaco.org/index.php?page=viewproblem2&amp;cpid=1011" rel="nofollow noreferrer">this</a> problem with Python 3.8. In my code, I used 3 nested for loops to check every single point and storing the largest area with each set of points. This program works fine, but it's <span class="math-container">\$ O(n^3) \$</span> time complexity, and I'm wondering if there are any more elegant/efficient solutions. Is there a more efficient algorithm that doesn't loop through every single point, or is that necessary?</p> <p>My code:</p> <pre><code>with open(&quot;triangles.in&quot;, &quot;r&quot;) as file_in: lines = [x.strip() for x in file_in.readlines()] n, points = lines[0], lines[1:] def main(points): largest = 0 for corner in points: cx, cy = corner.split() for leg in points: lx, ly = leg.split() for width in points: wx, wy = width.split() if lx == cx and wy == cy: area = abs(int(ly)-int(cy)) * abs(int(wx)-int(cx)) if area &gt; largest: largest = area return str(largest) with open(&quot;triangles.out&quot;, &quot;w+&quot;) as file_out: file_out.write(main(points)) file_out.close() </code></pre> <p>The input file <code>triangles.in</code>:</p> <pre><code>4 0 0 0 1 1 0 1 2 </code></pre> <p><strong>Problem synopsis:</strong> Given a set of <span class="math-container">\$ n \$</span> distinct points <span class="math-container">\$ (X_1, Y_1) \$</span> to <span class="math-container">\$ (X_n, Y_n) \$</span>, find the largest triangle's area multiplied by 2, given that the triangle is a right triangle (one of the lines of the triangle in parallel to the x-axis, and one other parallel to the y-axis).</p>
[]
[ { "body": "<p>An obvious improvement is to not split the strings and convert the parts to <code>int</code> <em>over and over again</em>. Do it once, at the start:</p>\n<pre><code>def main(points):\n points = [tuple(map(int, point.split())) for point in points]\n largest = 0\n\n for cx, cy in points:\n for lx, ly in points:\n for wx, wy in points:\n if lx == cx and wy == cy:\n area = abs(ly-cy) * abs(wx-cx)\n if area &gt; largest:\n largest = area\n\n return str(largest)\n</code></pre>\n<p>And it can be solved in O(n). For every &quot;corner&quot; as you call it, you go through all point pairs. Instead, just look up the point furthest away on the same y-coordinate and the point furthest away on the same x-coordinate. That can be precomputed in O(n):</p>\n<pre><code>with open('triangles.in') as f:\n next(f)\n points = [tuple(map(int, line.split())) for line in f]\n\nxmin, xmax, ymin, ymax = {}, {}, {}, {}\nfor x, y in points:\n xmin[y] = min(xmin.get(y, x), x)\n xmax[y] = max(xmax.get(y, x), x)\n ymin[x] = min(ymin.get(x, y), y)\n ymax[x] = max(ymax.get(x, y), y)\n\nresult = max(max(x - xmin[y], xmax[y] - x) * max(y - ymin[x], ymax[x] - y)\n for x, y in points)\n\nwith open('triangles.out', 'w') as f:\n print(result, file=f)\n</code></pre>\n<p>Note that I also did the output a bit differently. No need to <code>close</code> yourself. Getting the file closed for you kinda is the reason you used <code>with</code> in the first place, remember? And I prefer <code>print</code> over <code>write</code>, as I don't have to convert to string then and trust line endings to be done as appropriate for the platform (maybe not an issue here, as the output is just one line and apparently they don't care how it ends).</p>\n<p>P.S. Those darn... they kept saying my solution failed due to <em>&quot;Runtime error or memory limit exceeded&quot;</em> and it took me a while to figure out: Instead of <code>tuple(map(...))</code> I had used my preferred <code>[*map(...)]</code>. But they're inexplicably using Python 3.4 and it didn't exist back then. But that should be a <em>syntax</em> error. Grrrr....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T14:05:57.327", "Id": "490916", "Score": "0", "body": "about the file.close: yeah i'm kinda stupid LOL" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T14:43:28.710", "Id": "490919", "Score": "0", "body": "also, yeah. USACO's error messages are incredibly confusing. I don't understand why they won't update their python version. would it be that difficult?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T11:43:45.077", "Id": "250221", "ParentId": "250205", "Score": "5" } }, { "body": "<p><em>This will be pretty similar to superb rain's great answer.</em></p>\n<p><strong>Write functions</strong></p>\n<p>Writing functions will help you to write easier to maintain code. Also, for the algorithmic challenges, it will help you to focus on the algorithm itself instead of dealing with input/output.</p>\n<p><strong>Write tests</strong></p>\n<p>Once you have a function, it is easier to write tests. (You could also write the tests before the function). This will help to test various implementations, to test them, to compare them (both in correctness and in performances)</p>\n<p><strong>Optimisations advices</strong></p>\n<p><em>Compute as little as possible, stop as soon as possible.</em></p>\n<p>Here, that could mean checking <code>lx == cx</code> as soon as you can and computing <code>abs(ly-cy)</code> only once per tuple (ly, cy).</p>\n<pre><code>def get_solution_naive_on_smaller_range(points):\n largest = 0\n for cx, cy in points:\n for lx, ly in points:\n if lx == cx:\n dy = abs(ly-cy)\n for wx, wy in points:\n if wy == cy:\n dx = abs(wx-cx)\n area = dy * dx\n if area &gt; largest:\n largest = area\n return largest\n</code></pre>\n<p><em>Precompute as much as possible</em></p>\n<p>Instead of having to iterate through all points to find the points on the same line or columns that the point being considered, we could perform some precomputation to be able to find quickly all points in the same line (or column) that the current point.</p>\n<pre><code>def get_solution_using_dicts(points):\n largest = 0\n by_x = dict()\n by_y = dict()\n for x, y in points:\n by_x.setdefault(x, []).append(y)\n by_y.setdefault(y, []).append(x)\n for cx, cy in points:\n for ly in by_x[cx]:\n dy = abs(ly-cy)\n for wx in by_y[cy]:\n dx = abs(wx - cx)\n area = dy * dx\n if area &gt; largest:\n largest = area\n return largest\n</code></pre>\n<p><em>Compute as little as possible (again)</em></p>\n<p>For a given point, we don't have to consider all other points in the same line and all the other points in the same column. We can just consider the one the furthest vertically or horizontally.</p>\n<p>Thus, for a given point, we can quickly have the best candidates:</p>\n<pre><code>def get_solution_using_dicts_and_maxabs(points):\n largest = 0\n by_x = dict()\n by_y = dict()\n for x, y in points:\n by_x.setdefault(x, []).append(y)\n by_y.setdefault(y, []).append(x)\n for cx, cy in points:\n max_y_delta = max(abs(y-cy) for y in by_x[cx])\n max_x_delta = max(abs(x-cx) for x in by_y[cy])\n area = max_x_delta * max_y_delta\n if area &gt; largest:\n largest = area\n return largest\n</code></pre>\n<hr />\n<p>Final code</p>\n<pre><code># https://codereview.stackexchange.com/questions/250205/most-efficient-solution-for-usaco-triangles-python\n# http://usaco.org/index.php?page=viewproblem2&amp;cpid=1011\n\nimport random\n\ndef get_random_points(n, mini, maxi):\n # First generate a triangle so that there is at least one\n points = set([(5, 0), (0, 0), (0, 5)])\n # Generate remainings points\n while len(points) &lt; n:\n a = random.randint(mini, maxi)\n b = random.randint(mini, maxi)\n points.add((a, b))\n # Shuffle\n l = list(points)\n random.shuffle(l)\n return l\n\ndef get_solution_naive(points):\n largest = 0\n for cx, cy in points:\n for lx, ly in points:\n for wx, wy in points:\n if lx == cx and wy == cy:\n area = abs(ly-cy) * abs(wx-cx)\n if area &gt; largest:\n largest = area\n return largest\n\n\ndef get_solution_naive_on_smaller_range(points):\n largest = 0\n for cx, cy in points:\n for lx, ly in points:\n if lx == cx:\n dy = abs(ly-cy)\n for wx, wy in points:\n if wy == cy:\n dx = abs(wx-cx)\n area = dy * dx\n if area &gt; largest:\n largest = area\n return largest\n\ndef get_solution_using_dicts(points):\n largest = 0\n by_x = dict()\n by_y = dict()\n for x, y in points:\n by_x.setdefault(x, []).append(y)\n by_y.setdefault(y, []).append(x)\n for cx, cy in points:\n for ly in by_x[cx]:\n dy = abs(ly-cy)\n for wx in by_y[cy]:\n dx = abs(wx - cx)\n area = dy * dx\n if area &gt; largest:\n largest = area\n return largest\n\ndef get_solution_using_dicts_and_maxabs(points):\n largest = 0\n by_x = dict()\n by_y = dict()\n for x, y in points:\n by_x.setdefault(x, []).append(y)\n by_y.setdefault(y, []).append(x)\n for cx, cy in points:\n max_y_delta = max(abs(y-cy) for y in by_x[cx])\n max_x_delta = max(abs(x-cx) for x in by_y[cy])\n area = max_x_delta * max_y_delta\n if area &gt; largest:\n largest = area\n return largest\n\n\ndef perform_check(points, solution):\n ret = get_solution_naive(points)\n ret1 = get_solution_naive_on_smaller_range(points)\n ret2 = get_solution_using_dicts(points)\n ret3 = get_solution_using_dicts_and_maxabs(points)\n if ret != solution:\n print(&quot;ret&quot;, points, ret, solution)\n if ret1 != solution:\n print(&quot;ret1&quot;, points, ret1, solution)\n if ret2 != solution:\n print(&quot;ret2&quot;, points, ret2, solution)\n if ret3 != solution:\n print(&quot;ret3&quot;, points, ret3, solution)\n\n# Provided test case\nperform_check([(0, 0), (0, 1), (1, 0), (1, 2)], 2)\n\n# Generated test case\nperform_check([(5, 0), (-1, 1), (-5, -3), (1, -5), (5, -2), (4, 5), (-2, 5), (-2, 1), (-4, -3), (5, -4), (-4, 3), (-5, -1), (0, 0), (-2, -5), (3, 1), (3, 2), (-4, 2), (2, 3), (0, 5), (5, 5)] , 70)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T14:08:07.503", "Id": "490917", "Score": "0", "body": "Hmm, you don't really precompute as much as possible, and end up taking quadratic time for example for `points = [(x, 0) for x in range(n)]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T16:32:07.530", "Id": "490929", "Score": "0", "body": "Yeah, I could not come up with the same solution as yours on my own." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T17:27:10.980", "Id": "490931", "Score": "1", "body": "Well, feel free to adopt :-). You could for example add `for v in by_x.values(): v[:] = min(v), max(v)` and the same for `by_y`. That would suffice to make it O(n)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:37:03.330", "Id": "250223", "ParentId": "250205", "Score": "3" } } ]
{ "AcceptedAnswerId": "250221", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T23:12:36.247", "Id": "250205", "Score": "3", "Tags": [ "python", "complexity" ], "Title": "Most Efficient Solution for USACO: Triangles - Python" }
250205
<p>I have the following program. I have 90 million domain names split between 87 files. I need to resolve the IP of all. Right now I feel like this is super slow.</p> <pre><code>import multiprocessing import fileinput import socket from datetime import datetime socket.setdefaulttimeout(2) def worker(i): filename = (str(i).zfill(len(str(111)))) buffer_array = [] for line in fileinput.input(f&quot;./data/{filename}&quot;): domain = '.'.join( list( reversed( line.split('\t')[1].split('.') ) ) ) try: ip_list = socket.gethostbyname(domain) buffer_array.append(ip_list) if(len(buffer_array) == 1000): with open(f&quot;./parsed_data/{i}&quot;, &quot;a+&quot;) as save_file: save_file.write(&quot;\n&quot;.join(buffer_array)) buffer_array = [] print(f&quot;{datetime.now()} -- WRITING: worker {i}&quot;) save_file.close() except Exception as e: pass with open(f&quot;./parsed_data/{i}&quot;, &quot;a+&quot;) as save_file: save_file.write(&quot;\n&quot;.join(buffer_array)) print(f&quot;{datetime.now()} -- WRITING ***FINAL***: worker {i}&quot;) save_file.close() if __name__ == '__main__': jobs = [] for i in range(87): p = multiprocessing.Process(target=worker, args=(i,)) jobs.append(p) p.start() </code></pre> <p>In node, I was able to do 1,000,000 on a 2017 macbook pro in about 12 hours without using workers. Right now this accomplished 39 million in 32 hours. My hope was I could make it do it's thing in 12 hours (1m per worker in in 12 hours) on a AWS T3aXL</p> <p>Does anyone have a bit faster way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T01:29:46.200", "Id": "490837", "Score": "4", "body": "Surely the bottleneck is speed of DNS lookups." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T08:23:15.167", "Id": "490858", "Score": "2", "body": "where is multiprocessing being used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:55:49.603", "Id": "490913", "Score": "0", "body": "@hjpotter92 I forgot it lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:56:12.703", "Id": "490914", "Score": "0", "body": "I'm wondering if there's a way to do this faster with an async library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T18:27:42.890", "Id": "490939", "Score": "0", "body": "Generally, use threads or async for I/O bound code such as yours. See [ThreadPoolExecutor](https://docs.python.org/3.7/library/concurrent.futures.html#threadpoolexecutor-example) or maybe [asyncio.gather](https://docs.python.org/3.7/library/asyncio-task.html#running-tasks-concurrently)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T06:45:00.673", "Id": "491004", "Score": "0", "body": "@Quesofat Before worrying about async, start as simple as possible: use [threading](https://docs.python.org/3.8/library/threading.html). That alone might be fast enough for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T18:18:53.380", "Id": "491061", "Score": "0", "body": "Threading slowed things down quite a bit." } ]
[ { "body": "<h2>Minor Python cleanup</h2>\n<p>First, a bunch of little stuff:</p>\n<p>This -</p>\n<pre><code>(str(i).zfill(len(str(111))))\n</code></pre>\n<p>does not need outer parens. Also, why the acrobatics to get &quot;3&quot;? Just declare a <code>MAX_DIGITS = 3</code>.</p>\n<p>This -</p>\n<pre><code>'.'.join( list( reversed( line.split('\\t')[1].split('.') ) ) )\n</code></pre>\n<p>should not be creating an inner list. The output of <code>reversed</code> is iterable.</p>\n<p>This -</p>\n<pre><code>if(len(buffer_array) == 1000):\n</code></pre>\n<p>does not need outer parens; you're not in (C/Java/etc).</p>\n<p>This -</p>\n<pre><code>save_file.close()\n</code></pre>\n<p>needs to be deleted both places that it appears. There's an implicit <code>close()</code> from your use of a <code>with</code>.</p>\n<p>This -</p>\n<pre><code> except Exception as e:\n pass\n</code></pre>\n<p>is a bad idea. Log or output the exception.</p>\n<p><code>87</code> deserves a named constant.</p>\n<h2>Broad performance</h2>\n<p><code>gethostbyname</code> is probably slow (as indicated in the comments). Consider running a local caching DNS resolution service to eliminate the first network hop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T15:56:59.357", "Id": "491544", "Score": "0", "body": "I appreciate it. I'm not a Python dev. I'm a node / ruby dev. What's this about local caching DNS resolution? Do you have a link to some literature?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T17:51:28.140", "Id": "491553", "Score": "0", "body": "https://nlnetlabs.nl/projects/unbound/about/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T22:32:46.040", "Id": "491679", "Score": "0", "body": "Thanks mate! Cheers" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T22:08:35.510", "Id": "250449", "ParentId": "250207", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T00:19:52.653", "Id": "250207", "Score": "4", "Tags": [ "python", "concurrency" ], "Title": "Speeding up I/O bound python program" }
250207
<p>I was doing LeetCode heater problem.</p> <p>Question: <a href="https://leetcode.com/problems/heaters/" rel="nofollow noreferrer">https://leetcode.com/problems/heaters/</a></p> <blockquote> <p>Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.</p> <p>Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.</p> <p>So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.</p> </blockquote> <p>Example Input</p> <pre><code>Input: [1,2,3],[2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. </code></pre> <p>The solution I wrote is accepted by leetcode but it isn't optimal</p> <blockquote> <p>Runtime: 656 ms, faster than 39.02% of JavaScript online submissions for Heaters. Memory Usage: 48.2 MB, less than 12.20% of JavaScript online submissions for Heaters.</p> </blockquote> <p>My solution with comments</p> <pre><code>function findClosest (house, heaters) { // if only one heater in array of heaters, subtract it with house number to get the difference and return it if (heaters.length === 1) return Math.abs(house - heaters[0]) const middleIndex = Math.floor((heaters.length - 1)/2) // if middle heater is equal to house, heater exist on that house number, difference would be zero if (house === heaters[middleIndex]) return 0 // heater on the leftside and rightside of the middle Heater, if leftside and rightside does not contain any elements (undefinned) then middle would be the left and right most element const left = heaters[middleIndex - 1] || heaters[middleIndex] const right = heaters[middleIndex + 1] || heaters[middleIndex] // if the left side heater location is greater than current house location, we need to move to left if (left &gt; house) { return findClosest(house, heaters.slice(0, middleIndex+1)) } // if the right side heater is less than current house, we need to move to right if (house&gt;right) { return findClosest(house, heaters.slice(middleIndex + 1, heaters.length)) } // finding diff b/w left, right and middle index and returning the ones with lease distance const middleDiff = Math.abs(house-heaters[middleIndex]) const leftDiff = house - left const rightDiff = right - house return Math.min(middleDiff, leftDiff, rightDiff) } function findRadius (houses, heater) { let maxIndex = 0 houses.sort((a,b) =&gt; a-b) heater.sort((a,b) =&gt; a-b) for (let i=0; i&lt;houses.length; i++) { const currentIndex = findClosest(houses[i], heater) if (currentIndex &gt; maxIndex) maxIndex = currentIndex // if the current returned distance is the highest, set that as maxIndex } return maxIndex } </code></pre> <p>Can someone help me in optimising it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T06:10:53.710", "Id": "490852", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T03:56:20.130", "Id": "490995", "Score": "0", "body": "@Mast Sorry, I wasn't able to follow your instruction. where did I go wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T03:11:56.750", "Id": "491084", "Score": "2", "body": "if you read the link, right near the top is says:\n\nTitling your question\n\nState what your code does in your title, not your main concerns about it. Be descriptive and interesting, and you'll attract more views to your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:02:31.560", "Id": "491086", "Score": "0", "body": "@Turksarama Sorry for spamming, Can you please let me know if this is any better? Want to understand better way of writing question. Apparently, the other related question also have improper title (probably) -> https://imgur.com/a/r4yIZx0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:02:41.567", "Id": "491087", "Score": "0", "body": "@Mast Sorry for spamming, Can you please let me know if this is any better? Want to understand better way of writing question. Apparently, the other related question also have improper title (probably) -> https://imgur.com/a/r4yIZx0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T08:00:12.040", "Id": "491094", "Score": "1", "body": "The status of other questions is irrelevant for determining the quality of *your* question. When in doubt, see our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) for guidance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T11:57:42.303", "Id": "491119", "Score": "0", "body": "@Mast Right. Do you think title is any better now?" } ]
[ { "body": "<p><strong>Performance</strong> The main optimization that can be made here is to, while iterating over the sorted houses, to inch along the heaters one-by-one while testing their distance. Increment a heater index only if the difference between the house and the next heater is <em>less</em> than the difference between the house and the current heater. This way, whenever a heater is tested, if the distance between it and the current house has become too great, that heater never gets tested again.</p>\n<p>For example, when iterating over 5 houses and 5 heaters, the persistent indicies for each collection being used by the algorithm could look like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Indicies being examined:\nhouses heaters\n0 0\n1 0\n2 0\n2 1 // at this point, heater 1 is found to be closer to house 2 than heater 0\n2 2 // heater 2 is found to be closer to house 2 than heater 1\n3 2\n4 2\n4 3\n4 4\n5 4\n5 5\n</code></pre>\n<p>And that's it. And, of course, on every iteration, check the distance difference between the heater and the house, and call <code>Math.max</code> on that difference and the current distance record to get the new distance record.</p>\n<p>This approach reduces the overall computational complexity from <code>O(n log m)</code> (a binary search for every house) to <code>O(n + m)</code>.</p>\n<pre><code>function findRadius(houses, heaters) {\n houses.sort((a, b) =&gt; a - b);\n heaters.sort((a, b) =&gt; a - b);\n // Persistent variable of the current closest heater to the house being iterated over\n let closestHeater = heaters[0];\n // and its index\n let closestHeaterIndex = 0;\n // Current record of needed heater radius\n let requiredRadius = 0;\n\n for (let i = 0, len = houses.length; i &lt; len; i++) {\n let lastDiff = Math.abs(houses[i] - closestHeater);\n // If we aren't at the end of the heater array,\n // test the next heater to see if we need to increment the heater index:\n while (heaters[closestHeaterIndex + 1]) {\n const nextDiff = Math.abs(heaters[closestHeaterIndex + 1] - houses[i]);\n if (nextDiff &gt; lastDiff) break;\n // This heater is closer to houses[i] than the current one in closestHeater\n lastDiff = nextDiff;\n closestHeaterIndex++;\n closestHeater = heaters[closestHeaterIndex];\n }\n requiredRadius = Math.max(requiredRadius, lastDiff);\n }\n return requiredRadius;\n}\n</code></pre>\n<p>Result (<a href=\"https://i.stack.imgur.com/CUzEO.png\" rel=\"nofollow noreferrer\">screenshot</a>):</p>\n<blockquote>\n<p>Runtime: 88 ms, <strong>faster than 98.89%</strong> of JavaScript online submissions for Heaters.</p>\n</blockquote>\n<blockquote>\n<p>Memory Usage: 42.6 MB, less than 5.56% of JavaScript online submissions for Heaters.</p>\n</blockquote>\n<p>A couple other notes regarding your code:</p>\n<p><strong>Save array length</strong> If performance is an issue (it rarely is except in these competitions), you can save the current length of the array in a <code>for</code> loop in a variable to save a bit of calculations, like I did above:</p>\n<pre><code>for (let i = 0, len = houses.length; i &lt; len; i++) {\n</code></pre>\n<p><strong>Branches are expensive</strong> Logical branches like <code>if</code> and <code>else</code> are often required, but keep in mind that they generally slow things down more than most other operations:</p>\n<blockquote>\n<p>As a general rule of thumb, branches are slower than straight-line code (on all CPUs, and with all programming languages). -<a href=\"https://stackoverflow.com/questions/54166875/why-are-two-calls-to-string-charcodeat-faster-than-having-one-with-another-one/54186960#54186960\">jmrk, V8 developer</a></p>\n</blockquote>\n<p>If you have a lot of branches, your code may not be as fast as you'd want it to be. Reduce them when possible if performance really is an issue.</p>\n<p><strong>Braced blocks create environments</strong> - or environment records, which are internal mappings of identifiers to their variable names. If you follow the specification exactly, having such blocks results in a <em>bit more</em> operations being performed. I'm not sure if it's an issue with modern engines, or if they can optimize it away completely, but leaving off <code>{</code> and <code>}</code>s when the block contains only a single statement might make things a smidgen faster. (But on the other hand, leaving off braces arguably makes the code a bit harder to read...)</p>\n<p><strong>Use representative variable names</strong> You defined the function as</p>\n<pre><code>function findRadius (houses, heater) {\n</code></pre>\n<p>but <code>heater</code> is a collection of heaters; seeing <code>heater.sort((a,b) =&gt; a-b)</code> confused me at first glance. Best to name collections something <em>plural</em>, probably.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T05:23:34.507", "Id": "250394", "ParentId": "250209", "Score": "4" } } ]
{ "AcceptedAnswerId": "250394", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T01:44:45.963", "Id": "250209", "Score": "3", "Tags": [ "javascript", "programming-challenge" ], "Title": "LeetCode heater binary search solution (w recursion) optimisation" }
250209
<p>This is a console password manager in C# script. It has 370 lines of code, from shebang to the last <code>}</code>.</p> <ul> <li>Are there any ways to make it even smaller without inlining and changing in formatting? Maybe using helpers from some nuget package, modern C# features, etc?</li> <li>Any security concerns?</li> </ul> <p>Link to github: <a href="https://github.com/AlexAtNet/pwd/blob/master/pwd.csx" rel="nofollow noreferrer">https://github.com/AlexAtNet/pwd/blob/master/pwd.csx</a></p> <pre><code>#!/usr/bin/env dotnet-script #r &quot;nuget: ReadLine, 2.0.1&quot; #r &quot;nuget: YamlDotNet, 8.1.2&quot; #r &quot;nuget: PasswordGenerator, 2.0.5&quot; using System; using System.Security.Cryptography; using System.Text.RegularExpressions; using YamlDotNet.RepresentationModel; static Exception Try(Action action) { try { action(); return null; } catch (Exception e) { return e; } } static Aes CreateAes(byte[] salt, string password) { var aes = Aes.Create(); (aes.Mode, aes.Padding) = (CipherMode.CBC, PaddingMode.PKCS7); // 10000 and SHA256 are defaults for pbkdf2 in openssl using var rfc2898 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256); (aes.Key, aes.IV) = (rfc2898.GetBytes(32), rfc2898.GetBytes(16)); return aes; } static byte[] ReadBytes(Stream stream, int length) { var chunk = new byte[length]; stream.Read(chunk, 0, length); return chunk; } static byte[] Encrypt(string password, string text) { var salt = new byte[8]; using var rng = new RNGCryptoServiceProvider(); rng.GetBytes(salt); using var aes = CreateAes(salt, password); using var stream = new MemoryStream(); var preambule = Encoding.ASCII.GetBytes(&quot;Salted__&quot;).Concat(salt).ToArray(); stream.Write(preambule, 0, preambule.Length); using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write); var data = Encoding.UTF8.GetBytes(text); cryptoStream.Write(data, 0, data.Length); cryptoStream.Close(); return stream.ToArray(); } static string Decrypt(string password, byte[] data) { using var stream = new MemoryStream(data); if (&quot;Salted__&quot; != Encoding.ASCII.GetString(ReadBytes(stream, 8))) throw new FormatException(&quot;Expecting the data stream to begin with Salted__.&quot;); var salt = ReadBytes(stream, 8); using var aes = CreateAes(salt, password); using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using var cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read); using var reader = new StreamReader(cryptoStream); return reader.ReadToEnd(); } static bool IsFileEncrypted(string path) { using var stream = File.OpenRead(path); // openssl adds Salted__ at the beginning of a file, let's use to to check whether it is enrypted or not return &quot;Salted__&quot; == Encoding.ASCII.GetString(ReadBytes(stream, 8)); } static string JoinPath(string path1, string path2) =&gt; (path1 == &quot;.&quot; ? &quot;&quot; : $&quot;{path1}/&quot;) + path2; static IEnumerable&lt;string&gt; GetFiles( string path, bool recursively = false, bool includeFolders = false, bool includeDottedFilesAndFolders = false) =&gt; Directory.Exists(path) ? new DirectoryInfo(path) .EnumerateFileSystemInfos() .OrderBy(info =&gt; info.Name) .SelectMany(info =&gt; info switch { FileInfo file when !file.Name.StartsWith(&quot;.&quot;) || includeDottedFilesAndFolders =&gt; new[] { JoinPath(path, file.Name) }, DirectoryInfo dir when !dir.Name.StartsWith(&quot;.&quot;) || includeDottedFilesAndFolders =&gt; (recursively ? GetFiles(JoinPath(path, dir.Name), recursively, includeFolders, includeDottedFilesAndFolders) : new string[0]).Concat(includeFolders ? new[] { JoinPath(path, dir.Name) } : new string[0]), _ =&gt; new string[0] }) : Enumerable.Empty&lt;string&gt;(); static (string, string, string) ParseRegexCommand(string text, int idx = 0) { string Read() { var begin = ++idx; bool escape = false; for (; idx &lt; text.Length; idx++) { var ch = text[idx]; if (!escape &amp;&amp; ch == '\\') { escape = true; continue; } else if (!escape &amp;&amp; ch == '/') return text.Substring(begin, idx - begin); escape = false; } return text.Substring(begin); } var (pattern, replacement, options) = (Read(), Read(), Read()); replacement = Regex.Replace(replacement, @&quot;\\.&quot;, m =&gt; m.Groups[0].Value[1] switch { 'n' =&gt; &quot;\n&quot;, 't' =&gt; &quot;\t&quot;, 'r' =&gt; &quot;\r&quot;, var n =&gt; $&quot;{n}&quot; }); return (pattern, replacement, options); } static Exception CheckYaml(string text) { using var input = new StringReader(text); return Try(() =&gt; new YamlStream().Load(input)); } public class Session { private string _password; public Session(string password) =&gt; _password = password; public string Path { get; private set; } public string Content { get; private set; } public bool Modified { get; private set; } public IEnumerable&lt;string&gt; GetItems(string path = null) =&gt; GetFiles(path ?? &quot;.&quot;, includeFolders: true) .Where(item =&gt; !File.Exists(item) || IsFileEncrypted(item)); public IEnumerable&lt;string&gt; GetEncryptedFilesRecursively(string path = null, bool includeHidden = false) =&gt; GetFiles(path ?? &quot;.&quot;, recursively: true, includeDottedFilesAndFolders: includeHidden) .Where(IsFileEncrypted); public string Read(string path) =&gt; Decrypt(_password, File.ReadAllBytes(path)); public void Write(string path, string content) { File.WriteAllBytes(path, Encrypt(_password, content)); if (Path == path) (Content, Modified) = (content, false); } public string ExportContentToTempFile() { var path = System.IO.Path.GetTempFileName() + &quot;.yaml&quot;; System.IO.File.WriteAllText(path, Content); return path; } public void ReadContentFromFile(string path) =&gt; (Content, Modified) = (File.ReadAllText(path), path != Path); public void Open(string path) =&gt; (Path, Content, Modified) = (path, Read(path), false); public void Close() =&gt; (Path, Content, Modified) = (&quot;&quot;, &quot;&quot;, false); public void Save() { if (Path == &quot;&quot;) return; Write(Path, Content); Modified = false; } public void Replace(string command) { var (pattern, replacement, options) = ParseRegexCommand(command); var re = new Regex( pattern, options.Contains('i') ? RegexOptions.IgnoreCase : RegexOptions.None); Content = re.Replace(Content, replacement, options.Contains('g') ? -1 : 1); Modified = true; } public void Check() { var names = GetEncryptedFilesRecursively(includeHidden: true).ToList(); if (names.Count == 0) return; var wrongPassword = new List&lt;string&gt;(); var notYaml = new List&lt;string&gt;(); foreach (var name in names) { var content = default(string); try { content = Decrypt(_password, File.ReadAllBytes(name)); if (content.Any(ch =&gt; char.IsControl(ch) &amp;&amp; !char.IsWhiteSpace(ch))) content = default; } catch { } if (content == default) { wrongPassword.Add(name); Console.Write('*'); } else if (CheckYaml(content) != null) { notYaml.Add(name); Console.Write('+'); } else Console.Write('.'); } Console.WriteLine(); if (wrongPassword.Count &gt; 0) { var more = wrongPassword.Count &gt; 3 ? &quot;, ...&quot; : &quot;&quot;; var failuresText = string.Join(&quot;, &quot;, wrongPassword.Take(Math.Min(3, wrongPassword.Count))); throw new Exception($&quot;Integrity check failed for: {failuresText}{more}&quot;); } if (notYaml.Count &gt; 0) Console.Error.WriteLine($&quot;YAML check failed for: {(string.Join(&quot;, &quot;, notYaml))}&quot;); } public void CheckContent() { if (CheckYaml(Content) is { Message: var msg }) Console.Error.WriteLine(msg); } } class AutoCompletionHandler : IAutoCompleteHandler { private Session _session; public AutoCompletionHandler(Session session) { _session = session; } public char[] Separators { get; set; } = new char[] { '/' }; public string[] GetSuggestions(string text, int index) { if (text.StartsWith(&quot;.&quot;)) return null; var path = text.Split('/'); var folder = string.Join(&quot;/&quot;, path.Take(path.Length - 1)); var query = path.Last(); return _session.GetItems(folder.Length == 0 ? &quot;.&quot; : folder) .Where(item =&gt; item.StartsWith(query)) .ToArray(); } } (string, string, string) ParseCommand(string input) { var match = Regex.Match(input, @&quot;^\.(\w+)(?: +(.+))?$&quot;); return match.Success ? (&quot;&quot;, match.Groups[1].Value, match.Groups[2].Value) : (input, &quot;&quot;, &quot;&quot;); } Action&lt;Session&gt; Route(string input) =&gt; ParseCommand(input) switch { (_, &quot;save&quot;, _) =&gt; session =&gt; session.Save(), (&quot;..&quot;, _, _) =&gt; session =&gt; session.Close(), _ when input.StartsWith(&quot;/&quot;) =&gt; session =&gt; { if (session.Path == &quot;&quot;) return; session.Replace(input); Console.WriteLine(session.Content); }, (_, &quot;check&quot;, _) =&gt; session =&gt; { if (string.IsNullOrEmpty(session.Path)) session.Check(); else session.CheckContent(); }, (_, &quot;open&quot;, var path) =&gt; session =&gt; { if (!File.Exists(path) || !IsFileEncrypted(path)) return; session.Open(path); Console.WriteLine(session.Content); }, (_, &quot;archive&quot;, _) =&gt; session =&gt; { if (session.Path == &quot;&quot;) return; if (!Directory.Exists(&quot;.archive&quot;)) Directory.CreateDirectory(&quot;.archive&quot;); File.Move(session.Path, &quot;.archive/&quot; + session.Path); session.Close(); }, (_, &quot;rm&quot;, _) =&gt; session =&gt; { if (session.Path == &quot;&quot;) return; Console.Write(&quot;Delete '&quot; + session.Path + &quot;'? (y/n)&quot;); if (Console.ReadLine().Trim().ToUpperInvariant() != &quot;Y&quot;) return; File.Delete(session.Path); session.Close(); }, (_, &quot;rename&quot;, var name) =&gt; session =&gt; { if (session.Path == &quot;&quot;) return; File.Move(session.Path, name); session.Close(); session.Open(name); }, (_, &quot;edit&quot;, var editor) =&gt; session =&gt; { editor = string.IsNullOrEmpty(editor) ? Environment.GetEnvironmentVariable(&quot;EDITOR&quot;) : editor; if (string.IsNullOrEmpty(editor)) throw new Exception(&quot;The editor is not specified and the environment variable EDITOR is not set.&quot;); var originalContent = session.Content; var path = session.ExportContentToTempFile(); try { var process = Process.Start(new ProcessStartInfo(editor, path)); process.WaitForExit(); session.ReadContentFromFile(path); Console.WriteLine(session.Content); Console.Write(&quot;Save the content (y/n)? &quot;); var choice = Console.ReadLine(); if (choice.ToLowerInvariant() == &quot;y&quot;) session.Save(); else session.Write(session.Path, originalContent); } finally { File.Delete(path); } }, (_, &quot;pwd&quot;, _) =&gt; session =&gt; Console.WriteLine(new PasswordGenerator.Password().Next()), (_, &quot;add&quot;, var path) =&gt; session =&gt; { var folder = Path.GetDirectoryName(path); if (folder != &quot;&quot; &amp;&amp; !Directory.Exists(folder)) Directory.CreateDirectory(folder); var line = &quot;&quot;; var content = new StringBuilder(); while (&quot;&quot; != (line = Console.ReadLine())) content.AppendLine(line.Replace(&quot;***&quot;, new PasswordGenerator.Password().Next())); session.Write(path, content.ToString()); session.Open(path); Console.WriteLine(session.Content); }, (_, &quot;cc&quot;, var name) =&gt; session =&gt; { var match = Regex.Match(session.Content, @$&quot;{name}: *([^\n]+)&quot;); if (match.Success) { var process = default(Process); if (Try(() =&gt; process = Process.Start(new ProcessStartInfo(&quot;clip.exe&quot;) { RedirectStandardInput = true })) == null || Try(() =&gt; process = Process.Start(new ProcessStartInfo(&quot;pbcopy&quot;) { RedirectStandardInput = true })) == null || Try(() =&gt; process = Process.Start(new ProcessStartInfo(&quot;xclip -sel clip&quot;) { RedirectStandardInput = true })) == null) { process.StandardInput.Write(match.Groups[1].Value); process.StandardInput.Close(); } } }, (_, &quot;ccu&quot;, _) =&gt; Route(&quot;.cc user&quot;), (_, &quot;ccp&quot;, _) =&gt; Route(&quot;.cc password&quot;), _ =&gt; session =&gt; { if (!string.IsNullOrEmpty(session.Path)) { Console.WriteLine(session.Content); return; } var names = session.GetEncryptedFilesRecursively() .Where(name =&gt; name.StartsWith(input, StringComparison.OrdinalIgnoreCase)) .ToList(); var name = names.Count == 1 &amp;&amp; input != &quot;&quot; ? names[0] : names.FirstOrDefault(name =&gt; string.Equals(name, input, StringComparison.OrdinalIgnoreCase)); if (name != default) { session.Open(name); Console.WriteLine(session.Content); return; } Console.Write(string.Join(&quot;&quot;, names.Select(name =&gt; $&quot;{name}\n&quot;))); } }; if (!Args.Contains(&quot;-t&quot;)) { var password = ReadLine.ReadPassword(&quot;Password: &quot;); var session = new Session(password); var e1 = Try(() =&gt; session.Check()); if (e1 != null) { Console.Error.WriteLine(e1.Message); return; } if (!session.GetEncryptedFilesRecursively(&quot;.&quot;, true).Any()) { var confirmPassword = ReadLine.ReadPassword(&quot;It seems that you are creating a new repository. Please confirm password:&quot;); if (confirmPassword != password) { Console.WriteLine(&quot;passwords do not match&quot;); return; } session.Write(&quot;template&quot;, &quot;site: xxx\nuser: xxx\npassword: xxx\n&quot;); } ReadLine.HistoryEnabled = true; ReadLine.AutoCompletionHandler = new AutoCompletionHandler(session); while (true) { var input = ReadLine.Read((session.Modified ? &quot;*&quot; : &quot;&quot;) + session.Path + &quot;&gt; &quot;).Trim(); if (input == &quot;.quit&quot;) break; var e2 = Try(() =&gt; Route(input)?.Invoke(session)); if (e2 != null) Console.Error.WriteLine(e2.Message); } Console.Clear(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T02:39:25.050", "Id": "490839", "Score": "3", "body": "all your `var aes = CreateAes(...)` should be `using var aes = CreateAes(..)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T03:07:37.313", "Id": "490840", "Score": "1", "body": "Thanks @JesseC.Slicer, I've updated the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T11:01:10.760", "Id": "490887", "Score": "3", "body": "_\"Are there any ways to make it even smaller without inlining and changing in formatting?\"_ Why? What are you trying to achieve? Condensing otherwise correct and legible code tends to lower readability, which decreases its quality, rather than improving it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T11:44:25.147", "Id": "490888", "Score": "0", "body": "I'm basically looking for three things: 1) syntax constructions and techniques (is there anything in C#9 that may help?), 2) other ways of doing things (encrypting and decrypting look quite massive, readline autocomlete is a mess too), 3) library of helpers (something like ReadBytes should be probably implemented hundred times already)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:02:29.380", "Id": "491109", "Score": "0", "body": "Is there any `man` page or `-?` output or usage examples? How to use it? Can you explain what's the purpose and the problem that has been solved by writing this script?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:19:43.180", "Id": "491131", "Score": "1", "body": "@aepot, all here: https://github.com/AlexAtNet/pwd/blob/master/README.md" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:25:19.907", "Id": "491133", "Score": "0", "body": "It would be nice if you add the link to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:50:35.047", "Id": "491138", "Score": "0", "body": "I afraid it might be considered as self-advertising. I do not want to abuse the resource in this way." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T01:48:04.983", "Id": "250210", "Score": "3", "Tags": [ "c#", ".net" ], "Title": "Console Password Manager in C# in 370 lines" }
250210
<p>Hi I'm implementing a few leetcode examples in Rust. <a href="https://leetcode.com/problems/flood-fill/" rel="nofollow noreferrer">https://leetcode.com/problems/flood-fill/</a></p> <p>(looks to be same question as <a href="https://codereview.stackexchange.com/questions/240274/leetcode-floodfill-c">LeetCode: FloodFill C#</a>)</p> <p>The input is one matrix, a position and its new colour. The output is the modified matrix</p> <pre><code>// Input: // image = [[1,1,1],[1,1,0],[1,0,1]] // sr = 1, sc = 1, newColor = 2 // Output: [[2,2,2],[2,2,0],[2,0,1]] // Explanation: // From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected // by a path of the same color as the starting pixel are colored with the new color. // Note the bottom corner is not colored 2, because it is not 4-directionally connected // to the starting pixel. </code></pre> <p>I use <code>q.pop_front()</code> to fill the neighbouring cells first. Is <code>VecDeque</code> the best data structure for this que?</p> <p>I do a lot of casting from between <code>i32</code> and <code>usize</code> as I want to be able to check if index is out of bounds by subtracting 1. Is there a better way?</p> <p>Is <code>if (0..image.len()).contains(x1)</code> better than <code>if x1&gt;=0 &amp;&amp; x1&lt;image.len()</code> for the range check?</p> <pre><code>use std::collections::VecDeque; fn flood_fill(mut image: Vec&lt;Vec&lt;i32&gt;&gt;, sr: i32, sc: i32, new_color: i32) -&gt; Vec&lt;Vec&lt;i32&gt;&gt; { let mut q:VecDeque&lt;(i32,i32)&gt; = VecDeque::new(); q.push_back((sr,sc)); let c0 = image[sr as usize][sc as usize]; if c0 != new_color { while ! q.is_empty() { if let Some((sr,sc))=q.pop_front() { if image[sr as usize][sc as usize] == c0 { image[sr as usize][sc as usize] = new_color; for delta in vec![(-1,0),(1,0),(0,-1),(0,1)] { let new_r:i32 = sr+delta.0; let new_c:i32 = sc+delta.1; if (0..image.len() as i32).contains( &amp;new_r ) &amp;&amp; (0..image[0].len() as i32).contains( &amp;new_c){ q.push_back((new_r,new_c)); } } } } } } image } #[cfg(test)] mod test{ #[test] fn test_lc_default(){ assert_eq!(super::flood_fill(vec![vec![1 as i32 ,1,1],vec![1,1 as i32,0],vec![1,0,1]],1, 1, 2),vec![vec![2,2,2],vec![2,2,0],vec![2,0,1]]) ; } } </code></pre> <p><a href="https://i.stack.imgur.com/XjSbY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XjSbY.png" alt="Still need some work on memory" /></a> It looks like I could use some memory optimization too.</p>
[]
[ { "body": "<h1>Formatting</h1>\n<p>I assume the indentation to be a copy-paste error when removing the\nboilerplate <code>struct Solution</code> mandated by LeetCode.</p>\n<p>Run <code>cargo fmt</code> on your code to conform to the standard Rust\nformatting guidelines.</p>\n<h1>Interface</h1>\n<p>LeetCode made a poor choice by using <code>Vec&lt;Vec&lt;i32&gt;&gt;</code> to represent a\ntwo-dimensional array, which is generally inefficient as it stores\nelements in multiple segmented allocations, incur double indirection\ncosts, and fail to maintain proper structure (against jagged arrays).\nWe can't do anything against this, though, so I'll ignore it for the\nrest of the post.</p>\n<p>Similarly, <code>i32</code> is not ideal for color representation — a\ndedicated type (e.g., <code>struct Color(i32);</code>) is clearly superior. At\nthe very least, we can somehow improve readability by using a type\nalias and use it consistently for colors in the code:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>type Color = i32;\n</code></pre>\n<h1><code>i32</code> vs. <code>usize</code></h1>\n<p>Generally, it is preferred to store and compute indexes in <code>usize</code>,\nwhich is the natural type for this purpose. One way you can avoid\nsubtracting <code>1</code> is by using <code>usize::MAX</code> and <code>wrapping_add</code>.</p>\n<p>To convert from the <code>i32</code> values that the function receives,\n<a href=\"https://doc.rust-lang.org/std/primitive.usize.html#method.try_from\" rel=\"nofollow noreferrer\"><code>try_from</code></a> is preferred over <code>as</code>, since the latter silently\ntruncates invalid values. <code>unwrap</code> can be used here since it's for\nLeetCode; in real-world code, the error should be handled accordingly.</p>\n<blockquote>\n<p>Is <code>if (0..image.len()).contains(x1)</code> better than <code>if x1&gt;=0 &amp;&amp; x1&lt;image.len()</code> for the range check?</p>\n</blockquote>\n<p>I'd say yes. It indicates the intent more clearly.</p>\n<h1>Simplifying control flow</h1>\n<p>Instead of wrapping everything in an <code>if</code> expression, check for\n<code>image[sr][sc] == new_color</code> and return early.</p>\n<h1><code>while let</code></h1>\n<p>This:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>while !cells.is_empty() {\n if let Some((sr, sc)) = cells.pop_front() {\n</code></pre>\n<p>is just a convoluted way of saying</p>\n<pre class=\"lang-rust prettyprint-override\"><code>while let Some((sr, sc)) = cells.pop_front() {\n</code></pre>\n<hr />\n<p>Here's how I modified your implementation:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>type Color = i32;\n\npub fn flood_fill(\n mut image: Vec&lt;Vec&lt;Color&gt;&gt;,\n sr: i32,\n sc: i32,\n new_color: Color,\n) -&gt; Vec&lt;Vec&lt;Color&gt;&gt; {\n use std::collections::VecDeque;\n use std::convert::TryFrom;\n\n let sr = usize::try_from(sr).unwrap();\n let sc = usize::try_from(sc).unwrap();\n\n let initial_color = image[sr][sc];\n\n if initial_color == new_color {\n return image;\n }\n\n let height = image.len();\n let width = image[0].len();\n\n let mut cells: VecDeque&lt;(usize, usize)&gt; = VecDeque::new();\n cells.push_back((sr, sc));\n\n while let Some((sr, sc)) = cells.pop_front() {\n let cell = &amp;mut image[sr][sc];\n\n if *cell != initial_color {\n continue;\n }\n\n *cell = new_color;\n\n const OFFSETS: &amp;[(usize, usize)] = &amp;[(0, usize::MAX), (usize::MAX, 0), (0, 1), (1, 0)];\n\n for (delta_r, delta_c) in OFFSETS.iter().copied() {\n let new_r = sr.wrapping_add(delta_r);\n let new_c = sc.wrapping_add(delta_c);\n\n if new_r &lt; height &amp;&amp; new_c &lt; width {\n cells.push_back((new_r, new_c));\n }\n }\n }\n\n image\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T15:34:42.813", "Id": "491148", "Score": "0", "body": "wrapping add not really the thing he wanted to do i think. it wraps size of integer (255+1 => 0 for u8 , for example) , but he adds point offsets, and it will not work, coz he checks image bounds, not an integer bounds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T15:37:17.193", "Id": "491150", "Score": "0", "body": "also bfs and dfs not really different in this case, because he need to fill color field, not find path in it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T01:45:07.103", "Id": "491187", "Score": "0", "body": "dfs bfs is only if poping from the front or the back of the queue" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T02:32:33.787", "Id": "491189", "Score": "1", "body": "Thanks for feedback, auto format and `while let Some(x) = cells.pop_front()` are habits I will do more of. I `try_from()` instead of `as i32` is also good however I think it is clearer to use a signed type for subtraction than using the wraparound trick - it is too similar to the abnormality we use in C all the time `unsigned int = -1`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T02:36:45.527", "Id": "491191", "Score": "0", "body": "@Sugar `.wrapping_add(usize::MAX)` to a `usize` value is equivalent to `.wrapping_sub(1)`, because \\$\\mathbb{Z} / 2^{n}\\mathbb{Z}\\$ forms a ring under the wrapping operations. The image bounds, of course, has to be checked separately. I was also relying on valid indexes being strictly less than `usize::MAX`; that is, `usize::MAX` itself is always treated as an out-of-range value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T02:40:35.340", "Id": "491192", "Score": "1", "body": "@Simson You're welcome. The wraparound hack is indeed sub-optimal, so I tried to present it as an option only (as opposed to a recommendation). I don't like signedness conversion either, so I took this approach instead, but that's purely subjective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T09:03:57.837", "Id": "491205", "Score": "0", "body": "@L.F. but he don't need any wrapping operations. Clamping, yes, not wrapping" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T09:44:49.457", "Id": "491213", "Score": "0", "body": "@Sugar The wrapping was to work around `usize` not supporting `+ (-1)`, not to clamp the index to the range. We can of course use an array of closures or something along those lines, but I didn't think that would be clearer than `.wrapping_add(usize::MAX)`." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:55:42.910", "Id": "250324", "ParentId": "250214", "Score": "1" } } ]
{ "AcceptedAnswerId": "250324", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T05:59:49.373", "Id": "250214", "Score": "4", "Tags": [ "rust" ], "Title": "LeetCode: FloodFill Rust" }
250214
<p>I have a code that should read diameters of barrels from a txt file. If a barrel is smaller than the last one, smaller gets put inside bigger one. One package like that is lied on a stack. at the end, code should give out how many stacks we get and how many barrels were in a file. also sum of diameters.</p> <p>If one number is repeated 3 times, we get 3 stack, if we have 5 repeating nmbers, then 5. What can I do that I wouldn´t have to write simillar blocks n times.</p> <pre><code>using System; using System.Collections.Generic; using System.IO; namespace TaaviSimsonTest { class Program { static void Main(string[] args) { using (TextReader reader = File.OpenText(&quot;C:\\temp\\andmed2&quot;)) { int sum = 0; string line = string.Empty; List&lt;int&gt; numbersList = new List&lt;int&gt;(); while ((line = reader.ReadLine()) != null) { int i = int.Parse(line); sum += i; numbersList.Add(int.Parse(line)); } int[] numbersListArray = numbersList.ToArray(); int numberOfStacks = numbersListArray.Length; //Max number of stacks equals to inital array length Array.Sort(numbersListArray); //Array is ascending orded Array.Reverse(numbersListArray); //Array in descending order //Puts smaller barrels inside bigger. Decreases number of stacks. List&lt;int&gt; repeatedBrarrelSizes = new List&lt;int&gt;(); for (int j = 0; j &lt; (numbersListArray.Length - 1); j++) { if (numbersListArray[j] &gt; numbersListArray[j + 1]) { numberOfStacks--; } else if (numbersListArray[j] == numbersListArray[j + 1]) { repeatedBrarrelSizes.Add(numbersListArray[j + 1]); } } int[] repeatedBarrelSizesArray = repeatedBrarrelSizes.ToArray(); //Repeats the cycle with repeating numbers List&lt;int&gt; repeatedBarrelSizes2 = new List&lt;int&gt;(); for (int k = 0; k &lt; (repeatedBarrelSizesArray.Length-1); k++) { if (repeatedBarrelSizesArray[k] &gt; repeatedBarrelSizesArray[k+1]) { numberOfStacks--; } else if (repeatedBarrelSizesArray[k] == repeatedBarrelSizesArray[k + 1]) { repeatedBarrelSizes2.Add(repeatedBarrelSizesArray[k + 1]); } } int[] repeatedBarrelSizes2Array = repeatedBarrelSizes2.ToArray(); //Repeats the cycle again, until no barrels left List&lt;int&gt; repeatedBarrelSizes3 = new List&lt;int&gt;(); for (int k = 0; k &lt; (repeatedBarrelSizes2Array.Length - 1); k++) { if (repeatedBarrelSizes2Array[k] &gt; repeatedBarrelSizes2Array[k + 1]) { numberOfStacks--; } else if (repeatedBarrelSizes2Array[k] == repeatedBarrelSizes2Array[k + 1]) { repeatedBarrelSizes3.Add(repeatedBarrelSizes2Array[k + 1]); } } int[] repeatedBarrelSizes3Array = repeatedBarrelSizes3.ToArray(); foreach (int value in repeatedBarrelSizes3Array) { Console.WriteLine(value + &quot; &quot;); } Console.WriteLine(&quot;Sum: &quot; + sum); Console.WriteLine(&quot;Number of barrels: &quot; + numbersListArray.Length); Console.WriteLine(&quot;Stacks: &quot; + numberOfStacks); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T16:40:16.713", "Id": "491045", "Score": "2", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>DRY = Don't Repeat Yourself.</p>\n<p>If you have repeating parts of code, something went wrong then. Also you may use <code>Linq</code>.</p>\n<p>Consider this example.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main(string[] args)\n{\n string[] lines = File.ReadAllLines(@&quot;C:\\temp\\andmed2&quot;);\n List&lt;int&gt; numbersList = lines.Select(line =&gt; int.Parse(line)).OrderByDescending(x =&gt; x).ToList();\n int sum = numbersList.Aggregate(0, (x, y) =&gt; x + y);\n int numberOfStacks = numbersList.Count;\n\n List&lt;int&gt; repeatedBarrelSizes = numbersList;\n int count;\n do\n {\n count = 0;\n List&lt;int&gt; result = new List&lt;int&gt;();\n for (int i = 0; i &lt; repeatedBarrelSizes.Count - 1; i++)\n {\n if (repeatedBarrelSizes[i] &gt; repeatedBarrelSizes[i + 1])\n count++;\n else if (repeatedBarrelSizes[i] == repeatedBarrelSizes[i + 1])\n result.Add(repeatedBarrelSizes[i + 1]);\n }\n repeatedBarrelSizes = result;\n numberOfStacks -= count;\n } while (count &gt; 0);\n\n Console.WriteLine(string.Join(&quot; &quot;, repeatedBarrelSizes));\n\n Console.WriteLine(&quot;Sum: &quot; + sum);\n Console.WriteLine(&quot;Number of barrels: &quot; + numbersList.Count);\n Console.WriteLine(&quot;Stacks: &quot; + numberOfStacks);\n}\n</code></pre>\n<p><em>I'm sorry but I can't test it because I have no source file with numbers to compare the results.</em></p>\n<p><strong>Total:</strong> two loops.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T19:23:11.513", "Id": "250335", "ParentId": "250216", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T09:53:25.517", "Id": "250216", "Score": "2", "Tags": [ "c#", "performance", "array" ], "Title": "I want to get rid of unneccessary repetiton of cycles" }
250216
<p>Recently I was learning to code using PyQt5 and Python. I was doing a school project on Calculator. Here is my graphic class:</p> <pre><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'calculator.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Calculator(object): def setupUi(self, Calculator): Calculator.setObjectName(&quot;Calculator&quot;) Calculator.resize(240, 361) font = QtGui.QFont() font.setFamily(&quot;Comic Sans MS&quot;) Calculator.setFont(font) Calculator.setLayoutDirection(QtCore.Qt.LeftToRight) self.centralwidget = QtWidgets.QWidget(Calculator) self.centralwidget.setObjectName(&quot;centralwidget&quot;) self.Display = QtWidgets.QLabel(self.centralwidget) self.Display.setGeometry(QtCore.QRect(0, 0, 241, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(16) font.setBold(False) font.setWeight(50) self.Display.setFont(font) self.Display.setLayoutDirection(QtCore.Qt.RightToLeft) self.Display.setStyleSheet(&quot;QLabel {\n&quot; &quot; qproperty-alignment: \'AlignVCenter | AlignRight\';\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;\n&quot; &quot;background-color : white;&quot;) self.Display.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.Display.setObjectName(&quot;Display&quot;) self.Clear = QtWidgets.QPushButton(self.centralwidget) self.Clear.setGeometry(QtCore.QRect(0, 60, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.Clear.setFont(font) self.Clear.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(215, 215, 215);\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #BEBEBE, stop: 1 #D7D7D7);\n&quot; &quot;}&quot;) self.Clear.setObjectName(&quot;Clear&quot;) self.btndiv = QtWidgets.QPushButton(self.centralwidget) self.btndiv.setGeometry(QtCore.QRect(180, 60, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btndiv.setFont(font) self.btndiv.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(255, 151, 57);\n&quot; &quot; color: white; \n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #FF7832, stop: 1 #FF9739);\n&quot; &quot;}&quot;) self.btndiv.setObjectName(&quot;btndiv&quot;) self.btnpercent = QtWidgets.QPushButton(self.centralwidget) self.btnpercent.setGeometry(QtCore.QRect(120, 60, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btnpercent.setFont(font) self.btnpercent.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(215, 215, 215);\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #BEBEBE, stop: 1 #D7D7D7);\n&quot; &quot;}&quot;) self.btnpercent.setObjectName(&quot;btnpercent&quot;) self.btnneg = QtWidgets.QPushButton(self.centralwidget) self.btnneg.setGeometry(QtCore.QRect(60, 60, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btnneg.setFont(font) self.btnneg.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(215, 215, 215);\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #BEBEBE, stop: 1 #D7D7D7);\n&quot; &quot;}&quot;) self.btnneg.setObjectName(&quot;btnneg&quot;) self.btn8 = QtWidgets.QPushButton(self.centralwidget) self.btn8.setGeometry(QtCore.QRect(60, 120, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn8.setFont(font) self.btn8.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn8.setObjectName(&quot;btn8&quot;) self.btn7 = QtWidgets.QPushButton(self.centralwidget) self.btn7.setGeometry(QtCore.QRect(0, 120, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn7.setFont(font) self.btn7.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn7.setObjectName(&quot;btn7&quot;) self.btnmul = QtWidgets.QPushButton(self.centralwidget) self.btnmul.setGeometry(QtCore.QRect(180, 120, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btnmul.setFont(font) self.btnmul.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(255, 151, 57);\n&quot; &quot; color: white; \n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #FF7832, stop: 1 #FF9739);\n&quot; &quot;}&quot;) self.btnmul.setObjectName(&quot;btnmul&quot;) self.btn9 = QtWidgets.QPushButton(self.centralwidget) self.btn9.setGeometry(QtCore.QRect(120, 120, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn9.setFont(font) self.btn9.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn9.setObjectName(&quot;btn9&quot;) self.btn5 = QtWidgets.QPushButton(self.centralwidget) self.btn5.setGeometry(QtCore.QRect(60, 180, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn5.setFont(font) self.btn5.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn5.setObjectName(&quot;btn5&quot;) self.btn4 = QtWidgets.QPushButton(self.centralwidget) self.btn4.setGeometry(QtCore.QRect(0, 180, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn4.setFont(font) self.btn4.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn4.setObjectName(&quot;btn4&quot;) self.btnsub = QtWidgets.QPushButton(self.centralwidget) self.btnsub.setGeometry(QtCore.QRect(180, 180, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btnsub.setFont(font) self.btnsub.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(255, 151, 57);\n&quot; &quot; color: white; \n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #FF7832, stop: 1 #FF9739);\n&quot; &quot;}&quot;) self.btnsub.setObjectName(&quot;btnsub&quot;) self.btn6 = QtWidgets.QPushButton(self.centralwidget) self.btn6.setGeometry(QtCore.QRect(120, 180, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn6.setFont(font) self.btn6.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn6.setObjectName(&quot;btn6&quot;) self.btn0 = QtWidgets.QPushButton(self.centralwidget) self.btn0.setGeometry(QtCore.QRect(0, 300, 121, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn0.setFont(font) self.btn0.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn0.setObjectName(&quot;btn0&quot;) self.btndecimal = QtWidgets.QPushButton(self.centralwidget) self.btndecimal.setGeometry(QtCore.QRect(120, 300, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btndecimal.setFont(font) self.btndecimal.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(215, 215, 215);\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #BEBEBE, stop: 1 #D7D7D7);\n&quot; &quot;}&quot;) self.btndecimal.setObjectName(&quot;btndecimal&quot;) self.btnequal = QtWidgets.QPushButton(self.centralwidget) self.btnequal.setGeometry(QtCore.QRect(180, 300, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btnequal.setFont(font) self.btnequal.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(255, 151, 57);\n&quot; &quot; color: white; \n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #FF7832, stop: 1 #FF9739);\n&quot; &quot;}&quot;) self.btnequal.setObjectName(&quot;btnequal&quot;) self.btn3 = QtWidgets.QPushButton(self.centralwidget) self.btn3.setGeometry(QtCore.QRect(120, 240, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn3.setFont(font) self.btn3.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn3.setObjectName(&quot;btn3&quot;) self.btn2 = QtWidgets.QPushButton(self.centralwidget) self.btn2.setGeometry(QtCore.QRect(60, 240, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn2.setFont(font) self.btn2.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn2.setObjectName(&quot;btn2&quot;) self.btn1 = QtWidgets.QPushButton(self.centralwidget) self.btn1.setGeometry(QtCore.QRect(0, 240, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btn1.setFont(font) self.btn1.setStyleSheet(&quot;QPushButton {\n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #dadbde, stop: 1 #f6f7fa);\n&quot; &quot;}&quot;) self.btn1.setObjectName(&quot;btn1&quot;) self.btnplus = QtWidgets.QPushButton(self.centralwidget) self.btnplus.setGeometry(QtCore.QRect(180, 240, 61, 61)) font = QtGui.QFont() font.setFamily(&quot;Lucida Console&quot;) font.setPointSize(12) self.btnplus.setFont(font) self.btnplus.setStyleSheet(&quot;QPushButton {\n&quot; &quot; background-color: rgb(255, 151, 57);\n&quot; &quot; color: white; \n&quot; &quot; border: 1px solid gray;\n&quot; &quot;}\n&quot; &quot;\n&quot; &quot;QPushButton:pressed {\n&quot; &quot; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n&quot; &quot; stop: 0 #FF7832, stop: 1 #FF9739);\n&quot; &quot;}&quot;) self.setFixedSize(self.size()) self.btnplus.setObjectName(&quot;btnplus&quot;) Calculator.setCentralWidget(self.centralwidget) self.retranslateUi(Calculator) QtCore.QMetaObject.connectSlotsByName(Calculator) def retranslateUi(self, Calculator): _translate = QtCore.QCoreApplication.translate Calculator.setWindowTitle(_translate(&quot;Calculator&quot;, &quot;Calculator&quot;)) self.Display.setText(_translate(&quot;Calculator&quot;, &quot;0&quot;)) self.Clear.setText(_translate(&quot;Calculator&quot;, &quot;C&quot;)) self.btndiv.setText(_translate(&quot;Calculator&quot;, &quot;/&quot;)) self.btnpercent.setText(_translate(&quot;Calculator&quot;, &quot;%&quot;)) self.btnneg.setText(_translate(&quot;Calculator&quot;, &quot;+/-&quot;)) self.btn8.setText(_translate(&quot;Calculator&quot;, &quot;8&quot;)) self.btn7.setText(_translate(&quot;Calculator&quot;, &quot;7&quot;)) self.btnmul.setText(_translate(&quot;Calculator&quot;, &quot;X&quot;)) self.btn9.setText(_translate(&quot;Calculator&quot;, &quot;9&quot;)) self.btn5.setText(_translate(&quot;Calculator&quot;, &quot;5&quot;)) self.btn4.setText(_translate(&quot;Calculator&quot;, &quot;4&quot;)) self.btnsub.setText(_translate(&quot;Calculator&quot;, &quot;-&quot;)) self.btn6.setText(_translate(&quot;Calculator&quot;, &quot;6&quot;)) self.btn0.setText(_translate(&quot;Calculator&quot;, &quot;0&quot;)) self.btndecimal.setText(_translate(&quot;Calculator&quot;, &quot;.&quot;)) self.btnequal.setText(_translate(&quot;Calculator&quot;, &quot;=&quot;)) self.btn3.setText(_translate(&quot;Calculator&quot;, &quot;3&quot;)) self.btn2.setText(_translate(&quot;Calculator&quot;, &quot;2&quot;)) self.btn1.setText(_translate(&quot;Calculator&quot;, &quot;1&quot;)) self.btnplus.setText(_translate(&quot;Calculator&quot;, &quot;+&quot;)) if __name__ == &quot;__main__&quot;: import sys app = QtWidgets.QApplication(sys.argv) Calculator = QtWidgets.QMainWindow() ui = Ui_Calculator() ui.setupUi(Calculator) Calculator.show() sys.exit(app.exec_()) </code></pre> <p>I added my operations on another file but the problem is coming when I am trying to do multiple operations. Also please help me make my code more shorter if possible. Here is the operations or the main.py file:</p> <pre><code>from PyQt5 import QtWidgets from calculatorui import Ui_Calculator class Calculator(QtWidgets.QMainWindow, Ui_Calculator): first_num = None second_num = 0 user_enter_second_num = False def __init__(self): super().__init__() self.setupUi(self) # for the digits self.btn0.clicked.connect(self.digit_pressed) self.btn1.clicked.connect(self.digit_pressed) self.btn2.clicked.connect(self.digit_pressed) self.btn3.clicked.connect(self.digit_pressed) self.btn4.clicked.connect(self.digit_pressed) self.btn5.clicked.connect(self.digit_pressed) self.btn6.clicked.connect(self.digit_pressed) self.btn7.clicked.connect(self.digit_pressed) self.btn8.clicked.connect(self.digit_pressed) self.btn9.clicked.connect(self.digit_pressed) # For the decimal point self.btndecimal.clicked.connect(self.decimal_pressed) # For the unary operators self.btnpercent.clicked.connect(self.unary_press) self.btnneg.clicked.connect(self.unary_press) # Make binary operators ready to get checked self.btnplus.setCheckable(True) self.btnsub.setCheckable(True) self.btnmul.setCheckable(True) self.btndiv.setCheckable(True) # Binding the binary operators with their functions self.btnplus.clicked.connect(self.binary_operations) self.btnsub.clicked.connect(self.binary_operations) self.btnmul.clicked.connect(self.binary_operations) self.btndiv.clicked.connect(self.binary_operations) # Binding the equal button self.btnequal.clicked.connect(self.equal_operation) self.show() def digit_pressed(self): label = self.sender() if (self.btnplus.isChecked() or self.btnmul.isChecked() or self.btnsub.isChecked() or self.btndiv.isChecked()) and (not self.user_enter_second_num): new_label = format(float(label.text()), '.15g') self.user_enter_second_num = True else: if '.' in self.Display.text() and (label.text() == &quot;0&quot;): new_label = format(self.Display.text()+label.text(), '.15') else: new_label = format(float(self.Display.text() + label.text()), '.15g') if new_label == &quot;inf&quot;: pass else: self.Display.setText(new_label) def decimal_pressed(self): label = self.Display.text() if &quot;.&quot; in label: pass else: self.Display.setText(label + '.') def unary_press(self): label = self.sender() new_label = float(self.Display.text()) if label.text() == &quot;+/-&quot;: new_label *= -1 else: # Check for % sign new_label *= 0.01 label = format(new_label, '.15g') self.Display.setText(label) def binary_operations(self): button = self.sender() self.first_num = float(self.Display.text()) button.setChecked(True) self.user_enter_second_num = False def equal_operation(self): self.second_num = float(self.Display.text()) if self.btnplus.isChecked(): label_number = self.first_num + self.second_num new_label = format(label_number, '.15g') self.Display.setText(new_label) self.btnplus.setChecked(False) elif self.btnsub.isChecked(): label_number = self.first_num - self.second_num new_label = format(label_number, '.15g') self.Display.setText(new_label) self.btnsub.setChecked(False) elif self.btnmul.isChecked(): label_number = self.first_num * self.second_num new_label = format(label_number, '.15g') self.Display.setText(new_label) self.btnmul.setChecked(False) elif self.btndiv.isChecked(): label_number = self.first_num / self.second_num new_label = format(label_number, '.15g') self.Display.setText(new_label) self.btndiv.setChecked(False) else: pass self.user_enter_second_num = False if __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) calc = Calculator() sys.exit(app.exec_()) <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Not a lot of time on my hands, so this is not a comprehensive review but a few suggestions.</p>\n<p>This:</p>\n<pre><code># for the digits\nself.btn0.clicked.connect(self.digit_pressed)\nself.btn1.clicked.connect(self.digit_pressed)\nself.btn2.clicked.connect(self.digit_pressed)\nself.btn3.clicked.connect(self.digit_pressed)\nself.btn4.clicked.connect(self.digit_pressed)\nself.btn5.clicked.connect(self.digit_pressed)\nself.btn6.clicked.connect(self.digit_pressed)\nself.btn7.clicked.connect(self.digit_pressed)\nself.btn8.clicked.connect(self.digit_pressed)\nself.btn9.clicked.connect(self.digit_pressed)\n</code></pre>\n<p>Could become:</p>\n<pre><code># and so on...\nbuttons = (self.btn0, self.btn1, self.btn2)\nfor button in buttons:\n button.clicked.connect(self.digit_pressed)\n</code></pre>\n<p>There is some <strong>repetitive code</strong>, that can be shortened a bit. For example in equal_operation:</p>\n<pre><code>if self.btnplus.isChecked():\n label_number = self.first_num + self.second_num\n new_label = format(label_number, '.15g')\n self.Display.setText(new_label)\n self.btnplus.setChecked(False)\n\nelif self.btnsub.isChecked():\n label_number = self.first_num - self.second_num\n new_label = format(label_number, '.15g')\n self.Display.setText(new_label)\n self.btnsub.setChecked(False)\n...\n</code></pre>\n<p>It can be shortened like this basically:</p>\n<pre><code>if self.btnplus.isChecked():\n label_number = self.first_num + self.second_num\nelif self.btnsub.isChecked():\n label_number = self.first_num - self.second_num\nelif self.btnmul.isChecked():\n label_number = self.first_num * self.second_num\nelif self.btndiv.isChecked():\n label_number = self.first_num / self.second_num\n\nnew_label = format(label_number, '.15g')\nself.Display.setText(new_label)\nself.btndiv.setChecked(False)\n</code></pre>\n<p>There is stuff that is repeated for every condition.</p>\n<hr />\n<p>Personally, I prefer to use the QT designer to build my forms, then load them from Python (with loaduic). This is more visual, and results in less code + separation between logic and presentation.</p>\n<p>The <strong>UI declaration</strong> is probably not going to change a lot over time but the code is nonetheless tedious to read. Some <strong>comments</strong> would come in handy, and some <strong>line spacing</strong> too. I take it that this is the result of pyuic5 but it could be improved, because it is clearly bloated and not optimized.</p>\n<p>I suppose you've used the QT designer too, and this is the finished product, so not going to delve into this too much.</p>\n<hr />\n<blockquote>\n<p>I added my operations on another file but the problem is coming when I\nam trying to do multiple operations.</p>\n</blockquote>\n<p>Not sure this is what you mean, but if I type 6*3+2 I get 5 whereas I would expect 20. Is this what you mean. Seems to me that one possible fix is to raise an explicit equal operation before plus/minus/etc.</p>\n<hr />\n<p>In fact you could even reduce the number of functions. Because it is possible to get the name of the button that was clicked. Try this in one of your functions:</p>\n<pre><code>print(f&quot;sender: {self.sender().objectName()}&quot;)\n</code></pre>\n<p>So once you've got the name of the control, you can decide on what action you want to perform.</p>\n<p>In unary_press you do this, instead relying on the <strong>text</strong> inside the button:</p>\n<pre><code>label = self.sender()\n</code></pre>\n<p>There are situations where it's better to rely on the name of the control.</p>\n<hr />\n<p>Warning: your program does not handle <strong>division by zero</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T08:36:03.740", "Id": "491095", "Score": "0", "body": "Thank you for your review @Anonymous. Can you tell me how will i Raise that explicit equal operation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T08:36:33.817", "Id": "491096", "Score": "0", "body": "I did not use loaduic because i did not know about it as there are not many tutorials on PyQt5" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T08:37:06.513", "Id": "491097", "Score": "0", "body": "I will surely try to Handle divisionn by zero" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T08:41:43.167", "Id": "491098", "Score": "0", "body": "Can you also help me with an IDE Pycharm is very heavy and slows my system and visual studio does not have enough suggestions even using Kite does not help there" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T21:01:04.543", "Id": "250245", "ParentId": "250217", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T10:51:27.847", "Id": "250217", "Score": "3", "Tags": [ "python-3.x", "calculator", "pyqt" ], "Title": "I want to add multiple inputs to this PyQt5 calculator" }
250217
<p><strong>What is the transpose of a matrix:</strong></p> <p>In linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal; that is, it switches the row and column indices of the matrix A by producing another matrix, often denoted by Aᵀ.</p> <p><strong>Code</strong></p> <pre><code>dimension = int(input()) matrix = [] transpose = [] for row in range(dimension): entry = list(map(int,input().split())) matrix.append(entry) for i in range(dimension): for j in range(dimension): transpose.append(matrix[j][i]) m = 0 n = dimension for x in range(dimension+1): row = transpose[m:n] list1 = [str(item) for item in row] string2 = &quot; &quot;.join(list1) print(string2) m = n n = n + dimension </code></pre> <p><strong>My question</strong></p> <p>What all modifications I can do to this code to make it better furthermore efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T22:01:34.857", "Id": "490975", "Score": "1", "body": "Example input and output would be useful." } ]
[ { "body": "<p>You could do something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>dimension = int(input())\nmatrix = [list(map(int,input().split())) for _ in range(dimension)]\ntranspose = [[matrix[j][i] for j in range(dimension)] for i in range(dimension)]\n</code></pre>\n<p>PD: This still has to pass by every item on the matrix but it is a little more compact code, and if you're used to python you could find it a little more legible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T20:15:35.367", "Id": "490960", "Score": "0", "body": "Other than code is more compact is there a performance improvement, does the code run faster?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T20:53:03.390", "Id": "490965", "Score": "0", "body": "Practically this code does less iterations, `2n^2` where `n` is the dimension (yours do `3n^2`) But in terms of algorithmic complexity this is still `O(n^2)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T19:19:44.763", "Id": "250238", "ParentId": "250219", "Score": "3" } }, { "body": "<p>You're converting the matrix elements to int and then back to string without doing anything with the ints, so that's just wasteful.</p>\n<p>Anyway, the usual way to transpose is <code>zip</code>. Demo including mock input:</p>\n<pre><code>input = iter('''3\n1 2 3\n4 5 6\n7 8 9'''.splitlines()).__next__\n\nmatrix = [input().split() for _ in range(int(input()))]\n\nfor column in zip(*matrix):\n print(*column)\n</code></pre>\n<p>Output:</p>\n<pre><code>1 4 7\n2 5 8\n3 6 9\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T22:12:38.277", "Id": "250248", "ParentId": "250219", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T11:35:14.663", "Id": "250219", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Transpose of a matrix using Python 3.8" }
250219
<p>I wrote this function to multiply vector with a matrix and I was wondering if someone experienced can spot something can improved its performance.</p> <pre><code>class matrix: def __init__(self, width, height): self.width = width self.height = height self.m = [[0 for i in range(width)]for i in range(height)] class vec2: def __init__(self, x, y): self.x, self.y = x, y self.vals = [x, y] class vec3: def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z self.vals = [x, y, z] matrix = matrix(3, 3) matrix.m[0][0] = 2 matrix.m[0][1] = 1 matrix.m[0][2] = 0.5 matrix.m[1][0] = 1 matrix.m[2][0] = 1 matrix.m[1][2] = 0.2 vector = vec3(1, 10, 10) def multVecMat(vec, mat): canCarryOut = False if vec.__class__.__name__ == &quot;vec3&quot;: if mat.width == 3 and mat.height == 3: canCarryOut = True newVec = vec3(0, 0, 0) else: if vec.__class__.__name__ == &quot;vec2&quot;: if mat.width == 2 and mat.height == 2: canCarryOut = True newVec = vec2(0, 0) if canCarryOut: vecValues = [] for v in range(mat.width): tempValues = [] for m in range(mat.height): tempValues.append(vec.vals[v]*mat.m[v][m]) vecValues.append(sum(tempValues)) if vec.__class__.__name__ == &quot;vec3&quot;: newVec.x, newVec.y, newVec.z = vecValues[0], vecValues[1], vecValues[2] else: newVec.x, newVec.y = vecValues[0], vecValues[1] return newVec raise ValueError v = multVecMat(vector, matrix) print(v.x, v.y, v.z) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:00:16.090", "Id": "490897", "Score": "0", "body": "First thing to notice is, that you check for square matrices. But you can multiply vectors (essentially rectangular matrices) with non-square matrices, which results in a new rectangular matrix. Only if the matrix is square, you'll get a vector in return." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:21:46.703", "Id": "490901", "Score": "0", "body": "Ah yes. I noticed that as well but I wasn't too sure about how I would go about doing that. For 3d, I came up with this but I am still not sure If it works for all cases: `if vec.__class__.__name__ == \"vec3\":\n if mat.height == 3 and mat.width < 4:`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:30:10.380", "Id": "490906", "Score": "0", "body": "since the arguments are (vec, math), you multiply a row vector with a matrix. the matrix's row size must match the vector column size. For further reading [see here](https://en.wikipedia.org/wiki/Matrix_multiplication)" } ]
[ { "body": "<p>Throw out the works and use Numpy. Seriously. Rolling your own matrix multiplication is fun and educational, but pretty much immediately reaches its limit if you care about performance. There is no universe in which a native Python implementation of low-level matrix operations will out-perform a well-written C library that has FFI to Python.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T18:04:30.610", "Id": "250436", "ParentId": "250220", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T11:39:58.477", "Id": "250220", "Score": "2", "Tags": [ "python", "performance", "matrix", "mathematics" ], "Title": "Improving performance of function to multiply vector with a matrix?" }
250220
<p>I am a little bit confused on Factory Method with multiple parameters in which all parameters can change from GUI by user as seen below picture. <a href="https://i.stack.imgur.com/babR1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/babR1.png" alt="enter image description here" /></a></p> <p>For each combobox item I have an interface and concrete implementations.</p> <p>I have a SignalProcessor class which gets parameters as this 3 interfaces as below:</p> <pre><code>public interface ISignalProcessor { double[] Process(double[] data); } public class SignalProcessor : ISignalProcessor { private IFft _fft; private IWindowing _windowing; private IInverseSpectrum _inverseSpectrum; private IDecimation _decimation; public SignalProcessor(IWindowing windowing, IFft fft, IInverseSpectrum inverseSpectrum, IDecimation decimation) { _windowing = windowing; _fft = fft; _inverseSpectrum = inverseSpectrum; _decimation = decimation; } public double[] Process(double[] data) { var windowingResult = _windowing.Calculate(data); var fftResult = _fft.Calculate(windowingResult); var inverseSpectrumResult = _inverseSpectrum.Calculate(fftResult); return _decimation.Calculate(inverseSpectrumResult); } } </code></pre> <p>I decided to produce and use concrete classes according to the selected combobox values so the following factory class created.</p> <pre><code> public static class FactorySP { public static ISignalProcessor Create(string windowingType, int fftSize, bool isInverse, string decimationType) { return new SignalProcessor(CreateWindowing(windowingType), CreateFft(fftSize), CreateInverseSpectrum(isInverse), CreateDecimation(decimationType)); } private static IWindowing CreateWindowing(string windowingType) { switch (windowingType) { case &quot;Triangular&quot;: return new Triangular(); case &quot;Rectangular&quot;: return new Rectangular(); case &quot;Hanning&quot;: return new Hanning(); } } private static IFft CreateFft(int fftSize) { switch (fftSize) { case 128: return new Fft128(); case 256: return new Fft256(); case 512: return new Fft512(); default: return new FftNull(); } } private static IInverseSpectrum CreateInverseSpectrum(bool isInverse) { if (isInverse) return new InverseSpectrumTrue(); return new InverseSpectrumFalse(); } private static IDecimation CreateDecimation(string decimationType) { if (decimationType == &quot;RealTimeDecimation&quot;) return new RealTimeDecimation(); return new SweepDecimation(); } } </code></pre> <p>Then used as follows:</p> <pre><code>_signalProcessor = FactorySP.Create(WindowingType, FftSize, InverseSpectrum, DecimationType); result = _signalProcessor.Process(Enumerable.Range(0, 100).Select(a =&gt; (double)a).ToArray()); </code></pre> <p>Is there a better way to get what I want than that? I feel there is something missing in the method I use :) I know Factory method is not like that but otherwise I have to create all combinations and permutations of overload of factory classes. Should I use the builder pattern to create the SignalProcessor object?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:41:55.963", "Id": "491167", "Score": "0", "body": "If you do it in MVVM way, the parameter source will be Property, not UI." } ]
[ { "body": "<p>If I understand your intent and code properly then you rather have an <a href=\"https://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow noreferrer\">abstract factory</a> implementation than a <a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">factory method</a> pattern implementation.</p>\n<blockquote>\n<p>The Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition.</p>\n</blockquote>\n<blockquote>\n<p>The Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.</p>\n</blockquote>\n<p><a href=\"http://www.buyya.com/254/Patterns/Factory-2pp.pdf\" rel=\"nofollow noreferrer\">Reference 24th slide</a> | <a href=\"https://stackoverflow.com/questions/5739611/what-are-the-differences-between-abstract-factory-and-factory-design-patterns\">Detailed discussion about the differences</a></p>\n<p>Your <code>FactoryFP</code> exposes several methods to create multiple different objects (so called object family). Whereas a Factory Method's scope is a single object. And because of this an Abstract Factory can rely on multiple Factory Methods.</p>\n<hr />\n<p><em>&quot;Is there a better way to get what I want than that?&quot;</em><br />\nAs always it depends what do you want.</p>\n<ul>\n<li>Do you want to hide direct object creation possibility? (<a href=\"https://refactoring.guru/replace-constructor-with-factory-method\" rel=\"nofollow noreferrer\">Factory method refactoring</a>)</li>\n<li>Do you want to ease complex object creation? (<a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">Builder design pattern</a>)</li>\n<li>Do you want to have an easy to read complex object creation interface? (<a href=\"https://www.martinfowler.com/bliki/FluentInterface.html\" rel=\"nofollow noreferrer\">Fluent interface pattern</a>)</li>\n<li>etc.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T05:38:46.707", "Id": "491302", "Score": "1", "body": "Thank you that is what I am looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T07:10:45.300", "Id": "250264", "ParentId": "250222", "Score": "2" } } ]
{ "AcceptedAnswerId": "250264", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T13:04:22.260", "Id": "250222", "Score": "3", "Tags": [ "c#", "design-patterns", "factory-method" ], "Title": "Implement Factory pattern with multiple parameters and each parameters are interface" }
250222
<p>I'm slurping up fields from an API that returns an array of fields. Each field in the array is a String that actually contains two separate fields (a number and a date). The number is enclosed in parentheses and the date is following this and a space. The following is an example of the format.</p> <pre><code>const data = [ &quot;(2) 2020-09-15&quot;, &quot;(3) 2020-09-16&quot; ]; </code></pre> <p>I'm parsing this field and then storing the data separately in my app. I have my own numbers and dates fields that will be a String in which each number and date is separated by a newline.</p> <p>I'm achieving this by doing the following.</p> <pre><code>let numbers = '', dates = numbers; for (let datum of data) { datum = datum.split(/[() ]/); numbers += `${datum[1]}\n`; dates += `${datum[3]}\n`; } </code></pre> <p>See an <a href="https://jsfiddle.net/wp9orjzm/28/" rel="nofollow noreferrer">example here</a>.</p> <p>I don't particularly like this and am wondering if there's a more efficient and cleaner way to write this.</p>
[]
[ { "body": "<p>Rather than declaring the variables with <code>let</code> (you should always <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">prefer <code>const</code></a>) and concatenating and reassigning, consider creating arrays of numbers and dates instead, eg:</p>\n<p><code>[2, 3]</code> and <code>[&quot;2020-09-15&quot;, &quot;2020-09-16&quot;]</code></p>\n<p>Then after the loop is done, join all elements by newlines.</p>\n<p>For the regular expression, rather than <code>split</code>, I think <code>match</code> would be more appropriate. You can use <code>\\((\\d+)\\) (\\S+)</code>:</p>\n<ul>\n<li><code>\\(</code> - literal <code>(</code></li>\n<li><code>(\\d+)</code> - 1st capturing group, composed of digits</li>\n<li><code>\\)</code> - literal <code>)</code></li>\n<li><code> </code> - literal space</li>\n<li><code>(\\S+)</code> - 2nd capturing group, composed of non-spaces</li>\n</ul>\n<p>Then extract the 1st and 2nd capturing groups.</p>\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 data = [\n \"(2) 2020-09-15\", \"(3) 2020-09-16\"\n];\nconst numbers = [];\nconst dates = [];\nfor (const item of data) {\n const [, number, date] = item.match(/\\((\\d+)\\) (\\S+)/);\n numbers.push(number);\n dates.push(date);\n}\nconsole.log(numbers.join('\\n'));\nconsole.log(dates.join('\\n'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:59:25.347", "Id": "490923", "Score": "0", "body": "I liked the `let vs const` post you put up. But does introducing the two arrays and pushes have any mem impact?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T16:10:55.680", "Id": "490925", "Score": "3", "body": "Every variable has a memory impact, but unless you have tens of thousands of items or something, it's not something to worry about. In general, better for code to focus on clarity and readability first. Then, if you find the script is running too slowly, run a performance analysis to see what are the bottlenecks, and fix those bottlenecks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T16:22:15.357", "Id": "490927", "Score": "0", "body": "Makes sense, thanks! Any go-to performance tools that you use?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T16:24:12.297", "Id": "490928", "Score": "2", "body": "For Node, use the `--inspect` flag: https://developer.ibm.com/technologies/node-js/articles/profiling-slow-code-in-nodejs/ then you can examine it with Chrome" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:22:03.430", "Id": "250225", "ParentId": "250224", "Score": "4" } }, { "body": "<p>I would use something like this:</p>\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 data = [\n \"(2) 2020-09-15\", \"(3) 2020-09-16\"\n ];\n\n let pairs = [];\n \n const regex = /^\\((\\d+)\\)\\s+(\\d{4}-\\d{2}-\\d{2})$/;\n \n for (let datum of data) {\n // Idea from the previous answer:\n let pair = {};\n [, pair.number, pair.date] = regex.exec(datum);\n pairs.push (pair);\n }\n\n console.log(pairs);</code></pre>\r\n</div>\r\n</div>\r\n\nEvery pair of number and date is packed as an object. The first comma in <code>[, pair.number, pair.date]</code> discards the whole match, which is not needed.</p>\n<p>Unlike the solution proposed by the question's author, the related date and number are united in one object. Also, splitting is not used, as it relies on the details of the text format that can change later and semantically better suits extracting an indefinite number of similar fragments from the text.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:44:36.927", "Id": "490921", "Score": "1", "body": "Welcome to Code Review! If you haven't already, please read [The help center page _How do I write a good answer?_](https://codereview.stackexchange.com/help/how-to-answer). Note it states: \"_Every answer must make at least one **insightful observation** about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:37:19.960", "Id": "250226", "ParentId": "250224", "Score": "1" } }, { "body": "<h2>Edge cases</h2>\n<p>In the real world, input isn't always well-formed. What happens if there is a typo in the data? For example:</p>\n<pre><code>const data = [\n &quot;(2) 2020-09-15&quot;, &quot;(3] 2020-09-16&quot;\n];\n</code></pre>\n<p>This will lead to <code>undefined</code> appearing in the output for the dates. In other cases/frameworks/languages an exception might be thrown that could crash your script/program. It would be better to guard against such scenarios by throwing an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error\" rel=\"nofollow noreferrer\">Error</a> or at least skipping addition of such data.</p>\n<hr />\n<h2>Variable clobbering</h2>\n<p>In the loop setup, <code>datum</code> is assigned each string in <code>data</code>:</p>\n<blockquote>\n<pre><code>for (let datum of data) {\n</code></pre>\n</blockquote>\n<p>This line over-writes that variable with an array:</p>\n<blockquote>\n<pre><code>datum = datum.split(/[() ]/);\n</code></pre>\n</blockquote>\n<p>This is legal in JavaScript because it is loosely-typed. But think of anyone reading this code (including your future-self!) when modifying this code. What if you decide later to use <code>datum</code> to display the output differently - you would need to determine whether it is the <code>datum</code> that is a string or the <code>datum</code> that is an array. A separate variable name might lead to less confusion in that respect, and also provide a better hint as to what is in the array - e.g. <code>parts</code>, or as is suggested by CertainPerformance's answer, using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring\" rel=\"nofollow noreferrer\">destructuring assignment</a> can help avoid that scenario altogether.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:58:22.703", "Id": "490922", "Score": "0", "body": "Thanks. In regards to the overwriting of datum - are there any concerns about memory with assigning to a separate var?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T16:57:11.517", "Id": "490930", "Score": "1", "body": "I doubt there would be much to be concerned about for such small code but going along with [CertainPerformance's comment](https://codereview.stackexchange.com/questions/250224/efficient-way-to-parse-custom-string-format/250230?noredirect=1#comment490925_250225) if you notice performance issues then you might want to look into the memory allocation of variables - consider eliminating variables that don't need to be assigned, or those that are only used once after being assigned." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:54:20.610", "Id": "250230", "ParentId": "250224", "Score": "3" } } ]
{ "AcceptedAnswerId": "250225", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:15:08.583", "Id": "250224", "Score": "7", "Tags": [ "javascript", "parsing", "node.js", "regex", "ecmascript-6" ], "Title": "parse date and number from API results" }
250224
<p>I am trying to refactor a service by providing some options on what to bring back. I can't decide what is best way to go between the below</p> <p><strong>A. Use a class for the options</strong> Create a new class for the options like</p> <pre><code> public class Options { public bool Addresses { get; set; } public bool Documents { get; set; } } </code></pre> <p>and call the services as below</p> <pre><code> public List&lt;Entity&gt; GetEntitiesByOptions(List&lt;int&gt; entityIds, Options options) { if (options.Addresses) { // Add the addresses } if (options.Documents) { // Add the Documents } } </code></pre> <p><strong>or B. Use the type of class as a parameter</strong></p> <p>and use with something like that</p> <pre><code> public List&lt;Entity&gt; GetEntitiesByOptions(List&lt;int&gt; entityIds, List&lt;Type&gt; options) { if (options.Any(x =&gt; x == typeof(Address))) { // Add the addresses } if (options.Any(x =&gt; x == typeof(Document))) { // Add the Documents } } </code></pre> <p>Would there be a big impact in the performance if I use reflection?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T08:12:42.150", "Id": "491009", "Score": "0", "body": "Have you considered to use [OneOf](https://github.com/mcintyre321/OneOf) or [Either](https://louthy.github.io/language-ext/LanguageExt.Core/LanguageExt/Either_L_R.htm) constructs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T14:29:02.597", "Id": "491038", "Score": "1", "body": "@PeterCsala thanks for the suggestion. I will take a look at them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T09:53:03.587", "Id": "491108", "Score": "1", "body": "Looks like a regular question for StackOverflow, not Code Review. You may test the performance easily with `Stopwatch` and accurately with `Benchmark.NET`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:38:49.410", "Id": "250227", "Score": "2", "Tags": [ "c#", "reflection" ], "Title": "Performance impact of using reflection instead of an \"Options\" class" }
250227
<p>This code works, but I feel bad about it. Did I achieve Python Zen or create a terrible monster? Note: it doesn't have to be super-fast or work on super-huge directory trees.</p> <pre><code>import glob from typing import List # Provide pathname without a trailing / def find_files_with_extension(pathname: str, extension: str) -&gt; List[str]: return list({item for sublist in [glob.iglob(s + &quot;**.&quot; + extension) for s in glob.iglob(pathname + &quot;/**/&quot;, recursive=True)] for item in sublist}) </code></pre>
[]
[ { "body": "<p>A few suggestions:</p>\n<ol>\n<li>This doesn't need to be a one line function. Writing it on one line makes it much harder to understand and makes finding mistakes more difficult.</li>\n<li>Use <code>os.path.join</code> to assemble your full pathname + wildcard + extension. That way, you don't need to worry about whether or not your pathname is given with or without a trailing <code>/</code></li>\n<li>If you're going to worry about a trailing <code>/</code> in your <code>pathname</code>, you should be equally worried about a preceding <code>.</code> in your <code>extension</code>.</li>\n<li><code>glob.glob</code> already returns a list with the matching files. I don't see any need for the complicated, nested list comprehensions you're using. Your function should essentially be a wrapper for calling <code>glob.glob</code> that simply makes combining the pathname + extension a little easier for the user.</li>\n</ol>\n<p>That being said, here's how I might re-write this function:</p>\n<pre><code>import glob\nimport os\n\nfrom typing import List\n\ndef find_files_with_extension(path_name: str, extension: str) -&gt; List[str]:\n extension_wildcard = &quot;*&quot;\n\n if extension[0] != &quot;.&quot;: # suggestion #3\n extension_wildcard += &quot;.&quot;\n extension_wildcard += extension\n\n path_name_wildcard = os.path.join(path_name, &quot;**&quot;, extension_wildcard) # suggestion #2\n\n return glob.glob(path_name_wildcard, recursive=True)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T13:23:00.907", "Id": "491234", "Score": "0", "body": "The hardest thing about this is you didn't actually test your code! Python uses # for comments not //. But it's better than mine. +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T18:46:31.147", "Id": "491257", "Score": "0", "body": "Apologies, I wrote and tested it without comments, then added them in before I posted!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T18:18:11.030", "Id": "250236", "ParentId": "250228", "Score": "4" } }, { "body": "<p>Here's a solution which should work fine, using the new, convenient <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">pathlib</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pathlib\n\n\ndef find_files_with_extension(path_name, extension):\n return list(pathlib.Path(path_name).rglob(&quot;*.&quot; + extension))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-13T00:11:32.917", "Id": "491685", "Score": "1", "body": "Thanks for this! I wonder how many more years it will take for Python teachers to teach pathlib instead of os.path. However, you should not return a list. rglob already returns an iterable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-13T00:12:49.720", "Id": "491686", "Score": "0", "body": "@Zababa I don't mind if teachers are slow to adapt, I just wish more people here (and on SO) made use of it!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T00:03:06.800", "Id": "250454", "ParentId": "250228", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T15:41:09.853", "Id": "250228", "Score": "2", "Tags": [ "python" ], "Title": "Python use glob to search for files by extension" }
250228
<p>I have below json which I need to deserialize in <code>C#</code> -</p> <pre><code>{ &quot;clientSettings&quot;:[ { &quot;clientId&quot;:12345, &quot;entries&quot;:[ { &quot;key&quot;:&quot;abc&quot;, &quot;value&quot;:false }, { &quot;key&quot;:&quot;def&quot;, &quot;value&quot;:false }, { &quot;key&quot;:&quot;ghi&quot;, &quot;value&quot;:false } ] }, { &quot;clientId&quot;:9876, &quot;entries&quot;:[ { &quot;key&quot;:&quot;lkmn&quot;, &quot;value&quot;:false } ] } ], &quot;productSettings&quot;:[ { &quot;productId&quot;:11, &quot;entries&quot;:[ { &quot;key&quot;:&quot;jkl&quot;, &quot;value&quot;:true }, { &quot;key&quot;:&quot;mno&quot;, &quot;value&quot;:true } ] }, { &quot;productId&quot;:12, &quot;entries&quot;:[ { &quot;key&quot;:&quot;jkl&quot;, &quot;value&quot;:true }, { &quot;key&quot;:&quot;mno&quot;, &quot;value&quot;:true } ] } ], &quot;customerSettings&quot;:[ { &quot;key&quot;:&quot;enableData&quot;, &quot;value&quot;:false }, { &quot;key&quot;:&quot;minPriceValue&quot;, &quot;value&quot;:&quot;10.28&quot; }, { &quot;key&quot;:&quot;presentData&quot;, &quot;value&quot;:&quot;AEGIS&quot; } ], &quot;thothTest&quot;:{ &quot;9876&quot;:[ &quot;K&quot; ], &quot;5431&quot;:[ &quot;A&quot;, &quot;L&quot; ], &quot;5123&quot;:[ &quot;L&quot; ] }, &quot;osirisTest&quot;:{ &quot;7678&quot;:[ &quot;K&quot; ] } } </code></pre> <p>Below is the classes I created to deserialzie json into -</p> <pre><code>public class ProcessHolder : Holder { public IDictionary&lt;int, ISet&lt;string&gt;&gt; OsirisTest { get; set; } public IDictionary&lt;int, ISet&lt;string&gt;&gt; ThothTest { get; set; } } public class Holder { public IList&lt;Mapping&gt; CustomerSettings { get; set; } public IList&lt;ClientSettingsMapping&gt; ClientSettings { get; set; } public IList&lt;ProductSettingsMapping&gt; ProductSettings { get; set; } } public class Mapping { public string Key { get; set; } public object Value { get; set; } } public class ProductSettingsMapping : Mapping { public int ProductId { get; set; } } public class ClientSettingsMapping : Mapping { public int ClientId { get; set; } } </code></pre> <ul> <li>I want to load all <code>customerSettings</code> values into <code>CustomerSettings</code> object of <code>Holder</code> class.</li> <li>Similarly I want to load all <code>clientSettings</code> values into <code>ClientSettings</code> object of <code>Holder</code> class.</li> <li>Similarly all <code>productSettings</code> values into <code>ProductSettings</code> object of <code>Holder</code> class.</li> <li>Similarly <code>thothTest</code> values into <code>ThothTest</code> and <code>osirisTest</code> values into <code>OsirisTest</code> object.</li> </ul> <p><strong>Note:</strong> Above POCO classes used to work with old json format and we were deserializing it directly using Newton JSON library but for some internal reason we are working on redesigning the json into new json which is what I shared above in my question. And now with this new json design we cannot directly deserialize it to my above POCO classes so that's why I came up with below code to do it manually. Since above POCO classes are used at so many places so thats why I don't want to touch that interface.</p> <p>Below is my working code which manually parses that json and populate above classes. I wanted to see if there is any way we can improve below code base as it looks like I am repeating lot of things. I think it can be organized by having some helper methods which can do the job for me but not able to figure it out on how to do this?</p> <pre><code>public static void Main(string[] args) { var jsonContent = File.ReadAllText(&quot;/beta/Downloads/test.json&quot;); var parsed = JObject.Parse(jsonContent); var parsedClientSettings = parsed[&quot;clientSettings&quot;]; List&lt;ClientSettingsMapping&gt; clientSettings = new List&lt;ClientSettingsMapping&gt;(); foreach (var parsedClientSetting in parsedClientSettings) { var clientId = parsedClientSetting.Value&lt;int&gt;(&quot;clientId&quot;); foreach (var entry in parsedClientSetting[&quot;entries&quot;]) { clientSettings.Add(new ClientSettingsMapping { ClientId = clientId, Key = entry[&quot;key&quot;].ToString(), Value = entry[&quot;value&quot;].ToString() }); } } var parsedproductSettings = parsed[&quot;productSettings&quot;]; List&lt;ProductSettingsMapping&gt; productSettings = new List&lt;ProductSettingsMapping&gt;(); foreach (var parsedproductSetting in parsedproductSettings) { var productId = parsedproductSetting.Value&lt;int&gt;(&quot;productId&quot;); foreach (var entry in parsedproductSetting[&quot;entries&quot;]) { productSettings.Add(new ProductSettingsMapping { ProductId = productId, Key = entry[&quot;key&quot;].ToString(), Value = entry[&quot;value&quot;].ToString() }); } } var parsedCustomerSettings = parsed[&quot;customerSettings&quot;]; List&lt;Mapping&gt; customerSettings = new List&lt;Mapping&gt;(); foreach (var entry in parsedCustomerSettings) { customerSettings.Add(new Mapping { Key = entry[&quot;key&quot;].ToString(), Value = entry[&quot;value&quot;].ToString() }); } var parsedthothTests = parsed[&quot;thothTest&quot;]; IDictionary&lt;int, ISet&lt;string&gt;&gt; thothTest = new Dictionary&lt;int, ISet&lt;string&gt;&gt;(); foreach (JProperty x in (JToken)parsedthothTests) { int name = int.Parse(x.Name); JToken value = x.Value; ISet&lt;string&gt; values = new HashSet&lt;string&gt;(); foreach (var val in value) { values.Add((string)val); } thothTest.Add(name, values); } var parsedOsirisTests = parsed[&quot;osirisTest&quot;]; IDictionary&lt;int, ISet&lt;string&gt;&gt; osirisTest = new Dictionary&lt;int, ISet&lt;string&gt;&gt;(); foreach (JProperty x in (JToken)parsedOsirisTests) { int name = int.Parse(x.Name); JToken value = x.Value; ISet&lt;string&gt; values = new HashSet&lt;string&gt;(); foreach (var val in value) { values.Add((string)val); } osirisTest.Add(name, values); } ProcessHolder processHolder = new ProcessHolder() { ClientSettings = clientSettings, ProductSettings = productSettings, CustomerSettings = customerSettings, ThothTest = thothTest, OsirisTest = osirisTest }; // now use &quot;processHolder&quot; object here } </code></pre>
[]
[ { "body": "<p>You can take advantage of the <a href=\"https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_ToObject__1.htm\" rel=\"nofollow noreferrer\">ToObject() method of the JToken</a>.</p>\n<p>With that your parsing logic could be simplified to this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var jsonContent = File.ReadAllText(&quot;/beta/Downloads/test.json&quot;);\nvar parsed = JObject.Parse(jsonContent);\n\n//ClientSettings needs special handling\nvar parsedClientSettings = parsed[&quot;clientSettings&quot;];\nvar clientSettings = new List&lt;ClientSettingsMapping&gt;();\nforeach (var parsedClientSetting in parsedClientSettings)\n{\n var clientId = parsedClientSetting.Value&lt;int&gt;(&quot;clientId&quot;);\n var entries = parsedClientSetting[&quot;entries&quot;].ToObject&lt;List&lt;Mapping&gt;&gt;();\n clientSettings.AddRange(entries\n .Select(entry =&gt; new ClientSettingsMapping { ClientId = clientId, Key = entry.Key, Value = entry.Value }));\n}\n\n//ProductSettings needs special handling\nvar parsedproductSettings = parsed[&quot;productSettings&quot;];\nvar productSettings = new List&lt;ProductSettingsMapping&gt;();\nforeach (var parsedproductSetting in parsedproductSettings)\n{\n var productId = parsedproductSetting.Value&lt;int&gt;(&quot;productId&quot;);\n var entries = parsedproductSetting[&quot;entries&quot;].ToObject&lt;List&lt;Mapping&gt;&gt;();\n productSettings.AddRange(entries\n .Select(entry =&gt; new ProductSettingsMapping {ProductId = productId, Key = entry.Key, Value = entry.Value}));\n}\n\nvar processHolder = new ProcessHolder\n{\n ClientSettings = clientSettings,\n ProductSettings = productSettings,\n CustomerSettings = parsed[&quot;customerSettings&quot;].ToObject&lt;List&lt;Mapping&gt;&gt;(),\n ThothTest = parsed[&quot;thothTest&quot;].ToObject&lt;Dictionary&lt;int, ISet&lt;string&gt;&gt;&gt;(),\n OsirisTest = parsed[&quot;osirisTest&quot;].ToObject&lt;Dictionary&lt;int, ISet&lt;string&gt;&gt;&gt;()\n};\n</code></pre>\n<h3><code>clientSettings/entries</code></h3>\n<ul>\n<li>Here you can use <code>ToObject&lt;List&lt;Mapping&gt;</code>\n<ul>\n<li>then you can use LINQ to construct a list of <code>ClientSettingsMapping</code></li>\n</ul>\n</li>\n</ul>\n<h3><code>productSettings/entries</code></h3>\n<ul>\n<li>Here you can use <code>ToObject&lt;List&lt;Mapping&gt;</code>\n<ul>\n<li>then you can use LINQ to construct a list of <code>ProductSettingsMapping</code></li>\n</ul>\n</li>\n</ul>\n<h3><code>customerSettings</code></h3>\n<ul>\n<li>Here you can use <code>ToObject&lt;List&lt;Mapping&gt;</code></li>\n</ul>\n<h3><code>thothTest</code> and <code>osirisTest</code></h3>\n<ul>\n<li>Here you can use <code>ToObject&lt;Dictionary&lt;int, ISet&lt;string&gt;&gt;&gt;</code></li>\n</ul>\n<hr />\n<p><strong>UPDATE #1</strong>: Adding helper method to reduce code duplication</p>\n<p>In order to reduce code duplication (the Client and Product settings are handled almost in the same way) we can introduce the following helper method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private List&lt;T&gt; ParseSettings&lt;T&gt;(JToken parsed, string settingsNodeName, string idNodeName, Func&lt;(int id, string key, object value), T&gt; mapper)\n{\n var rawSettings = parsed[settingsNodeName];\n var settings = new List&lt;T&gt;();\n foreach (var setting in rawSettings)\n {\n var id = setting.Value&lt;int&gt;(idNodeName);\n var entries = setting[&quot;entries&quot;].ToObject&lt;List&lt;Mapping&gt;&gt;();\n settings.AddRange(entries\n .Select(entry =&gt; mapper((id, entry.Key, entry.Value))));\n }\n\n return settings;\n}\n</code></pre>\n<p>Its usage would look like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var productSettings = ParseSettings(parsed, &quot;productSettings&quot;, &quot;productId&quot;,\n mapping=&gt; new ProductSettingsMapping {ProductId = mapping.id, Key = mapping.key, Value = mapping.value});\nvar clientSettings = ParseSettings(parsed, &quot;clientSettings&quot;, &quot;clientId&quot;,\n mapping=&gt; new ClientSettingsMapping {ClientId = mapping.id, Key = mapping.key, Value = mapping.value});\n</code></pre>\n<hr />\n<p><strong>UPDATE #2</strong>: Adding an alternative implementation (uses <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/linq/query-expression-basics\" rel=\"nofollow noreferrer\">linq query expression syntax</a>) for <code>ParseSettings</code>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static List&lt;T&gt; ParseSettings&lt;T&gt;(JToken parsed, string settingsNodeName, string idNodeName, \n Func&lt;(int id, string key, object value), T&gt; mapper)\n =&gt;\n (from setting in parsed[settingsNodeName]\n let id = setting.Value&lt;int&gt;(idNodeName)\n let entries = setting[&quot;entries&quot;].ToObject&lt;List&lt;Mapping&gt;&gt;()\n from entry in entries\n select mapper((id, entry.Key, entry.Value)))\n .ToList();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T14:03:18.883", "Id": "491035", "Score": "1", "body": "I wasn't aware of `ToObject() method of the JToken`. This is nice. Thanks for showing me this. Also do you think we can simplify `clientSettings` and `productSettings` into some helper methods so that we don't have to duplicate same code which is being used in them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T14:23:44.217", "Id": "491037", "Score": "0", "body": "@DavidTodd I've updated my answer to include that helper method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-19T16:52:55.033", "Id": "493589", "Score": "1", "body": "Looks like there is a bug in `ParseSettings` method where it only keeps one object in it but I have multiple json objects for `productSettings` and `clientSettings`. It seems to overwriting previous entries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-19T17:03:28.950", "Id": "493590", "Score": "0", "body": "For example: `productSettings` object only has 12 as `productId` and its entries. 11 as the productId and its entries is missing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-20T09:07:57.797", "Id": "493660", "Score": "0", "body": "@DavidTodd Yepp, you are right, sorry for the inconvenience. We need to use `AddRange`. I've updated my answer, please check it again." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T08:04:15.317", "Id": "250267", "ParentId": "250233", "Score": "6" } } ]
{ "AcceptedAnswerId": "250267", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T17:44:01.843", "Id": "250233", "Score": "4", "Tags": [ "c#", "json" ], "Title": "Parse json manually to POCO classes" }
250233
<p>I'm building an MVC web app with ASP.CORE 3.1 and EF connected to MSSQL.</p> <p>Today, finally after 3 days, I've somewhat reached a working code for filtering my view.</p> <p>I've got database of</p> <ul> <li>Date stamps (15 minute intervals) and</li> <li>INT values of cars (3 types (OA, NA, NS))</li> <li>going through Border (13 of them).</li> <li>Data are for both directions (Plus, Minus).</li> <li>I need to filter this by above plus change time interval (60, 30, 15 minutes)</li> <li>and by Weekdays (Monday, Friday, Sat, Sun, and Ordinary (Tuesday-Thursday)).</li> </ul> <p>But I'm doing filtering for the <strong>first time in my life</strong> here. Happy it works but would love to hear how can I improve this. Dataset is not big. Around 17 columns x 300 000 rows.</p> <h3>Visualization</h3> <p><a href="https://i.stack.imgur.com/IbOCs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IbOCs.png" alt="enter image description here" /></a></p> <h3>Model</h3> <p>Borders.cs</p> <pre class="lang-cs prettyprint-override"><code>public class Borders { [Key] public int Id { get; set; } public int TransitId { get; set; } public DateTime Day { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public int OA_Plus { get; set; } public int NA_Plus { get; set; } public int NS_Plus { get; set; } public int ALL_Plus { get; set; } public int OA_Minus { get; set; } public int NA_Minus { get; set; } public int NS_Minus { get; set; } public int ALL_Minus { get; set; } public int OA_Sum { get; set; } public int NA_Sum { get; set; } public int NS_Sum { get; set; } public int ALL_Sum { get; set; } } </code></pre> <h3>ViewModel</h3> <p>BordersViewModel.cs</p> <pre class="lang-cs prettyprint-override"><code>public class BordersViewModel { // DB items public IEnumerable&lt;Borders&gt; Borders { get; set; } // Other ViewModels public IEnumerable&lt;ChartIntensityVM&gt; ChartIntensityVM { get; set; } // Contains only String Key, Int Value // Filters public string FilterTransitNumber { get; set; } = &quot;All&quot;; public string FilterSeason { get; set; } = &quot;All&quot;; public string FilterDay { get; set; } = &quot;All&quot;; public string FilterTimeInterval { get; set; } = &quot;1&quot;; public string FilterDirection { get; set; } = &quot;All&quot;; public bool FilterChkboxOA { get; set; } = true; public bool FilterChkboxNA { get; set; } = true; public bool FilterChkboxNS { get; set; } = true; // SelectListItems public List&lt;SelectListItem&gt; ListTransitNumbers { get; set; } = new List&lt;SelectListItem&gt;() { new SelectListItem { Value = &quot;All&quot;, Text = &quot;All&quot; }, }; public List&lt;SelectListItem&gt; ListSeasons { get; set; } = new List&lt;SelectListItem&gt;() { new SelectListItem { Value = &quot;All&quot;, Text = &quot;All&quot; }, new SelectListItem { Value = &quot;Q1&quot;, Text = &quot;Spring (1-3)&quot; }, new SelectListItem { Value = &quot;Q2&quot;, Text = &quot;Summer (3-6)&quot; }, new SelectListItem { Value = &quot;Q3&quot;, Text = &quot;Fall (6-9)&quot; }, new SelectListItem { Value = &quot;Q4&quot;, Text = &quot;Winter (9-12)&quot; }, }; public List&lt;SelectListItem&gt; ListDays { get; set; } = new List&lt;SelectListItem&gt;() { new SelectListItem { Value = &quot;All&quot;, Text = &quot;All&quot; }, new SelectListItem { Value = &quot;Ordinary&quot;, Text = &quot;Ordinary day (Tue, Wed, Thr)&quot; }, new SelectListItem { Value = &quot;Friday&quot;, Text = &quot;Friday&quot; }, new SelectListItem { Value = &quot;Sunday&quot;, Text = &quot;Sunday&quot; }, new SelectListItem { Value = &quot;Monday&quot;, Text = &quot;Monday&quot; }, }; public List&lt;SelectListItem&gt; ListTimeIntervals { get; set; } = new List&lt;SelectListItem&gt;() { new SelectListItem { Value = &quot;60&quot;, Text = &quot;1 hr&quot; }, new SelectListItem { Value = &quot;30&quot;, Text = &quot;0.5 hr&quot; }, new SelectListItem { Value = &quot;15&quot;, Text = &quot;0.25 hr&quot; }, }; public List&lt;SelectListItem&gt; ListDirections { get; set; } = new List&lt;SelectListItem&gt;() { new SelectListItem { Value = &quot;All&quot;, Text = &quot;All&quot; }, new SelectListItem { Value = &quot;Plus&quot;, Text = &quot;Plus&quot; }, new SelectListItem { Value = &quot;Minus&quot;, Text = &quot;Minus&quot; }, }; } </code></pre> <h3>View</h3> <p>Index.cshtml</p> <pre class="lang-html prettyprint-override"><code>classical view, you can see that in the picture above SelectLists, Checkboxes, Filterbutton that is doing form POST method </code></pre> <h3>Controller</h3> <p>BordersController.cs</p> <pre class="lang-cs prettyprint-override"><code>[HttpPost] [ValidateAntiForgeryToken] public async Task&lt;IActionResult&gt; Index(BordersViewModel vm) { if (ModelState.IsValid) { vm.Borders = await _db.Borders.OrderBy(x =&gt; x.Start).ToListAsync(); populateListTransitNumbers(vm); } // FILTER - TransitNumber (1 - 16) //================================ if (vm.FilterTransitNumber != &quot;All&quot;) { vm.Borders = vm.Borders.Where(x =&gt; x.TransitId == Convert.ToInt32(vm.FilterTransitNumber)); } // // FILTER - Day (Monday, Friday, Sunday, Ordinary [Tuesday, Wednesday, Thursday]) //================================================================================== if (vm.FilterDay != &quot;All&quot;) { List&lt;string&gt; ordinaryDays = new List&lt;string&gt;() { &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot; }; switch (vm.FilterDay) { case &quot;Monday&quot;: case &quot;Friday&quot;: case &quot;Sunday&quot;: vm.Borders = vm.Borders.Where(x =&gt; x.Start.DayOfWeek.ToString() == vm.FilterDay); break; default: vm.Borders = vm.Borders.Where(x =&gt; ordinaryDays.Contains(x.Start.DayOfWeek.ToString())); break; } } // FILTER - Season (Q1 - Q4) //========================== if (vm.FilterSeason != &quot;All&quot;) { switch (vm.FilterSeason) { case &quot;Q1&quot;: vm.Borders = vm.Borders.Where(x =&gt; x.Start.Month &gt;= 1 &amp;&amp; x.Start.Month &lt;= 3); break; case &quot;Q2&quot;: vm.Borders = vm.Borders.Where(x =&gt; x.Start.Month &gt;= 3 &amp;&amp; x.Start.Month &lt;= 6); break; case &quot;Q3&quot;: vm.Borders = vm.Borders.Where(x =&gt; x.Start.Month &gt;= 6 &amp;&amp; x.Start.Month &lt;= 9); break; case &quot;Q4&quot;: vm.Borders = vm.Borders.Where(x =&gt; x.Start.Month &gt;= 9 &amp;&amp; x.Start.Month &lt;= 12); break; } } // FILTER - TimeInterval (60, 30, 15) //=================================== var filteredBordersInterval = vm.Borders .GroupBy(x =&gt; { var stamp = x.Start; stamp = stamp.AddMinutes(-(stamp.Minute % Convert.ToInt32(vm.FilterTimeInterval))); stamp = stamp.AddMilliseconds(-stamp.Millisecond - 1000 * stamp.Second); return stamp; }) .Select(g =&gt; new { TransitId = g.First().TransitId, Start = g.Key, OA_Plus = g.Sum(gi =&gt; gi.OA_Plus), NA_Plus = g.Sum(gi =&gt; gi.NA_Plus), NS_Plus = g.Sum(gi =&gt; gi.NS_Plus), OA_Minus = g.Sum(gi =&gt; gi.OA_Minus), NA_Minus = g.Sum(gi =&gt; gi.NA_Minus), NS_Minus = g.Sum(gi =&gt; gi.NS_Minus), }); // ORDER BY TIME INTERVAL // Ignore the whole DateTime day, just group by HH:mm and SUM column rows //======================= var filteredBordersGrouped = filteredBordersInterval .GroupBy(x =&gt; x.Start.ToString(&quot;HH:mm&quot;)) .Select(g =&gt; new { DayTime = g.Key, OA_Plus = g.Sum(gi =&gt; gi.OA_Plus), NA_Plus = g.Sum(gi =&gt; gi.NA_Plus), NS_Plus = g.Sum(gi =&gt; gi.NS_Plus), OA_Minus = g.Sum(gi =&gt; gi.OA_Minus), NA_Minus = g.Sum(gi =&gt; gi.NA_Minus), NS_Minus = g.Sum(gi =&gt; gi.NS_Minus), }); // FINAL FILTER into X/Y values for the Chart // Sum only those cars that are checked and both or individual directions //=========================================== vm.ChartIntensityVM = filteredBordersGrouped .GroupBy(x =&gt; x.DayTime) .Select(g =&gt; { int PlusSum = g.Sum(gi =&gt; vm.FilterChkboxOA == true ? gi.OA_Plus : 0) + g.Sum(gi =&gt; vm.FilterChkboxNA == true ? gi.NA_Plus : 0) + g.Sum(gi =&gt; vm.FilterChkboxNS == true ? gi.NS_Plus : 0); int MinusSum = g.Sum(gi =&gt; vm.FilterChkboxOA == true ? gi.OA_Minus : 0) + g.Sum(gi =&gt; vm.FilterChkboxNA == true ? gi.NA_Minus : 0) + g.Sum(gi =&gt; vm.FilterChkboxNS == true ? gi.NS_Minus : 0); int AllSum = vm.FilterDirection == &quot;All&quot; ? PlusSum + MinusSum : (vm.FilterDirection == &quot;Plus&quot; ? PlusSum : MinusSum); return new ChartIntensityVM { Key = g.Key, Value = AllSum, }; }); return View(vm); } </code></pre>
[]
[ { "body": "<p>Some quick remarks</p>\n<ul>\n<li><p>Follow the naming standards. Property names etc. should not contain anything but alphanumeric characters. No underscores etc.</p>\n</li>\n<li><p>Use meaningful names. <code>&quot;OA&quot;</code> is meaningless, <code>&quot;OA_Plus&quot;</code> is even more confusing.</p>\n</li>\n<li><p>A class name shouldn't be a plural (some exceptions apply): <code>Borders</code>.</p>\n</li>\n<li><p>So many magic strings. <code>&quot;All&quot;</code> appears numerous times, for instance. Consider moving these to <code>static</code> classes as <code>public const string</code> properties.</p>\n</li>\n<li><p>Do not pointlessly abbreviate: naming it <code>Chkbox</code> isn't making your code run faster.</p>\n</li>\n<li><p>Do not call something a &quot;ListXXXX&quot;, e.g. <code>ListDays</code>. If it is a list of days, call it &quot;Days&quot;.</p>\n</li>\n<li><p><code>ListDays</code> seems to omit Saturday, and &quot;Thr&quot; isn't the correct abbreviation for &quot;Thursday&quot;.</p>\n</li>\n<li><p>Your seasons/quarters seem to overlap: <code>&quot;Spring (1-3)&quot;</code> vs. <code>&quot;Summer (3-6)&quot;</code>. IMHO it should be &quot;1-3&quot;, &quot;4-6&quot;, etc. However, this is also implemented this way in your business logic -- <code>vm.Borders.Where(x =&gt; x.Start.Month &gt;= 3 &amp;&amp; x.Start.Month &lt;= 6);</code> -- so I guess that is the &quot;correct&quot; logic? Still, it doesn't make sense to me that Q1 shows data for three months, whereas the others show data for four months. IMHO this look like a major bug.</p>\n</li>\n<li><p><code>public async Task&lt;IActionResult&gt; Index(BordersViewModel vm)</code> is more than 100 lines long. I'd move almost all of that code to a separate class.</p>\n</li>\n</ul>\n<hr />\n<p>The title of your question says &quot;Filtering database with Linq&quot;, yet your question works completely with the view model. I actually wonder if some of the filtering you do could be done more efficiently in a query, instead of (what you seem to be doing) dumping all of the available data in <code>Borders</code> objects and then applying a lot of filtering logic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T16:21:50.440", "Id": "250283", "ParentId": "250234", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T17:55:57.130", "Id": "250234", "Score": "3", "Tags": [ "c#", "mvc", "database", "asp.net-core" ], "Title": "Filtering database with Linq" }
250234
<p>I am absolutely new to c++ and am trying to learn SDL2 with c++. I am setting up my first project and I was unsure if the way I have structured the project is good or if I have over done it. Here is the code:</p> <p><code>generalFuncs.h</code></p> <pre><code>#pragma once #include &quot;SDL.h&quot; #include &lt;iostream&gt; struct State { bool quit = false; }; class CreateWindow { public: CreateWindow( int x, int y, int w, int h, bool fullScreen = false ) { pWindow = SDL_CreateWindow(&quot;&quot;, x, y, w, h, fullScreen); } inline SDL_Window* getWindow() { return pWindow; } private: SDL_Window* pWindow; }; class Events { public: void handleEvents(State* state) { while (SDL_PollEvent(&amp;event)) { if (event.type == SDL_QUIT) state-&gt;quit = true; } } private: SDL_Event event; }; </code></pre> <p><code>renderer.h</code></p> <pre><code>#pragma once #include &quot;SDL.h&quot; class Renderer { public: Renderer(SDL_Window* pWindow) { pRenderer = SDL_CreateRenderer(pWindow, -1, 0); } inline SDL_Renderer* getRenderer() { return pRenderer; } inline void clearScreen(int r, int g, int b, int a) { SDL_SetRenderDrawColor(pRenderer, r, g, b, a); SDL_RenderClear(pRenderer); } inline void update() { SDL_RenderPresent(pRenderer); } void render() { } private: SDL_Renderer* pRenderer; }; </code></pre> <p><code>main.cpp</code></p> <pre><code>#include &lt;iostream&gt; #include &lt;SDL.h&gt; #include &lt;vector&gt; #include &quot;generalFuncs.h&quot; #include &quot;renderer.h&quot; int main(int argc, char* argv[]) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout &lt;&lt; &quot;Could not initialze SDL properly \n&quot; &lt;&lt; SDL_GetError() &lt;&lt; std::endl; return 0; } CreateWindow window(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1200, 600); Renderer renderer(window.getWindow()); State state; Events events; if (window.getWindow() == NULL) { std::cout &lt;&lt; &quot;Could not window properly \n&quot; &lt;&lt; SDL_GetError() &lt;&lt; std::endl; return 0; } if (renderer.getRenderer() == NULL) { std::cout &lt;&lt; &quot;Could not window properly \n&quot; &lt;&lt; SDL_GetError() &lt;&lt; std::endl; return 0; } while (!state.quit) { events.handleEvents(&amp;state); renderer.clearScreen(255, 255, 255, 255); renderer.render(); renderer.update(); } SDL_DestroyWindow(window.getWindow()); SDL_Quit(); return EXIT_SUCCESS; } </code></pre> <p>The way I plan on using this is make other header files, include them to <code>render.h</code>, then draw them in the <code>render</code> method. Please let me know if there are better way to do things or if my setup can be improved. Thank you.</p>
[]
[ { "body": "<p>I think that yes, the code can be structured somewhat better.</p>\n<p>First of all, I'd tend to &quot;RAII all the things&quot;. Code like this at the end of <code>main</code> makes me extremely suspicious:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> SDL_DestroyWindow(window.getWindow());\n SDL_Quit();\n</code></pre>\n<p>I'd <em>strongly</em> prefer that those be handled in the destructor of some object so they happen automatically.</p>\n<p>So, I'd rename <code>CreateWindow</code> to just <code>Window</code>. Then I'd add a destructor that called <code>SDL_DestroyWindow</code>, so it'll automatically clean itself up when it goes out of scope.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Window {\npublic:\n Window(int x, int y, int w, int h, bool fullScreen = false) {\n pWindow = SDL_CreateWindow(&quot;&quot;, x, y, w, h, fullScreen);\n if (pWindow == nullptr)\n throw std::runtime_error(&quot;Unable to create window&quot;);\n }\n\n ~Window() { SDL_DestroyWindow(pWindow); }\n\n operator SDL_Window*() { return pWindow; }\n\nprivate:\n SDL_Window *pWindow;\n};\n</code></pre>\n<p>Likewise I'd add an <code>Application</code> class (or something on that order that calls <code>SDL_Init</code> in its ctor, and <code>SDL_Quit();</code> in its dtor, so simply defining a variable of that type automatically initializes SDL, and cleans up before it goes out of scope.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Application {\npublic: \n Application() { \n if (SDL_Init(SDL_INIT_EVERYTHING) != 0)\n {\n std::stringstream buffer;\n buffer &lt;&lt; &quot;Could not intialize SDL properly: &quot; &lt;&lt; SDL_GetError();\n\n throw std::runtime_error(buffer.str());\n } \n }\n\n ~Application() {\n SDL_Quit();\n }\n};\n</code></pre>\n<p>...and of course, Renderer should clean up after itself as well:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> ~Renderer() { \n SDL_DestroyRenderer(pRenderer);\n }\n</code></pre>\n<p>I'd also add definitions of copy assignment, move assignment, copy construction, and move construction to <code>Renderer</code>, <code>Window</code> and <code>Application</code>, so somebody won't accidentally do something nasty and breaking with them. In this case, they're probably move-only classes, so we'd do something on this order:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Renderer(Renderer const &amp;) = delete;\n Renderer(Renderer &amp;&amp;other) { \n pRenderer = other.pRenderer; \n other.pRenderer = nullptr; \n }\n Renderer &amp;operator=(Renderer const &amp;) = delete;\n Renderer &amp;operator=(Renderer &amp;&amp; other) { \n pRenderer = other.pRenderer; \n other.pRenderer = nullptr; \n return *this;\n }\n</code></pre>\n<p>Window would probably be similar in this regard, and Application should probably delete all of them.</p>\n<p>I'd also have each of the classes report problems with construction by throwing an exception, rather than leaving it to client code to detect the problem when (for example) it has failed to create a window.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Window(int x, int y, int w, int h, bool fullScreen = false) {\n pWindow = SDL_CreateWindow(&quot;&quot;, x, y, w, h, fullScreen);\n if (pWindow == nullptr)\n throw std::runtime_error(&quot;Unable to create window&quot;);\n }\n}\n</code></pre>\n<p>Rather than <code>Events::handleEvents</code> being passed a Boolean in a structure, I'd have it just return a value to indicate when the program should exit:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> bool handleEvents()\n {\n while (SDL_PollEvent(&amp;event))\n {\n if (event.type == SDL_QUIT)\n return false;\n }\n return true;\n }\n</code></pre>\n<p>I'd also put all of these in a namespace named something like <code>sdl</code> (or <code>sdl2</code>, or something on that order).</p>\n<p>With that &quot;stuff&quot; in place, our <code>main</code> can shrink to something on this order:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main(int argc, char* argv[])\n{\n try {\n sdl::Application app;\n\n sdl::Window window(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1600, 1200);\n sdl::Renderer renderer(window);\n sdl::Events events;\n\n while (events.handleEvents())\n {\n renderer.clearScreen(255, 255, 255, 255);\n renderer.render();\n renderer.update();\n }\n }\n catch(std::exception const &amp;e) { \n std::cerr &lt;&lt; e.what() &lt;&lt; &quot;\\n&quot;;\n }\n}\n</code></pre>\n<p>Although I haven't shown it above, I'd at least be <em>tempted</em> to require that a reference to an <code>sdl::Application</code> be passed to the ctor when you create an <code>sdl::Window</code> object. This assures that you've created an <code>sdl::Application</code> object first, thereby assuring that SDL is initialized before you try to create a window with it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T09:34:53.377", "Id": "491011", "Score": "0", "body": "Thank you very much. Appreciate it. I have one more question: What is the point of \"copy assignment, move assignment, copy construction, and move construction\". Pardon my ignorance, I am new." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T09:52:13.150", "Id": "491014", "Score": "0", "body": "Is `operator SDL_Window*() { return pWindow; }` operator overloading ? In tutorials I have only seen overloading with ints and other builtin data structures." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T06:51:49.577", "Id": "250262", "ParentId": "250239", "Score": "2" } } ]
{ "AcceptedAnswerId": "250262", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T19:21:47.063", "Id": "250239", "Score": "1", "Tags": [ "c++", "sdl", "sdl2" ], "Title": "Good way to structure a SDL project" }
250239
<p>I've developed a class which is designed to hold a range of percentage values. The following is the intended functionality:</p> <ol> <li>The range should store two bounds (a lower and an upper)</li> <li>The bounds should be percentages expressed as a double decimal and should be &gt;= 0 and &lt;=1</li> <li>Each bound could be inclusive or exclusive</li> <li>The lower bound should not be greater or equal than the lower</li> <li>The range class should have a method to tell whether a given double decimal is within the range.</li> </ol> <p>This is my code:</p> <pre><code>#include &lt;iostream&gt; using namespace std; // we are comparing doubles so we cannot rely on == bool cmpd (double num1, double num2) { const double epsilon = 0.000001; if (std::abs(num1 - num2) &lt;= epsilon) { return true; } return std::abs(num1 - num2) &lt;= epsilon * std::max(std::abs(num1), std::abs(num2)); } enum class BoundType { Inclusive, Exclusive }; struct Bound { private: double mBoundPerc; BoundType mBoundType; public: Bound() = default; Bound(double perc, BoundType bType) { // If bound is not greater than or equal to 0 then invalid if (!(perc &gt; 0) &amp;&amp; !cmpd(perc, 0) ) { throw &quot;Invalid range&quot;; } // If bound is not lower than or equal to 1 then invalid if (!(perc &lt; 1) &amp;&amp; !cmpd(perc,1)) { throw &quot;Invalid range&quot;; } mBoundPerc = perc, mBoundType = bType; } double getBound() { return mBoundPerc; } BoundType getBoundType() { return mBoundType; } }; class PercRange { private: Bound mLowerBound, mUpperBound; bool isRangeValid(Bound lower, Bound upper) { // a range is invalid if lower &gt;= upper if (lower.getBound() &gt; upper.getBound() || cmpd(lower.getBound(), upper.getBound()) ) { return false; } return true; } public: PercRange(Bound lower, Bound upper) { if (!setRange(lower, upper )) { throw &quot;Range invalid&quot;; } } bool setRange(Bound lower, Bound upper ) { if (!isRangeValid(lower, upper)) { return false; } mLowerBound = lower, mUpperBound = upper; return true; } bool isWithin(double num) { // if lower boud is inclusive then num must either be equal to or greater than lower bound if (mLowerBound.getBoundType() == BoundType::Inclusive &amp;&amp; !(cmpd(num, mLowerBound.getBound()) || num &gt; mLowerBound.getBound() ) ) { return false; } // if lower bound exclusive then num must be greater than lower bound if (mLowerBound.getBoundType() == BoundType::Exclusive &amp;&amp; !(num &gt; mLowerBound.getBound())) { return false; } // if upper boud is inclusive then num must either be equal to or less than upper bound if (mUpperBound.getBoundType() == BoundType::Inclusive &amp;&amp; !(cmpd(num, mUpperBound.getBound()) || num &lt; mUpperBound.getBound())) { return false; } // if upper bound exclusive then num must be less than upper bound if (mUpperBound.getBoundType() == BoundType::Exclusive &amp;&amp; !(num &lt; mUpperBound.getBound())) { return false; } return true; } }; int main() { PercRange range(Bound(0.2, BoundType::Inclusive), Bound(0.4, BoundType::Exclusive) ); cout &lt;&lt; range.isWithin(0.2) &lt;&lt; endl; // 1 cout &lt;&lt; range.isWithin(0.199) &lt;&lt; endl; // 0 cout &lt;&lt; range.isWithin(0.399) &lt;&lt; endl; // 1 cout &lt;&lt; range.isWithin(0.4) &lt;&lt; endl; // 0 Bound bound (1, BoundType::Inclusive); return 0; } </code></pre> <p>Thanks</p>
[]
[ { "body": "<h1>Avoid floating point math if you need it to be exact</h1>\n<p>Let's look at this code:</p>\n<pre><code>const double epsilon = 0.000001;\nif (std::abs(num1 - num2) &lt;= epsilon) {\n return true;\n}\n</code></pre>\n<p>Why did you pick that value of epsilon? Is it really precise enough? What if I do the following:</p>\n<pre><code>const double epsilon = 0.000001;\nPercRange range(Bound(0.2, BoundType::Inclusive), Bound(0.4, BoundType::Exclusive));\n\nstd::cout &lt;&lt; range.isWithin(0.2 - epsilon / 2.0) &lt;&lt; '\\n';\n</code></pre>\n<p>Clearly the value I'm testing is outside the range, but it's returning <code>1</code> anyway. That is not what you would expect.</p>\n<p>If you want to deal with values with two decimals, then use an integer type to store the values pre-multiplied by 100. This way you can use exact integer math and you will always exactly get what you want. However, that only works if you use those integers everywhere. As soon as you are converting to or from floating points, you have to deal with possible rounding errors.</p>\n<p>I you don't want to go this route, then just accept the way <a href=\"https://en.wikipedia.org/wiki/IEEE_754\" rel=\"nofollow noreferrer\">IEEE 754 floating point</a> works, and don't try to introduce epsilons.</p>\n<h1>Simplify your code</h1>\n<p>You are introducing two classes and and enum, just for checking if a value is between two other values. Is this really necessary? I would create single function that can check if a value is within the range of another:</p>\n<pre><code>bool isBetween(double value, double low, double high) {\n return value &gt;= low &amp;&amp; value &lt; high;\n}\n</code></pre>\n<p>You could consider adding an <code>assert(low &lt;= high)</code> statement to that function to get error checking. And then if I want to compare things often against the same range, I can write:</p>\n<pre><code>int main() {\n auto isInRange = [](double value){ return isBetween(value, 0.2, 0.4); };\n\n std::cout &lt;&lt; isInRange(0.2) &lt;&lt; '\\n';\n std::cout &lt;&lt; isInRange(0.199) &lt;&lt; '\\n';\n std::cout &lt;&lt; isInRange(0.399) &lt;&lt; '\\n';\n std::cout &lt;&lt; isInRange(0.4) &lt;&lt; '\\n';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T22:01:06.893", "Id": "250247", "ParentId": "250241", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T20:10:27.990", "Id": "250241", "Score": "2", "Tags": [ "c++" ], "Title": "Class to represent a Range of percentage values" }
250241
<p>so as a beginner in Python, I've been utilizing CodeWars to practice everyday alongside my courses, been happy by the results so far, however, what I really am focusing on is the logical thinking side of things and &quot;Thinking like a programmer&quot;. I got a question today on codewars that brought me here to ask. Although the end result of the code I wrote was a &quot;PASS&quot; and it worked out, I know for a fact there is a way to write shorter code using ITERATION for the same result.</p> <p>The Question was to write a function that takes in a string and returns the string with numbers associated with the alphabetical position. My code is below. Again, it worked, but what would you have done differently? And how do I get into the habit of thinking differently to achieve cleaner code?</p> <pre><code>def alphabet_position(text): alphabet = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'} text = text.lower() mylist = [] for letter in text: if letter in alphabet: mylist.append(alphabet[letter]) else: pass return ' '.join(mylist) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T22:28:55.163", "Id": "490978", "Score": "3", "body": "Why can't you give us the link?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T15:41:42.857", "Id": "491042", "Score": "3", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>You are already using iteration, by using a <code>for</code>-loop to iterate over the characters in <code>text</code>.</p>\n<p>However, programming is about automating tasks. So thinking like a programmer means finding ways to let the computer do things for you, so you don't have to. For example, instead of creating the dict <code>alphabet</code> by hand, which means typing out all 26 characters and their index, you can let the program do this for you, by making use of the <a href=\"https://docs.python.org/3/library/functions.html#chr\" rel=\"nofollow noreferrer\"><code>chr()</code></a> and <a href=\"https://docs.python.org/3/library/functions.html#ord\" rel=\"nofollow noreferrer\"><code>ord()</code></a> functions, which convert characters to <a href=\"http://www.asciitable.com/\" rel=\"nofollow noreferrer\">ASCII values</a> and back, respectively:</p>\n<pre><code>alphabet = {}\nfor i in range(26):\n alphabet[chr(ord('a') + i)] = i + 1\n</code></pre>\n<p>But you can write that more compactly using <a href=\"https://www.python.org/dev/peps/pep-0274/\" rel=\"nofollow noreferrer\">dict comprehension</a>:</p>\n<pre><code>alphabet = {chr(ord('a') + i): i + 1 for i in range(26)}\n</code></pre>\n<p>And now you should realize that you actually don't need <code>alphabet</code>, but can convert the characters in <code>text</code> immediately into indices:</p>\n<pre><code>mylist = [ord(letter) - ord('a') + 1 for letter in text]\n</code></pre>\n<p>And if you want you can just replace the whole function with:</p>\n<pre><code>def alphabet_position(text):\n return ' '.join([ord(letter) - ord('a') + 1 for letter in text])\n</code></pre>\n<p>However, if you feel more comfortable using <code>for</code>-loops, then by all means keep using those. It also helps if you create a function that converts a single letter to an index; this breaks up your code into simpler chunks that are more easy to reason about:</p>\n<pre><code>def alphabet_position_of_letter(letter):\n return ord(character) - ord('a') + 1\n\ndef alphabet_position(text):\n positions = [alphabet_position_of_letter(letter) for letter in text]\n return ' '.join(positions)\n</code></pre>\n<p>The above is a bit more verbose, but now the function and variable names help describe what everything means.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T21:01:15.697", "Id": "490968", "Score": "0", "body": "thank you for the feedback. I haven't gotten to the chapter where we use the chr() and ord() functions. That's probably why I don't understand it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T07:18:03.187", "Id": "491005", "Score": "1", "body": "`ord('a')` can be take out as a constant value too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T20:54:11.077", "Id": "250244", "ParentId": "250242", "Score": "3" } }, { "body": "<p>For string operations Python has a neat library called <a href=\"https://docs.python.org/3/library/string.html\" rel=\"nofollow noreferrer\">string</a>. You could go like this:</p>\n<pre><code>import string\n\ntext = &quot;Your text here&quot;\ntext_in_numbers = list(string.ascii_lowercase.index(letter) + 1 for letter in text.lowercase() if letter in string.ascii_lowercase)\n</code></pre>\n<p>and if you need it as a function, you can abstract it with lambda:</p>\n<pre><code>text_to_numbers = lambda(text: list(string.ascii_lowercase.index(letter) + 1 for letter in text.lowercase() if letter in string.ascii_lowercase))\n</code></pre>\n<p>or wrap it it in a def</p>\n<pre><code>def text_to_numbers(text: str) -&gt; list[int]:\n return list(string.ascii_lowercase.index(letter) + 1 for letter in text.lowercase() if letter in string.ascii_lowercase)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T04:27:35.757", "Id": "250393", "ParentId": "250242", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T20:11:47.690", "Id": "250242", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "What would you have done differently? How to approach this?" }
250242
<p>I'm fairly new to programming and I'm learning python. I've defined a function for a dice roll and set it up to roll multiple.</p> <pre><code>def d20(num): rolls = 0 for i in range(num): rolls += randint(1,20) return rolls </code></pre> <p><a href="https://github.com/thonny/thonny" rel="nofollow noreferrer">Thonny</a> and my assistant tab gives me a warning:</p> <pre><code>Line 3: Unused variable 'i' </code></pre> <p>The code works fine but I like a clean workspace. I was wondering if there is an alternate way to write the range loop or is this just something I need to learn to deal with?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T23:27:16.963", "Id": "490985", "Score": "4", "body": "`return sum(randint(1, 20) for _ in range(num))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T03:56:31.133", "Id": "490996", "Score": "1", "body": "I'd turn the thole thing in a `roll_dice(num, dice)` function that takes `d20` as an argument as well." } ]
[ { "body": "<p>Use an underscore _ instead of i</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T04:08:09.237", "Id": "490999", "Score": "3", "body": "Welcome to Code Review! While OPs are [encouraged to answer their own questions](https://codereview.stackexchange.com/help/self-answer) bear in mind that [\"_Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\"](https://codereview.stackexchange.com/help/how-to-answer)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T02:31:01.320", "Id": "495308", "Score": "1", "body": "Specifically, you should explain why!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T22:57:33.437", "Id": "250250", "ParentId": "250249", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T22:21:44.680", "Id": "250249", "Score": "0", "Tags": [ "python", "beginner" ], "Title": "Unused variable clean-up" }
250249
<p>My program uses merge and insertion sort to sort a set of numbers. It works perfectly fine for small inputs, less than 2 seconds for 1,000 ints. But I need to sort 1,000,000 ints. When I try with 1 million, it takes over 2 hours to sort. Can someone please help me optimize this program so it works faster?</p> <p>FYI: I have several versions of this program because I have been trying to make it faster. Originally, my program would read 1 million ints from a text file, sort, then output the sorted numbers to a text file. But I assumed that was taking a large portion of the running time so I took that out completely.</p> <p>Instead, I initialized the vector with 1,000,000 ints in the main program, like so:</p> <pre><code>vector&lt;int&gt; vec {7000, 8090, 189, 19, 0, 29032, ... ,90}; </code></pre> <p>Again, my program works great with small input sizes. Any advice? Thank you!</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; #include &lt;time.h&gt; #include &lt;stdio.h&gt; #include&lt;fstream&gt; using namespace std; void merge(vector&lt;int&gt; &amp;vec, int left, int center, int right, int originalsize) { int leftVsize, rightVsize; //left and right vector sizes vector&lt;int&gt; vec1; leftVsize = center-left+1; //calculating left and right temporary vector sizes rightVsize = right - center; vector&lt;int&gt; tempLeft(leftVsize); //initializing temp left and right vectors vector&lt;int&gt; tempRight(rightVsize); for(int i = 0; i &lt; tempLeft.size(); ++i) { tempLeft.at(i) = vec.at(left+i); //initializing left vector } for(int i = 0; i &lt; tempRight.size(); ++i) { tempRight.at(i) = vec.at(i+center+1); //initializing right vector } int i = left, j = 0, k = 0; while((j &lt; tempLeft.size()) &amp;&amp; (k &lt; tempRight.size())) //while left and right vector have elements { if(tempLeft.at(j) &lt;= tempRight.at(k)) //if left element is smaller { vec.at(i) = tempLeft.at(j); //add value to original vector j++; } else //else { vec.at(i) = tempRight.at(k); //add value to original vector k++; } i++; } while(j &lt; tempLeft.size()) //while left vector has elements { vec.at(i++) = tempLeft.at(j++); } while(k &lt; tempRight.size()) //while right vector has elements { vec.at(i++) = tempRight.at(k++); } } void insertionSort(vector&lt;int&gt; &amp;vec, int originalsize) { for(int i = 1; i &lt; originalsize; ++i) //starting from 1 for original vector size { int tempval = vec[i]; //set tempval to vector value at 1 int j = i; //j now equals i for(j = i; ((j &gt; 0)&amp;&amp;(tempval &lt; vec[j-1])); --j) //for j=i while j is greater than 0 and tempval is less than the number before it { vec[j] = vec[j-1]; //set vector[j] to vector[j-1] } vec[j] = tempval; //tempval now holds vec[j] } } void sort(vector&lt;int&gt; &amp;vec, int left, int right, int originalsize) { int insertion = right - left; if(insertion &lt;= 8) //if righ-left is less than or equal to 8 { insertionSort(vec, originalsize); // call insertion sort } if(left &lt; right) { int center = (left+right)/2; //calculating center of vector sort(vec, left, center, originalsize); //calling sort for temp vector sort(vec, center+1, right, originalsize); //calling sort for temp vector merge(vec, left, center, right, originalsize); //calling merge to merge two vectors together } } int main() { vector&lt;int&gt; vec { 1 million ints }; int temp; clock_t q, q1, q2,t; int orgsize = vec.size(); q=clock(); sort(vec, 0, (vec.size()-1), orgsize); //calling sort function q=clock()-q; cout &lt;&lt; &quot;Total Time: &quot;&lt;&lt; ((float)q)/CLOCKS_PER_SEC &lt;&lt;&quot;\n&quot;; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T02:32:31.067", "Id": "490989", "Score": "0", "body": "[crossposted](https://stackoverflow.com/q/64218120/13008439)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T02:34:39.630", "Id": "490991", "Score": "0", "body": "And as you've already been told there but I guess didn't see yet because you just walked away, you should rethink `insertionSort(vec, originalsize)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T04:04:09.380", "Id": "490998", "Score": "2", "body": "`less than 2 seconds for 1,000 ints`. That's not a good sort time. 2 milli seconds would be good. 2 seconds is a time for `1'000'000` integers." } ]
[ { "body": "<h3>Performance</h3>\n<p>For the moment, let's look at only one small part:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void sort(vector&lt;int&gt; &amp;vec, int left, int right, int originalsize)\n{\n int insertion = right - left;\n if(insertion &lt;= 8) //if righ-left is less than or equal to 8\n {\n insertionSort(vec, originalsize); // call insertion sort\n }\n if(left &lt; right)\n {\n int center = (left+right)/2; //calculating center of vector\n sort(vec, left, center, originalsize); //calling sort for temp vector\n sort(vec, center+1, right, originalsize); //calling sort for temp vector\n merge(vec, left, center, right, originalsize); //calling merge to merge two vectors together\n }\n }\n</code></pre>\n<p>This has a couple of problems. The first has already been pointed out: when you call <code>insertionSort</code>, you're telling it to sort the entire array, rather than just the small section you're currently dealing with.</p>\n<p>From there, however, it just gets worse. Because after you do an insertion sort on the entire array, you don't just return can call it good. You continue to call <code>sort</code> recursively as long as <code>left &lt; right</code>.</p>\n<p>So that means when you get a partition down to 8 elements, you do insertion sort on the entire array. Then you create two partitions of 4 elements--and for each of them, you insertion sort the whole array again. Then from each of those you create two partitions of 2 elements--and for each of them...yup, you insertion sort the whole array yet again.</p>\n<p>So not only are you do an <span class=\"math-container\">\\$O(N^2)\\$</span> insertion sort on the whole array--with the array of a million elements, you're doing it 500,000 + 250,000 + 125,000 = 875,000 times!</p>\n<h3>Comments</h3>\n<p>Some of your comments are quite good:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> while(j &lt; tempLeft.size()) //while left vector has elements\n {\n vec[i++] = tempLeft[j++];\n }\n</code></pre>\n<p>That's a real help in showing what your intent was. Some of the other comments aren't nearly so helpful though. For example, none of these strikes me as being very helpful at all:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> for(int i = left; i &lt; right; ++i) //starting from 1 for original vector size\n {\n int tempval = vec[i]; //set tempval to vector value at 1\n int j;\n\n for(j = i; ((j &gt; 0)&amp;&amp;(tempval &lt; vec[j-1])); --j) //for j=i while j is greater than 0 and tempval is less than the number before it\n {\n vec[j] = vec[j-1]; //set vector[j] to vector[j-1]\n }\n vec[j] = tempval; //tempval now holds vec[j]\n}\n</code></pre>\n<p>The last of those goes beyond useless and into misleading (sounds like you think it assigned from <code>vec[j]</code> <em>to</em> <code>tempval</code>, when you actually did the reverse).</p>\n<h3>Indentation</h3>\n<p>Indentation is an important tool in keeping code understandable. The <em>precise</em> parameters you choose don't seem to matter a whole lot (within reason), but whatever you do, do it consistently. This code is sadly lacking in that respect.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T04:21:21.167", "Id": "250259", "ParentId": "250251", "Score": "4" } }, { "body": "<p>Here's a rewrite incorporating everything said before, as well as an idea I got from Timsort: Instead of moving <em>both</em> halves out for the merge, only move <em>one</em> half out. I chose the left half. This saves space, saves the move costs, and also eliminates the need at the end to move remaining right values, as they're already where they belong. Also, I show the first and last few elements before and after the sort and whether it's actually sorted.</p>\n<p>For a million ints it takes about one second <a href=\"https://repl.it/repls/BlindTrustyFunnel\" rel=\"nofollow noreferrer\">on repl.it</a>:</p>\n<pre><code>first few: 1804289383 846930886 1681692777\nlast few: 639902526 2025884438 429357853\ntotal time: 0.988527\nfirst few: 1210 3722 4686\nlast few: 2147476900 2147477011 2147480021\nsorted? true\n</code></pre>\n<p>Here's the code. One note: I used the names <code>first</code>, <code>middle</code> and <code>last</code>, as those are the names C++ itself uses (e.g., in <a href=\"https://en.cppreference.com/w/cpp/algorithm/inplace_merge\" rel=\"nofollow noreferrer\"><code>inplace_merge</code></a>). Also see <a href=\"https://stackoverflow.com/q/42186617/1672429\">Why the “begin/end” vs “first/last” discrepancy?</a>.</p>\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;ctime&gt;\n#include &lt;iomanip&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\ntemplate&lt;typename I&gt;\nvoid merge(I first, I middle, I last, I tmp_first) {\n std::move(first, middle, tmp_first);\n\n I left = tmp_first, left_last = tmp_first + (middle - first);\n I right = middle, right_last = last;\n I write = first;\n\n while (left != left_last &amp;&amp; right != right_last)\n *write++ = *right &lt; *left ? *right++ : *left++;\n\n std::move(left, left_last, write);\n}\n\ntemplate&lt;typename I&gt;\nvoid insertion_sort(I first, I last) {\n if (first == last)\n return;\n for (I i = first + 1; i != last; ++i) {\n int tempval = *i;\n I j = i;\n for (; (j != first) &amp;&amp; (tempval &lt; *(j-1)); --j)\n *j = *(j-1);\n *j = tempval;\n }\n}\n\ntemplate&lt;typename I&gt;\nvoid sort(I first, I last, I tmp_first) {\n int size = last - first;\n if (size &lt;= 8) {\n insertion_sort(first, last);\n } else {\n I middle = first + size / 2;\n sort(first, middle, tmp_first);\n sort(middle, last, tmp_first);\n merge(first, middle, last, tmp_first);\n }\n}\n\ntemplate&lt;typename I&gt;\nvoid sort(I first, I last) {\n std::vector&lt;int&gt; tmp((last - first) / 2);\n sort(first, last, tmp.begin());\n}\n\ntemplate&lt;typename I&gt;\nvoid show(std::string label, I first, I last) {\n std::cout &lt;&lt; label &lt;&lt; ':';\n while (first != last)\n std::cout &lt;&lt; ' ' &lt;&lt; *first++;\n std::cout &lt;&lt; std::endl;\n}\n\ntemplate&lt;typename I&gt;\nbool is_sorted(I first, I last) {\n if (first == last)\n return true;\n ++first;\n for (; first != last; ++first)\n if (*first &lt; *(first - 1))\n return false;\n return true;\n}\n\nint main() {\n // Create vector of n random ints.\n int n = 1000000;\n std::vector&lt;int&gt; data;\n for (int i = 0; i &lt; n; i++)\n data.push_back(rand());\n\n // Show first and last few elements.\n show(&quot;first few&quot;, data.begin(), data.begin() + 3);\n show(&quot;last few&quot;, data.end() - 3, data.end());\n\n // Sort and show how long it took.\n clock_t q = clock();\n sort(data.begin(), data.end());\n q = clock() - q;\n std::cout &lt;&lt; &quot;total time: &quot; &lt;&lt; ((float)q) / CLOCKS_PER_SEC &lt;&lt; &quot;\\n&quot;;\n\n // Show first and last few elements and whether it's indeed sorted.\n show(&quot;first few&quot;, data.begin(), data.begin() + 3);\n show(&quot;last few&quot;, data.end() - 3, data.end());\n std::cout &lt;&lt; &quot;sorted? &quot; &lt;&lt; std::boolalpha\n &lt;&lt; is_sorted(data.begin(), data.end()) &lt;&lt; std::endl;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T12:26:56.243", "Id": "250275", "ParentId": "250251", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-05T23:42:07.923", "Id": "250251", "Score": "4", "Tags": [ "c++", "performance", "algorithm", "sorting" ], "Title": "Merge/Insertion sort program taking longer than an hour to finish - C++" }
250251
<p>I wrote a small utility in <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged &#39;bash&#39;" rel="tag">bash</a> that allows me to edit config files anywhere. So, whenever I want to edit a config file, I don't have to type its full path or have to remember where it is.</p> <p>First, I have to do:</p> <pre><code>$ edfig add &lt;name&gt; &lt;config file path&gt; </code></pre> <p>Then, I will be able to edit the corresponding config file by:</p> <pre><code>$ edfig &lt;name&gt; </code></pre> <p>Code:</p> <pre><code>#! /usr/bin/env bash # edfig.sh -- Config file manager # @annahri set -o nounset config_list=&quot;$HOME/.config/configs.list&quot; CMD=&quot;${0##*/}&quot; EDITOR=&quot;${EDITOR:-vi}&quot; short_usage() { echo -e &quot;${bold}Usage:${reset} $CMD [subcommand|name] [...]&quot; } usage() { short_usage echo -e &gt;&amp;2 echo -e &quot;${bold}Subcommands:${reset}&quot; &gt;&amp;2 echo -e &quot; ${bold}add${reset} Add new config file to list&quot; &gt;&amp;2 echo -e &quot; ${bold}rm${reset} Remove config file from list&quot; &gt;&amp;2 echo -e &quot; ${bold}edit${reset} Edit an entry&quot; &gt;&amp;2 echo -e &quot; ${bold}ls${reset} List all stored configs&quot; &gt;&amp;2 echo -e &quot; ${bold}help${reset} Print this&quot; &gt;&amp;2 echo -e &gt;&amp;2 echo -e &quot;${bold}Example:${reset}&quot; &gt;&amp;2 echo -e &quot; $CMD add vim \&quot;\$HOME/.vimrc\&quot;&quot; &gt;&amp;2 echo -e &quot; $CMD vim&quot; &gt;&amp;2 echo -e &quot; $CMD edit vim&quot; &gt;&amp;2 echo -e &quot; $CMD rm vim&quot; &gt;&amp;2 echo -e &quot; $CMD ls&quot; &gt;&amp;2 echo -e &gt;&amp;2 echo -e &quot;$CMD is a command line tool to ease config files editing&quot; &gt;&amp;2 exit } #============================================================= # Colors #============================================================= bold='\e[1m' red='\033[1;31m' green='\033[1;32m' reset='\033[0m' #============================================================= #============================================================= # Helper Functions #============================================================= msg_error() { echo -e &quot; ${red}x$reset $1&quot; &gt;&amp;2 &amp;&amp; exit &quot;$2&quot;; } msg_ok() { echo -e &quot; ${green}v$reset $1&quot; &gt;&amp;2; } #============================================================= #============================================================= # Edfig main functions #============================================================= # # Get config file path from the specified config name # config_getPath() { sed -n &quot;s/^$1 *= \([^ ]*.*\)/\1/p&quot; &quot;$config_list&quot; } # # Add new config path to list # config_add() { test &quot;$#&quot; -ne 2 &amp;&amp; msg_error &quot;Usage: $CMD add &lt;name&gt; &lt;config path&gt;&quot; 8 local name=&quot;$1&quot; local path=&quot;${2:-}&quot; case &quot;$name&quot; in add|edit|rm|ls|help) msg_error &quot;Reserved name. Please use another.&quot; 1 ;; *) if [[ &quot;${name:0:1}&quot; =~ ^.*([!?.,])+.*$ ]]; then msg_error &quot;Cannot use ${bold}${name:0:1}${reset} as the begining of name.&quot; 1 fi ;; esac test -f &quot;$path&quot; || msg_error &quot;Not found: $path&quot; 9 echo -e &quot;$name = $path&quot; | tee -a &quot;$config_list&quot; &gt; /dev/null || msg_error &quot;Cannot add new config.&quot; 7 msg_ok &quot;New config has been added.&quot; exit } # # Modify specified config name and its path # `edfig edit` with no argument will edit entire configs.list # config_edit() { local name=&quot;${1:-}&quot; test -z &quot;$name&quot; &amp;&amp; if ! $EDITOR &quot;$config_list&quot; 2&gt; /dev/null; then msg_error &quot;Cannot execute $EDITOR. Exiting&quot; 3 fi awk '{print $1}' &quot;$config_list&quot; | grep -qw &quot;$name&quot; || msg_error &quot;Config for ${bold}$name${reset} not found in $config_list&quot; 1 cleanup() { rm -f &quot;$tempfile&quot;; } trap cleanup EXIT INT QUIT tempfile=$(mktemp /tmp/config-XXX.tmp) linenum=$(grep -wn &quot;$name&quot; &quot;$config_list&quot; | cut -d: -f1) grep -w &quot;$name&quot; &quot;$config_list&quot; | tee &quot;$tempfile&quot; &gt; /dev/null || msg_error &quot;Error ocurred.&quot; 2 raw=&quot;$(head -1 &quot;$tempfile&quot;)&quot; $EDITOR &quot;$tempfile&quot; 2&gt; /dev/null || msg_error &quot;Error on $EDITOR. Aborting&quot; 3 test $(grep '\S' &quot;$tempfile&quot; | wc -l) -ne 1 &amp;&amp; msg_error &quot;Invalid syntax. Must not contain multiple lines.&quot; 8 test &quot;$raw&quot; == &quot;$(head -1 &quot;$tempfile&quot;)&quot; &amp;&amp; msg_ok &quot;No changes.&quot; &amp;&amp; exit line=&quot;$(sed 's/&quot;/\\&quot;/g;s/\//\\\//g' &quot;$tempfile&quot;)&quot; sed &quot;${linenum}s/.*/$line/&quot; &quot;$config_list&quot; | sponge &quot;$config_list&quot; || msg_error &quot;Error editing entry.&quot; 4 msg_ok &quot;Successfully edited.&quot; cleanup &amp;&amp; trap -- EXIT INT QUIT exit } # # Delete a config from list # config_rm() { local name=&quot;${1:-}&quot; test &quot;$name&quot; || msg_error &quot;What to remove?&quot; 1 line=$(awk -v name=&quot;$name&quot; '$1 == name' &quot;$config_list&quot;) test &quot;$line&quot; || msg_error &quot;Config for ${bold}$name${reset} not found in $config_list&quot; 1 cleanup() { rm -f &quot;$tempfile&quot;; } trap cleanup EXIT INT QUIT tempfile=$(mktemp /tmp/configs-XXX.tmp) tee &quot;$tempfile&quot; &lt; &quot;$config_list&quot; &gt; /dev/null || msg_error &quot;Unable to make temporary copy of $(basename $config_list).&quot; 2 grep -v &quot;$line&quot; &quot;$tempfile&quot; | tee &quot;$config_list&quot; &gt; /dev/null || msg_error &quot;Unable to remove ${bold}$name${reset} from list&quot; 4 msg_ok &quot;Successfully removed.&quot; cleanup &amp;&amp; trap -- EXIT INT QUIT exit } # # List all stored configs # config_ls() { echo -e &quot;${bold}Stored Configs:${reset}&quot; grep -v '^#' &quot;$config_list&quot; | \ sort | \ column -s= -t | \ awk '{print &quot; &quot;,$0}' exit } #============================================================= # # Begin Script, argument parsing # test &quot;$#&quot; -eq 0 &amp;&amp; short_usage &amp;&amp; exit case &quot;$1&quot; in add|rm|edit|ls) _cmd=&quot;$1&quot;; shift config_${_cmd} &quot;$@&quot; ;; help|-h|--help) usage ;; *) name=&quot;$1&quot; ;; esac test -s &quot;$config_list&quot; || msg_error &quot;$config_list doesn't exist or is empty. Try adding something first.\n edfig add &lt;name&gt; &lt;path&gt;&quot; 13 # # Get config path and check if it's existed # config_path=$(config_getPath &quot;$name&quot;) test &quot;$config_path&quot; || msg_error &quot;${bold}$name${reset} doesn't exist in configs list.&quot; 1 # # Trap EXIT QUIT INT signal to clean temporary file # cleanup() { rm -f &quot;$config_tmp&quot;; } trap cleanup EXIT QUIT INT config_file=&quot;${config_path##*/}&quot; config_tmp=&quot;/tmp/edfig-${name}-$config_file&quot; cp &quot;$config_path&quot; &quot;$config_tmp&quot; 2&gt; /dev/null || msg_error &quot;Error creating temporary file. Aborting&quot; 10 $EDITOR &quot;${config_tmp}&quot; 2&gt; /dev/null || msg_error &quot;Cannot execute $EDITOR. Exiting&quot; 3 diff &quot;$config_tmp&quot; &quot;$config_path&quot; &amp;&gt; /dev/null &amp;&amp; msg_ok &quot;No changes.&quot; &amp;&amp; exit tee &quot;$config_path&quot; &lt; &quot;$config_tmp&quot; &gt; /dev/null || msg_error &quot;Cannot save changes. Aborting&quot; 11 msg_ok &quot;Saving changes.&quot; cleanup &amp;&amp; exit </code></pre> <p>configs.list example:</p> <pre><code>i3 = &quot;/home/user/.config/i3/config&quot; vim = &quot;/home/user/.vimrc&quot; bash = &quot;/home/user/.bashrc&quot; </code></pre> <p>Is there something I can improve?</p>
[]
[ { "body": "<p>I get that it's been <em>a while</em> since you posted this, and you might have fixed any number of these issues already. Still, I was bored, so here I am, pointing them out, hoping some of it will help.</p>\n<h2>config_getPath</h2>\n<p>Depending on what <code>$1</code> contains, this might not be well-behaved - consider cases like <code>config_getPath '.*|'</code> - that turns into <code>sed s/^.*| *= \\([^ ]*.*\\)/\\1/p</code> which probably isn't what you want.</p>\n<p>There <em>are</em> ways to somewhat-robustly escape strings for use in <code>sed</code> patterns, but you may want to look into a different approach to reading, and perhaps even to storing, the data.</p>\n<p>By the way, you're only looking for files whose paths contain no newlines. Those <em>are</em> permitted in file names. <code>edfig add</code> will happily add them.</p>\n<h2>config_add</h2>\n<p>You seem to check the name against your subcommands, to make sure nobody accidentally uses the name <code>add</code> and ends up unable to access that config using <code>edfig add</code> (which has a different meaning). But you don't check for <code>-h</code> or <code>--help</code>, so <code>edfig add --help &quot;$XDG_CONFIG_HOME/some-util.conf&quot;</code> works just fine. Which is a bit strange, since you <em>did</em> reserve <code>rm</code>, <code>edit</code>, <code>add</code>, <code>help</code> and <code>ls</code>, so it feels a bit inconsistent.</p>\n<p>When validating the name, you're taking a length-1 substring, but checking it against the regex <code>^.*([!?.,])+.*$</code> which seems overcomplicated. It's a single character - the only way it's going to match that is if it also matches <code>[!?.,]</code>. Or if all of <code>$name</code> matches <code>^[!?.,]</code> for that matter.</p>\n<p>Why are <em>those</em> characters in particular banned from the start of the name anyway? There doesn't seem to be an obvious reason to ban those but not also ban a bunch of others. And why only at the start - why is <code>edfig add .hello</code> worse than <code>edfig add h.ello</code>?</p>\n<p>If given a relative path, you <em>save</em> the relative path. I could do something like <code>edfig add vim .vimrc</code> while standing in my home directory and it'll work fine, but then when I try to <code>edfig vim</code> it might fail, or even open <em>the wrong file</em>, depending on what directory I'm in. That's not ideal - you should probably store the full path.</p>\n<p>You don't check whether the name is already in use. The program just adds another path at the end of the list, and then there are <em>two</em> paths under the same name, which seems to cause problems later on. I feel like utilities should make an effort to not corrupt their own configuration files - if the name is already in use you should either refuse to write another one, or replace the existing path for that name (though probably ask before replacing).</p>\n<h2>config_edit</h2>\n<p>Don't assume people want their temporary files is <code>/tmp/</code> - you might not even be <em>able</em> to write to <code>/tmp</code>. <code>$TMPDIR</code> exists to let users control where their temporary files go, and <code>mktemp</code> already knows how to respect that , so use <code>mkdir --tmpdir config-XXX.tmp</code>.</p>\n<p>Instead of <code>grep | wc -l</code>, you probably want <code>grep -c</code>. Also, you may want to quote that <code>grep</code> - it's <em>almost</em> certainly safe not to, but still.</p>\n<h2>config_rm</h2>\n<p>Your approach here seems a bit overengineered. Couldn't the initial <code>awk</code> just grab every line <em>except</em> the one you want to remove? And then you could just write all those lines? Like, no tempfiles, just <code>awk -v &quot;name=$name&quot; '$1 != name' &quot;$config_list&quot; | sponge &quot;$config_list&quot;</code>?</p>\n<p>Though, side note, if I add a file with a newline in its name, the part of the name that comes after the newline is just... left in the file. That doesn't seem ideal, especially since <code>edfig add</code> <em>does</em> allow me to add such files if I want to.</p>\n<p>Why the <code>tee &gt; /dev/null</code>s? If you only want to write to one location... you can just use redirection, right? So why <code>grep ... &quot;$tempfile&quot; | tee &quot;$config_list&quot; &gt; /dev/null</code> instead of just <code>grep ... &quot;$tempfile&quot; &gt; &quot;$config_list&quot;</code>?</p>\n<p>Manually running the cleanup and then removing the exit trap seems unnecessary. You're about to exit either way. Just exit and let the trap handle the cleanup.</p>\n<p><code>grep -v &quot;$line&quot;</code> treats <code>$line</code> as a regex pattern - and it's taken from a file which can contain anything. It might end up matching things you don't want it to, causing too many config lines to be removed. Or if <code>$name</code> (and thus <code>$line</code>) begins with a <code>-</code>, <code>grep</code> could misinterpret it as a command line option of some kind. <code>grep -Fv -- &quot;$line&quot; &quot;$tempfile&quot;</code> avoids both those issues.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T15:00:03.633", "Id": "521710", "Score": "0", "body": "Hmm, I cannot recall the reason why did I put the name validation. Good advice, anyway." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T17:32:51.603", "Id": "263335", "ParentId": "250253", "Score": "3" } }, { "body": "<blockquote>\n<pre><code>EDITOR=&quot;${EDITOR:-vi}&quot;\n</code></pre>\n</blockquote>\n<p>Good! Respect the user's choice of editor, and use the well-known environment variable to convey that.</p>\n<hr />\n<blockquote>\n<pre><code>bold='\\e[1m'\nred='\\033[1;31m'\ngreen='\\033[1;32m'\nreset='\\033[0m'\n</code></pre>\n</blockquote>\n<p>Eww, please don't do that. Even when output and error streams are connected to a terminal, not all terminals use the same escape sequences. It's much better to use <code>tput</code> to generate control strings suitable for the actual terminal (or empty strings if not possible). That leads to much nicer output (for example in the Emacs compilation buffer I'm using for testing).</p>\n<hr />\n<blockquote>\n<pre><code>usage() {\n short_usage\n echo -e &gt;&amp;2\n echo -e &quot;${bold}Subcommands:${reset}&quot; &gt;&amp;2\n echo -e &quot; ${bold}add${reset} Add new config file to list&quot; &gt;&amp;2\n ⋮\n exit\n}\n</code></pre>\n</blockquote>\n<p>This is the kind of function you might want to take and adapt for other shell scripts, so it's best to avoid the Bash-specific <code>echo -e</code> there. It's not clear why you're passing that option anyway, since you don't include any backslash-escapes to be expanded.</p>\n<p>It may well be easier to <code>cat</code> from a here-document rather than have multiple commands to produce that output.</p>\n<p>Personally, I would do the redirection to <code>&amp;2</code> externally, to allow use of the same function for the error case (invalid arguments) and non-error case (help requested). For the same reason, I would either <code>exit</code> from the caller or pass in the desired exit value, so that the error case can <code>exit 1</code> and the non-error case can <code>exit 0</code>.</p>\n<pre><code>usage() {\n short_usage\n cat &lt;&lt;END\n\n${bold}Subcommands:${reset}\n ${bold}add${reset} Add new config file to list\n ${bold}rm${reset} Remove config file from list\n ${bold}edit${reset} Edit an entry\n ${bold}ls${reset} List all stored configs\n ${bold}help${reset} Print this\n\n${bold}Example:${reset}\n $CMD add vim \\&quot;\\$HOME/.vimrc\\&quot;\n $CMD vim\n $CMD edit vim\n $CMD rm vim\n $CMD ls\n\n$CMD is a command line tool to ease config files editing\nEND\n}\n</code></pre>\n\n<pre><code>case &quot;${1:--}&quot; in\n -)\n short_usage &gt;&amp;2\n exit 1\n ;;\n help|-h|--help)\n usage\n exit 0\n ;;\nesac\n</code></pre>\n<hr />\n<p>This check looks a bit odd, given that we're already within a <code>case</code> construct:</p>\n<blockquote>\n<pre><code> case &quot;$name&quot; in\n add|edit|rm|ls|help)\n msg_error &quot;Reserved name. Please use another.&quot; 1\n ;;\n *)\n if [[ &quot;${name:0:1}&quot; =~ ^.*([!?.,])+.*$ ]]; then\n msg_error &quot;Cannot use ${bold}${name:0:1}${reset} as the begining of name.&quot; 1\n fi\n ;;\n esac\n</code></pre>\n</blockquote>\n<p>It would be simpler to just check the invalid strings as another match:</p>\n<pre><code> case &quot;$name&quot; in\n add|edit|rm|ls|help)\n msg_error &quot;Reserved name. Please use another.&quot; 1\n ;;\n [!?.,]*)\n msg_error &quot;Cannot use ${bold}${name:0:1}${reset} as the beginning of name.&quot; 1\n ;;\n esac\n</code></pre>\n<p>That also removes some more Bash-specific code, easing the way to making this a portable script.</p>\n<p>We might want to perform some extra tests on the pathname: since we use newline as separator in our config file, the code will break if that's present in a filename. And the current implementation will break if we use spaces (due to how we <code>cut</code> the contents), but that can be fixed.</p>\n<hr />\n<p>Some of the error recovery looks surprising:</p>\n<blockquote>\n<pre><code>cleanup() { rm -f &quot;$tempfile&quot;; }\ntrap cleanup EXIT INT QUIT\n</code></pre>\n</blockquote>\n<p>It's good that we're using <code>trap</code>, and many shell programmers don't clean up robustly. But it's strange to trap <code>INT</code> and <code>QUIT</code> with the same command as <code>EXIT</code>. I think if we get one of those, we want to just take the default action, which is to exit (running the <code>EXIT</code> trap). We don't want to just clean up and carry on!</p>\n<p>Also, we have:</p>\n<blockquote>\n<pre><code>cleanup &amp;&amp;\n trap -- EXIT INT QUIT\n\nexit\n</code></pre>\n</blockquote>\n<p>This all seems unnecessary. If we simply <code>exit</code>, then <code>cleanup</code> will be run, so there's no need to run it ourselves or to reset the trap.</p>\n<hr />\n<p>Shellcheck suggests</p>\n<pre class=\"lang-none prettyprint-override\"><code>note: Consider using grep -c instead of grep|wc -l. [SC2126]\n</code></pre>\n<hr />\n<p>It's usually an error to specify a specific directory for tempfiles like this:</p>\n<pre><code>tempfile=$(mktemp /tmp/config-XXX.tmp)\n</code></pre>\n<p>Just respect the user's <code>TMPDIR</code>. In particular, specifying <code>/tmp</code> as we do can reduce security, since everyone can see what's in that directory, unlike the per-user directories created by <code>pam_tmpdir</code> on systems where that's used.</p>\n<p>While considering security, it might be a good idea to set a more restrictive <code>umask</code> to keep the config files' contents private (which could be significant, e.g. if the file is a user's <code>.netrc</code>).</p>\n<hr />\n<p>When we're storing filenames, we really should be converting them to absolute pathnames, since it's quite likely that we'll have changed working directory between the <code>add</code> and <code>edit</code> operations.</p>\n<hr />\n<p>What's the point of <code>tee</code> here?</p>\n<blockquote>\n<pre><code>grep -v &quot;$line&quot; &quot;$tempfile&quot; | tee &quot;$config_list&quot; &gt; /dev/null ||\n</code></pre>\n</blockquote>\n<p>I don't see how that's different from simple</p>\n<pre><code>grep -v &quot;$line&quot; &quot;$tempfile&quot; &gt;&quot;$config_list&quot; ||\n</code></pre>\n<p>We probably want to be using <code>grep -F</code>, to avoid treating any of the line as regexp metacharacters.</p>\n<hr />\n<p>Having looked at this for a while, I don't think that storing our filename aliases in a file is really the right way to go. If we use a directory instead, then each alias can be stored as a symbolic link, which solves many of the problems of the config file in one easy stroke. For example, we can use normal filesystem operations to add or remove entries (without risk of breaking any others if the program crashes) and to test existence.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T14:57:46.910", "Id": "521709", "Score": "0", "body": "You know what, using symlinks is actually a good idea! Might try it some other time" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T10:17:38.507", "Id": "263508", "ParentId": "250253", "Score": "2" } } ]
{ "AcceptedAnswerId": "263335", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T02:06:49.860", "Id": "250253", "Score": "7", "Tags": [ "bash", "linux" ], "Title": "Utility to edit config files globally" }
250253
<p>I'm building a chart component and it behaves differently if <code>data</code> has been passed in or not.</p> <p>Here are two ways I can think of to conditionally fill chart variables.<br /> (<code>data</code> will be empty <code>{}</code> or have non-empty values)</p> <pre class="lang-javascript prettyprint-override"><code>// helper function isEmptyObject(obj) { for (const i in obj) return false; return true; } </code></pre> <pre class="lang-javascript prettyprint-override"><code>const gridInterval = 5; let yTopTickValue; let yBottomTickValue; let yTickCount; let xTopTickValue; let xBottomTickValue; let xTickCount; if (!isEmptyObject(data)) { yTopTickValue = Math.ceil(data.yMax / gridInterval) * gridInterval; yBottomTickValue = Math.floor(data.yMin / gridInterval) * gridInterval; yTickCount = (yTopTickValue - yBottomTickValue) / gridInterval + 1; xTopTickValue = Math.ceil(data.yMax / gridInterval) * gridInterval; xBottomTickValue = Math.floor(data.yMin / gridInterval) * gridInterval; xTickCount = (xTopTickValue - xBottomTickValue) / gridInterval + 1; } </code></pre> <p>and</p> <pre class="lang-javascript prettyprint-override"><code>const gridInterval = 5; const isDataEmpty = isEmptyObject(data); const yTopTickValue = isDataEmpty ? null: Math.ceil(data.yMax / gridInterval) * gridInterval; const yBottomTickValue = isDataEmpty ? null: Math.floor(data.yMin / gridInterval) * gridInterval; const yTickCount = isDataEmpty ? null: (yTopTickValue - yBottomTickValue) / gridInterval + 1; const xTopTickValue = isDataEmpty ? null: Math.ceil(data.yMax / gridInterval) * gridInterval; const xBottomTickValue = isDataEmpty ? null: Math.floor(data.yMin / gridInterval) * gridInterval; const xTickCount = isDataEmpty ? null: (xTopTickValue - xBottomTickValue) / gridInterval + 1; </code></pre> <p>Are there any other clever versions I'm missing?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T02:34:34.577", "Id": "490990", "Score": "0", "body": "\"Clever\" and more DRY, I can think of one, maybe (an object of functions), but it would be notably harder to understand at a glance. I prefer your current approaches." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T02:42:23.663", "Id": "490992", "Score": "0", "body": "Thanks for the comment @CertainPerformance. I've settled on using the first for readability but am on the hunt for a readable and DRY version. Not that there has to be one. " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T00:42:28.417", "Id": "491185", "Score": "0", "body": "@BCdotWEB done. Thanks. " } ]
[ { "body": "<p>Since you have a reasonable number of variables that all relate to one particular thing (chart settings), rather than having lots of standalone variables, you might consider using a single object instead. Regardless of any other issues with the code, I'd consider a single object to be slightly more appropriate than multiple similar standalone variables regardless.</p>\n<p>Using a single object can also let you exploit a shortcut: if <code>data</code> doesn't exist, just use an empty object. Otherwise, type out the object literal using your formulas:</p>\n<pre><code>const getChartSettings = (gridInterval, data) =&gt; {\n if (isEmptyObject(data)) {\n return {};\n }\n const yTopTickValue = Math.ceil(data.yMax / gridInterval) * gridInterval;\n const yBottomTickValue = Math.floor(data.yMin / gridInterval) * gridInterval;\n const xTopTickValue = Math.ceil(data.yMax / gridInterval) * gridInterval;\n const xBottomTickValue = Math.floor(data.yMin / gridInterval) * gridInterval;\n return {\n yTopTickValue,\n yBottomTickValue,\n yTickCount : (chartSettings.yTopTickValue - chartSettings.yBottomTickValue) / gridInterval + 1,\n xTopTickValue,\n xBottomTickValue,\n xTickCount : (chartSettings.xTopTickValue - chartSettings.xBottomTickValue) / gridInterval + 1,\n };\n};\n</code></pre>\n<p>Then you can call the function, reference <code>chartSettings.yBottomTickValue</code>, and either get a number or <code>undefined</code>.</p>\n<p>YMMV on whether that's worth using or not.</p>\n<p>It's unfortunate that the <code>TickCount</code>s depend on the prior calculated values - if they didn't, it could be made to look a lot simpler by just returning the single object literal instead of defining variables beforehand.</p>\n<p>You could still return an object alone without prior defined variables by making the TickCounts <em>getters</em> instead, but that'd be weird-looking, I wouldn't use it:</p>\n<pre><code>return {\n yTopTickValue: Math.ceil(data.yMax / gridInterval) * gridInterval,\n yBottomTickValue: Math.floor(data.yMin / gridInterval) * gridInterval,\n get yTickCount() {\n return (this.yTopTickValue - this.yBottomTickValue) / gridInterval + 1;\n },\n // ...\n</code></pre>\n<p><strong>Operator position</strong> You also might consider putting the <code>+ 1</code> at the beginning, rather than at the end, eg:</p>\n<pre><code>xTickCount : 1 + (chartSettings.xTopTickValue - chartSettings.xBottomTickValue) / gridInterval,\n</code></pre>\n<p>I think that's a bit clearer than putting it right next to the <code>/ gridInterval</code>. You could also consider using <a href=\"https://eslint.org/docs/rules/no-mixed-operators\" rel=\"nofollow noreferrer\"><code>no-mixed-operators</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T17:45:42.583", "Id": "491058", "Score": "0", "body": "Hi @CertainPerformance. Thanks again for the help! `+1` You set me on a path that lead to a solution I really like. It's basically your first option with some spread magic." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T03:18:52.883", "Id": "250255", "ParentId": "250254", "Score": "3" } }, { "body": "<p>Based on @CertainPerformance's feedback, here is where I landed.<br />\nThis is the most DRY version possible.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const chartSettings = (gridInterval, data) =&gt; {\n if (isEmptyObject(data)) return;\n\n const ticks = {\n yTopTick: Math.ceil(+data.yMax / gridInterval) * gridInterval,\n yBottomTick: Math.floor(+data.yMin / gridInterval) * gridInterval,\n xTopTick: Math.ceil(+data.yMax / gridInterval) * gridInterval,\n xBottomTick: Math.floor(+data.yMin / gridInterval) * gridInterval,\n };\n\n return {\n ...ticks,\n yTickCount: 1 + (ticks.yTopTick - ticks.yBottomTick) / gridInterval,\n xTickCount: 1 + (ticks.xTopTick - ticks.xBottomTick) / gridInterval,\n };\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T20:22:36.650", "Id": "491067", "Score": "0", "body": "While OPs are [encouraged to answer their own questions](https://codereview.stackexchange.com/help/self-answer) bear in mind that [\"_Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\"](https://codereview.stackexchange.com/help/how-to-answer)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T20:38:04.697", "Id": "491069", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ, I'm not exactly sure what else to add to this answer to make if fit better. It seems to have the context necessary by pointing to CertainPerformance's answer. I want to be a good codereview citizen. If you could give specific feedback it would help me going forward. Thanks! " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T20:51:48.600", "Id": "491070", "Score": "0", "body": "Please see the Help Center page [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) - the section **I improved my code based on the reviews. What next?**. It appears you have already taken option #2 - so bear in mind \"_Your answer must meet the standards of a Code Review answer, just like any other answer. **Describe what you changed, and why** [Code-only answers that don't actually review the code are insufficient](https://codereview.meta.stackexchange.com/q/1463/120114) and are subject to deletion._\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T01:01:28.253", "Id": "491080", "Score": "0", "body": "ok, based on all those links it looks like my answer meets the criteria. Thanks for the help." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T17:47:06.263", "Id": "250287", "ParentId": "250254", "Score": "1" } } ]
{ "AcceptedAnswerId": "250287", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T02:07:53.730", "Id": "250254", "Score": "2", "Tags": [ "javascript" ], "Title": "More DRY way of conditionally filling variables?" }
250254
<p>I came across a problem where given a array of integer arrays of different lengths <code>[[1,2,3],[4,1,1], [9,2,1]]</code> you need to return an array of arrays, each array containing indices of the arrays (of the input array) such that the corresponding arrays have the same mean: <code>[[0,1],[2]]</code> This seems relatively simple to solve using Python:</p> <pre><code>def groupByMean(a): d,e=[],[] for i,j in enumerate(a): if sum(j)/len(j)not in e: e+=[sum(j)/len(j)] d+=[[i]] else: d[e.index(sum(j)/len(j))]+=[i] return d </code></pre> <p>However, when trying to solve this in Java this was my approach: using a hashmap, map each new mean to a list of the corresponding indices. Then iterate the hashmap, to get the arraylists and convert them to int[] arrays and construct the 2d array ...</p> <p>Is there a simpler approach to solve this using Java?</p> <p>This is my java code - looking for a different way to solve this:</p> <pre><code>public static void main(String[] args) { int[][] arr = { { 1, 2, 3 }, { 2, 3, 4 }, { 2, 4, 0 } }; for (int[] nums : groupBySum(arr)) { for (int n : nums) { System.out.print(n + &quot; &quot;); } System.out.println(); } } public static int[][] groupByMean(int[][] arr) { Map&lt;Double, List&lt;Integer&gt;&gt; map = new HashMap&lt;&gt;(); int i = 0; for (int[] nums : arr) { double average = getAverage(nums); if (!map.containsKey(average)) { List&lt;Integer&gt; indices = new ArrayList&lt;&gt;(); indices.add(i); map.put(average, indices); } else { map.get(average).add(i); } i++; } int[][] result = new int[map.size()][]; int row = 0; for (List&lt;Integer&gt; indices : map.values()) { result[row] = new int[indices.size()]; for (int k = 0; k &lt; indices.size(); k++) { result[row][k] = indices.get(k); } row++; } return result; } public static double getAverage(int[] arr) { int sum = 0; for (int num : arr) { sum += num; } return ((double) sum) / arr.length; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T09:54:01.183", "Id": "491015", "Score": "0", "body": "Please state in the title what your code does. You can find more info on [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T10:48:09.463", "Id": "491016", "Score": "0", "body": "What if the input array is empty?" } ]
[ { "body": "<p>Nice implementation. Few suggestions to make the method <code>groupByMean</code> more compact using Java Streams:</p>\n<ul>\n<li><strong>Calculate the average</strong>:\n<pre><code>public static double getAverage(int[] arr) {\n int sum = 0;\n for (int num : arr) {\n sum += num;\n }\n return ((double) sum) / arr.length;\n}\n</code></pre>\nTo:\n<pre><code>public static double getAverage(int[] arr) {\n return Arrays.stream(nums).average().getAsDouble();\n}\n</code></pre>\n</li>\n<li><strong>Group by average</strong>:\n<pre><code>if (!map.containsKey(average)) {\n List&lt;Integer&gt; indices = new ArrayList&lt;&gt;();\n indices.add(i);\n map.put(average, indices);\n} else {\n map.get(average).add(i);\n}\n</code></pre>\nTo:\n<pre><code>map.computeIfAbsent(average, v -&gt; new ArrayList&lt;&gt;()).add(i);\n</code></pre>\n</li>\n<li><strong>Convert list to array</strong>:\n<pre><code>for (int k = 0; k &lt; indices.size(); k++) {\n result[row][k] = indices.get(k);\n}\n</code></pre>\nTo:\n<pre><code>result[row] = indices.stream().mapToInt(index-&gt;index).toArray();\n</code></pre>\n</li>\n<li><strong>Convert map's values to a matrix</strong>:\n<pre><code>int[][] result = new int[map.size()][];\nint row = 0;\nfor (List&lt;Integer&gt; indices : map.values()) {\n result[row] = new int[indices.size()];\n for (int k = 0; k &lt; indices.size(); k++) {\n result[row][k] = indices.get(k);\n }\n row++;\n}\nreturn result;\n</code></pre>\nTo:\n<pre><code>return map.values().stream()\n .map(v -&gt; v.stream().mapToInt(index-&gt;index).toArray())\n .toArray(int[][]::new);\n</code></pre>\n</li>\n</ul>\n<h2>Time/Space Complexity</h2>\n<p>In terms of complexity there are no relevant differences between your solution and the one using Streams. The time complexity is still <span class=\"math-container\">\\$O(n*m)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the number of arrays and <span class=\"math-container\">\\$m\\$</span> is the size of the longest array. Basically, for each array we need to calculate the average.</p>\n<p>To check which approach is faster you need to benchmark the solutions.</p>\n<h2>Final code</h2>\n<pre><code>public static void main(String[] args) {\n int[][] arr = {{ 1, 2, 3 }, { 2, 3, 4 }, { 2, 4, 0 }};\n Arrays.stream(groupByMean(arr)).map(Arrays::toString)\n .forEach(System.out::println);\n}\n\npublic static int[][] groupByMean(int[][] arr) {\n Map&lt;Double, List&lt;Integer&gt;&gt; map = new HashMap&lt;&gt;();\n for (int i=0 ; i&lt;arr.length; i++) {\n double average = Arrays.stream(arr[i]).average().getAsDouble();\n map.computeIfAbsent(average, v -&gt; new ArrayList&lt;&gt;()).add(i);\n }\n return map.values().stream()\n .map(v -&gt; v.stream().mapToInt(index-&gt;index).toArray())\n .toArray(int[][]::new);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T07:52:04.983", "Id": "491007", "Score": "0", "body": "Thank you!! What are the advantages in terms of time/space complexity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T09:48:22.550", "Id": "491013", "Score": "0", "body": "@beginnercs12 I am glad I could help ;). I updated my answer to answer your comment." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T06:18:42.750", "Id": "250261", "ParentId": "250256", "Score": "5" } }, { "body": "<p>I would suggest using the <code>groupingBy</code> collector.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n int[][] arr = {{ 1, 2, 3 }, { 2, 3, 4 }, { 2, 4, 0 }};\n IntStream.range(0, arr.length)\n .boxed()\n .collect(groupingBy(i-&gt;Arrays.stream(arr[i]).average().getAsDouble()))\n .values()\n .forEach(System.out::println);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T15:29:19.203", "Id": "250281", "ParentId": "250256", "Score": "3" } } ]
{ "AcceptedAnswerId": "250261", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T03:21:43.137", "Id": "250256", "Score": "5", "Tags": [ "python", "java", "array" ], "Title": "Identifying arrays with the same mean" }
250256
<p>I am trying to fetch the format (e.g. background color, border settings) of each cell in Excel file with Microsoft.Office.Interop.Excel class. I know that there are many tools could be used well in data reading, such as ExcelDataReader. However, many of them cannot retrieve cell format (<a href="https://github.com/ExcelDataReader/ExcelDataReader/issues/48" rel="nofollow noreferrer">https://github.com/ExcelDataReader/ExcelDataReader/issues/48</a>, <a href="https://github.com/ExcelDataReader/ExcelDataReader/issues/87" rel="nofollow noreferrer">https://github.com/ExcelDataReader/ExcelDataReader/issues/87</a>). The problem is that Excel interop is slow because this way is basically remote-controlling an instance of the Excel application. The following code is used for fetching the background color of each cell in Excel file. Could I make any other improvements? All suggestions are welcome.</p> <p>The size of Test.xlsx here is 20 row * 9 column and runTime is 00:00:04.53, 00:00:03.25 and 00:00:03.21 @intel(r) core(tm) i9-9900k cpu.</p> <pre><code>using System; using System.Diagnostics; namespace CsharpMicrosoftOfficeInteropExcelApplicationTest { class Program { static void Main(string[] args) { string FilenameInput = &quot;./Test.xlsx&quot;; Console.WriteLine(&quot;Open file: &quot; + System.Environment.CurrentDirectory + FilenameInput + System.Environment.NewLine); Stopwatch stopWatch = new Stopwatch(); // for code performance measurement stopWatch.Start(); Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open( System.Environment.CurrentDirectory + FilenameInput); for (uint LoopNumberX = 0; LoopNumberX &lt; ExcelWorkbook.Worksheets[&quot;Test&quot;].UsedRange.Columns.Count; LoopNumberX++) { for (uint LoopNumberY = 0; LoopNumberY &lt; ExcelWorkbook.Worksheets[&quot;Test&quot;].UsedRange.Rows.Count; LoopNumberY++) { System.Drawing.Color SystemDrawingColor = GetBackgroundColor(ExcelWorkbook, &quot;Test&quot;, LoopNumberX, LoopNumberY); Console.WriteLine(&quot;Location: (&quot; + LoopNumberX.ToString() + &quot;, &quot; + LoopNumberY.ToString() + &quot;)\tColor=&quot; + SystemDrawingColor.ToString()); } } stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; // Format and display the TimeSpan value. string elapsedTime = String.Format(&quot;{0:00}:{1:00}:{2:00}.{3:00}&quot;, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine(&quot;RunTime &quot; + elapsedTime); Console.ReadKey(); } static private System.Drawing.Color GetBackgroundColor( Microsoft.Office.Interop.Excel.Workbook WorkbookObject, string SheetName, uint LocationX, uint LocationY ) { Microsoft.Office.Interop.Excel.Worksheet ExcelWorksheet = WorkbookObject.Worksheets[SheetName]; return System.Drawing.ColorTranslator.FromOle( System.Convert.ToInt32(ExcelWorksheet.Cells[LocationY + 1, LocationX + 1].Interior.Color) ); } } } </code></pre> <p><strong>Oct 7, 2020 Update</strong></p> <p>Based on the above code, the input parameter &quot;LocationX&quot; and &quot;LocationY&quot; of the GetBackgroundColor method are separated, is it a good idea to bundle them together for better readability?</p> <pre><code> static private System.Drawing.Color GetBackgroundColor( Microsoft.Office.Interop.Excel.Workbook WorkbookObject, string SheetName, Tuple&lt;uint, uint&gt; Location // Location.Item1 is LocationX, and Location.Item2 is LocationY ) { Microsoft.Office.Interop.Excel.Worksheet ExcelWorksheet = WorkbookObject.Worksheets[SheetName]; return System.Drawing.ColorTranslator.FromOle( System.Convert.ToInt32(ExcelWorksheet.Cells[Location.Item2 + 1, Location.Item1 + 1].Interior.Color) ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T09:41:57.803", "Id": "491105", "Score": "1", "body": "Tip: For the code readability you may add `using System.Drawing;` and change all `System.Drawing.Color` to `Color` then. And the same for other namesapces." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T07:46:10.950", "Id": "250265", "Score": "2", "Tags": [ "c#", "performance", "excel" ], "Title": "Extracting Excel cell format with Microsoft.Office.Interop.Excel in C#" }
250265
<p>Dynamically growing arrays are a type of array. They are very useful when you don't know the exact size of the array at design time. First you need to define an initial number of elements. (<a href="https://en.wikipedia.org/wiki/Dynamic_array" rel="noreferrer">Wikipedia</a>)</p> <p>I have written a Python solution and converted it to <a href="https://cython.org/" rel="noreferrer">Cython</a>. Cython can be used to improve the speed of nested for loops in Python. Where my Cython code is slightly faster. My Cython solution is obviously not the fastest. I am trying to perform a nested for loop similar to the one in my Python code as fast as possible in Cython.</p> <p>It would help to have some experience in C, which I don't. The main problem that I ran into is that Cython has different scoping rules to Python. Since C and Python have different scoping rules. In other words, we cannot create a new vector in the loop and assign it to the same name.</p> <p>My solution works but is too slow. Can anyone improve Cython code above by using a more C like approach.</p> <p><strong>Python</strong></p> <pre class="lang-py prettyprint-override"><code>import numpy as np my_list = [1,2,3] n = 10 a = 0.5 Estimate_1_list = [] Estimate_2_list = [] for l in my_list: # Resizable matrices a_mat = np.zeros((l,n+1),float) b_mat = np.zeros((l,n+1),float) for i in range(n): t = i*a for j in range(l): # Fill matrices a_mat[j,i+1] = a_mat[j,i+1] + np.random.random() b_mat[j,i+1] = a_mat[j,i+1]/(2*t+3) # Append values of interest to use at different values of matrix size Estimate_1_list.append(np.mean(a_mat[:,n])) Estimate_2_list.append(np.std(a_mat[:,n])) results = [Estimate_1_list,Estimate_2_list] </code></pre> <p><strong>Cython</strong></p> <pre class="lang-cython prettyprint-override"><code>import cython # Load cython extension %load_ext Cython %%cython import numpy as np def my_function(list my_list, int n, int a ): cdef list Estimate_1_list = [] cdef list Estimate_2_list = [] cdef int l,i,t,j for l in my_list: # Resizable matrices (could I use memory view?) a_mat = np.zeros((l,n+1),float) b_mat = np.zeros((l,n+1),float) for i in range(n): t = i*a for j in range(l): # Fill matrices a_mat[j,i+1] = a_mat[j,i+1] + np.random.random() b_mat[j,i+1] = a_mat[j,i+1]/(2*t+3) # Append values of interest to use at different values of matrix size Estimate_1_list.append(np.mean(a_mat[:,n])) Estimate_2_list.append(np.std(a_mat[:,n])) # Return results results = [Estimate_1_list,Estimate_2_list] return results </code></pre> <p><strong>Tests</strong></p> <pre class="lang-py prettyprint-override"><code># Test cython to show that the function is running my_list = [1,2,3] n = 10 a = 0.5 my_function(my_list, n, a) [[0.13545224609230933, 0.6603542545719762, 0.6632002117071227], [0.0, 0.19967544614685195, 0.22125180486616808]] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T17:42:03.527", "Id": "491057", "Score": "4", "body": "What is the task an execution of the code is to accomplish? What is `b_mat` (plus non good name) filled for? You import numpy: why open code filling with random data/performing linear algebra?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T17:45:46.850", "Id": "491059", "Score": "0", "body": "I am interested in estimating some parameter. The goal was to simplify the code since the problem has to do with a parallel simulation of a random walk this had all the moving parts still intact but a lot easier to see the problem which is to do with how a_mat and b_mat are recreated at each iteration of the for loop. @greybeard" } ]
[ { "body": "<h2>Zeros</h2>\n<p>This:</p>\n<pre><code>a_mat = np.zeros\n</code></pre>\n<p>is not the right call for your purpose. You want <code>np.empty</code> instead, because you don't actually care what the initial values are since you do a comprehensive initialization loop right after.</p>\n<p>Further to that: since you're adding <code>random()</code> to every element of <code>a_mat</code>, simply initialize <code>a_mat</code> to a single call of <code>random()</code> with the correct shape, rather than having to do element-wise addition.</p>\n<h2>Vectorization</h2>\n<p>You have an outer dimension (<code>l</code> through <code>my_list</code>), a second dimension (<code>l</code>) and a third dimension (<code>n + 1</code>). The second dimension is variable; the first and third are constant. This means that you can more efficiently represent this if you rearrange your dimensions so that the fixed ones are on the interior. In other words, if you had</p>\n<pre><code>len(my_list) = 3\nl = 1, 2, 3\nn = 10\n</code></pre>\n<p>then you can actually represent this as a single three-dimensional matrix of dimensions 6 * 3 * 10, where <code>6 == len(my_list) * (len(my_list) - 1)</code>. I think it's possible to do all of this without a single <code>for</code> loop, which is the ideal for vectorized performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T17:25:34.710", "Id": "250435", "ParentId": "250277", "Score": "1" } }, { "body": "<p>In addition to Reinderien's answer, may I suggest:</p>\n<h3>Yes, Use Memoryviews to speed up access</h3>\n<p>In addition to the code you have, I would also type the <code>a_mat</code> and <code>b_mat</code> matrixes as <code>double[:,::1]</code> following the <a href=\"https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html\" rel=\"nofollow noreferrer\">Typed Memoryviews</a> guide. (the &quot;1&quot; means contiguous and is allows for slightly faster access). You are right in that you can not <code>cdef</code> declare variables in a loop, but you can <code>cdef</code> declare variables at the top of the function, and reassign within the loop.</p>\n<pre><code>\n ...\n cdef list Estimate_1_list = []\n cdef list Estimate_2_list = []\n cdef int l,i,t,j\n cdef double[:, ::1] a_mat # declare here\n cdef double[:, ::1] b_mat\n for l in my_list:\n \n # Resizable matrices (could I use memory view?)\n a_mat = np.zeros((l,n+1),float) # assign in loop\n b_mat = np.zeros((l,n+1),float)\n ...\n\n</code></pre>\n<h3>Turn off Boundscheck And Wrap Around check</h3>\n<p>Once you are sure that code is bug free. You can locally turn off bounds and wraparound checks using the decorators or with statements for additional speed up. (<a href=\"https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html#compiler-directives\" rel=\"nofollow noreferrer\">Compiler Directives</a>, <a href=\"https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html?highlight=boundscheck#locally\" rel=\"nofollow noreferrer\">Local Directives</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T07:47:49.337", "Id": "508635", "Score": "0", "body": "Good job on suggesting to keep turning off runtime checks local." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T05:15:31.563", "Id": "257505", "ParentId": "250277", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T12:55:26.770", "Id": "250277", "Score": "4", "Tags": [ "python", "performance", "beginner", "numpy", "cython" ], "Title": "Cython with variable-length arrays" }
250277
<p>This is my approach on creating a sudoku generator and solver with backtracking. Is right for sudoku generator to inherit from soduku solver? What is your general overview on the class structure, data members, variable names and data structure used.</p> <p>Here is the code</p> <pre><code>#ifndef SUDOKUGEN_HH #define SUDOKUGEN_HH /****************************************************************** * Name: SudokuGen.hh * Author: Samuel Oseh * Description: SudokuGen class method-function prototype * Purpose: This class generates a sudoku puzzle for a 9 x 9 array * ****************************************************************/ #include &lt;vector&gt; #include &lt;array&gt; #include &quot;SudokuSolver.hh&quot; class SudokuGen : public SudokuSolver { public: SudokuGen(); ~SudokuGen(){} bool generateBoard( const std::string &amp;difficulty ); std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; board{}; private: std::vector&lt; int &gt; validChoices; // utility functions void setValidChoices(); void shuffleChoices( std::vector&lt; int &gt; &amp; ); void setBoard( const std::string &amp;difficulty ); }; #endif </code></pre> <pre><code>#ifndef SUDOKUSOLVER_HH #define SUDOKUSOLVER_HH /****************************************************************** * Name: SudokuSolver.hh * Author: Samuel Oseh * Description: SudokuSolver class method-function prototype * Purpose: This class solves a sudoku puzzle for a 9 x 9 array * ****************************************************************/ #include &lt;array&gt; class SudokuSolver { public: SudokuSolver(){} SudokuSolver( const std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board ); ~SudokuSolver(){} bool solve(); void printBoard( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board ) const; protected: std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; board; bool isRowValid( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board, int, int, int ); bool isColValid( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board, int, int, int ); bool isBlockValid( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board, int, int, int ); bool choiceIsValid( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board, int, int, int ); std::array&lt; int , 2 &gt; getNextEmpty( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board ); }; #endif </code></pre> <pre><code>/****************************************************************** * Name: SudokuGen.cc * Author: Samuel Oseh * Description: SudokuGen class method-function definitions * Purpose: This class generates a sudoku puzzle for a 9 x 9 array * ****************************************************************/ #include &lt;iostream&gt; #include &lt;random&gt; #include &quot;SudokuGen.hh&quot; SudokuGen::SudokuGen() { setValidChoices(); shuffleChoices( validChoices ); } void SudokuGen::setValidChoices() { for ( unsigned int counter = 1; counter &lt;= 9; ++counter ) { validChoices.push_back( counter ); } } void SudokuGen::shuffleChoices( std::vector&lt; int &gt; &amp;choices ) { std::default_random_engine engine ( static_cast&lt; unsigned int &gt; ( time(0) ) ); std::uniform_int_distribution&lt; unsigned int &gt; randomInt( 0, choices.size() - 1 ); for ( size_t i = 0; i &lt; choices.size(); ++i ) { int swapIndex = randomInt( engine ); for ( ; swapIndex == i; ) { swapIndex = randomInt( engine ); } // swap int temp = choices[ i ]; choices[ i ] = choices[ swapIndex ]; choices[ swapIndex ] = temp; } } bool SudokuGen::generateBoard( const std::string &amp;difficulty ) { std::array&lt; int , 2 &gt; empty = getNextEmpty( board ); if ( empty[ 0 ] == -1 &amp;&amp; empty [ 1 ] == -1 ) { setBoard( difficulty ); return true; } for ( unsigned int counter = 0; counter &lt; validChoices.size(); ++counter ) { if ( choiceIsValid( this-&gt;board, empty[ 0 ], empty[ 1 ], validChoices[ counter ] ) ) { board[ empty[ 0 ] ][ empty[ 1 ] ] = validChoices[ counter ]; if ( generateBoard( difficulty ) ) return true; } board[ empty[ 0 ] ][ empty[ 1 ] ] = 0; } return false; } void SudokuGen::setBoard( const std::string &amp;difficulty ) { std::default_random_engine engine ( static_cast&lt; unsigned int &gt; ( time(0) ) ); std::uniform_int_distribution&lt; unsigned int &gt; randomInt( 0, 8 ); int row = 0, col = 0; int counter = 0; int limit = 0; if ( difficulty == &quot;Easy&quot; ) limit = 25; else if ( difficulty == &quot;Medium&quot; ) limit = 35; else if ( difficulty == &quot;Hard&quot; ) limit = 45; else if ( difficulty == &quot;Legend&quot; ) limit = 55; else { throw std::invalid_argument( &quot;Invalid argument&quot; ); } while( counter &lt; limit ) { row = randomInt( engine ); col = randomInt( engine ); if ( board[ row ][ col ] != 0 ) { board[ row ][ col ] = 0; ++counter; } } } </code></pre> <pre><code>/****************************************************************** * Name: SudokuSolver.cc * Author: Samuel Oseh * Description: SudokuSolver class method-function definitions * Purpose: This class solves a sudoku puzzle for a 9 x 9 array * ****************************************************************/ #include &lt;iostream&gt; #include &quot;SudokuSolver.hh&quot; SudokuSolver::SudokuSolver ( const std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board ) { this-&gt;board = board; } bool SudokuSolver::solve() { std::array&lt; int , 2 &gt; empty = getNextEmpty( board ); if ( empty[ 0 ] == -1 &amp;&amp; empty [ 1 ] == -1 ) { printBoard( board ); return true; } for ( unsigned int guess = 1; guess &lt; 10; ++guess ) { if ( choiceIsValid( board, empty[ 0 ], empty[ 1 ], guess ) ) { board[ empty[ 0 ] ][ empty[ 1 ] ] = guess ; if ( solve() ) return true; } board[ empty[ 0 ] ][ empty[ 1 ] ] = 0; } return false; } std::array&lt; int , 2 &gt; SudokuSolver::getNextEmpty( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board ) { for ( int row = 0; row &lt; board.size(); ++row ) { for ( int col = 0; col &lt; board.size(); ++col ) { if ( board[ row ][ col ] == 0 ) { std::array&lt; int, 2 &gt; empty { row, col }; return empty; } } } std::array&lt; int, 2 &gt; empty { -1, -1 }; return empty; } bool SudokuSolver::choiceIsValid( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board, int row, int column, int guess ) { // row wise check bool result = isRowValid( board, row, column, guess ); // columnwise check if ( result == true ) result = isColValid( board, row, column, guess ); // block check if ( result == true ) result = isBlockValid( board, row, column, guess ); return result; } bool SudokuSolver::isRowValid( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board, int row, int column, int guess ) { for ( unsigned int counter = 0; counter &lt; board.size(); ++counter ) { if ( board[ counter ][ column ] == guess ) return false; } return true; } bool SudokuSolver::isColValid( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board, int row, int column, int guess ) { for ( unsigned int counter = 0; counter &lt; board.size(); ++counter ) { if ( board[ row ][ counter ] == guess ) return false; } return true; } bool SudokuSolver::isBlockValid( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board, int row, int column, int guess ) { int segmentX = 3 * ( row / 3 ); int segmentY = 3 * ( column / 3 ); for ( unsigned int i = segmentX; i &lt; segmentX + 3; ++i ) { for ( unsigned int j = segmentY; j &lt; segmentY + 3; ++j ) { if ( board[ i ][ j ] == guess ) return false; } } return true; } void SudokuSolver::printBoard( std::array&lt; std::array&lt; int, 9 &gt;, 9 &gt; &amp;board ) const { for ( unsigned int counter = 97; counter &lt; 106; ++counter ) std::cout &lt;&lt; &quot; &quot; &lt;&lt; static_cast&lt; char &gt;( counter ); std::cout &lt;&lt; std::endl; for ( unsigned int row = 0; row &lt; board.size(); ++row ) { std::cout &lt;&lt; &quot; |-------|-------|-------|-------|-------|-------|-------|-------|-------|&quot; &lt;&lt; std::endl; std::cout &lt;&lt; ( row + 1 ) &lt;&lt; &quot; &quot;; for ( unsigned int column = 0; column &lt; board.size(); ++column ) { if ( board[ row ][ column ] == 0 ) std::cout &lt;&lt; &quot;| &quot;; else std::cout &lt;&lt; &quot;| &quot; &lt;&lt; board[ row ][ column ] &lt;&lt; &quot; &quot;; } std::cout &lt;&lt; &quot;|&quot;; std::cout &lt;&lt; std::endl; std::cout &lt;&lt; &quot; | | | | | | | | | |&quot; &lt;&lt; std::endl; } std::cout &lt;&lt; &quot; |-------|-------|-------|-------|-------|-------|-------|-------|-------|&quot; &lt;&lt; &quot;\n\n&quot;; } </code></pre> <pre><code>#include &lt;iostream&gt; #include &quot;SudokuGen.hh&quot; #include &quot;SudokuSolver.hh&quot; using namespace std; int main() { SudokuGen soduku; soduku.generateBoard( &quot;Legend&quot; ); sudoku.printBoard( sudoku.board ); std::cout &lt;&lt; &quot;\n\nSOLVED===========================================\n\n&quot;; SudokuSolver sudokuSolver( sudoku.board ); sudokuSolver.solve(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T16:16:46.257", "Id": "491043", "Score": "0", "body": "if you write \"std::array<std::array<int, 9>, 9>\" (no leading/trailing spaces inside \"<>\"'s) instead of \"std::array< std::array< int, 9 >, 9 >\" it makes your code a lot more readable, IMPO..\n\nAnd why does the generator inherit from the solver??? As far as I can see they share no members." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T17:20:01.083", "Id": "491052", "Score": "0", "body": "They share some methods....They both check if a guess is valid and also get the next empty location" } ]
[ { "body": "<p>I don't think the generator should inherit from the solver. Rather, any methods that they both need could be moved into a third class that either 1) they both inherit from or 2) they both include as a member.</p>\n<p>I would try to do #2.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T13:01:17.697", "Id": "250320", "ParentId": "250280", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T15:13:09.940", "Id": "250280", "Score": "1", "Tags": [ "c++", "algorithm", "object-oriented", "design-patterns" ], "Title": "Soduku Generator and Solver" }
250280
<p>I have completed my first attempt of a simple music visualizer app for windows in C++ using SDL. It takes system audio and outputs the soundwave in real-time. I'd appreciate some feedback on how I can improve the code, especially the OOP design and where I can use modern C++ features.</p> <p><a href="https://i.stack.imgur.com/cPdxo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cPdxo.png" alt="Example of a single frame from the visualizer" /></a></p> <p><strong>main.cpp:</strong></p> <pre><code>#include &lt;chrono&gt; #include &lt;thread&gt; #include &quot;visualizer.h&quot; constexpr int sleep_time = 20; int main(int argc, char* argv[]) { Visualizer generator; bool continue_app = generator.init_successful(); while (continue_app) { continue_app = generator.update(); std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time)); } return 0; } </code></pre> <p><strong>audio_sink.h:</strong></p> <pre><code>#pragma once // Abstract base class to copy data from an AudioRecorder class AudioSink { public: // Copy a packet of data from the audio recorder // param: data - pointer to data values // param: channels - the number of audio channels // param: frames - the number of frames of data virtual void copy_data(float * data, int channels, int frames) = 0; }; </code></pre> <p><strong>audio_recorder.h:</strong></p> <pre><code>#pragma once #include &lt;atomic&gt; #include &lt;Audioclient.h&gt; #include &lt;Audiopolicy.h&gt; #include &lt;Mmdeviceapi.h&gt; #include &quot;audio_sink.h&quot; // Class for recording system audio via WASAPI Loopback // class AudioRecorder { public: AudioRecorder(); ~AudioRecorder(); // The status of the initialization process // return: bool - whether the initialization was successful bool init_successful() const; // Record audio data from the system indefinitely // param: audio_sink - class which copies the recorded packets // param: exit_flag - flag to stop recording (passed by ref so it can be stopped externally) void record(AudioSink * audio_sink, std::atomic_bool &amp;exit_flag) const; private: mutable HRESULT m_hr; IMMDeviceEnumerator * m_device_enumerator = nullptr; IMMDevice * m_audio_device_endpoint = nullptr; IAudioClient * m_audio_client = nullptr; IAudioCaptureClient *m_capture_client = nullptr; int m_num_channels; static const int sleep_time = 10; // Time spent sleeping tp wait for new packets }; </code></pre> <p><strong>audio_recorder.cpp:</strong></p> <pre><code>#include &quot;audio_recorder.h&quot; #include &lt;comdef.h&gt; #include &lt;Audioclient.h&gt; #include &lt;Audiopolicy.h&gt; #include &lt;Mmdeviceapi.h&gt; #include &lt;chrono&gt; #include &lt;iostream&gt; #include &lt;thread&gt; // Define IIDs for initialization const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); const IID IID_IAudioClient = __uuidof(IAudioClient); const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient); AudioRecorder::AudioRecorder() { m_hr = S_OK; m_audio_client = nullptr; // Initialize audio device endpoint CoInitialize(nullptr); m_hr = CoCreateInstance( CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&amp;m_device_enumerator); if (m_hr == S_OK &amp;&amp; m_device_enumerator) { m_hr = m_device_enumerator-&gt;GetDefaultAudioEndpoint(eRender, eConsole, &amp;m_audio_device_endpoint); } // init audio client WAVEFORMATEX *pwfx = nullptr; REFERENCE_TIME hns_requested_duration = 100000000; if (m_hr == S_OK &amp;&amp; m_audio_device_endpoint) { m_hr = m_audio_device_endpoint-&gt;Activate(IID_IAudioClient, CLSCTX_ALL, nullptr, (void**)&amp;m_audio_client); } if (m_hr == S_OK &amp;&amp; m_audio_client) { m_hr = m_audio_client-&gt;GetMixFormat(&amp;pwfx); if (m_hr == S_OK &amp;&amp; pwfx) { if (pwfx-&gt;wFormatTag != WAVE_FORMAT_EXTENSIBLE || reinterpret_cast&lt;WAVEFORMATEXTENSIBLE *&gt;(pwfx)-&gt;SubFormat != KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) { std::cout &lt;&lt; &quot;Error: the audio format is not supported&quot; &lt;&lt; std::endl; m_hr = S_FALSE; } } if (m_hr == S_OK) { m_hr = m_audio_client-&gt;Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, hns_requested_duration, 10, pwfx, nullptr); } if (m_hr == S_OK &amp;&amp; pwfx) { m_num_channels = pwfx-&gt;nChannels; } if (m_hr == S_OK) { m_hr = m_audio_client-&gt;GetService(IID_IAudioCaptureClient, (void**)&amp;m_capture_client); } if (m_hr == S_OK &amp;&amp; m_capture_client) { m_hr = m_audio_client-&gt;Start(); // Start recording. } } if (m_hr != S_OK) { std::cout &lt;&lt; &quot;Error: During AudioRecorder intialization - &quot; &lt;&lt; _com_error(m_hr).ErrorMessage() &lt;&lt; std::endl; } }; // safely release and nullify pointers (in destructor) template&lt;class T&gt; inline void safe_release(T* &amp;p_object) { if (p_object) { p_object-&gt;Release(); p_object = nullptr; } } AudioRecorder::~AudioRecorder() { if (m_audio_client) { m_audio_client-&gt;Stop(); // Stop recording. } safe_release(m_device_enumerator); safe_release(m_audio_device_endpoint); safe_release(m_audio_client); safe_release(m_capture_client); } bool AudioRecorder::init_successful() const { return (m_hr == S_OK) &amp;&amp; m_audio_client &amp;&amp; m_capture_client; } void AudioRecorder::record(AudioSink * audio_sink, std::atomic_bool &amp;exit_flag) const { m_hr = S_OK; UINT32 packet_length = 0; BYTE *data = nullptr; UINT32 num_frames_available; DWORD flags; while (!exit_flag) { m_hr = m_capture_client-&gt;GetNextPacketSize(&amp;packet_length); while (packet_length != 0 &amp;&amp; !exit_flag) // while there are available packets { // Get the available data in the shared buffer. data = nullptr; m_hr = m_capture_client-&gt;GetBuffer( &amp;data, &amp;num_frames_available, &amp;flags, nullptr, nullptr); if (flags &amp; AUDCLNT_BUFFERFLAGS_SILENT) { data = nullptr; // data pointer is null for silence } audio_sink-&gt;copy_data((float*)data, m_num_channels, num_frames_available); m_hr = m_capture_client-&gt;ReleaseBuffer(num_frames_available); m_hr = m_capture_client-&gt;GetNextPacketSize(&amp;packet_length); } std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time)); } } </code></pre> <p><strong>visualizer.h:</strong></p> <pre><code>#pragma once #include &lt;atomic&gt; #include &lt;mutex&gt; #include &lt;vector&gt; #include &lt;thread&gt; #include &quot;audio_recorder.h&quot; #include &quot;audio_sink.h&quot; #include &quot;SDL.h&quot; // Visualizer class // This class owns the SDL window and performs visual updates based on system audio class Visualizer: public AudioSink { public: Visualizer(); ~Visualizer(); // The status of the initialization process // return: bool - whether the initialization was successful bool init_successful() const; // Update the visuals based on the most recent packet // return: bool - whether the update was successful bool update(); // Copy a packet of data from the audio recorder // Must override the method from AudioSink // param: data - pointer to data values // param: channels - the number of audio channels // param: frames - the number of frames of data void copy_data(float * data, int channels, int frames) override; private: SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; SDL_Event current_event; int window_width = 1000; int window_height = 600; bool mFullScreen = false; bool mMinimized = false; AudioRecorder recorder; std::thread recording_thread; std::atomic_bool exit_recording_thread_flag = false; std::mutex packet_buffer_mutex; typedef std::vector&lt;float&gt; packet; packet packet_buffer; // Must use mutex to access // Handle SDL window events // param: e - the SDL window event to handle void handle_event(const SDL_Event &amp; e); // Draw a horizontal soundwave with the most recent packet data // param: start - the leftmost starting pixel of the wave // param: length - the length in pixels of the wave // param: pixel_amplitude - the maximum amplitude of the wave // param: color - the color of the wave void draw_wave(const SDL_Point &amp;start, int length, int pixel_amplitude, const SDL_Color &amp; color); }; </code></pre> <p><strong>visualizer.cpp:</strong></p> <pre><code>#pragma once #include &quot;visualizer.h&quot; #include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;vector&gt; #include &quot;SDL.h&quot; Visualizer::Visualizer(): recorder() { if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cout &lt;&lt; &quot;Unable to initialize SDL: &quot; &lt;&lt; SDL_GetError() &lt;&lt; std::endl; return; } window = SDL_CreateWindow(&quot;Visualizer&quot;, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, window_width, window_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (window) { renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); } if (renderer) { SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); } if (recorder.init_successful()) { recording_thread = std::thread(&amp;AudioRecorder::record, &amp;recorder, (AudioSink *)this, std::ref(exit_recording_thread_flag)); } } Visualizer::~Visualizer() { // Stop recording thread before implicitly destroying AudioRecorder if (recording_thread.joinable()) { exit_recording_thread_flag = true; recording_thread.join(); } // Destroy SDL window SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); } bool Visualizer::init_successful() const { return (renderer &amp;&amp; recording_thread.joinable()); } void Visualizer::handle_event(const SDL_Event &amp; e) { //Window event occured if (e.type == SDL_WINDOWEVENT) { switch (e.window.event) { //Get new dimensions and repaint on window size change case SDL_WINDOWEVENT_SIZE_CHANGED: window_width = e.window.data1; window_height = e.window.data2; SDL_RenderPresent(renderer); break; //Repaint on exposure case SDL_WINDOWEVENT_EXPOSED: SDL_RenderPresent(renderer); break; case SDL_WINDOWEVENT_MINIMIZED: mMinimized = true; break; case SDL_WINDOWEVENT_MAXIMIZED: mMinimized = false; break; case SDL_WINDOWEVENT_RESTORED: mMinimized = false; break; } } //Enter exit full screen on return key else if (e.type == SDL_KEYDOWN &amp;&amp; e.key.keysym.sym == SDLK_RETURN) { if (mFullScreen) { SDL_SetWindowFullscreen(window, SDL_FALSE); mFullScreen = false; } else { SDL_SetWindowFullscreen(window, SDL_TRUE); mFullScreen = true; mMinimized = false; } } } void Visualizer::copy_data(float * data, int channels, int frames) { std::lock_guard&lt;std::mutex&gt;read_guard(packet_buffer_mutex); if (data) { packet_buffer = packet(data, data + channels * frames); } else { // use an empty vector if there is no data (silence) packet_buffer = packet(); } } bool Visualizer::update() { //Handle events on queue while (SDL_PollEvent(&amp;current_event) != 0) { if (current_event.type == SDL_QUIT) { return false; } handle_event(current_event); } // Do not render if minimized if (mMinimized) { return true; } // Render visualizer SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); draw_wave(SDL_Point{ 0, window_height / 2 }, window_width, window_height, SDL_Color{ 255,255,255,255 }); SDL_RenderPresent(renderer); return true; } void Visualizer::draw_wave(const SDL_Point &amp;start, int length, int pixel_amplitude, const SDL_Color &amp; color) { std::vector&lt;SDL_Point&gt; points; std::unique_lock&lt;std::mutex&gt;read_guard(packet_buffer_mutex); if (!packet_buffer.empty()) { // use smallest possible step so soundwave fills window int step = (int)ceil((double)length / (double)packet_buffer.size()); auto amplitude = packet_buffer.begin(); for (int i = 0; i &lt; length; i+=step) { points.push_back(SDL_Point{ start.x + i, (int)(start.y + (*amplitude) * pixel_amplitude) }); ++amplitude; } } else { // silence points.push_back(SDL_Point{ start.x, start.y }); points.push_back(SDL_Point{ start.x + length - 1, start.y }); } read_guard.unlock(); SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); SDL_RenderDrawLines(renderer, &amp;points[0], (int)points.size()); } </code></pre>
[]
[ { "body": "<p>The only thing I think worth calling out is your <code>init_successful</code> pattern. This is somewhat antithetical to the way that object-oriented languages with exception handling encourage us to think about construction. The way to &quot;make a constructor fail&quot; is to throw an exception, which in turn effectively prevents us from retaining a constructed object at all. With your method, there is an intermediate state possible where an object exists in memory, its members can be called, but it's invalid. That's bad.</p>\n<p>If you need special logic to handle a failed construction, catch the exception you throw from the constructor.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T11:16:31.593", "Id": "491624", "Score": "0", "body": "So I should throw from the contructor, catch within the constructor and cleanup if needed, then rethrow and catch in main where the object is being initialized and exit cleanly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T14:15:51.677", "Id": "491630", "Score": "0", "body": "I encourage you to read this - https://stackoverflow.com/questions/188693/is-the-destructor-called-if-the-constructor-throws-an-exception - I did as well, since I'm rusty on the details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T14:18:03.807", "Id": "491631", "Score": "0", "body": "Basically, if you take C++ object orientation to its extreme, any sub-object of `AudioRecorder` would have its own class with its own destructor. If this is the case, a throw from the outer `AudioRecorder` constructor would automatically call the destructors of all members, and no additional cleanup would be needed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T21:08:37.707", "Id": "250446", "ParentId": "250282", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T16:09:45.360", "Id": "250282", "Score": "8", "Tags": [ "c++", "object-oriented", "audio", "winapi", "sdl2" ], "Title": "Audio visualizer in C++" }
250282
<p>I am an Android developer with only 5 months of experience. I am still learning and trying to do my best.</p> <p>Right now I am interested in concept of <code>Separation of concerns</code>. I do understand what it means and I am trying my best to follow it in my android development, however, I found myself a bit confused when I started learning about Clean Architecture.</p> <p>I would like to show my bit of code, and if, possible, get some feedback on my implementation and its correctness when it comes to <code>Separation of concerns</code></p> <p>Code [Note: I am using MVVM in this app]:</p> <p>PopularMoviesFragment:</p> <pre><code>class MoviesPopularFragment : Fragment() { private val moviesViewModel: MoviesViewModel by activityViewModels() private val adapter = PopularMoviesRecyclerAdapter() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = FragmentMoviesPopularBinding.inflate(inflater, container, false) binding.viewModel = moviesViewModel binding.popularMoviesRV.layoutManager = GridLayoutManager(requireContext(), 2) binding.popularMoviesRV.adapter = adapter moviesViewModel.popularMoviesState.observe(viewLifecycleOwner, { state -&gt; when (state) { is PopularMoviesState.Content -&gt; { // TODO: Find a way to deal with this via DataBinding binding.popularMoviesSwipeRefresh.isRefreshing = false binding.progressBarLayout.visibility = View.GONE binding.pageNavigation.visibility = View.VISIBLE adapter.submitList(state.response.results) } is PopularMoviesState.Failure -&gt; { // TODO: Find a way to deal with this via DataBinding binding.popularMoviesSwipeRefresh.isRefreshing = false binding.progressBarLayout.visibility = View.GONE binding.pageNavigation.visibility = View.VISIBLE adapter.submitList(state.cachedListOfMovies) showSnackbar(requireView(), getString(R.string.movies_popular_message_viewing_cached_content), Snackbar.LENGTH_INDEFINITE) } } }) // TODO: Look into implementing this via DataBinding binding.popularMoviesSwipeRefresh.setOnRefreshListener { binding.popularMoviesSwipeRefresh.isRefreshing = true moviesViewModel.fetchPopularMovies() } return binding.root } private fun showSnackbar(view: View, message: String, length: Int) { val snackbar = Snackbar.make(view, message, length) snackbar.animationMode = Snackbar.ANIMATION_MODE_SLIDE snackbar.setAction(view.context.getString(R.string.alert_dialog_default_button_ok)) { snackbar.dismiss() } snackbar.show() } } </code></pre> <p>MoviesViewModel.kt:</p> <pre><code>fun fetchPopularMovies(page: Int = currentPage) { viewModelScope.launch { val result = MainRepository.fetchPopularMovies(page = page) _popularMoviesState.value = when (result) { is PopularMoviesState.Loading -&gt; PopularMoviesState.Loading is PopularMoviesState.Content -&gt; { //TODO: Perhaps find a way to work with pages in a better, more isolated way. currentPage = result.response.page PopularMoviesState.Content(result.response) } is PopularMoviesState.Failure -&gt; { PopularMoviesState.Failure(result.errorMessage, result.cachedListOfMovies) } } } } </code></pre> <p>MainRepository.kt</p> <pre><code>suspend fun fetchPopularMovies(page: Int = 1) = try { val response = IPopularMovies.getInstance().getMovies(page = page) if (response.code() == 200) { savePopularMoviesToCache(response.body()!!.results) PopularMoviesState.Content(response.body()!!) } else { PopularMoviesState.Failure(response.body()!!.status_message, popularMovieDao.getMovies() ?: listOf()) } } catch (error: Throwable) { PopularMoviesState.Failure(error.localizedMessage!!, popularMovieDao.getMovies() ?: listOf()) } private suspend fun savePopularMoviesToCache(listOfMovies: List&lt;PopularMovie&gt;) { popularMovieDao.clearTable() popularMovieDao.addMovies(listOfMovies) } </code></pre> <p>I am mostly interested in <code>MainRepository</code> and its implementation of <code>fetchPopularMovies</code> As you can see, this one function does not have only 1 job, in fact, it does multiple things depending on the situation it is in.</p> <ol> <li>It fetches movies using Retrofit Interface. -&gt; Exactly what it should do Then it either: 2.1. Saves movies to cache or 2.2. Gets movies from cache</li> </ol> <p>Therefore it does not really do 1 thing as it should if we follow the <code>Separation of concerns</code> if I understand correctly.</p> <p>Here is how I think a correct implementation could look:</p> <ol> <li><p>In MainRepository, create 2 separate functions. 1 for saving movies to cache, 1 for getting movies from cache</p> </li> <li><p>In ViewModel do the same thing and create 2 separate functions. 1 for saving to cache. 1 for getting from cache</p> </li> <li><p>In Fragment, where we observe. If success -&gt; call saveCache function in ViewModel if Failure -&gt; call getCache in ViewModel</p> </li> </ol> <p>Please give me some feedback on my thought process. I would really appreciate this!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:17:22.183", "Id": "491130", "Score": "0", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T17:24:25.553", "Id": "250285", "Score": "3", "Tags": [ "android", "kotlin", "mvvm" ], "Title": "A better understanding for separation of concerns. Android; Kotlin" }
250285
<p><strong>Basics</strong></p> <p>I created a simple comment system. My goal was it to create a system that can easily be used on everyone's server without having to install a load of programs. I also tried to create it as privacy-friendly as possible (no email-address, no cookies). I also need to solve this problem without databases.</p> <p><strong>Functionality</strong></p> <ul> <li>Basic form to submit new comments</li> <li>Flag-functionality (with simple email send to the owner of the website)</li> <li>Answer functionality with indented answers</li> </ul> <blockquote> <p><a href="https://i.stack.imgur.com/JptIQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JptIQ.png" alt="enter image description here" /></a></p> </blockquote> <p><strong>Code</strong></p> <p><code>simpleComments.php</code></p> <p>This script provides the main functionality: Spam-protection (with suggestions from <a href="https://codereview.stackexchange.com/questions/248695/contact-form-with-spam-prevention">here</a> and <a href="https://codereview.stackexchange.com/questions/249036/contact-form-with-spam-prevention-follow-up">here</a>), sending, answering and flagging comments. I think that especially the function <code>save()</code> looks is a rather hacky solution. If you know a better alternative (without databases), I would be happy to hear it.</p> <pre class="lang-php prettyprint-override"><code>//The password for the AES-Encryption (has to be length=16) $encryptionPassword = &quot;****************&quot;; //============================================================================================ //============================================================================================ // == // FROM HERE ON NO ADJUSTMENT NECESSARY == // == //============================================================================================ //============================================================================================ /** * Creates image * * This function creates a black image with the random exercise created by randText() on it. * Additionally the function adds some random lines to make it more difficult for bots to read * the text via OCR. The result (for example) looks like this: https://imgur.com/a/6imIE73 * * @author Philipp Wilhelm * * @since 1.0 * * @param string $rand Random exercise created by randText() * @param int $width Width of the image (default = 200) * @param int $height Height of the image (default = 50) * @param int $textColorRed R-RGB value for the textcolor (0-255) (default = 255) * @param int $textColorGreen G-RGB value for the textcolor (0-255) (default = 255) * @param int $textColorBlue B-RGB value for the textcolor (0-255) (default = 255) * @param int $linesColorRed R-RGB value for the random lines (0-255) (default = 192) * @param int $linesColorGreen G-RGB value for the random lines (0-255) (default = 192) * @param int $linesColorBlue B-RGB value for the random lines (0-255) (default = 192) * @param int $fontSize font size of the text on the image (1-5) (default = 5) * @param int $upperLeftCornerX x-coordinate of upper-left corner of the first char (default = 18) * @param int $upperLeftCornerY y-coordinate of the upper-left corner of the first char (default = 18) * @param int $angle angle the text will be rotated by (default = 10) * * @return string created image surrounded by &lt;img&gt; */ function randExer($rand, $width = 200, $height = 50, $textColorRed = 255, $textColorGreen = 255, $textColorBlue = 255, $linesColorRed = 192, $linesColorGreen = 192, $linesColorBlue = 192, $fontSize = 5, $upperLeftCornerX = 18, $upperLeftCornerY = 18, $angle = 10) { global $encryptionPassword; $random = openssl_decrypt($rand,&quot;AES-128-ECB&quot;, $encryptionPassword); $random = substr($random, 0, -40); //Creates a black picture $img = imagecreatetruecolor($width, $height); //uses RGB-values to create a useable color $textColor = imagecolorallocate($img, $textColorRed, $textColorGreen, $textColorBlue); $linesColor = imagecolorallocate($img, $linesColorRed, $linesColorGreen, $linesColorBlue); //Adds text imagestring($img, $fontSize, $upperLeftCornerX, $upperLeftCornerY, $random . &quot; = ?&quot;, $textColor); //Adds random lines to the images for($i = 0; $i &lt; 5; $i++) { imagesetthickness($img, rand(1, 3)); $x1 = rand(0, $width / 2); $y1 = rand(0, $height / 2); $x2 = $x1 + rand(0, $width / 2); $y2 = $y1 + rand(0, $height / 2); imageline($img, $x1, $x2, $x2, $y2, $linesColor); } $rotate = imagerotate($img, $angle, 0); //Attribution: https://stackoverflow.com/a/22266437/13634030 ob_start(); imagejpeg($rotate); $contents = ob_get_contents(); ob_end_clean(); $imageData = base64_encode($contents); $src = &quot;data:&quot; . mime_content_type($contents) . &quot;;base64,&quot; . $imageData; return &quot;&lt;img alt='' src='&quot; . $src . &quot;'/&gt;&quot;; }; /** * Returns time stamp * * This function returns the current time stamp, encrypted with AES, by using the standard function time(). * * @author Philipp Wilhelm * * @since 1.0 * * @return int time stamp */ function getTime() { global $encryptionPassword; return openssl_encrypt(time() . bin2hex(random_bytes(20)),&quot;AES-128-ECB&quot;, $encryptionPassword); } /** * Creates random exercise * * This function creates a random simple math-problem, by choosing two random numbers between &quot;zero&quot; and &quot;ten&quot;. * The result looks like this: &quot;three + seven&quot; * * @author Philipp Wilhelm * * @since 1.0 * * @return string random exercise */ function randText() { global $encryptionPassword; //Creating random (simple) math problem $arr = array(&quot;zero&quot;, &quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;, &quot;seven&quot;, &quot;eight&quot;, &quot;nine&quot;, &quot;ten&quot;); $item1 = $arr[array_rand($arr)]; $item2 = $arr[array_rand($arr)]; $random = $item1 . &quot; + &quot; . $item2; $encrypted = openssl_encrypt($random . bin2hex(random_bytes(20)),&quot;AES-128-ECB&quot;, $encryptionPassword); return $encrypted; } /** * flags comment * * This function sends an email to the specified adress containing the id of the flagged comment * * @author Philipp Wilhelm * * @since 1.0 * * @param string $to Email-adress the mail will be send to * @param string $url URL of the site the comment was flagged on * */ function flag($to, $url) { //Which comment was flagged? $id = $_POST[&quot;comment&quot;]; //At what side was the comment flagged? $referer = $_SERVER[&quot;HTTP_REFERER&quot;]; $subject = &quot;FLAG&quot;; $body = $id . &quot; was flagged at &quot; . $referer . &quot;.&quot;; //Send the mail mail($to, $subject, $body); //Redirect to what page after flag? //(In this case to the same page) header(&quot;Location:&quot; . $url); exit(); } /** * redirects to the same page, but with the added parameter to specify to which * comment will be answered and jumps right to the comment-form * * * @author Philipp Wilhelm * * @since 1.0 * * @param string $url the url of the current page * @param string $buttonName URL of the site the comment was flagged on * @param string $urlName the &quot;id-name&quot; * */ function answer($url, $buttonName, $urlName) { header(&quot;Location:&quot; . $url . &quot;?&quot; . $urlName . &quot;=&quot; . $_POST[&quot;comment&quot;] . &quot;#&quot; . $buttonName); exit(); } /** * error message * * Redirects to the specified url to tell the user that something went wrong * e.g. entered wrong solution to math-exercise * * @author Philipp Wilhelm * * @since 1.0 * * @param string $urlError The specified url * */ function error($urlError) { header(&quot;Location:&quot; . $urlError); die(); } /** * Redirects to specified url when user enters words that are on the &quot;blacklist&quot; * * @author Philipp Wilhelm * * @since 1.0 * * @param string $urlBadWords The specified url to which will be redirected * */ function badWords($urlBadWords) { header(&quot;Location:&quot; . $urlBadWords); die(); } /** * Redirects to same url after comment is successfully submitted - comment will be visible * immediately * * @author Philipp Wilhelm * * @since 1.0 * * @param string $url URL of the site * */ function success($url) { header(&quot;Location:&quot; . $url); die(); } /** * checks if user enters any words that are on the &quot;blacklist&quot; * * @author Philipp Wilhelm * * @since 1.0 * * @param string $text The user-entered text * @param string $blackList filename of the &quot;blacklist&quot; * * @return boolean true if user entered a word that is on the &quot;blacklist&quot; * */ function isForbidden($text, $blackList) { //gets content of the blacklist-file $content = file_get_contents($blackList); $text = strtolower($text); //Creates an array with all the words from the blacklist $explode = explode(&quot;,&quot;, $content); foreach($explode as &amp;$value) { //Pattern checks for whole words only ('hell' in 'hello' will not count) $pattern = sprintf(&quot;/\b(%s)\b/&quot;,$value); if(preg_match($pattern, $text) == 1) { return true; } } return false; } /** * saves a new comment or an answer to a comment * * @author Philipp Wilhelm * * @since 1.0 * * @param string $url Email-adress the mail will be send to * @param string $urlError URL to the &quot;error&quot;-page * @param string $urlBadWords URL to redirect to , when user uses words on the &quot;blacklist&quot; * @param string $blacklist filename of the blacklist * @param string $fileName filename of the file the comments are stored in * @param string $nameInputTagName name of the input-field for the &quot;name&quot; * @param string $messageInputTagName name of the input-field for the &quot;message&quot; * @param string exerciseInputTagName name of the input-field the math-problem is stored in * @param string solutionInputTagName name of the input-field the user enters the solution in * @param string $answerInputTagName in this field the id of the comment the user answers to is saved * (if answering to a question) * @param string $timeInputTagName name of the input-field the timestamp is stored in * */ function save($url, $urlError, $urlBadWords, $blacklist, $fileName, $nameInputTagName, $messageInputTagName, $exerciseInputTagName, $solutionInputTagName, $answerInputTagName, $timeInputTagName) { global $encryptionPassword; $solution = filter_input(INPUT_POST, $solutionInputTagName, FILTER_VALIDATE_INT); $exerciseText = filter_input(INPUT_POST, $exerciseInputTagName); if ($solution === false || $exerciseText === false) { error($urlError); } $time = openssl_decrypt($_POST[$timeInputTagName], &quot;AES-128-ECB&quot;, $encryptionPassword); if(!$time) { error($urlError); } $time = substr($time, 0, -40); $t = intval($time); if(time() - $t &gt; 300) { error($urlError); } //Get simple math-problem (e.g. four + six) $str = openssl_decrypt($_POST[$exerciseInputTagName], &quot;AES-128-ECB&quot;, $encryptionPassword); $str = substr($str, 0, -40); if (!$str) { error($urlError); } $arr = array(&quot;zero&quot;, &quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;, &quot;seven&quot;, &quot;eight&quot;, &quot;nine&quot;, &quot;ten&quot;); //gets array with written numbers $words = array_map(&quot;trim&quot;, explode(&quot;+&quot;, $str)); //gets the numbers as ints $numbers = array_intersect($arr, $words); if (count($numbers) != 2) { error($urlError); } $sum = array_sum(array_keys($numbers)); $urlPicture = &quot;identicon.php/?size=24&amp;hash=&quot; . md5($_POST[$nameInputTagName]); //Did user enter right solution? if ($solution == $sum) { $name = $_POST[$nameInputTagName]; $comment = htmlspecialchars($_POST[$messageInputTagName]); $content = file_get_contents($fileName); if(strcmp($content, &quot;&lt;p&gt;No comments yet!&lt;/p&gt;&quot;) == 0 || strcmp($content, &quot;&lt;p&gt;No comments yet!&lt;/p&gt;\n&quot;) == 0) { $content = &quot;&lt;p&gt;Identicons created with &lt;a href='https://github.com/timovn/identicon'&gt;identicon.php&lt;/a&gt; (licensed under &lt;a href='http://www.gnu.org/licenses/gpl-3.0.en.html'&gt;GPL-3.0&lt;/a&gt;).&lt;/p&gt;&quot;; } $id = bin2hex(random_bytes(20)); $answerID = $_POST[$answerInputTagName]; //Checks if user used any words from the blacklist if(isForbidden($comment, $blacklist)) { badWords($urlBadWords); } //Case the user writes a new comment (not an answer) if(strlen($answerID) &lt; 40) { file_put_contents($fileName, //Needed styles &quot;&lt;style&gt;&quot; . &quot;.commentBox {&quot; . &quot;display: block;&quot; . &quot;background: LightGray;&quot; . &quot;width: 90%;&quot; . &quot;border-radius: 10px;&quot; . &quot;padding: 10px;&quot; . &quot;margin-bottom: 5px;&quot; . &quot;} &quot; . &quot;input[name='flag'], input[name='answer'] {&quot; . &quot;border: none;&quot; . &quot;padding: 0;&quot; . &quot;margin: 0;&quot; . &quot;margin-top: 5px;&quot; . &quot;padding: 2px;&quot; . &quot;background: transparent;&quot; . &quot;}&quot; . &quot;&lt;/style&gt;&quot; . //get random avatar &quot;&lt;img class='icon' style='vertical-align:middle;' src='&quot; . $urlPicture . &quot;'/&gt;&quot; . //Displaying user name &quot;&lt;span&gt;&lt;b&gt; &quot; . $name . &quot;&lt;/b&gt;&lt;/span&gt; says:&lt;br&gt;&quot; . //Current UTC-time and -date &quot;&lt;span style='font-size: small'&gt;&quot; . gmdate(&quot;d-m-Y H:i&quot;) . &quot; UTC&lt;/span&gt;&lt;br&gt;&quot; . //The main comment &quot;&lt;div class='commentBox'&gt;&quot; . $comment . &quot;&lt;br&gt;&quot; . &quot;&lt;/div&gt;&quot;. &quot;&lt;div style='width: 90%; font-size: small; float: left'&gt;&quot; . //Flag-button &quot;&lt;form style='margin: 0; padding: 0; float: left;' method='POST' action='simpleComments.php'&gt;&quot; . &quot;&lt;input style='display: none;' name='comment' type='text' value='&quot; . $id . &quot;'/&gt;&quot; . &quot;&lt;input style='color: red;' type='submit' name='flag' value='Flag'/&gt;&quot; . &quot;&lt;/form&gt;&quot; . //Answer-button &quot;&lt;form id='answer' style='margin-left: 0; padding: 0; float: left;' method='POST' action='simpleComments.php'&gt;&quot; . &quot;&lt;input style='display: none;' name='comment' type='text' value='&quot; . $id . &quot;'/&gt;&quot; . &quot;&lt;input style='color: green;' type='submit' name='answer' value='Answer'/&gt;&quot; . &quot;&lt;/form&gt;&quot; . &quot;&lt;!-- &quot; . $id . &quot; --&gt;&quot; . &quot;&lt;/div&gt;&quot; . &quot;&lt;br&gt;&lt;br&gt;&quot; . $content); success($url); } //Case that user writes an answer else { if(strpos($content, $answerID) !== false) { $explode = explode(&quot;&lt;!-- &quot; . $answerID . &quot; --&gt;&quot;, $content); file_put_contents($fileName, $explode[0] . &quot;&lt;/div&gt;&quot; . &quot;&lt;br&gt;&lt;br&gt;&quot; . //Needed styles &quot;&lt;style&gt;&quot; . &quot;.answerBox {&quot; . &quot;display: block;&quot; . &quot;background: LightGray;&quot; . &quot;width: 90%;&quot; . &quot;border-radius: 10px;&quot; . &quot;padding: 10px;&quot; . &quot;margin-bottom: 5px;&quot; . &quot;} &quot; . &quot;input[name='flag'] {&quot; . &quot;border: none;&quot; . &quot;padding: 0;&quot; . &quot;margin: 0;&quot; . &quot;margin-top: 5px;&quot; . &quot;padding: 2px;&quot; . &quot;background: transparent;&quot; . &quot;}&quot; . &quot;&lt;/style&gt;&quot; . &quot;&lt;div style='margin-left: 50px'&gt;&quot; . //get random avatar &quot;&lt;img class='icon' style='vertical-align:middle;' src='&quot; . $urlPicture . &quot;'/&gt;&quot; . //Displaying user name &quot;&lt;span&gt;&lt;b&gt; &quot; . $name . &quot;&lt;/b&gt;&lt;/span&gt; says:&lt;br&gt;&quot; . //Current UTC-time and -date &quot;&lt;span style='font-size: small'&gt;&quot; . gmdate(&quot;d-m-Y H:i&quot;) . &quot; UTC&lt;/span&gt;&lt;br&gt;&quot; . //The main comment &quot;&lt;div class='answerBox'&gt;&quot; . $comment . &quot;&lt;br&gt;&quot; . &quot;&lt;/div&gt;&quot;. //Flag-button &quot;&lt;div style='width: 90%; font-size: small; float: left'&gt;&quot; . &quot;&lt;form style='margin: 0; padding: 0; float: left;' method='POST' action='simpleComments.php'&gt;&quot; . &quot;&lt;input style='display: none;' name='comment' type='text' value='&quot; . $id . &quot;'/&gt;&quot; . &quot;&lt;input style='color: red;' type='submit' name='flag' value='Flag'/&gt;&quot; . &quot;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&quot; . &quot;&lt;/div&gt;&quot; . &quot;&lt;!-- &quot; . $answerID . &quot; --&gt;&quot; . $explode[1]); success($url); } } } error($urlError); } //============================================================================================ //============================================================================================ // == // FROM HERE ON ADJUSTMENT ARE NECESSARY == // == //============================================================================================ //============================================================================================ /** * start point of the script * * @author Philipp Wilhelm * * @since 1.0 * * */ function start() { //To what email-adress should the flag-notification be send? $to = &quot;example@example.com&quot;; //What's the url you are using this system for? (exact link to e.g. the blog-post) $url = &quot;https://example.com/post001.html&quot;; //Which page should be loaded when something goes wrong? $urlError = &quot;https://example.com/messageError.html&quot;; //What page should be loaded when user submits words from your &quot;blacklist&quot;? $urlBadWords = &quot;https://example.com/badWords.html&quot;; //In which file are the comments saved? $fileName = &quot;testComments.php&quot;; //What's the filename of your &quot;blacklist&quot;? $blackList = &quot;blacklist.txt&quot;; //Replace with the name-attribute of the respective input-field //No action needed here, if you didn't update form.php $nameInputTagName = &quot;myName&quot;; $messageInputTagName = &quot;myMessage&quot;; $exerciseInputTagName = &quot;exerciseText&quot;; $solutionInputTagName = &quot;solution&quot;; $answerInputTagName = &quot;answerID&quot;; $timeInputTagName = &quot;time&quot;; $buttonName = &quot;postComment&quot;; $urlName = &quot;id&quot;; if (isset($_POST[&quot;flag&quot;])) { flag($to, $url); } if (isset($_POST[&quot;answer&quot;])) { answer($url, $buttonName, $urlName); } if (isset($_POST[$buttonName])) { save($url, $urlError, $urlBadWords, $blackList, $fileName, $nameInputTagName, $messageInputTagName, $exerciseInputTagName, $solutionInputTagName, $answerInputTagName, $timeInputTagName); } } start(); ?&gt; </code></pre> <p>The code was checked with <a href="https://phpcodechecker.com/" rel="nofollow noreferrer">phpcodechecker.com</a> and it didn't find any problems.</p> <p>The other files are not really worth reviewing, so I will leave it here.</p> <p><strong>Links</strong></p> <p>For those who are nevertheless interested in the other files and a how-to, please see the <a href="https://codeberg.org/philippwilhelm/Simple_Comments" rel="nofollow noreferrer">repository</a> for this project.</p> <p>There also is a <a href="https://demo.wilhelm.lol/index.php" rel="nofollow noreferrer">live-demo</a> for those of you who want to test it.</p> <p><strong>Question</strong></p> <p>Every suggestions are welcome. As mentioned before, I would be especially interested in a more elegant solution for the <code>save()</code>-function.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T23:22:02.653", "Id": "491078", "Score": "0", "body": "This is going to take some time to thoroughly review. Please hunt&kill \"single-use variables\" (`$encrypted = ...; return $encrypted;`). Ask yourself why `$value` needs to be modifiable by reference if you never modify it. `preg_match()` returns a truthy/falsey value. If `+` has a space on both sides, why not `explode()` on 3 characters instead of 1? (avoiding iterated `trim()` calls) You must not like my previous suggestion https://codereview.stackexchange.com/questions/248695/contact-form-with-spam-prevention#comment487464_248695" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T00:32:28.003", "Id": "491079", "Score": "0", "body": "Why aren't the css style blocks unconditionally applied to the document? I'd like to see no inline styling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T09:39:37.287", "Id": "491103", "Score": "0", "body": "@mickmackusa I really appreciated your comment and did the best I could do to improve the security. Could you maybe give a detailed explanation on how to improve it and what your thoughts were when writing this comment? I don't really want to use SESSION, because I prefer to keep it \"cookie-free\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T20:48:58.140", "Id": "491171", "Score": "1", "body": "I have noticed that the captcha session can be reused. Once I have provided the valid challenge I can click back on my browser and submit another comment, and potentially spam your site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T10:37:52.770", "Id": "491216", "Score": "0", "body": "@Anonymous Oh thanks for the hint. Problem solved :)" } ]
[ { "body": "<p>This is just a single suggestion, and not a complete review of your code.</p>\n<p>Most comment systems are used for commenting on something that is not itself a comment. Like in your demo page. This means that your code <strong>will be included</strong> in someone else's page. This might be a very complex page. In other words, your code will have to live alongside, a possibly endless variety of, other code. What if that code includes functions like <code>getTime()</code>, <code>error()</code> or <code>save()</code>? Then your code will break that page.</p>\n<p>This is why, code we want to share with other developers, is almost always written in an object oriented programming (OOP) style. Objects, and name spaces, are used isolate your code from the code of those who use your code.</p>\n<p>Some links:</p>\n<p><a href=\"https://phpenthusiast.com/object-oriented-php-tutorials\" rel=\"noreferrer\">https://phpenthusiast.com/object-oriented-php-tutorials</a></p>\n<p><a href=\"https://www.thoughtfulcode.com/a-complete-guide-to-php-namespaces\" rel=\"noreferrer\">https://www.thoughtfulcode.com/a-complete-guide-to-php-namespaces</a></p>\n<p><a href=\"https://phptherightway.com\" rel=\"noreferrer\">https://phptherightway.com</a></p>\n<p>Even if you leave your code, as it is now, I would advise to be more creative with the names you choose. For instance, the function name <code>randExer()</code> means nothing to me. A better name would be something like <code>getCaptchaImageHtml()</code>. This name actually describes what the function does and what it returns. The same applies to the other functions. It is <em>my opinion</em> that uncommon abbreviation should be avoided in function names.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T03:43:03.083", "Id": "491085", "Score": "0", "body": "Symbol conflicts are unlikely the reason for OOP style. You can write FP with namespaces, no problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T09:50:40.100", "Id": "491107", "Score": "0", "body": "@slepic Yes, you're right, using only namespaces would also be sufficient to prevent symbol conflicts. Note that global variables are not isolated by namespaces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:23:36.773", "Id": "491113", "Score": "1", "body": "Yeah, that even made me post an answer targeting the global variables aspect of OP's code, because you didn't mention globals in your answer and it would probably remain unnoticed by OP here in comments..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T23:22:10.497", "Id": "250294", "ParentId": "250286", "Score": "5" } }, { "body": "<p>Avoid using global variables.</p>\n<p>The variable <code>$encryptionPassword</code> should be passed as an argument to all functions that need it (<code>randExer</code>, <code>getTime</code>, <code>randText</code> and <code>save</code>).</p>\n<p>There are several reasons for doing so:</p>\n<ul>\n<li>You avoid conflicts with other global variables (not that there should be any)</li>\n<li>You avoid accidental access to that variable by those who should not access it.</li>\n<li>Signatures of the functions hide the dependency on an encryption password, which makes it harder to understand the code by readers, because they have to read the function body to understand that there is such a dependency. Reading just the function's signature should be enough.</li>\n<li>The functions are easier to test</li>\n<li>and probably more...</li>\n</ul>\n<p>A function that uses a global variable cannot be pure by definition. Pure functions are generally prefered for the reasons mentioned above.</p>\n<p>EDIT:\nA possible way to solve the global variable problem is to promote the functions to class methods and pass the encryption password to its constructor:</p>\n<pre><code>class ASuitableClassName\n{\n private string $encryptionPassword;\n\n public function __construct(string $encryptionPassword)\n {\n $this-&gt;encryptionPassword = $encryptionPassword;\n }\n\n public function getTime()\n {\n return openssl_encrypt(time() . bin2hex(random_bytes(20)),&quot;AES-128-ECB&quot;, $this-&gt;encryptionPassword);\n }\n \n // ....\n}\n\n$obj = new ASuitableClassName(&quot;****************&quot;);\n$obj-&gt;getTime();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:55:32.980", "Id": "491117", "Score": "1", "body": "@PhilippWilhelm I have edited my post to show you a possible way" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T21:48:26.927", "Id": "491267", "Score": "0", "body": "I agree that your solution to the global variable problem will work, but then why did you comment on my answer: \"Symbol conflicts are unlikely the reason for OOP style.\"? Perhaps it's more likely than you thought at that moment? Oh, and have you seen the bounty? It is worth the effort of rewriting this code? I don't think so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T03:16:55.280", "Id": "491297", "Score": "0", "body": "@KIKOSoftware I made an edit because OP asked in the comments specifically for solution where the password is not passed as argument to those functions. The comment Is gone tho. And honestly the reasoning was flawed but I showed the possibility anyway. But it Is not at all necesary to do it OOP style..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T04:13:50.303", "Id": "491299", "Score": "0", "body": "Although I also find OOP more appealing, maybe just because I am used to it. But I dont think symbol conflicts is among the top reasons to use it. And no I dont find it worth it rewriting OPs code for 100 points bounty." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:20:10.433", "Id": "250313", "ParentId": "250286", "Score": "3" } }, { "body": "<h1>Initial Feedback</h1>\n<p>I like the usage of docblocks above the functions. The <code>save()</code> function makes good use of returning early to limit indentation levels, except for the last check - when <code>$solution</code> does not match <code>$sum</code> then it can call <code>error()</code> right away. Overall that function is quite lengthy - it violates the <a href=\"https://deviq.com/single-responsibility-principle/\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>. The functionality to write to the file could be moved to separate functions for each case (comment vs answer). The stylesheets can be moved out to a CSS file(s).</p>\n<p>Like I mentioned in <a href=\"https://codereview.stackexchange.com/a/249165/120114\">this answer</a> CSRF tokens could replace the need for the image creation, encoding and decoding.</p>\n<h1>Suggestions</h1>\n<h2>Global variables</h2>\n<p>As others have suggested, <a href=\"https://softwareengineering.stackexchange.com/q/148108/244085\">global variables have more negative aspects than positives</a>. You <em>could</em> pass the encryption password to each function that needs it, but that would require updating the signature of each function that needs it. Another option is to create a named constant using <a href=\"https://php.net/define\" rel=\"nofollow noreferrer\"><code>define()</code></a>.</p>\n<pre><code>define('ENCRYPTION_PASSWORD', 'xyz');\n</code></pre>\n<p>This could be done in a separate file that is included via <a href=\"https://php.net/include\" rel=\"nofollow noreferrer\"><code>include()</code></a> (or <a href=\"https://php.net/include_once\" rel=\"nofollow noreferrer\"><code>include_once()</code></a>) or <a href=\"https://php.net/require\" rel=\"nofollow noreferrer\"><code>require()</code></a> (or <a href=\"https://php.net/require_once\" rel=\"nofollow noreferrer\"><code>require_once()</code></a>), which could be separate from version control (e.g. a .env file)</p>\n<p>Constants can also be created using the <a href=\"https://www.php.net/const\" rel=\"nofollow noreferrer\"><code>const</code></a> keyword - outside of a class as of PHP 5.3.0<sup><a href=\"https://www.php.net/const\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n<pre><code>const ENCRYPTION_PASSWORD = 'xyz';\n</code></pre>\n<p>As was already suggested, using a class with a namespace is a great idea. A class would allow the use of a <a href=\"https://www.php.net/manual/en/language.oop5.constants.php\" rel=\"nofollow noreferrer\">class constant</a> that would be namespaced to the class and have a specific <a href=\"https://www.php.net/manual/en/language.oop5.visibility.php\" rel=\"nofollow noreferrer\">visibility</a> as of PHP 7.1<sup><a href=\"https://www.php.net/manual/en/language.oop5.visibility.php\" rel=\"nofollow noreferrer\">2</a></sup>.</p>\n<p>Hopefully your code is running on PHP 7.2 or later, since those versions are officially supported<sup><a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">3</a></sup>.</p>\n<h2>Iteration by reference</h2>\n<p>The function <code>isForbidden</code> iterates over the contents of the file pointed to in <code>$blacklist</code> assigning the value by reference:</p>\n<blockquote>\n<pre><code> foreach($explode as &amp;$value) {\n</code></pre>\n</blockquote>\n<p>This seems unnecessary because <code>$value</code> is not modified within the loop. It might be best to avoid such a practice unless you are certain the array elements need to be modified.</p>\n<h2>Strict equality</h2>\n<p>You may have heard this already: <a href=\"https://softwareengineering.stackexchange.com/q/126585/244085\">it is a good habit to use strict comparison operators</a> - i.e. <code>===</code> and <code>!==</code> when possible - e.g. for this comparison within <code>save()</code>:</p>\n<blockquote>\n<pre><code>if (count($numbers) != 2) {\n</code></pre>\n</blockquote>\n<p><code>count()</code> returns an <code>int</code> and <code>2</code> is an <code>int</code> so <code>!==</code> can be used as there is no need for type conversion.</p>\n<h2>Hidden inputs</h2>\n<p>The HTML generated for the forms contains:</p>\n<blockquote>\n<pre><code>&lt;input style='display: none;' \n</code></pre>\n</blockquote>\n<p>This could be simplified slightly using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden\" rel=\"nofollow noreferrer\"><em>hidden</em></a> input type:</p>\n<pre><code>&lt;input type=&quot;hidden&quot;\n</code></pre>\n<p>While any input could be displayed by the user by modifying the page via browser console or other means, the hidden input was created for the purpose of hiding form values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:55:57.707", "Id": "250384", "ParentId": "250286", "Score": "3" } } ]
{ "AcceptedAnswerId": "250384", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T17:26:27.270", "Id": "250286", "Score": "4", "Tags": [ "beginner", "php", "html", "iteration" ], "Title": "PHP comment system" }
250286
<p>So I wrote this fixed timestep &amp; rendering game loop. I am posting it here to see if there are ways to optimize it/make it more accurate.</p> <pre><code> const float updatesRate = 1 / 60.0f; const float framesRate = 1 / 308.0f; double currentTime = hireTimeInSeconds( ); double accumulator = 0.0; double accumulator2 = 0.0; uint32_t frames = 0, updates = 0; double timer = hireTimeInSeconds( ); while ( true ) { double newTime = hireTimeInSeconds( ); if ( newTime - timer &gt;= 1 ) { //Printing fps and ups here updates = 0; frames = 0; timer = newTime; } double frameTime = newTime - currentTime; if ( frameTime &gt; 0.25 ) frameTime = 0.25; currentTime = newTime; accumulator += frameTime; accumulator2 += frameTime; //Polling input here while ( accumulator &gt;= updatesRate ) { //Updating here accumulator -= updatesRate; updates++; } const double alpha = accumulator / updatesRate; while ( accumulator2 &gt;= framesRate ) { //Rendering frames++; accumulator2 -= framesRate; } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<pre><code>const float updatesRate = 1 / 60.0f;\nconst float framesRate = 1 / 308.0f;\n</code></pre>\n<p>The other time values are all <code>double</code>s, it's a bit strange to use <code>float</code>s here.</p>\n<hr />\n<pre><code> if ( newTime - timer &gt;= 1 ) {\n ...\n if ( frameTime &gt; 0.25 ) frameTime = 0.25;\n</code></pre>\n<p>These magic numbers should be named constants.</p>\n<hr />\n<p>C++ now provides a variety of time-related utilities through the <code>&lt;chrono&gt;</code> header. We should use the clock types, type-safe duration types, and conversions that it provides.</p>\n<hr />\n<pre><code>double accumulator = 0.0;\ndouble accumulator2 = 0.0;\nuint32_t frames = 0, updates = 0;\ndouble timer = hireTimeInSeconds( );\n</code></pre>\n<p>The naming of these variables leaves their purpose very unclear. Perhaps we could define an <code>Accumulator</code> class to group the variables for each accumulator and remove the duplication (see example code below).</p>\n<hr />\n<p><code>hireTimeInSeconds</code> This should probably be <code>highResTimeInSeconds</code>.</p>\n<hr />\n<pre><code> while ( accumulator2 &gt;= framesRate ) {\n //Rendering\n frames++;\n accumulator2 -= framesRate;\n }\n</code></pre>\n<p>I don't think this makes sense. We only want to render one frame, even if lots of time has passed. (We're not doing any updates between rendering frames in this loop, so we'd just be rendering the exact same thing over and over).</p>\n<hr />\n<p>Applying the above suggestions, we might get something like the code below. It is quite a few more lines of code, but is also much more reusable (especially the <code>accumulator</code> and <code>frame_timer</code> classes), and is hopefully clearer in intent:</p>\n<pre><code>#include &lt;chrono&gt;\n#include &lt;iostream&gt;\n\ntemplate&lt;class c_t&gt;\nclass accumulator\n{\npublic:\n\n using clock_t = c_t;\n using duration_t = typename clock_t::duration;\n\n template&lt;class d_t&gt;\n explicit accumulator(d_t tick_length):\n m_tick_length(std::chrono::duration_cast&lt;duration_t&gt;(tick_length)) { }\n\n std::size_t accumulate(duration_t delta_time) // note: returns the number of ticks of m_tick_length triggered by this call\n {\n m_accumulated_time += delta_time;\n\n auto ticks = std::size_t{ 0 };\n\n while (m_accumulated_time &gt;= m_tick_length)\n {\n ++ticks;\n m_accumulated_time -= m_tick_length;\n }\n\n return ticks;\n }\n\n duration_t get_tick_length() const\n {\n return m_tick_length;\n }\n\nprivate:\n\n duration_t m_tick_length;\n duration_t m_accumulated_time;\n};\n\ntemplate&lt;class c_t&gt;\nclass frame_timer\n{\npublic:\n\n using clock_t = c_t;\n using duration_t = typename clock_t::duration;\n using time_point_t = typename clock_t::time_point;\n\n template&lt;class d_t&gt;\n explicit frame_timer(d_t initial_last_frame_time):\n m_last_frame_time(std::chrono::duration_cast&lt;duration_t&gt;(initial_last_frame_time)),\n m_last_tick(clock_t::now()) { }\n \n void tick()\n {\n auto now = clock_t::now();\n m_last_frame_time = now - m_last_tick;\n m_last_tick = now;\n }\n\n duration_t get_last_frame_time() const\n {\n return m_last_frame_time;\n }\n\nprivate:\n\n duration_t m_last_frame_time;\n time_point_t m_last_tick;\n};\n\nint main()\n{\n using clock_t = std::chrono::high_resolution_clock;\n using duration_t = clock_t::duration;\n using time_point_t = clock_t::time_point;\n using seconds_t = std::chrono::duration&lt;float&gt;;\n\n auto const update_time = seconds_t(1.f / 60.f);\n auto update_accumulator = accumulator&lt;clock_t&gt;(update_time);\n\n auto const render_time = seconds_t(1.f / 308.f);\n auto render_accumulator = accumulator&lt;clock_t&gt;(render_time);\n\n auto const print_time = seconds_t(1.f);\n auto print_accumulator = accumulator&lt;clock_t&gt;(print_time);\n\n auto const initial_frame_time = update_time;\n auto timer = frame_timer&lt;clock_t&gt;(initial_frame_time);\n\n auto const max_frame_time = std::chrono::duration_cast&lt;duration_t&gt;(seconds_t(0.25f));\n\n while (true)\n {\n auto const last_frame_time = (timer.get_last_frame_time() &gt; max_frame_time) ? max_frame_time : timer.get_last_frame_time();\n\n if (print_accumulator.accumulate(last_frame_time) != 0) // note: will skip update periods if frames are super long (&gt; print_time)\n {\n // ... print frames\n std::cout &lt;&lt; &quot;ping!&quot; &lt;&lt; std::endl;\n }\n\n auto const update_ticks = update_accumulator.accumulate(last_frame_time); // note: don't put this directly in the loop condition, we only want to call it once!\n\n for (auto i = std::size_t{ 0 }; i != update_ticks; ++i)\n {\n // ... do update\n std::cout &lt;&lt; &quot;update&quot; &lt;&lt; std::endl;\n }\n\n if (render_accumulator.accumulate(last_frame_time) != 0) // note: only ever render 1 frame, even if we should have rendered more\n {\n // ... render\n std::cout &lt;&lt; &quot;render&quot; &lt;&lt; std::endl;\n }\n\n timer.tick();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T09:21:33.930", "Id": "250308", "ParentId": "250288", "Score": "3" } } ]
{ "AcceptedAnswerId": "250308", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T18:32:29.090", "Id": "250288", "Score": "1", "Tags": [ "c++", "game" ], "Title": "Fixed timestep & rendering game loop" }
250288
<p>I use the following which <strong>works</strong>( I remove the unnnecery parts to the question)</p> <p><a href="https://play.golang.org/p/OozjexJ4hZk" rel="nofollow noreferrer">https://play.golang.org/p/OozjexJ4hZk</a></p> <p>The program is doing the following:</p> <blockquote> <ol> <li>run concurrent functions</li> <li>each function should return response</li> <li>calculate the response</li> </ol> </blockquote> <p>I will add a logs and comments but I want to get feedback on the code. What Im not sure if I use <code>clientA</code> and <code>clientB</code> in a clean way,but it works...</p> <pre><code> package main import ( &quot;context&quot; &quot;fmt&quot; `net/http` &quot;time&quot; &quot;github.com/gammazero/workerpool&quot; `k8s.io/client-go/kubernetes` ) type JobReact struct { name string Duration time.Duration Info interface{} Error error } func (m *JobReact) Name() string { return m.name } type GenClient struct { ClientA http.Client ClientB kubernetes.Clientset } type ResultList struct { response http.Response } // Jobs holds job data type Jobs struct { Name string Runner func(*GenClient) JobReact } func wrapper(timeDuration time.Duration, reacts chan JobReact, jobs Jobs, genClient GenClient, ) func() { contextWithTimeout, tc := context.WithTimeout(context.Background(), timeDuration) return func() { now := time.Now() go func(contx context.Context, cancelFunc context.CancelFunc, jobReacts chan JobReact, jobs Jobs, timer time.Time, ) { // Here I need to use the combined clients , should I use some interface? if yes how? runner := jobs.Runner(&amp;genClient) runner.Duration = time.Since(timer) runner.name = jobs.Name if contextWithTimeout.Err() == nil { jobReacts &lt;- runner } cancelFunc() }(contextWithTimeout, tc, reacts, jobs, now) select { case &lt;-contextWithTimeout.Done(): switch contextWithTimeout.Err() { case context.DeadlineExceeded: reacts &lt;- JobReact{ name: jobs.Name, Error: context.DeadlineExceeded, Duration: time.Since(now), } } } } } func main() { // init clients genClients := GenClient{ClientA: ClientA(), ClientB: ClientB()} jobs := []Jobs{ { Name: &quot;job1&quot;, Runner: func(GenClient *GenClient) JobReact { // In this func I need to use client A GenClient.ClientA ... }, }, { Name: &quot;job2&quot;, Runner: func(genClient *GenClient) JobReact { // In this func I need to use client b GenClient.ClientB ... }, }, { Name: &quot;job3&quot;, Runner: func(genClient *GenClient) JobReact { // In this func I need to use Client A &amp; client B GenClient.ClientB GenClient.ClientA ... }, }, } JobRes := make(chan JobReact, len(jobs)) pool := workerpool.New(5) for _, worker := range jobs { pool.Submit(wrapper(time.Duration(time.Second * 10), JobRes, worker, genClients)) } pool.StopWait() GetAllResponses(JobRes) } func GetAllResponses(wr chan JobReact) ResultList { for jobChannel := range wr { if jobChannel.Info != 200 { fmt.Printf(&quot;job %s: took '%d' sec response: %s\n&quot;, jobChannel.Name(), jobChannel.Duration.Seconds(), jobChannel.Error) return ResultList{response: http.Response{StatusCode: 500}} } fmt.Printf(&quot;job %s: took '%d' sec response: %s\n&quot;, jobChannel.Name(), jobChannel.Duration.Seconds(), jobChannel.Info) } return ResultList{response: http.Response{StatusCode: 200}} } func ClientA() http.Client { c := &amp;http.Client{} return *c } func ClientB() kubernetes.Clientset { .... return *clientset } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T18:32:51.353", "Id": "250289", "Score": "2", "Tags": [ "beginner", "multithreading", "go" ], "Title": "Using go jobs with generic function" }
250289
<p>I was recently told I need to change my coding style. An Interviewer told me he would like to see &quot;more formalized class structure and organization&quot;. I have attached few of my cpp files.</p> <p>if you can you review it and give me your feedback on the things I can improve that will be extremely helpful.</p> <h3>Challenge:</h3> <p>Given n robots (n different paths), m nodes, how much time all the robots requires to complete the circuit. If 2 robots arrive at a node, the 2nd robot should wait till the 1st robot completes its task.</p> <p>File structure:</p> <pre><code>├── Solution │ ├── data │ │ ├── ***.csv │ │ ├── ***.csv │ │ ├── ***.csv │ ├── include │ │ ├── robot.h │ │ ├── node.h │ │ ├── simulation.h │ ├── output │ │ ├── ***.csv │ │ ├── ***.csv │ ├── src │ │ ├── main.cpp │ │ ├── planner.cpp │ │ ├── read_write.cpp │ │ ├── simulation.cpp │ ├── test │ │ ├── simulationTest.cpp │ ├── CMakeLists.txt │ ├── README.md </code></pre> <p>simulation.h</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once ...//all headers #include &quot;robot.h&quot; #include &quot;node.h&quot; class simulation{ private: std::string robots_ip_string; std::string paths_ip_string; std::string nodes_ip_string; std::string time_op_string; std::string visits_op_string; std::vector&lt;robot*&gt; robots; //stores the robot info std::unordered_map&lt;int, node*&gt; nodes; std::unordered_map&lt;int, std::vector&lt;int&gt;&gt; paths; public: simulation(); ~simulation(); void read_robots_input(); void read_paths_input(); void read_nodes_input(); void print_robots(); void print_nodes(); void print_paths(); void run_simulation(); void simulation_time(); void visited_node_info(); std::vector&lt;robot*&gt; get_robots(); }; </code></pre> <p>robot.h</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once struct robot{ int robot_id; std::string robot_type; int robot_speed; std::vector&lt;int&gt; path_to_follow; int path_length; int run_time; }; </code></pre> <p>planner.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;simulation.h&quot; struct Path_Queue_Comparator{ bool operator() (std::pair&lt;robot*,int&gt; const&amp; r1, std::pair&lt;robot*,int&gt; const&amp; r2){ if (r1.first-&gt;run_time == r2.first-&gt;run_time) return (r2.first-&gt;robot_type == &quot;organizer&quot;) ? true : false; return r1.first-&gt;run_time &gt; r2.first-&gt;run_time; } }; void simulation::run_simulation(){ std::priority_queue&lt; std::pair&lt;robot*,int&gt;, std::vector&lt;std::pair&lt;robot*,int&gt;&gt;, Path_Queue_Comparator&gt; path_q; for(auto r: robots) path_q.push({r, 0}); while(!path_q.empty()){ std::pair&lt;robot*,int&gt; temp = path_q.top(); robot* current_state = temp.first; int current_index = temp.second; path_q.pop(); int next_index = current_index+1; if(current_index &lt; current_state-&gt;path_length){ int node_idx = current_state-&gt;path_to_follow[current_index]; int wait_time; int task_time = (current_state-&gt;robot_type == &quot;organizer&quot;) ? nodes[current_state-&gt;path_to_follow[current_index]]-&gt;task_time_organizer_robot : nodes[current_state-&gt;path_to_follow[current_index]]-&gt;task_time_mover_robot; if (current_state-&gt;run_time &gt;= nodes[node_idx]-&gt;leave_time){ wait_time = 0; nodes[node_idx]-&gt;entry_time = current_state-&gt;run_time; nodes[node_idx]-&gt;leave_time = current_state-&gt;run_time + task_time; } else{ wait_time = nodes[node_idx]-&gt;leave_time - current_state-&gt;run_time; nodes[node_idx]-&gt;entry_time = current_state-&gt;run_time + wait_time; nodes[node_idx]-&gt;leave_time = current_state-&gt;run_time + wait_time + task_time; } current_state-&gt;run_time += wait_time; current_state-&gt;run_time += task_time; if(next_index &lt; current_state-&gt;path_to_follow.size()) current_state-&gt;run_time += current_state-&gt;robot_speed; nodes[node_idx]-&gt;visited_robots.insert(current_state); path_q.push({current_state, next_index}); } } } </code></pre> <p>This is how I usually code (other files are similar). Please let me know the things I need to change in my coding style! It will be extremely helpful.</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T21:03:19.497", "Id": "491071", "Score": "1", "body": "@Emma challenge: Given n robots (n different paths), m nodes, how much time all the robots requires to complete the circuit. If 2 robots arrive at a node, the 2nd robot should wait till the 1st robot completes its task." } ]
[ { "body": "<h1>Avoid storing redundant data in classes</h1>\n<p>I see variables like these in <code>class simulation</code>:</p>\n<pre><code>std::string robots_ip_string;\nstd::string paths_ip_string;\nstd::string nodes_ip_string;\n...\n</code></pre>\n<p>Usually, repeating the name of the type in the name of a variable is unnecessary, so at first sight I would say: why not just call them <code>robots_ip</code>, <code>paths_ip</code>, and so on? However, a closer look shows that there is also:</p>\n<pre><code>std::vector&lt;robot*&gt; robots;\nstd::unordered_map&lt;int, node*&gt; nodes;\nstd::unordered_map&lt;int, std::vector&lt;int&gt;&gt; paths;\n</code></pre>\n<p>This looks to me like you read the input into a string, and them later convert the textual input into more structured data. But is it really necessary to keep the input strings around? I would remove the <code>*_string</code> member variables, and ensure that any function that reads input stores it in a local variable in that function, and them immediately converts it into the vectors and maps.</p>\n<p>Another potentially case of redundant information is in <code>struct robot</code>:</p>\n<pre><code>struct robot{\n ...\n std::vector&lt;int&gt; path_to_follow;\n int path_length;\n ...\n};\n</code></pre>\n<p>A <code>std::vector</code> knows how long it is. Instead of storing <code>path_length</code>, maybe you can get the same information from calling <code>path_to_follow.size()</code>? If so, I would remove <code>path_length</code>.</p>\n<h1>Separate input/output as much as possible from logic</h1>\n<p>In <code>class simulation</code>, there are <code>read_*_input()</code> functions, <code>print_*()</code> functions, <code>run_simulation()</code> and a few other functions, most of them take no arguments and return <code>void</code>. If I see a function like:</p>\n<pre><code>void read_robots_input();\n</code></pre>\n<p>Then I cannot tell where it is reading the input from. Is it from a file, standard input, the network? If it's from a file, which filename? Also, why are there three different <code>read_*_input()</code> functions? Would you ever use one but not the others? Also, what if I create an instance of <code>class simulation</code> but never call <code>read_*_inputs()</code>? Here are a few suggested changes:</p>\n<ul>\n<li>Have the constructor read all required inputs. This way, after creating an instance of <code>class simulation</code>, you know that it is in a valid state and ready to run the simulation.</li>\n<li>Have a way to tell the constructor which inputs to read. This could be three filenames, or even better three references to <a href=\"http://www.cplusplus.com/reference/istream/istream/\" rel=\"nofollow noreferrer\"><code>std::istream</code></a> objects, so that the constructor no longer cares if the input comes from a file, a stringstream or anything else with the <code>std::istream</code> interface.</li>\n</ul>\n<p>Note that this doesn't mean you have to put everything into the constructor itself, you can still have <code>private</code> helper functions that parse the individual files and call those from the constructor.</p>\n<p>For writing the output, use (a) function(s) that takes references to <code>std::ostream</code> objects. Again, this allows the caller to decide whether to print to a file or to <code>std::cout</code> for example.</p>\n<p>What do <code>simulation_time()</code> and <code>visited_node_info()</code> do? Do they <em>print</em> this information somewhere? If so, make it clear from the name, and have them match the other <code>print_*()</code> functions.</p>\n<h1>Use an <code>enum class</code> for <code>robot_type</code></h1>\n<p>Using an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\"><code>enum class</code></a> for <code>robot_type</code> will avoid expensive string comparisons such as in:</p>\n<pre><code>return (r2.first-&gt;robot_type == &quot;organizer&quot;) ? true : false;\n</code></pre>\n<p>Instead, make it so you can write it like:</p>\n<pre><code>return r2.first-&gt;robot_type == RobotType::ORGANIZER;\n</code></pre>\n<h1>Avoid repeating the name of a class in its member variables</h1>\n<p>Again, the goal is to avoid being redundant and repeating yourself. <code>struct robot</code> can be written as:</p>\n<pre><code>struct robot{\n int id;\n RobotType type;\n int speed;\n std::vector&lt;int&gt; path_to_follow;\n int path_length;\n int run_time; \n};\n</code></pre>\n<h1>Call <code>continue/break/return</code> early to reduce indentation levels</h1>\n<p>In <code>run_simulation()</code>, there is a big <code>if</code>-statement that contains most of the code. However, you can just do with a very small <code>if</code>-statement that goes to the next iteration of the loop:</p>\n<pre><code>while(!path_q.empty()){\n ...\n\n if(current_index == current_state-&gt;path_length)\n continue;\n\n int node_idx = ...\n ...\n}\n</code></pre>\n<h1>Use more <code>auto</code>, structured bindings</h1>\n<p>Avoid repeating types by using <code>auto</code>. For example:</p>\n<pre><code>std::pair&lt;robot*,int&gt; temp = path_q.top();\n</code></pre>\n<p>Can be rewritten as:</p>\n<pre><code>auto temp = path_q.top();\n</code></pre>\n<p>If you can use C++17, then it becomes even easier to unpack the pair:</p>\n<pre><code>auto [current_state, current_index] = path_q.top();\n</code></pre>\n<h1>Use references as aliases</h1>\n<p>I see the following piece of code repeated more than once:</p>\n<pre><code>nodes[current_state-&gt;path_to_follow[current_index]]-&gt;...\n</code></pre>\n<p>That's quite long, and it makes it hard to see what is going on. First, you could have used <code>node_idx</code> to shorten this to:</p>\n<pre><code>nodes[node_idx]-&gt;...\n</code></pre>\n<p>But it would be better to give a clear name to this expression. You can do this by creating a reference, like so:</p>\n<pre><code>auto &amp;current_node = nodes[node_idx];\n</code></pre>\n<p>Then the rest of the code becomes much clearer:</p>\n<pre><code>int task_time = current_state-&gt;type == RobotType::ORGANIZER ?\n current_node-&gt;task_time_organizer_robot :\n current_node-&gt;task_time_mover_robot;\n\nif (current_state-&gt;run_time &gt;= current_node-&gt;leave_time) {\n wait_time = 0;\n current_node-&gt;entry_time = current_state-&gt;run_time;\n ...\n</code></pre>\n<p>Note that <code>current_state</code> should probably be named <code>current_robot</code>, to be consistent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T22:14:50.753", "Id": "491075", "Score": "1", "body": "By the way, there's just been a nice talk at CppCon about the issue with those `void()` member functions: https://www.youtube.com/watch?v=Wg1f9Sufyic" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T22:12:04.300", "Id": "250293", "ParentId": "250290", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T19:10:19.840", "Id": "250290", "Score": "4", "Tags": [ "c++", "programming-challenge", "interview-questions" ], "Title": "Graph: N Robots and M Nodes" }
250290
<p>I have created a modular design pattern which provide a single interface that can be used create instances with swapable back-end components, however I'm not entirely satisfied with it.</p> <p>My practical implementation involves creating a generic interface to certain kinds of device drivers. The hope is that I can create an interface which exposes a layer meant as an adapter (for initializing drivers which non-interface conforming implementations) and to bring up framework infrastructure.</p> <p>To bring focus to the design pattern itself I am showing a simplified example.</p> <p>The source code can be found <a href="https://github.com/ReggieMarr/ProteanDesign" rel="nofollow noreferrer">here</a>.</p> <p>say I have some application with a main.c like so:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;boatModuleIF.h&quot; int main(int argc, char *argv[]) { char *type = argv[1]; int typeNum = atoi(type); moduleIF_t *IF = init_moduleIF(typeNum); if (IF) { IF-&gt;printCfg(IF-&gt;ctx); } else { printf(&quot;Failed to init module&quot;); } return 0; } </code></pre> <p>I use boatModuleIFDefs as a header which is common to all boatModuleComponents (i.e. boatModule, boatModuleIF, cnc, beneteau)</p> <p>It exposes the following to those components: boatModuleIFDefs.h</p> <pre><code>#ifndef __MODULEIFDEFS_H_ #define __MODULEIFDEFS_H_ typedef struct moduleIF_CTX *moduleIF_CTX_t; typedef struct { void (*printCfg)(moduleIF_CTX_t ctx); moduleIF_CTX_t ctx; } moduleIF_t; __attribute__((weak)) extern moduleIF_t *init_moduleIF_CNC(); __attribute__((weak)) extern moduleIF_t *init_moduleIF_Beneteau(); #endif // __MODULEIFDEFS_H_ </code></pre> <p>Note that the init function for the CNC and Beneteau module interfaces are declared as weak symbols. This means that this generic code can expose a symbol which may or may not be defined. This is used as a proxy to determine whether our application has been compiled with the cnc.c &quot;driver&quot;.</p> <p>with boatModuleIF's header and source implemented as:</p> <p>boatModuleIF.h</p> <pre><code>#ifndef __TESTMODULEIF_H_ #define __TESTMODULEIF_H_ #include &quot;boatModuleIFDefs.h&quot; enum { TYPE_CNC = 0, TYPE_BENETEAU, }; moduleIF_t *init_moduleIF(int type); #endif // __TESTMODULEIF_H_ </code></pre> <p>boatModuleIF.c</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &quot;boatModuleIFDefs.h&quot; #include &quot;boatModuleIF.h&quot; moduleIF_t *init_moduleIF(int type) { switch (type) { case TYPE_CNC: if (init_moduleIF_CNC) { return init_moduleIF_CNC(); } else { printf(&quot;failed cnc&quot;); return 0; } break; case TYPE_BENETEAU: if (init_moduleIF_Beneteau) { return init_moduleIF_Beneteau(); } else { printf(&quot;failed ben&quot;); return 0; } break; default: return 0; } } </code></pre> <p>boatModule also has a defs file which looks like:</p> <pre><code>#ifndef __TESTMTRDEFS_H_ #define __TESTMTRDEFS_H_ #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; typedef struct { uint8_t size; uint8_t speed; } boatCfg_t; __attribute__((weak)) extern boatCfg_t dfltBoatCfg; #endif // __TESTMTRDEFS_H_ </code></pre> <p>Note that the dfltBoatCfg is defined as a weak symbol similarily to our init functions. This is useful if we have multiple kinds of configurations that may not be applicaple to all sailboats.</p> <p>boatModule's header and source implemented as:</p> <p>boatModule.h</p> <pre><code>#ifndef __TESTMODULE_H_ #define __TESTMODULE_H_ #include &quot;boatModuleIFDefs.h&quot; moduleIF_t *init_moduleIF(); #endif // __TESTMODULE_H_ </code></pre> <p>boatModule.c</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &quot;boatModuleIFDefs.h&quot; #include &quot;boatModule.h&quot; #include &quot;boatModuleDefs.h&quot; struct moduleIF_CTX { uint8_t size; uint8_t speed; }; static void printCfg(moduleIF_CTX_t ctx) { printf(&quot;speed %d size %d&quot;, ctx-&gt;speed, ctx-&gt;size); } moduleIF_t *init_moduleIF() { struct moduleIF_CTX * const CTX = calloc(1, sizeof(struct moduleIF_CTX)); if (&amp;dfltBoatCfg) { CTX-&gt;size = dfltBoatCfg.size; CTX-&gt;speed = dfltBoatCfg.speed; } moduleIF_t * const IF = (moduleIF_t *) calloc(1, sizeof(moduleIF_t)); IF-&gt;ctx = CTX; IF-&gt;printCfg = printCfg; return IF; } </code></pre> <p>Then we have two source files for two different boatModule implementations (which here are a stand-in for drivers)</p> <p>cnc.c</p> <pre><code>#include &quot;boatModuleDefs.h&quot; boatCfg_t dfltBoatCfg = { .size = 10, .speed= 10, }; </code></pre> <p>beneteau.c</p> <pre><code>#include &quot;boatModuleDefs.h&quot; boatCfg_t dfltBoatCfg = { .size = 5, .speed= 5, }; </code></pre> <p>The interesting part (imho) is really in the makefile however.</p> <p>makefile</p> <pre class="lang-sh prettyprint-override"><code>all: joinedModules joinedModules: boatModule_Cnc.o boatModule_Beneteau.o boatModuleIF.o boatModuleDefs.h gcc boatModuleIF.o boatModule_Cnc.o boatModule_Beneteau.o main.c -o getBoatCfg boatModuleIF.o: gcc -c boatModuleIF.c boatModule_Beneteau.o: boatModule.o beneteau.o boatModuleDefs.h ld -r beneteau.o boatModule.o -o boatModule_Beneteau.o objcopy --redefine-sym printCfg=printCfg_Beneteau boatModule_Beneteau.o objcopy --redefine-sym init_moduleIF=init_moduleIF_Beneteau boatModule_Beneteau.o objcopy --redefine-sym dfltBoatCfg=dfltBoatCfg_Beneteau boatModule_Beneteau.o boatModule_Cnc.o: boatModule.o cnc.o boatModuleDefs.h ld -r cnc.o boatModule.o -o boatModule_Cnc.o objcopy --redefine-sym printCfg=printCfg_CNC boatModule_Cnc.o objcopy --redefine-sym init_moduleIF=init_moduleIF_CNC boatModule_Cnc.o objcopy --redefine-sym dfltBoatCfg=dfltBoatCfg_CNC boatModule_Cnc.o boatModule.o: beneteau.o cnc.o boatModuleDefs.h gcc -c -fPIE boatModule.c cnc.o: boatModuleDefs.h gcc -c -fPIE cnc.c beneteau.o: boatModuleDefs.h gcc -c -fPIE beneteau.c </code></pre> <p>Essentially what I am doing is merging both the module object file and a backend component together to create a new merged object file. I can then redefine the global symbols used by both to prevent symbol collisions in such a way that maintains the &quot;simplicity&quot; of the generic module interface files.</p> <p>This has some benefits, notably:</p> <ul> <li>During initialization of the interface I don't need some messy switch case which would have to check whether each type boat has each kind of boat config.</li> <li>Supports code reuse.</li> <li>If I want to add new configuration's there's little that needs to be added (except for one addtional if statement in the moduleif init and the definition in the boat/driver that actually cares about that config).</li> <li>If I want to add a new boat then all I need is to add a new init weak symbol and some tweaks to the makefile (really just adding the source name, the rest could be done automatically with make rules)</li> </ul> <p>The issue is this doesn't quiet <em>feel right</em> and I'm wondering if this is some kind of <a href="https://en.wikipedia.org/wiki/Code_smell" rel="nofollow noreferrer">code smell</a>?</p> <p>It could make evaluating the code much more difficult (e.g. I have not defined any symbol named dfltBoatCfg, it's redefined as dfltBoatCfg_CNC and dfltBoatCfg_Beneteau) however this could be mitigated with good comments/documentation.</p> <p>If so is there some better/modified approach I could take would allow me to create this kind of modular design pattern that is future proofed against maintanence hell in the event that we should have to support many types of boats with many different configurations?</p> <p>Any and all feedback is much appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T13:50:54.043", "Id": "491237", "Score": "0", "body": "In general, I would avoid linker tricks to generate a certain result. The whole point of using design patterns is to create portable cross-platform templates. By using non-standard GNU extensions and linker/make file tricks, you restrict your code to gcc tool chain and \"ELF like\" linkers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T14:37:12.267", "Id": "491238", "Score": "0", "body": "By non-standard extensions are you referring to the __attributes? I feel like the weak attribute seems to be pretty standard amongst most GCC compilers. I do understand it is a somewhat non-standard approach. To be honest I'm most apprehensive about the redefining symbols part.\nDo you feel like both these things should be avoided at all costs? \nOr is there some approach you would take that would realize greater benefit for the cost of such a non-standard approach." } ]
[ { "body": "<h1>Don't hide pointers</h1>\n<p>Don't hide pointers in a typedef:</p>\n<pre><code>typedef struct moduleIF_CTX *moduleIF_CTX_t;\n</code></pre>\n<p>This makes it really hard to spot when things are passed by value or by pointer in the rest of the code. You could make it more explicit:</p>\n<pre><code>typedef struct moduleIF_CTX *moduleIF_CTX_ptr_t;\n</code></pre>\n<p>But I would just do this:</p>\n<pre><code>typedef struct moduleIF_CTX moduleIF_CTX;\n</code></pre>\n<p>Yes, you can <code>typedef</code> a <code>struct</code> to its own name, and it does what you want. And now you can use this as follows:</p>\n<pre><code>typedef struct {\n void (*printCfg)(moduleIF_CTX *ctx);\n moduleIF_CTX *ctx;\n} moduleIF;\n</code></pre>\n<p>It's both a bit less to type and more explicit at the same time.</p>\n<h1>Consider using a dynamically created registry for modules</h1>\n<p>The main drawback of your approach is having to change <code>init_moduleIF()</code> every time you add or remove a module. It would be nicer if modules could somehow register themselves in an array or list. One way to do that is to write functions that are called at program startup and/or library loading time. These are functions that go into a special dynamic linker section. How to get functions in there is not standard C, but with GCC at least you can use <code>__attribute((constructor))</code> to mark a function as having to run before <code>main()</code> is started. Here is an example of how it could be used. First, ensure <code>moduleIF</code> contains its type identifier, and a pointer to the next <code>moduleIF</code>:</p>\n<pre><code>typedef struct moduleIF {\n const int type; // or char *moduleName...\n struct moduleIF *next;\n\n struct moduleIF *(*init)(void);\n void (*printCfg)(moduleIF_CTX *ctx);\n ...\n} moduleIF;\n</code></pre>\n<p>Then add a global variable that holds a pointer to the first module, and create a function to add new modules to that list:</p>\n<pre><code>moduleIF *modules = NULL;\n\nvoid registerIF(moduleIF *if) {\n if-&gt;next = modules;\n modules = if;\n}\n</code></pre>\n<p>Then in a module itself, like <code>boatModule_Cnc.c</code>, do:</p>\n<pre><code>static moduleIF boatIF {\n .type = TYPE_CNC,\n .init = init_Cnc,\n .printCfg = printCfg_Cnc,\n};\n\nstatic void registerBoatIF(void) __attribute__((constructor));\nstatic void registerBoatIF(void) {\n registerIF(&amp;boatIF);\n}\n</code></pre>\n<p>If you now link multiple modules into a single binary, then all of their constructor functions will be called before <code>main()</code> starts, so at that time <code>modules</code> will be a linked list containing all the registered module interface definitions. You can then change <code>init_moduleIF()</code> to:</p>\n<pre><code>moduleIF *init_moduleIF(int type) {\n for (moduleIF *if = modules; if; if = if-&gt;next) {\n if (if-&gt;type == type &amp;&amp; if-&gt;init) {\n return if-&gt;init();\n }\n }\n\n return NULL;\n}\n</code></pre>\n<h1>About using weak and renamed symbols</h1>\n<p>I think this approach is less flexible than the one I outlined above. Also, if you know at compile time which <code>.o</code> files you are going to link together, then instead of using weak symbols, you can also compile <code>boatModuleIF.c</code> with <code>-Dinit_moduleIF_CNC=NULL</code> if you know the CNC module is not compiled in, or define something else and use <code>#ifdef</code>s inside <code>init_moduleIF()</code> to compile only those <code>case</code>s that are valid. I think that is just as pretty (or ugly, depending what you think of it) as using weak symbols, except that it relies less on linker tricks.</p>\n<p>As for renaming the symbols, this is also unnecessary. <code>printCfg()</code> is <code>static</code>, and <code>init_moduleIF_*()</code> will just put a pointer to this local version of <code>printCfg()</code> in the <code>moduleIF_t</code> that is returned.</p>\n<p>You do need to rename <code>dfltBoatCfg</code>, because otherwise only of the <code>dfltBoatCfg</code> instances survives the weak linking. But if you don't rename that symbol, it will compile and link without errors.</p>\n<p>Another way to solve this issue is by not doing any symbol renaming tricks, and not having <code>boatModule.c</code> linked in multiple times. Instead, link it once in the final binary, and have it take a pointer argument that can be used to point to a custom <code>boatCfg_t</code>, like so:</p>\n<pre><code>moduleIF_t *init_moduleIF(const boatCfg_t *boatCfg) {\n ...\n if (cfg) {\n CTX-&gt;size = boatCfg.size;\n CTX-&gt;speed = boatCfg.speed;\n }\n ...\n}\n</code></pre>\n<p>And for example in <code>cnc.c</code>, write:</p>\n<pre><code>#include &quot;boatModuleDefs.h&quot;\n\nstatic const boatCfg_t boatCfg = {\n .size = 10,\n .speed= 10,\n};\n\nmoduleIF_t *init_moduleIF_CNC() {\n return init_moduleIF(boatCfg);\n}\n</code></pre>\n<p>It's just a few lines extra, but now I can just see what happens by looking at the source, instead of having to understand your build system as well. This approach is also more portable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T02:32:29.130", "Id": "491188", "Score": "0", "body": "So I totally agree with the point about the opaque pointer. Also the constructor attribute is quiet interesting. Combined with the linked list it creates a pretty clean interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T02:36:25.930", "Id": "491190", "Score": "0", "body": "Could you comment on my strategy of defining config components as weak symbols, merging modules with the moduleIF and redefining symbols to avoid collisions ?\n\n(see my edit in the question for pros and cons)\n\nOne of the biggest problems I deal with is managing configurations and it feels like utilizing weak symbols and compiler tricks (like objcopy --redefine sym) might be useful but I don't think I'm using them correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:22:58.077", "Id": "491271", "Score": "0", "body": "@ReginaldMarr: I added another section about weak symbols and symbol renaming. I think it boils down to, as we Dutch say: \"doe maar gewoon, dan doe je al gek genoeg” (just do it the normal way, that's already crazy enough)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T00:20:53.600", "Id": "491287", "Score": "0", "body": "@G.Slipen thanks for that, I had hoped to leverage the weak symbols to avoid complicated type and cfg based conditionals inside of the moduleIF however I agree that a weak symbol in that case doesn't do the job any better than an `ifdef` and has the downside of increased code size.\nI'd be interested to know if there is some use case where its advantageous enough to leverage redefinition of symbols for modular design but it seems it's not this one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T06:30:31.227", "Id": "491303", "Score": "0", "body": "@ReginaldMarr: I have used weak symbols myself in projects, where you could `dlopen()` a plugin. In that case, you need the symbol to exist in the main executable, otherwise it won't link, but the symbols were actually not used until the plugin is loaded. As for redefining symbols, this is actually the first time I've seen it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T23:07:30.363", "Id": "250345", "ParentId": "250291", "Score": "4" } } ]
{ "AcceptedAnswerId": "250345", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T19:11:23.713", "Id": "250291", "Score": "4", "Tags": [ "c", "design-patterns", "modules" ], "Title": "Modular Design Patterns in C" }
250291
<p>I've learned JavaFX recently (with Scene Builder) and made a MineSweeper game, would love to receive feedback and tips for improvement! Thanks.</p> <p>Below is mines class, I've commented out some lines for the GUI part to work:</p> <pre><code>import java.util.Random; //import java.util.Scanner; public class Mines { private int height /* rows */, width /* columns */, numMines, totalToReveal /* excluding mines */; public String[][] board; private Random rand = new Random(); // Generate random numbers private int h, w; // Assist with random received values static int winLose=-1; // @SuppressWarnings(&quot;resource&quot;) public Mines(int height, int width, int numMines) { /* int newMines = -1; */ // boolean checkMinesNum = false; // If number of mines is legal // Scanner sc = new Scanner(System.in); this.height = height; this.width = width; /* * if (numMines &lt; width * height &amp;&amp; numMines &gt;= 0) checkMinesNum = true; while * (checkMinesNum != true) { * System.out.println(&quot;Please enter a valid number of mines (lower than &quot; + * height * width + &quot;):&quot;); newMines = sc.nextInt(); if (newMines &lt; width * * height &amp;&amp; newMines &gt;= 0) { checkMinesNum = true; numMines = newMines; } } // * sc.close(); // Can't do, because I need to close at the end of Main class */ this.numMines = numMines; totalToReveal = (height * width) - this.numMines; board = new String[height][width]; // Create game's board with nulls initialized for (int i = 0; i &lt; height; i++) // Initialize all slots in the board for (int j = 0; j &lt; width; j++) board[i][j] = &quot;NF.&quot;; // Nothing ON slot, False none is revealed yet and . as default while (numMines != 0) { h = rand.nextInt(height - 1); // Generate random number for height w = rand.nextInt(width - 1); // Generate random number for width if (board[h][w].charAt(2) != 'M') { // Make sure place wasn't used before board[h][w] = board[h][w].substring(0, 2) + &quot;M&quot;; // Mark a place containing a mine with M numMines--; } } for (int i = 0; i &lt; height; i++) // Initialize slot values for (int j = 0; j &lt; width; j++) board[i][j] = board[i][j].substring(0, 2) + get(i, j); } public int getCol() { return width; } public int getRow() { return height; } private void checkPlace(int i, int j) { // Is it a legal move? (borders) if (i &gt;= height || j &gt;= width || i &lt; 0 || j &lt; 0) throw new IllegalArgumentException(&quot;Illegal move on board!&quot;); } private boolean inBoard(int i, int j) { // Is move legal? (make move or not) if (i &gt;= height || j &gt;= width || i &lt; 0 || j &lt; 0) return false; return true; } public boolean addMine(int i, int j) { checkPlace(i, j); if (board[i][j].contains(&quot;M&quot;)) { System.out.println(&quot;Adding a mine has failed, slot already contains one!&quot;); return false; } board[i][j] = board[i][j].substring(0, 2) + &quot;M&quot;; numMines++; // Mine was added totalToReveal--; // Subtract one slot (occupied by mine) for (int r = 0; r &lt; height; r++) // Initialize slot values for (int c = 0; c &lt; width; c++) board[r][c] = board[r][c].substring(0, 2) + get(r, c); return true; } public boolean open(int i, int j) { checkPlace(i, j); if (board[i][j].charAt(1) == 'T') // Already revealed return true; if (board[i][j].charAt(2) == 'M') { // Slot contains a mine (user lost) board[i][j] = board[i][j].substring(0, 1) + &quot;T&quot; + &quot;B&quot;; // B for boom totalToReveal = 0; // Finish game isDone(); System.out.println(&quot;Game over, boy&quot;); winLose=0; return true; } if (board[i][j].charAt(2) != 'E' &amp;&amp; board[i][j].charAt(2) != 'M' &amp;&amp; board[i][j].charAt(2) != 'B') { board[i][j] = board[i][j].substring(0, 1) + &quot;T&quot; + board[i][j].substring(2, 3); totalToReveal--; if (isDone()) { System.out.println(&quot;You win, boy&quot;); winLose=1; } return true; } if (board[i][j].charAt(2) == 'E') { board[i][j] = board[i][j].substring(0, 1) + &quot;T&quot; + board[i][j].substring(2, 3); totalToReveal--; for (int r = -1; r &lt; 2; r++) { for (int c = -1; c &lt; 2; c++) { if (!(r == 0 &amp;&amp; c == 0) &amp;&amp; inBoard(i + r, j + c)) { if (isDone()) { System.out.println(&quot;You win, boy&quot;); winLose=1; } open(i + r, j + c); } } } return true; } return false; } public void toggleFlag(int x, int y) { checkPlace(x, y); if (board[x][y].contains(&quot;T&quot;)) return; board[x][y] = &quot;D&quot; + board[x][y].substring(1, 3); // Overwrite it with flag mark (D) } public void toggleQM(int x, int y) { checkPlace(x, y); if (board[x][y].contains(&quot;T&quot;)) return; board[x][y] = &quot;?&quot; + board[x][y].substring(1, 3); // Overwrite it with question mark (?) } public boolean isDone() { if (totalToReveal != 0) return false; setShowAll(); return true; // True if no more slots to reveal (won the game) } public String get(int i, int j) { checkPlace(i, j); Integer countMines = 0; // To use the object's toString method if (board[i][j].contains(&quot;F&quot;)) { // Slot not revealed if (board[i][j].contains(&quot;D&quot;)) // Slot has flag return &quot;F&quot;; // F for flag else if (board[i][j].contains(&quot;?&quot;)) // Slot is marked as question mark (unsure of slot's content) return &quot;?&quot;; } // Remaining slots are revealed if (board[i][j].contains(&quot;M&quot;)) return &quot;M&quot;; else { for (int r = -1; r &lt; 2; r++) { for (int c = -1; c &lt; 2; c++) { if (!(r == 0 &amp;&amp; c == 0) &amp;&amp; inBoard(i + r, j + c) &amp;&amp; board[i + r][j + c].contains(&quot;M&quot;)) { countMines++; if (countMines &gt; 8 || countMines &lt; 0) throw new IllegalArgumentException(&quot;Something went wrong - mines count is illegal&quot;); } } } } if (countMines == 0) return &quot;E&quot;; else return countMines.toString(); } public void setShowAll() { // Set all slots to be revealed when game is over (win\lose) for (int i = 0; i &lt; height; i++) for (int j = 0; j &lt; width; j++) if (!board[i][j].contains(&quot;T&quot;)) board[i][j] = board[i][j].substring(0, 1) + &quot;T&quot; + board[i][j].substring(2, 3); } @Override public String toString() { String s = &quot;&quot;; for (int r = 0; r &lt; height; r++) { for (int c = 0; c &lt; width; c++) { if (board[r][c].charAt(1) == 'T') s += board[r][c].substring(2, 3); else { // Meaning slot isn't revealed if (board[r][c].contains(&quot;D&quot;) || board[r][c].contains(&quot;?&quot;)) s += get(r, c); else s += &quot;X&quot;; } if (c == width - 1) // New row s += '\n'; } } return s; } } </code></pre> <p>the mainFX:</p> <pre><code>import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.VBox; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.stage.Stage; public class MainFX extends Application { static Media h = new Media(&quot;https://www.mboxdrive.com/Flavour-Wataboi.mp3&quot;); static MediaPlayer mediaPlayer = new MediaPlayer(h);; static int onOoff = 0; static int check = 0, check2 = 0; @Override public void start(Stage primaryStage) { try { Image backgroundColor = new Image(&quot;https://i.ibb.co/1KvhFmp/menu.jpg&quot;); BackgroundSize backgroundSize = new BackgroundSize(1280, 720, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); FXMLLoader loader = new FXMLLoader(); // Create loading object loader.setLocation(getClass().getResource(&quot;MainMenuFXML.fxml&quot;)); // fxml location VBox root = loader.load(); // Load layout // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/menu.jpg\&quot;)&quot;); Scene scene = new Scene(root); // Create scene with chosen layout // primaryStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); primaryStage.setTitle(&quot;BOOM Beach&quot;); // Set stage's title // primaryStage.setMinWidth(400); // Won't be allowed to make width/height smaller // primaryStage.setMinHeight(350); // primaryStage.setMaxWidth(600); // It will put constraints on the new scenes!! // primaryStage.setMaxHeight(450); primaryStage.setScene(scene); // Set scene to stage primaryStage.show(); // Show stage } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } public static boolean music() { check = onOoff; check2 = check % 2; if (check2 == 0) { mediaPlayer.play(); onOoff++; return true; } else { mediaPlayer.stop(); onOoff++; return false; } } } </code></pre> <p>main menu controller:</p> <pre><code>import java.io.IOException; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.stage.Stage; public class MainMenuCONTROLLER { @FXML private Button NewGame; @FXML private Button QuitGame; @FXML private Button Extras; @FXML private Tooltip ExtrasTT; @FXML private Button ExtraExtras; @FXML void ExtraExtras(ActionEvent event) throws IOException { Image backgroundColor = new Image(&quot;https://i.ibb.co/1Gr7PhP/Mandalorian.png&quot;); BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource(&quot;ExtraExtrasFXML.fxml&quot;)); AnchorPane root = loader.load(); // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/Secret.jpg\&quot;)&quot;); Scene scene = new Scene(root); Stage extrasStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); extrasStage.setTitle(&quot;Any guesses?&quot;); // extrasStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); /* * extrasStage.setMinHeight(700); extrasStage.setMinWidth(500); * extrasStage.setMaxHeight(700); extrasStage.setMaxWidth(500); */ extrasStage.setScene(scene); extrasStage.show(); } @FXML void Extras(ActionEvent event) { Extras.setOnAction(e -&gt; { boolean check = MainFX.music(); if (check) Extras.setText(&quot;ON&quot;); else Extras.setText(&quot;OFF&quot;); }); } @FXML void NewGame(ActionEvent event) throws IOException { Image backgroundColor = new Image(&quot;https://i.ibb.co/1Gr7PhP/Mandalorian.png&quot;); BackgroundSize backgroundSize = new BackgroundSize(1280, 853, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource(&quot;NewGameFXML.fxml&quot;)); AnchorPane root = loader.load(); // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/Mandalorian.png\&quot;)&quot;); Scene scene = new Scene(root); Stage GameStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); // GameStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); // GameStage.setMinWidth(1000); // Won't be allowed to make width/height smaller // GameStage.setMinHeight(500); // GameStage.setMaxWidth(2000); // GameStage.setMaxHeight(1000); GameStage.setTitle(&quot;BOOM Beach&quot;); GameStage.setScene(scene); GameStage.show(); } @FXML void QuitGame(ActionEvent event) { Platform.exit(); // Quit game } } </code></pre> <p>main menu fxml:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?import javafx.geometry.Insets?&gt; &lt;?import javafx.scene.control.Button?&gt; &lt;?import javafx.scene.control.Tooltip?&gt; &lt;?import javafx.scene.layout.HBox?&gt; &lt;?import javafx.scene.layout.VBox?&gt; &lt;?import javafx.scene.text.Font?&gt; &lt;VBox alignment=&quot;CENTER&quot; maxHeight=&quot;-Infinity&quot; maxWidth=&quot;-Infinity&quot; minHeight=&quot;-Infinity&quot; minWidth=&quot;-Infinity&quot; prefHeight=&quot;720.0&quot; prefWidth=&quot;1280.0&quot; xmlns=&quot;http://javafx.com/javafx/8.0.171&quot; xmlns:fx=&quot;http://javafx.com/fxml/1&quot; fx:controller=&quot;MS.MainMenuCONTROLLER&quot;&gt; &lt;children&gt; &lt;Button fx:id=&quot;NewGame&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#NewGame&quot; prefHeight=&quot;20.0&quot; prefWidth=&quot;140.0&quot; text=&quot;New Game&quot;&gt; &lt;VBox.margin&gt; &lt;Insets bottom=&quot;30.0&quot; right=&quot;10.0&quot; top=&quot;20.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;font&gt; &lt;Font size=&quot;20.0&quot; /&gt; &lt;/font&gt; &lt;/Button&gt; &lt;Button mnemonicParsing=&quot;false&quot; prefHeight=&quot;50.0&quot; prefWidth=&quot;140.0&quot; text=&quot;ScoreBoard (later)&quot;&gt; &lt;VBox.margin&gt; &lt;Insets bottom=&quot;30.0&quot; right=&quot;10.0&quot; top=&quot;10.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;tooltip&gt; &lt;Tooltip contentDisplay=&quot;CENTER&quot; height=&quot;40.0&quot; text=&quot;In the next update...&quot; textAlignment=&quot;CENTER&quot; width=&quot;150.0&quot;&gt; &lt;font&gt; &lt;Font name=&quot;Arial Black&quot; size=&quot;9.0&quot; /&gt; &lt;/font&gt; &lt;/Tooltip&gt; &lt;/tooltip&gt; &lt;/Button&gt; &lt;Button fx:id=&quot;QuitGame&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#QuitGame&quot; prefHeight=&quot;50.0&quot; prefWidth=&quot;140.0&quot; text=&quot;Quit Game&quot;&gt; &lt;VBox.margin&gt; &lt;Insets bottom=&quot;10.0&quot; right=&quot;10.0&quot; top=&quot;10.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;font&gt; &lt;Font size=&quot;20.0&quot; /&gt; &lt;/font&gt; &lt;/Button&gt; &lt;HBox alignment=&quot;CENTER&quot; prefHeight=&quot;60.0&quot; prefWidth=&quot;600.0&quot;&gt; &lt;children&gt; &lt;Button fx:id=&quot;Extras&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#Extras&quot; prefHeight=&quot;30.0&quot; prefWidth=&quot;110.0&quot; text=&quot;Check this out&quot;&gt; &lt;HBox.margin&gt; &lt;Insets bottom=&quot;10.0&quot; right=&quot;10.0&quot; /&gt; &lt;/HBox.margin&gt; &lt;font&gt; &lt;Font size=&quot;14.0&quot; /&gt; &lt;/font&gt; &lt;tooltip&gt; &lt;Tooltip fx:id=&quot;ExtrasTT&quot; contentDisplay=&quot;CENTER&quot; height=&quot;40.0&quot; text=&quot;Not really...&quot; textAlignment=&quot;CENTER&quot; width=&quot;150.0&quot;&gt; &lt;font&gt; &lt;Font name=&quot;Arial Black&quot; size=&quot;9.0&quot; /&gt; &lt;/font&gt; &lt;/Tooltip&gt; &lt;/tooltip&gt; &lt;/Button&gt; &lt;Button fx:id=&quot;ExtraExtras&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#ExtraExtras&quot; prefHeight=&quot;30.0&quot; prefWidth=&quot;110.0&quot; text=&quot;Top secret&quot;&gt; &lt;HBox.margin&gt; &lt;Insets bottom=&quot;10.0&quot; left=&quot;10.0&quot; right=&quot;10.0&quot; /&gt; &lt;/HBox.margin&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;14.0&quot; /&gt; &lt;/font&gt; &lt;/Button&gt; &lt;/children&gt; &lt;VBox.margin&gt; &lt;Insets /&gt; &lt;/VBox.margin&gt; &lt;/HBox&gt; &lt;/children&gt; &lt;/VBox&gt; </code></pre> <p>extra extras controller:</p> <pre><code>import java.io.IOException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class ExtraExtrasCONTROLLER { @FXML private AnchorPane ExtraExtrasPIC; @FXML private Button BackMainMenu; @FXML void MainMenu(ActionEvent event) throws IOException { Image backgroundColor = new Image(&quot;https://i.ibb.co/1KvhFmp/menu.jpg&quot;); BackgroundSize backgroundSize = new BackgroundSize(1280, 720, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); FXMLLoader loader = new FXMLLoader(); // Create loading object loader.setLocation(getClass().getResource(&quot;MainMenuFXML.fxml&quot;)); // fxml location VBox root = loader.load(); // Load layout // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/menu.jpg\&quot;)&quot;); Scene scene = new Scene(root); // Create scene with chosen layout Stage primaryStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); // primaryStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); primaryStage.setTitle(&quot;BOOM Beach&quot;); // Set stage's title // primaryStage.setMinWidth(400); // Won't be allowed to make width/height smaller // primaryStage.setMinHeight(350); // primaryStage.setMaxWidth(600); // primaryStage.setMaxHeight(450); primaryStage.setScene(scene); // Set scene to stage primaryStage.show(); // Show stage } } </code></pre> <p>extra extras fxml:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?import javafx.scene.control.Button?&gt; &lt;?import javafx.scene.layout.AnchorPane?&gt; &lt;AnchorPane fx:id=&quot;ExtraExtrasPIC&quot; maxHeight=&quot;-Infinity&quot; maxWidth=&quot;-Infinity&quot; minHeight=&quot;-Infinity&quot; minWidth=&quot;-Infinity&quot; xmlns=&quot;http://javafx.com/javafx/8.0.171&quot; xmlns:fx=&quot;http://javafx.com/fxml/1&quot; fx:controller=&quot;MS.ExtraExtrasCONTROLLER&quot;&gt; &lt;children&gt; &lt;Button fx:id=&quot;BackMainMenu&quot; alignment=&quot;BOTTOM_LEFT&quot; layoutX=&quot;14.0&quot; layoutY=&quot;600.0&quot; maxHeight=&quot;-Infinity&quot; maxWidth=&quot;-Infinity&quot; minHeight=&quot;-Infinity&quot; minWidth=&quot;-Infinity&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#MainMenu&quot; prefHeight=&quot;30.0&quot; prefWidth=&quot;120.0&quot; text=&quot;Back to menu&quot; textAlignment=&quot;CENTER&quot; AnchorPane.bottomAnchor=&quot;65.0&quot; AnchorPane.leftAnchor=&quot;14.0&quot; AnchorPane.rightAnchor=&quot;365.0&quot; AnchorPane.topAnchor=&quot;600.0&quot; /&gt; &lt;/children&gt; &lt;/AnchorPane&gt; </code></pre> <p>new game controller:</p> <pre><code>import java.io.IOException; import java.util.Random; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ButtonBase; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class NewGameCONTROLLER { static Mines game; static int rows, columns, mines; // To access them even when resetting board Button b; static int mouseClick = -1; @FXML private TextField NumRows; @FXML private TextField NumCols; @FXML private TextField NumM; @FXML private Button StartGame; @FXML private Button BackMainMenu; @FXML private Button RandomGame; @FXML private Button Music; @FXML void BackMainMenu(ActionEvent event) throws IOException { Image backgroundColor = new Image(&quot;https://i.ibb.co/1KvhFmp/menu.jpg&quot;); BackgroundSize backgroundSize = new BackgroundSize(1280, 720, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); FXMLLoader loader = new FXMLLoader(); // Create loading object loader.setLocation(getClass().getResource(&quot;MainMenuFXML.fxml&quot;)); // fxml location VBox root = loader.load(); // Load layout // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/menu.jpg\&quot;)&quot;); Scene scene = new Scene(root); // Create scene with chosen layout Stage primaryStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); // primaryStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); primaryStage.setTitle(&quot;BOOM Beach&quot;); // Set stage's title // primaryStage.setMinWidth(400); // Won't be allowed to make width/height smaller // primaryStage.setMinHeight(350); // primaryStage.setMaxWidth(600); // primaryStage.setMaxHeight(450); primaryStage.setScene(scene); // Set scene to stage primaryStage.show(); // Show stage } @FXML void RandomGame(ActionEvent event) throws IOException { Random rand = new Random(); int low = 3, high = 15; int minesLow = 1, minesHigh; rows = rand.nextInt(high - low) + low; columns = rand.nextInt(high - low) + low; if (rows &lt;= 0 || columns &lt;= 0) { rows = rand.nextInt(5) + 3; columns = rand.nextInt(5) + 3; } minesHigh = (rows * columns) - 1; mines = rand.nextInt(minesHigh - minesLow) + minesLow; if (mines &gt;= columns * rows) mines = (columns * rows) - 1; game = new Mines(rows, columns, mines); Image backgroundColor = new Image(&quot;https://i.ibb.co/1Gr7PhP/Mandalorian.png&quot;); BackgroundSize backgroundSize = new BackgroundSize(1280, 853, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); FXMLLoader loader = new FXMLLoader(); // Create loading object loader.setLocation(getClass().getResource(&quot;BoardFXML.fxml&quot;)); // fxml location AnchorPane root = loader.load(); // Load layout // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/Mandalorian.png\&quot;)&quot;); Scene scene = new Scene(root); // Create scene with chosen layout Stage gameStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); // gameStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); gameStage.setTitle(&quot;BOOM Beach&quot;); // Set stage's title // gameStage.setMinWidth(1000); // Won't be allowed to make width/height smaller // gameStage.setMinHeight(500); // gameStage.setMaxWidth(2000); // gameStage.setMaxHeight(1000); gameStage.setScene(scene); // Set scene to stage BoardCONTROLLER bCont = loader.getController(); // Prepare board in BoardCONTROLLER bCont.winLose.setVisible(false); for (int i = 0; i &lt; columns; i++) { for (int j = 0; j &lt; NewGameCONTROLLER.rows; j++) { b = new Button(&quot; &quot;); b.setMinSize(30, 30); b.setMaxSize(30, 30); b.setStyle(&quot;-fx-font-size:11&quot;); bCont.TheBoard.add(b, i, j); GridPane.setMargin(b, new Insets(5, 5, 5, 5)); GridPane.setHalignment(b, HPos.CENTER); GridPane.setValignment(b, VPos.CENTER); } } for (int i = 0; i &lt; bCont.TheBoard.getChildren().size(); i++) { ((ButtonBase) bCont.TheBoard.getChildren().get(i)).setOnMouseClicked(new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { int x, y; y = (int) ((Button) event.getSource()).getProperties().get(&quot;gridpane-column&quot;); x = (int) ((Button) event.getSource()).getProperties().get(&quot;gridpane-row&quot;); if (event.getButton().equals(MouseButton.PRIMARY)) game.open(x, y); else if (event.getButton().equals(MouseButton.SECONDARY)) game.toggleFlag(x, y); else if (event.getButton().equals(MouseButton.MIDDLE)) game.toggleQM(x, y); for (Node child : bCont.TheBoard.getChildren()) { int j = (int) ((Button) child).getProperties().get(&quot;gridpane-column&quot;); int i = (int) ((Button) child).getProperties().get(&quot;gridpane-row&quot;); if (game.board[i][j].charAt(1) == 'T') { ((Button) child).setText(game.board[i][j].substring(2, 3)); } if (game.board[i][j].charAt(1) == 'F' &amp;&amp; game.board[i][j].charAt(0) == 'D') ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/GtnDxdQ/flag.png)&quot;); if (game.board[i][j].charAt(1) == 'F' &amp;&amp; game.board[i][j].charAt(0) == '?') ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/fnw3Hr4/QM.jpg)&quot;); if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == 'E') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/txvBhCS/empty.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == 'M') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/6Jq9S3g/mine.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == 'B') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/wgRt8v9/boom.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '1') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/5Gd2H0Y/1.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '2') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/GHGj0KM/2.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '3') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/sww9b1n/3.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '4') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/nrTjpqp/4.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '5') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/gZ6Rjrz/5.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '6') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/wh9XnfT/6.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '7') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/k1905rT/7.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '8') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/RCs2s2H/8.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (Mines.winLose==1) { bCont.winLose.setVisible(true); bCont.winLose.setText(&quot;YOU WIN!&quot;); } if (Mines.winLose==0) { bCont.winLose.setVisible(true); bCont.winLose.setText(&quot;YOU LOSE! Try again...&quot;); } Mines.winLose=-1; } } }); } gameStage.show(); // Show stage } @FXML void StartGame(ActionEvent event) throws IOException { rows = Integer.parseInt(NumRows.getText()); columns = Integer.parseInt(NumCols.getText()); mines = Integer.parseInt(NumM.getText()); game = new Mines(rows, columns, mines); Image backgroundColor = new Image(&quot;https://i.ibb.co/1Gr7PhP/Mandalorian.png&quot;); BackgroundSize backgroundSize = new BackgroundSize(1280, 853, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); FXMLLoader loader = new FXMLLoader(); // Create loading object loader.setLocation(getClass().getResource(&quot;BoardFXML.fxml&quot;)); // fxml location AnchorPane root = loader.load(); // Load layout // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/Mandalorian.png\&quot;)&quot;); Scene scene = new Scene(root); // Create scene with chosen layout Stage gameStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); // gameStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); gameStage.setTitle(&quot;BOOM Beach&quot;); // Set stage's title // gameStage.setMinWidth(1000); // Won't be allowed to make width/height smaller // gameStage.setMinHeight(500); // gameStage.setMaxWidth(2000); // gameStage.setMaxHeight(1000); gameStage.setScene(scene); // Set scene to stage BoardCONTROLLER bCont = loader.getController(); // Prepare board in BoardCONTROLLER bCont.winLose.setVisible(false); for (int i = 0; i &lt; columns; i++) { for (int j = 0; j &lt; NewGameCONTROLLER.rows; j++) { b = new Button(&quot; &quot;); b.setMinSize(30, 30); b.setMaxSize(30, 30); b.setStyle(&quot;-fx-font-size:11&quot;); bCont.TheBoard.add(b, i, j); GridPane.setMargin(b, new Insets(5, 5, 5, 5)); GridPane.setHalignment(b, HPos.CENTER); GridPane.setValignment(b, VPos.CENTER); } } for (int i = 0; i &lt; bCont.TheBoard.getChildren().size(); i++) { ((ButtonBase) bCont.TheBoard.getChildren().get(i)).setOnMouseClicked(new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { int x, y; y = (int) ((Button) event.getSource()).getProperties().get(&quot;gridpane-column&quot;); x = (int) ((Button) event.getSource()).getProperties().get(&quot;gridpane-row&quot;); if (event.getButton().equals(MouseButton.PRIMARY)) game.open(x, y); else if (event.getButton().equals(MouseButton.SECONDARY)) game.toggleFlag(x, y); else if (event.getButton().equals(MouseButton.MIDDLE)) game.toggleQM(x, y); for (Node child : bCont.TheBoard.getChildren()) { int j = (int) ((Button) child).getProperties().get(&quot;gridpane-column&quot;); int i = (int) ((Button) child).getProperties().get(&quot;gridpane-row&quot;); if (game.board[i][j].charAt(1) == 'T') { ((Button) child).setText(game.board[i][j].substring(2, 3)); } if (game.board[i][j].charAt(1) == 'F' &amp;&amp; game.board[i][j].charAt(0) == 'D') ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/GtnDxdQ/flag.png)&quot;); if (game.board[i][j].charAt(1) == 'F' &amp;&amp; game.board[i][j].charAt(0) == '?') ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/fnw3Hr4/QM.jpg)&quot;); if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == 'E') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/txvBhCS/empty.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == 'M') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/6Jq9S3g/mine.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == 'B') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/wgRt8v9/boom.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '1') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/5Gd2H0Y/1.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '2') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/GHGj0KM/2.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '3') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/sww9b1n/3.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '4') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/nrTjpqp/4.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '5') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/gZ6Rjrz/5.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '6') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/wh9XnfT/6.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '7') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/k1905rT/7.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (game.board[i][j].charAt(1) == 'T' &amp;&amp; game.board[i][j].charAt(2) == '8') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/RCs2s2H/8.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (Mines.winLose==1) { bCont.winLose.setVisible(true); bCont.winLose.setText(&quot;YOU WIN!&quot;); } if (Mines.winLose==0) { bCont.winLose.setVisible(true); bCont.winLose.setText(&quot;YOU LOSE! Try again...&quot;); } Mines.winLose=-1; } } }); } gameStage.show(); // Show stage } @FXML void Music(ActionEvent event) { Music.setOnAction(e -&gt; { boolean check = MainFX.music(); if (check) Music.setText(&quot;ON&quot;); else Music.setText(&quot;OFF&quot;); }); } } </code></pre> <p>new game fxml:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?import javafx.geometry.Insets?&gt; &lt;?import javafx.scene.control.Button?&gt; &lt;?import javafx.scene.control.TextField?&gt; &lt;?import javafx.scene.layout.AnchorPane?&gt; &lt;?import javafx.scene.layout.HBox?&gt; &lt;?import javafx.scene.layout.VBox?&gt; &lt;?import javafx.scene.text.Font?&gt; &lt;?import javafx.scene.text.Text?&gt; &lt;AnchorPane maxHeight=&quot;-Infinity&quot; maxWidth=&quot;-Infinity&quot; minHeight=&quot;-Infinity&quot; minWidth=&quot;-Infinity&quot; prefHeight=&quot;853.0&quot; prefWidth=&quot;1280.0&quot; xmlns=&quot;http://javafx.com/javafx/8.0.171&quot; xmlns:fx=&quot;http://javafx.com/fxml/1&quot; fx:controller=&quot;MS.NewGameCONTROLLER&quot;&gt; &lt;children&gt; &lt;VBox alignment=&quot;TOP_CENTER&quot; prefHeight=&quot;171.0&quot; prefWidth=&quot;980.0&quot; AnchorPane.bottomAnchor=&quot;444.0&quot; AnchorPane.leftAnchor=&quot;10.0&quot; AnchorPane.rightAnchor=&quot;10.0&quot; AnchorPane.topAnchor=&quot;10.0&quot;&gt; &lt;children&gt; &lt;Text fill=&quot;RED&quot; strokeType=&quot;OUTSIDE&quot; strokeWidth=&quot;0.0&quot; text=&quot;You can finally go on your long awaited vacation!!&quot; textAlignment=&quot;CENTER&quot;&gt; &lt;VBox.margin&gt; &lt;Insets bottom=&quot;10.0&quot; top=&quot;20.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;20.0&quot; /&gt; &lt;/font&gt; &lt;/Text&gt; &lt;Text fill=&quot;RED&quot; strokeType=&quot;OUTSIDE&quot; strokeWidth=&quot;0.0&quot; text=&quot;The resort is just across the beach&quot; textAlignment=&quot;CENTER&quot;&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;20.0&quot; /&gt; &lt;/font&gt; &lt;VBox.margin&gt; &lt;Insets bottom=&quot;10.0&quot; top=&quot;20.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;/Text&gt; &lt;Text fill=&quot;RED&quot; strokeType=&quot;OUTSIDE&quot; strokeWidth=&quot;0.0&quot; text=&quot;DANGER! You entered BOOM Beach... You know what to do...&quot; textAlignment=&quot;CENTER&quot;&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;25.0&quot; /&gt; &lt;/font&gt; &lt;VBox.margin&gt; &lt;Insets top=&quot;30.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;/Text&gt; &lt;/children&gt; &lt;/VBox&gt; &lt;VBox alignment=&quot;CENTER&quot; layoutX=&quot;396.0&quot; layoutY=&quot;205.0&quot; prefHeight=&quot;410.0&quot; prefWidth=&quot;980.0&quot; AnchorPane.bottomAnchor=&quot;10.0&quot; AnchorPane.leftAnchor=&quot;10.0&quot; AnchorPane.rightAnchor=&quot;10.0&quot; AnchorPane.topAnchor=&quot;205.0&quot;&gt; &lt;children&gt; &lt;HBox alignment=&quot;TOP_CENTER&quot; prefHeight=&quot;40.0&quot; prefWidth=&quot;979.0&quot;&gt; &lt;children&gt; &lt;Text strokeType=&quot;OUTSIDE&quot; strokeWidth=&quot;0.0&quot; text=&quot;Number of rows:&quot;&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;18.0&quot; /&gt; &lt;/font&gt; &lt;HBox.margin&gt; &lt;Insets /&gt; &lt;/HBox.margin&gt; &lt;/Text&gt; &lt;TextField fx:id=&quot;NumRows&quot; prefHeight=&quot;23.0&quot; prefWidth=&quot;137.0&quot; promptText=&quot;2 and above&quot;&gt; &lt;font&gt; &lt;Font size=&quot;10.0&quot; /&gt; &lt;/font&gt; &lt;HBox.margin&gt; &lt;Insets left=&quot;5.0&quot; /&gt; &lt;/HBox.margin&gt; &lt;/TextField&gt; &lt;/children&gt; &lt;/HBox&gt; &lt;HBox alignment=&quot;TOP_CENTER&quot; prefHeight=&quot;40.0&quot; prefWidth=&quot;979.0&quot;&gt; &lt;children&gt; &lt;Text strokeType=&quot;OUTSIDE&quot; strokeWidth=&quot;0.0&quot; text=&quot;Number of columns:&quot;&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;18.0&quot; /&gt; &lt;/font&gt; &lt;HBox.margin&gt; &lt;Insets /&gt; &lt;/HBox.margin&gt; &lt;/Text&gt; &lt;TextField fx:id=&quot;NumCols&quot; prefHeight=&quot;23.0&quot; prefWidth=&quot;117.0&quot; promptText=&quot;2 and above&quot;&gt; &lt;font&gt; &lt;Font size=&quot;10.0&quot; /&gt; &lt;/font&gt; &lt;HBox.margin&gt; &lt;Insets left=&quot;5.0&quot; /&gt; &lt;/HBox.margin&gt; &lt;/TextField&gt; &lt;/children&gt; &lt;/HBox&gt; &lt;HBox alignment=&quot;TOP_CENTER&quot; prefHeight=&quot;40.0&quot; prefWidth=&quot;979.0&quot;&gt; &lt;children&gt; &lt;Text strokeType=&quot;OUTSIDE&quot; strokeWidth=&quot;0.0&quot; text=&quot;Number of mines:&quot;&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;18.0&quot; /&gt; &lt;/font&gt; &lt;HBox.margin&gt; &lt;Insets /&gt; &lt;/HBox.margin&gt; &lt;/Text&gt; &lt;TextField fx:id=&quot;NumM&quot; prefHeight=&quot;23.0&quot; prefWidth=&quot;133.0&quot; promptText=&quot;1 and above&quot;&gt; &lt;font&gt; &lt;Font size=&quot;10.0&quot; /&gt; &lt;/font&gt; &lt;HBox.margin&gt; &lt;Insets left=&quot;5.0&quot; /&gt; &lt;/HBox.margin&gt; &lt;/TextField&gt; &lt;/children&gt; &lt;/HBox&gt; &lt;HBox alignment=&quot;TOP_CENTER&quot; prefHeight=&quot;30.0&quot; prefWidth=&quot;979.0&quot;&gt; &lt;children&gt; &lt;Button fx:id=&quot;StartGame&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#StartGame&quot; prefHeight=&quot;30.0&quot; prefWidth=&quot;140.0&quot; text=&quot;Start&quot; textFill=&quot;RED&quot;&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;20.0&quot; /&gt; &lt;/font&gt; &lt;HBox.margin&gt; &lt;Insets /&gt; &lt;/HBox.margin&gt; &lt;/Button&gt; &lt;/children&gt; &lt;VBox.margin&gt; &lt;Insets bottom=&quot;10.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;/HBox&gt; &lt;HBox alignment=&quot;TOP_CENTER&quot; prefHeight=&quot;30.0&quot; prefWidth=&quot;979.0&quot;&gt; &lt;children&gt; &lt;Button fx:id=&quot;BackMainMenu&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#BackMainMenu&quot; prefHeight=&quot;30.0&quot; text=&quot;Back to menu&quot;&gt; &lt;HBox.margin&gt; &lt;Insets /&gt; &lt;/HBox.margin&gt; &lt;font&gt; &lt;Font size=&quot;20.0&quot; /&gt; &lt;/font&gt; &lt;/Button&gt; &lt;Button fx:id=&quot;RandomGame&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#RandomGame&quot; prefHeight=&quot;30.0&quot; text=&quot;Random board&quot; textFill=&quot;RED&quot;&gt; &lt;HBox.margin&gt; &lt;Insets left=&quot;10.0&quot; /&gt; &lt;/HBox.margin&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;20.0&quot; /&gt; &lt;/font&gt; &lt;/Button&gt; &lt;/children&gt; &lt;VBox.margin&gt; &lt;Insets bottom=&quot;10.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;/HBox&gt; &lt;Button fx:id=&quot;Music&quot; alignment=&quot;TOP_CENTER&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#Music&quot; prefHeight=&quot;30.0&quot; text=&quot;Music&quot;&gt; &lt;VBox.margin&gt; &lt;Insets right=&quot;10.0&quot; /&gt; &lt;/VBox.margin&gt; &lt;font&gt; &lt;Font size=&quot;16.0&quot; /&gt; &lt;/font&gt; &lt;/Button&gt; &lt;/children&gt; &lt;padding&gt; &lt;Insets right=&quot;1.0&quot; /&gt; &lt;/padding&gt; &lt;/VBox&gt; &lt;/children&gt; &lt;/AnchorPane&gt; </code></pre> <p>board controller:</p> <pre><code>import java.io.IOException; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ButtonBase; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class BoardCONTROLLER { Button b; @FXML public GridPane TheBoard; @FXML public Label winLose; @FXML private Button BackMenu; @FXML private Button Music; @FXML private Button ResetBoard; @FXML void BackMenu(ActionEvent event) throws IOException { Image backgroundColor = new Image(&quot;https://i.ibb.co/1KvhFmp/menu.jpg&quot;); BackgroundSize backgroundSize = new BackgroundSize(1280, 720, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); FXMLLoader loader = new FXMLLoader(); // Create loading object loader.setLocation(getClass().getResource(&quot;MainMenuFXML.fxml&quot;)); // fxml location VBox root = loader.load(); // Load layout // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/menu.jpg\&quot;)&quot;); Scene scene = new Scene(root); // Create scene with chosen layout Stage primaryStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); // primaryStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); primaryStage.setTitle(&quot;BOOM Beach&quot;); // Set stage's title // primaryStage.setMinWidth(400); // Won't be allowed to make width/height smaller // primaryStage.setMinHeight(350); // primaryStage.setMaxWidth(600); // primaryStage.setMaxHeight(450); primaryStage.setScene(scene); // Set scene to stage primaryStage.show(); // Show stage } @FXML void Music(ActionEvent event) { Music.setOnAction(e -&gt; { boolean check = MainFX.music(); if (check) Music.setText(&quot;ON&quot;); else Music.setText(&quot;OFF&quot;); }); } @FXML void ResetBoard(ActionEvent event) throws IOException { Image backgroundColor = new Image(&quot;https://i.ibb.co/1Gr7PhP/Mandalorian.png&quot;); BackgroundSize backgroundSize = new BackgroundSize(1280, 853, true, true, true, true); BackgroundImage backgroundImage = new BackgroundImage(backgroundColor, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); NewGameCONTROLLER.game = new Mines(NewGameCONTROLLER.rows, NewGameCONTROLLER.columns, NewGameCONTROLLER.mines); FXMLLoader loader = new FXMLLoader(); // Create loading object loader.setLocation(getClass().getResource(&quot;BoardFXML.fxml&quot;)); // fxml location AnchorPane root = loader.load(); // Load layout // root.setStyle(&quot;-fx-background-image: url(\&quot;file:///C:/EclipseProjects/MineSweeper/src/MS/Mandalorian.png\&quot;)&quot;); Scene scene = new Scene(root); // Create scene with chosen layout Stage gameStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); // gameStage.setFullScreen(true); root.setBackground(new Background(backgroundImage)); gameStage.setTitle(&quot;BOOM Beach&quot;); // Set stage's title // gameStage.setMinWidth(1000); // Won't be allowed to make width/height smaller // gameStage.setMinHeight(500); // gameStage.setMaxWidth(2000); // gameStage.setMaxHeight(1000); gameStage.setScene(scene); // Set scene to stage BoardCONTROLLER bCont = loader.getController(); // Prepare board in BoardCONTROLLER bCont.winLose.setVisible(false); for (int i = 0; i &lt; NewGameCONTROLLER.columns; i++) { for (int j = 0; j &lt; NewGameCONTROLLER.rows; j++) { b = new Button(&quot; &quot;); b.setMinSize(30, 30); b.setMaxSize(30, 30); b.setStyle(&quot;-fx-font-size:11&quot;); bCont.TheBoard.add(b, i, j); GridPane.setMargin(b, new Insets(5, 5, 5, 5)); GridPane.setHalignment(b, HPos.CENTER); GridPane.setValignment(b, VPos.CENTER); } } for (int i = 0; i &lt; bCont.TheBoard.getChildren().size(); i++) { ((ButtonBase) bCont.TheBoard.getChildren().get(i)).setOnMouseClicked(new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { int x, y; y = (int) ((Button) event.getSource()).getProperties().get(&quot;gridpane-column&quot;); x = (int) ((Button) event.getSource()).getProperties().get(&quot;gridpane-row&quot;); if (event.getButton().equals(MouseButton.PRIMARY)) NewGameCONTROLLER.game.open(x, y); else if (event.getButton().equals(MouseButton.SECONDARY)) NewGameCONTROLLER.game.toggleFlag(x, y); else if (event.getButton().equals(MouseButton.MIDDLE)) NewGameCONTROLLER.game.toggleQM(x, y); for (Node child : bCont.TheBoard.getChildren()) { int j = (int) ((Button) child).getProperties().get(&quot;gridpane-column&quot;); int i = (int) ((Button) child).getProperties().get(&quot;gridpane-row&quot;); if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T') { ((Button) child).setText(NewGameCONTROLLER.game.board[i][j].substring(2, 3)); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'F' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(0) == 'D') ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/GtnDxdQ/flag.png)&quot;); if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'F' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(0) == '?') ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/fnw3Hr4/QM.jpg)&quot;); if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == 'E') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/txvBhCS/empty.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == 'M') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/6Jq9S3g/mine.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == 'B') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/wgRt8v9/boom.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == '1') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/5Gd2H0Y/1.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == '2') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/GHGj0KM/2.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == '3') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/sww9b1n/3.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == '4') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/nrTjpqp/4.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == '5') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/gZ6Rjrz/5.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == '6') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/wh9XnfT/6.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == '7') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/k1905rT/7.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (NewGameCONTROLLER.game.board[i][j].charAt(1) == 'T' &amp;&amp; NewGameCONTROLLER.game.board[i][j].charAt(2) == '8') { ((Button) child).setStyle( &quot;-fx-background-image: url(https://i.ibb.co/RCs2s2H/8.jpg)&quot;); ((Button) child).setText(&quot; &quot;); } if (Mines.winLose==1) { bCont.winLose.setVisible(true); bCont.winLose.setText(&quot;YOU WIN!&quot;); } if (Mines.winLose==0) { bCont.winLose.setVisible(true); bCont.winLose.setText(&quot;YOU LOSE! Try again...&quot;); } Mines.winLose=-1; } } }); } gameStage.show(); // Show stage } } } </code></pre> <p>board fxml:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?import javafx.geometry.Insets?&gt; &lt;?import javafx.scene.control.Button?&gt; &lt;?import javafx.scene.control.Label?&gt; &lt;?import javafx.scene.layout.AnchorPane?&gt; &lt;?import javafx.scene.layout.GridPane?&gt; &lt;?import javafx.scene.layout.HBox?&gt; &lt;?import javafx.scene.paint.LinearGradient?&gt; &lt;?import javafx.scene.paint.Stop?&gt; &lt;?import javafx.scene.text.Font?&gt; &lt;AnchorPane maxHeight=&quot;-Infinity&quot; maxWidth=&quot;-Infinity&quot; minHeight=&quot;-Infinity&quot; minWidth=&quot;-Infinity&quot; xmlns=&quot;http://javafx.com/javafx/8.0.171&quot; xmlns:fx=&quot;http://javafx.com/fxml/1&quot; fx:controller=&quot;MS.BoardCONTROLLER&quot;&gt; &lt;children&gt; &lt;GridPane fx:id=&quot;TheBoard&quot; AnchorPane.bottomAnchor=&quot;90.0&quot; AnchorPane.leftAnchor=&quot;0.0&quot; AnchorPane.rightAnchor=&quot;0.0&quot; AnchorPane.topAnchor=&quot;0.0&quot;&gt; &lt;/GridPane&gt; &lt;HBox alignment=&quot;BOTTOM_LEFT&quot; fillHeight=&quot;false&quot; layoutX=&quot;14.0&quot; layoutY=&quot;560.0&quot; AnchorPane.bottomAnchor=&quot;20.0&quot; AnchorPane.leftAnchor=&quot;20.0&quot; AnchorPane.rightAnchor=&quot;700.0&quot; AnchorPane.topAnchor=&quot;560.0&quot;&gt; &lt;children&gt; &lt;Button fx:id=&quot;BackMenu&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#BackMenu&quot; text=&quot;Back to menu&quot; /&gt; &lt;Button fx:id=&quot;ResetBoard&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#ResetBoard&quot; text=&quot;Reset&quot; textFill=&quot;RED&quot;&gt; &lt;HBox.margin&gt; &lt;Insets left=&quot;10.0&quot; /&gt; &lt;/HBox.margin&gt; &lt;/Button&gt; &lt;Button fx:id=&quot;Music&quot; mnemonicParsing=&quot;false&quot; onAction=&quot;#Music&quot; text=&quot;Music&quot;&gt; &lt;HBox.margin&gt; &lt;Insets left=&quot;10.0&quot; /&gt; &lt;/HBox.margin&gt; &lt;/Button&gt; &lt;/children&gt; &lt;/HBox&gt; &lt;Label fx:id=&quot;winLose&quot; layoutX=&quot;796.0&quot; layoutY=&quot;535.0&quot; text=&quot;Label&quot; AnchorPane.bottomAnchor=&quot;100.0&quot; AnchorPane.rightAnchor=&quot;200.0&quot;&gt; &lt;font&gt; &lt;Font name=&quot;System Bold&quot; size=&quot;35.0&quot; /&gt; &lt;/font&gt; &lt;textFill&gt; &lt;LinearGradient endX=&quot;1.0&quot; endY=&quot;1.0&quot;&gt; &lt;stops&gt; &lt;Stop color=&quot;RED&quot; /&gt; &lt;Stop color=&quot;#00e1ff&quot; offset=&quot;1.0&quot; /&gt; &lt;/stops&gt; &lt;/LinearGradient&gt; &lt;/textFill&gt; &lt;/Label&gt; &lt;/children&gt; &lt;/AnchorPane&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T21:46:52.237", "Id": "491074", "Score": "0", "body": "We don't have the images that you link to in the program. You need to either replace them with images that are posted online, or else you need to modify the code to not use them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T23:09:39.207", "Id": "491077", "Score": "1", "body": "Done, uploaded them" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T21:02:54.173", "Id": "250292", "Score": "2", "Tags": [ "javafx", "minesweeper" ], "Title": "Feedback JavaFX code - MineSweeper using SceneBuilder" }
250292
<p>Having too much spare time during the quarantine I learned some basic python (plus tkinter for GUI) and made a little HangMan game :) Would love any feedback for improvement. Thank you.</p> <pre><code>import os import random from tkinter import * from PIL import ImageTk, Image from tkinter import messagebox import pygame # Window settings root = Tk() root.title(&quot;HangMan&quot;) root.iconbitmap(&quot;images/icon.ico&quot;) root.geometry(&quot;800x400&quot;) root.resizable(width=False, height=False) def disable_event(): pass root.protocol(&quot;WM_DELETE_WINDOW&quot;, disable_event) # Disable window &quot;X&quot; (close) button pygame.mixer.init() music_state = False def play_music(): global music_state if not music_state: pygame.mixer.music.load(&quot;music/The Witcher 3 OST.mp3&quot;) pygame.mixer.music.play(loops=0) music_state = True else: pygame.mixer.music.stop() music_state = False def main_menu_(): root.deiconify() global main_menu_bg global letter_change letter_change = 1 global word_change word_change = 2 # Create canvas and add background canvas = Canvas(root, width=&quot;800&quot;, height=&quot;450&quot;) canvas.pack() main_menu_bg = ImageTk.PhotoImage(Image.open(&quot;images/main_bg.jpg&quot;).resize((800, 450), Image.ANTIALIAS)) canvas.background = main_menu_bg canvas.create_image(0, 0, anchor=NW, image=main_menu_bg) # Add buttons to canvas start_btn = Button(root, text=&quot;New Game&quot;, width=15, command=new_game, borderwidth=5) canvas.create_window(400, 150, anchor=CENTER, window=start_btn) score_btn = Button(root, text=&quot;Score Board&quot;, width=15, command=score_board, borderwidth=5) canvas.create_window(400, 210, anchor=CENTER, window=score_btn) quit_btn = Button(root, text=&quot;Quit&quot;, width=15, command=quit_game, borderwidth=5) canvas.create_window(400, 270, anchor=CENTER, window=quit_btn) music_btn = Button(root, text=&quot;Music&quot;, command=play_music) canvas.create_window(770, 380, anchor=CENTER, window=music_btn) def new_game(): root.withdraw() # Hide root window, to make it visible again use root.deiconify() global new_game_bg global new_game_window new_game_window = Toplevel() new_game_window.title(&quot;HangMan&quot;) new_game_window.iconbitmap(&quot;images/icon.ico&quot;) new_game_window.geometry(&quot;800x400&quot;) new_game_window.resizable(width=False, height=False) new_game_window.protocol(&quot;WM_DELETE_WINDOW&quot;, disable_event) # Disable window &quot;X&quot; (close) button # Create canvas and add background canvas_new_game = Canvas(new_game_window, width=&quot;800&quot;, height=&quot;450&quot;) canvas_new_game.pack() new_game_bg = ImageTk.PhotoImage(Image.open(&quot;images/main_bg.jpg&quot;).resize((800, 450), Image.ANTIALIAS)) canvas_new_game.background = new_game_bg canvas_new_game.create_image(0, 0, anchor=NW, image=new_game_bg) instructions_lbl = Label(new_game_window, text=&quot;There are 4 different categories.\n&quot; &quot;Choose as many as you'd like,&quot; &quot;\nbut do choose wisely, this is not going to be easy!&quot;, bg=&quot;#a5a0b6&quot;) canvas_new_game.create_window(400, 60, anchor=CENTER, window=instructions_lbl) # Will help knowing which categories were chosen var1 = StringVar(value=&quot;&quot;) var2 = StringVar(value=&quot;&quot;) var3 = StringVar(value=&quot;&quot;) var4 = StringVar(value=&quot;&quot;) anime_btn = Checkbutton(new_game_window, text=&quot;Anime&quot;, variable=var1, onvalue=&quot;a&quot;, offvalue=&quot;&quot;) canvas_new_game.create_window(340, 120, anchor=CENTER, window=anime_btn) games_btn = Checkbutton(new_game_window, text=&quot;Games&quot;, variable=var2, onvalue=&quot;g&quot;, offvalue=&quot;&quot;) canvas_new_game.create_window(440, 120, anchor=CENTER, window=games_btn) movies_btn = Checkbutton(new_game_window, text=&quot;Movies&quot;, variable=var3, onvalue=&quot;m&quot;, offvalue=&quot;&quot;) canvas_new_game.create_window(340, 170, anchor=CENTER, window=movies_btn) tv_btn = Checkbutton(new_game_window, text=&quot;TV-Shows&quot;, variable=var4, onvalue=&quot;t&quot;, offvalue=&quot;&quot;) canvas_new_game.create_window(440, 170, anchor=CENTER, window=tv_btn) start_new_game_btn = Button(new_game_window, text=&quot;Start new game&quot;, width=15, command=lambda: [prepare(var1.get() + var2.get() + var3.get() + var4.get())] , borderwidth=5) canvas_new_game.create_window(390, 220, anchor=CENTER, window=start_new_game_btn) back_menu_btn = Button(new_game_window, text=&quot;Main Menu&quot;, width=15, command=lambda: [main_menu_(), new_game_window.destroy()] , borderwidth=5) canvas_new_game.create_window(390, 260, anchor=CENTER, window=back_menu_btn) # quit_game_btn = Button(new_game_window, text=&quot;Quit game&quot;, width=15, command=quit_game) # canvas_new_game.create_window(390, 300, anchor=CENTER, window=quit_game_btn) music_btn = Button(new_game_window, text=&quot;Music&quot;, command=play_music) canvas_new_game.create_window(770, 380, anchor=CENTER, window=music_btn) # choice variable will contain the user's wanted category for the game def prepare(choice): global count_lines # Create file of words movies = open(&quot;movies list.txt&quot;, &quot;r&quot;) # Open word files games = open(&quot;games list.txt&quot;, &quot;r&quot;) tv = open(&quot;tv list.txt&quot;, &quot;r&quot;) anime = open(&quot;anime list.txt&quot;, &quot;r&quot;) categories = &quot;&quot; file = open(&quot;temp.txt&quot;, &quot;a+&quot;) # File which will contain words from chosen categories if &quot;a&quot; or &quot;g&quot; or &quot;m&quot; or &quot;t&quot; in choice: if &quot;m&quot; in choice: categories += &quot;Movies / &quot; for i in movies.readlines(): file.write(i) if &quot;g&quot; in choice: categories += &quot;Games / &quot; for j in games.readlines(): file.write(j) if &quot;t&quot; in choice: categories += &quot;TV-Shows / &quot; for k in tv.readlines(): file.write(k) if &quot;a&quot; in choice: categories += &quot;Anime / &quot; for t in anime.readlines(): file.write(t) categories = categories[0:-3] # Will go in label movies.close() # Close word files anime.close() tv.close() games.close() file.close() # Get lines count categories_file = open(&quot;temp.txt&quot;, &quot;r&quot;) count_lines = get_lines_count(categories_file) categories_file.close() # Get random word to guess random_num = random.randint(1, count_lines) # Get a random integer word_to_guess = get_word(random_num) word_to_guess = word_to_guess[0:-1] # Remove the &quot;\n&quot; char # Count word chars chars_count = get_chars_count(list(word_to_guess)) # Create a variable same length as word to guess but made from _ under_lines_guess = hide_word(word_to_guess) play(under_lines_guess, word_to_guess, chars_count) def hide_word(word): hidden = &quot;&quot; for hide in range(len(word)): # for 0 in (x-1) if word[hide] == &quot; &quot;: hidden += &quot; &quot; else: hidden += &quot;_&quot; return hidden def get_chars_count(count_chars): counter_chars = 0 for index in count_chars: if index != &quot; &quot;: counter_chars += 1 return counter_chars def get_lines_count(file): return sum(1 for line in file) # For each line count 1+1+... def get_word(random_number): global count_lines f = open(&quot;temp.txt&quot;, &quot;r&quot;) lines = f.readlines() ret = lines[random_number - 1] f.close() f_new = open(&quot;temp.txt&quot;, &quot;w&quot;) for line in lines: # Write all lines to the file except the one with the word used if line != lines[random_number - 1]: f_new.write(line) f_new.close() count_lines -= 1 # Since one line is gone (used and deleted) return ret def close_window(): option_window.destroy() def option_a(): global count_lines global word_change global letter_change if word_change &lt;= 0: messagebox.showwarning(&quot;Used it all&quot;, &quot;You used all of your word change options!&quot;) option_window.destroy() return # Get random word to guess random_num = random.randint(1, count_lines) # Get a random integer word_to_guess = get_word(random_num) word_to_guess = word_to_guess[0:-1] # Remove the &quot;\n&quot; char # Count word chars chars_count = get_chars_count(list(word_to_guess)) # Create a variable same length as word to guess but made from _ under_lines_guess = hide_word(word_to_guess) word_change -= 1 play_window.destroy() option_window.destroy() play(under_lines_guess, word_to_guess, chars_count) def option_b(): global chars_bank global counter global letter_change if letter_change &lt;= 0: messagebox.showwarning(&quot;Used it all&quot;, &quot;You used all of your letter helper options!&quot;) option_window.destroy() return answer_b = list(wordd) # When done, do - &quot;&quot;.join(list to join as string) upper_word = wordd.upper() upper_word_list_b = list(upper_word) len_wordd = len(wordd) - 1 used_check = True while used_check: random_num = random.randint(0, len_wordd) char_reveal = wordd[random_num-1] if char_reveal not in chars_bank: chars_bank += char_reveal while char_reveal.upper() in str(answer_b).upper(): print(char_reveal.upper() + str(answer_b).upper()) i = upper_word_list_b.index(char_reveal.upper()) # Change input char and it's duplicates under_lines[i] = answer_b[i] answer_b[i] = &quot; &quot; upper_word_list_b[i] = &quot; &quot; counter -= 1 if counter == 0: messagebox.showinfo(&quot;WINNER&quot;, &quot;You win!!!&quot;) answer_ = messagebox.askyesno(&quot;HangMan&quot;, &quot;Would you like to play again?&quot;) if answer_ == 0: quit_game() else: if os.path.isfile(&quot;temp.txt&quot;): # In case the file was created os.remove(&quot;temp.txt&quot;) # Delete file (no longer needed) new_game_window.destroy() play_window.destroy() option_window.destroy() root.deiconify() used_check = False letter_change -= 1 list_chars_bank_ = list(chars_bank) bank_lbl = Label(play_window, text=&quot;Used characters bank:\n&quot; + &quot; &quot;.join(list_chars_bank_).upper()) canvas_play.create_window(70, 270, anchor=CENTER, window=bank_lbl) underlines_lbl = Label(play_window, text=&quot; &quot;.join(under_lines)) canvas_play.create_window(400, 310, anchor=CENTER, window=underlines_lbl) guesses_lbl = Label(play_window, text=&quot;You have &quot; + str(guesses) + &quot; guesses left&quot;) canvas_play.create_window(400, 340, anchor=CENTER, window=guesses_lbl) option_window.destroy() def assistance(): global word_change global letter_change global option_window if word_change == 0 and letter_change == 0: messagebox.showinfo(&quot;Assistance menu&quot;, &quot;You don't have any more assistance options to use.&quot;) else: option_window = Toplevel() option_window.title(&quot;Assistance menu&quot;) option_window.iconbitmap(&quot;images/icon.ico&quot;) option_window.geometry(&quot;270x219&quot;) option_window.resizable(width=False, height=False) option_window.attributes(&quot;-topmost&quot;, &quot;true&quot;) # Create canvas and add background canvas_option = Canvas(option_window, width=&quot;270&quot;, height=&quot;219&quot;) canvas_option.pack() option_bg = ImageTk.PhotoImage(Image.open(&quot;images/choosewisely.jpg&quot;).resize((270, 219), Image.ANTIALIAS)) canvas_option.background = option_bg canvas_option.create_image(0, 0, anchor=NW, image=option_bg) option_text = (&quot;Choose an option:\nA) Change word (uses left: &quot; + str(word_change) + &quot;)\nB) Letter helper (uses left: &quot; + str(letter_change) + &quot;)&quot;) option_lbl = Label(option_window, text=option_text) canvas_option.create_window(135, 55, anchor=CENTER, window=option_lbl) option_a_btn = Button(option_window, text=&quot;Option A&quot;, borderwidth=5, command=option_a) canvas_option.create_window(85, 150, anchor=CENTER, window=option_a_btn) option_b_btn = Button(option_window, text=&quot;Option B&quot;, borderwidth=5, command=option_b) canvas_option.create_window(185, 150, anchor=CENTER, window=option_b_btn) cancel_btn = Button(option_window, text=&quot;Nah... I don't need any help&quot;, borderwidth=5, command=close_window) canvas_option.create_window(135, 195, anchor=CENTER, window=cancel_btn) def my_answer(): global chars_bank global wordd global counter global guesses global list_chars_bank global under_lines if e.get()[0:1] in &quot;\n =+-*/.`~!@#$%^&amp;*()_,';:&quot;: messagebox.showwarning(&quot;Illegal input&quot;, &quot;Input is illegal. Enter a character in the range of (a-z) and (0-9)&quot;) e.delete(0, &quot;end&quot;) return if e.get()[0:1] in chars_bank: messagebox.showwarning(&quot;Illegal input&quot;, &quot;Input was used before.&quot;) e.delete(0, &quot;end&quot;) return else: len_align = (len(chars_bank) + 1) % 10 if len_align == 0: chars_bank += &quot;\n&quot; chars_bank += e.get()[0:1] if e.get()[0:1].upper() in str(answer).upper(): # upper in order to ignore if the letter is written while e.get()[0:1].upper() in str(answer).upper(): # Check if its there more than once i = upper_word_list.index(e.get()[0:1].upper()) # Returns index of the letter guessed under_lines[i] = answer[i] answer[i] = &quot; &quot; upper_word_list[i] = &quot; &quot; counter -= 1 if counter == 0: messagebox.showinfo(&quot;WINNER&quot;, &quot;You win!!!&quot;) answer_ = messagebox.askyesno(&quot;HangMan&quot;, &quot;Would you like to play again?&quot;) if answer_ == 0: quit_game() else: if os.path.isfile(&quot;temp.txt&quot;): # In case the file was created os.remove(&quot;temp.txt&quot;) # Delete file (no longer needed) new_game_window.destroy() play_window.destroy() root.deiconify() else: guesses -= 1 if guesses == 4: play_bg4 = ImageTk.PhotoImage(Image.open(&quot;images/4guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS)) canvas_play.background = play_bg4 canvas_play.create_image(0, 0, anchor=NW, image=play_bg4) if guesses == 3: play_bg3 = ImageTk.PhotoImage(Image.open(&quot;images/3guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS)) canvas_play.background = play_bg3 canvas_play.create_image(0, 0, anchor=NW, image=play_bg3) if guesses == 2: play_bg2 = ImageTk.PhotoImage(Image.open(&quot;images/2guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS)) canvas_play.background = play_bg2 canvas_play.create_image(0, 0, anchor=NW, image=play_bg2) if guesses == 1: play_bg1 = ImageTk.PhotoImage(Image.open(&quot;images/1guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS)) canvas_play.background = play_bg1 canvas_play.create_image(0, 0, anchor=NW, image=play_bg1) if guesses == 0: play_bg0 = ImageTk.PhotoImage(Image.open(&quot;images/0guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS)) canvas_play.background = play_bg0 canvas_play.create_image(0, 0, anchor=NW, image=play_bg0) messagebox.showinfo(&quot;LOSER&quot;, &quot;You lose!\nThe word was: &quot; + wordd) answer_ = messagebox.askyesno(&quot;HangMan&quot;, &quot;Would you like to play again?&quot;) if answer_ == 0: quit_game() else: if os.path.isfile(&quot;temp.txt&quot;): # In case the file was created os.remove(&quot;temp.txt&quot;) # Delete file (no longer needed) new_game_window.destroy() play_window.destroy() root.deiconify() e.delete(0, &quot;end&quot;) # letters_left_lbl = Label(play_window, text=str(counter) + &quot; letters left to solve the word&quot;) # canvas_play.create_window(400, 370, anchor=CENTER, window=letters_left_lbl) # list_chars_bank = list(chars_bank) bank_lbl = Label(play_window, text=&quot;Used characters bank:\n&quot; + &quot; &quot;.join(list_chars_bank).upper()) canvas_play.create_window(70, 270, anchor=CENTER, window=bank_lbl) underlines_lbl = Label(play_window, text=&quot; &quot;.join(under_lines)) canvas_play.create_window(400, 310, anchor=CENTER, window=underlines_lbl) guesses_lbl = Label(play_window, text=&quot;You have &quot; + str(guesses) + &quot; guesses left&quot;) canvas_play.create_window(400, 340, anchor=CENTER, window=guesses_lbl) def play(hidden, word, count): new_game_window.withdraw() global play_bg global play_window global canvas_play global chars_bank global e global answer global upper_word_list global under_lines global wordd wordd = word global guesses guesses = 5 global counter counter = count global list_chars_bank chars_bank = &quot;&quot; list_chars_bank = list(chars_bank) global word_change global letter_change play_window = Toplevel() play_window.title(&quot;HangMan&quot;) play_window.iconbitmap(&quot;images/icon.ico&quot;) play_window.geometry(&quot;800x400&quot;) play_window.resizable(width=False, height=False) play_window.protocol(&quot;WM_DELETE_WINDOW&quot;, disable_event) # Disable window &quot;X&quot; (close) button # Create canvas and add background canvas_play = Canvas(play_window, width=&quot;800&quot;, height=&quot;450&quot;) canvas_play.pack() play_bg = ImageTk.PhotoImage(Image.open(&quot;images/main_bg.jpg&quot;).resize((800, 450), Image.ANTIALIAS)) canvas_play.background = play_bg canvas_play.create_image(0, 0, anchor=NW, image=play_bg) under_lines = list(hidden) # Will make it easier to change chars in string answer = list(word) # When done, do - &quot;&quot;.join(list to join as string) upper_word = word.upper() upper_word_list = list(upper_word) chars_bank = &quot;&quot; # letters_left_lbl = Label(play_window, text=str(counter) + &quot; letters left to solve the word&quot;) # canvas_play.create_window(400, 370, anchor=CENTER, window=letters_left_lbl) # underlines_lbl = Label(play_window, text=&quot; &quot;.join(under_lines)) canvas_play.create_window(400, 310, anchor=CENTER, window=underlines_lbl) guesses_lbl = Label(play_window, text=&quot;You have &quot; + str(guesses) + &quot; guesses left&quot;) canvas_play.create_window(400, 340, anchor=CENTER, window=guesses_lbl) bank_lbl = Label(play_window, text=&quot;Used characters bank:\n&quot; + &quot; &quot;.join(list_chars_bank).upper()) canvas_play.create_window(70, 270, anchor=CENTER, window=bank_lbl) back_menu_btn_ = Button(play_window, text=&quot;Main Menu&quot;, borderwidth=5, width=15, command=lambda: [main_menu_(), play_window.destroy(), new_game_window.destroy()]) canvas_play.create_window(70, 370, anchor=CENTER, window=back_menu_btn_) e = Entry(play_window, width=4, borderwidth=2) canvas_play.create_window(380, 250, anchor=CENTER, window=e) assistance_btn = Button(play_window, text=&quot;Other options&quot;, width=15, borderwidth=5, command=assistance) canvas_play.create_window(70, 30, anchor=CENTER, window=assistance_btn) input_answer = Button(play_window, text=&quot;Confirm&quot;, command=my_answer, borderwidth=5) canvas_play.create_window(430, 250, anchor=CENTER, window=input_answer) music_btn = Button(play_window, text=&quot;Music&quot;, command=play_music) canvas_play.create_window(770, 380, anchor=CENTER, window=music_btn) def score_board(): return def quit_game(): if os.path.isfile(&quot;temp.txt&quot;): # In case the file was created os.remove(&quot;temp.txt&quot;) # Delete file (no longer needed) root.destroy() main_menu_() # Start game root.mainloop() </code></pre> <p>If needed, image are below: <a href="https://i.stack.imgur.com/lS5zX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lS5zX.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/zCMuk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zCMuk.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/7eKYi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7eKYi.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/PbsIl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PbsIl.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/DdrKm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DdrKm.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/q24e7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q24e7.jpg" alt="enter image description here" /></a> <a href="https://voca.ro/1envbI4tIZ9K" rel="nofollow noreferrer">link to the music file</a>, <a href="http://www.iconj.com/ico/3/h/3hmz39fbe7.ico" rel="nofollow noreferrer">link to the ico image</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:02:52.383", "Id": "491110", "Score": "2", "body": "I have rolled back your latest edit. 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)*." } ]
[ { "body": "<h2>Code/Logic</h2>\n<pre><code> if not music_state:\n pygame.mixer.music.load(&quot;music/The Witcher 3 OST.mp3&quot;)\n pygame.mixer.music.play(loops=0)\n music_state = True\n else:\n pygame.mixer.music.stop()\n music_state = False\n</code></pre>\n<p>This is backwards. Since you're handling both cases, the natural thing to do would be</p>\n<pre><code>if music_state:\n pygame.mixer.music.stop()\n music_state = False\nelse:\n pygame.mixer.music.load(&quot;music/The Witcher 3 OST.mp3&quot;)\n pygame.mixer.music.play(loops=0)\n music_state = True\n</code></pre>\n<p>But also, you're flipping the <code>music_state</code> in both cases, so you can take that out and rather move it after the if-else and do</p>\n<pre><code>music_state = not music_state\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T08:33:54.460", "Id": "250305", "ParentId": "250295", "Score": "1" } }, { "body": "<p>I changed the if statements of music_state as was answered.\nAlso, I've noticed that if the user lost the game and wishes to play again, the assistance options (letter change and word change) don't reset, so added:</p>\n<pre><code>word_change = 2\nletter_change = 1\n</code></pre>\n<p>in the methods which handles losing.\nAnother issue is that when using option b (letter helper) the loop had issues on two occasions, if the answer contained more than one word then if the &quot; &quot; is chosen randomly as the letter helper, the loop will become infinite, and the second issue is if the word contained for example an upper and lower &quot;A&quot;, then if the loop chooses &quot;a&quot;, it won't handle the upper case &quot;A&quot;.\nBelow is the new code:</p>\n<pre><code>import os\nimport random\nfrom tkinter import *\nfrom PIL import ImageTk, Image\nfrom tkinter import messagebox\nimport pygame\n\n# Window settings\nroot = Tk()\nroot.title(&quot;HangMan&quot;)\nroot.iconbitmap(&quot;images/icon.ico&quot;)\nroot.geometry(&quot;800x400&quot;)\nroot.resizable(width=False, height=False)\n\n\ndef disable_event():\n pass\n\n\nroot.protocol(&quot;WM_DELETE_WINDOW&quot;, disable_event) # Disable window &quot;X&quot; (close) button\n\n\npygame.mixer.init()\nmusic_state = False\n\n\ndef play_music():\n global music_state\n\n if music_state:\n pygame.mixer.music.stop()\n else:\n pygame.mixer.music.load(&quot;music/The Witcher 3 OST.mp3&quot;)\n pygame.mixer.music.play(loops=0)\n music_state = not music_state\n\n\ndef main_menu_():\n root.deiconify()\n\n global main_menu_bg\n\n global letter_change\n letter_change = 1\n global word_change\n word_change = 2\n\n # Create canvas and add background\n canvas = Canvas(root, width=&quot;800&quot;, height=&quot;450&quot;)\n canvas.pack()\n\n main_menu_bg = ImageTk.PhotoImage(Image.open(&quot;images/main_bg.jpg&quot;).resize((800, 450), Image.ANTIALIAS))\n canvas.background = main_menu_bg\n canvas.create_image(0, 0, anchor=NW, image=main_menu_bg)\n\n # Add buttons to canvas\n start_btn = Button(root, text=&quot;New Game&quot;, width=15, command=new_game, borderwidth=5)\n canvas.create_window(400, 150, anchor=CENTER, window=start_btn)\n\n score_btn = Button(root, text=&quot;Score Board&quot;, width=15, command=score_board, borderwidth=5)\n canvas.create_window(400, 210, anchor=CENTER, window=score_btn)\n\n quit_btn = Button(root, text=&quot;Quit&quot;, width=15, command=quit_game, borderwidth=5)\n canvas.create_window(400, 270, anchor=CENTER, window=quit_btn)\n\n music_btn = Button(root, text=&quot;Music&quot;, command=play_music)\n canvas.create_window(770, 380, anchor=CENTER, window=music_btn)\n\n\ndef new_game():\n root.withdraw() # Hide root window, to make it visible again use root.deiconify()\n\n global new_game_bg\n global new_game_window\n\n new_game_window = Toplevel()\n new_game_window.title(&quot;HangMan&quot;)\n new_game_window.iconbitmap(&quot;images/icon.ico&quot;)\n new_game_window.geometry(&quot;800x400&quot;)\n new_game_window.resizable(width=False, height=False)\n new_game_window.protocol(&quot;WM_DELETE_WINDOW&quot;, disable_event) # Disable window &quot;X&quot; (close) button\n\n # Create canvas and add background\n canvas_new_game = Canvas(new_game_window, width=&quot;800&quot;, height=&quot;450&quot;)\n canvas_new_game.pack()\n\n new_game_bg = ImageTk.PhotoImage(Image.open(&quot;images/main_bg.jpg&quot;).resize((800, 450), Image.ANTIALIAS))\n canvas_new_game.background = new_game_bg\n canvas_new_game.create_image(0, 0, anchor=NW, image=new_game_bg)\n\n instructions_lbl = Label(new_game_window, text=&quot;There are 4 different categories.\\n&quot;\n &quot;Choose as many as you'd like,&quot;\n &quot;\\nbut do choose wisely, this is not going to be easy!&quot;,\n bg=&quot;#a5a0b6&quot;)\n canvas_new_game.create_window(400, 60, anchor=CENTER, window=instructions_lbl)\n\n # Will help knowing which categories were chosen\n var1 = StringVar(value=&quot;&quot;)\n var2 = StringVar(value=&quot;&quot;)\n var3 = StringVar(value=&quot;&quot;)\n var4 = StringVar(value=&quot;&quot;)\n\n anime_btn = Checkbutton(new_game_window, text=&quot;Anime&quot;, variable=var1, onvalue=&quot;a&quot;, offvalue=&quot;&quot;)\n canvas_new_game.create_window(340, 120, anchor=CENTER, window=anime_btn)\n games_btn = Checkbutton(new_game_window, text=&quot;Games&quot;, variable=var2, onvalue=&quot;g&quot;, offvalue=&quot;&quot;)\n canvas_new_game.create_window(440, 120, anchor=CENTER, window=games_btn)\n movies_btn = Checkbutton(new_game_window, text=&quot;Movies&quot;, variable=var3, onvalue=&quot;m&quot;, offvalue=&quot;&quot;)\n canvas_new_game.create_window(340, 170, anchor=CENTER, window=movies_btn)\n tv_btn = Checkbutton(new_game_window, text=&quot;TV-Shows&quot;, variable=var4, onvalue=&quot;t&quot;, offvalue=&quot;&quot;)\n canvas_new_game.create_window(440, 170, anchor=CENTER, window=tv_btn)\n\n start_new_game_btn = Button(new_game_window, text=&quot;Start new game&quot;, width=15,\n command=lambda: [prepare(var1.get() + var2.get() + var3.get() + var4.get())]\n , borderwidth=5)\n canvas_new_game.create_window(390, 220, anchor=CENTER, window=start_new_game_btn)\n\n back_menu_btn = Button(new_game_window, text=&quot;Main Menu&quot;, width=15, command=lambda: [main_menu_(),\n new_game_window.destroy()]\n , borderwidth=5)\n canvas_new_game.create_window(390, 260, anchor=CENTER, window=back_menu_btn)\n\n # quit_game_btn = Button(new_game_window, text=&quot;Quit game&quot;, width=15, command=quit_game)\n # canvas_new_game.create_window(390, 300, anchor=CENTER, window=quit_game_btn)\n\n music_btn = Button(new_game_window, text=&quot;Music&quot;, command=play_music)\n canvas_new_game.create_window(770, 380, anchor=CENTER, window=music_btn)\n\n\n# choice variable will contain the user's wanted category for the game\ndef prepare(choice):\n global count_lines\n\n # Create file of words\n movies = open(&quot;movies list.txt&quot;, &quot;r&quot;) # Open word files\n games = open(&quot;games list.txt&quot;, &quot;r&quot;)\n tv = open(&quot;tv list.txt&quot;, &quot;r&quot;)\n anime = open(&quot;anime list.txt&quot;, &quot;r&quot;)\n categories = &quot;&quot;\n file = open(&quot;temp.txt&quot;, &quot;a+&quot;) # File which will contain words from chosen categories\n if &quot;a&quot; or &quot;g&quot; or &quot;m&quot; or &quot;t&quot; in choice:\n if &quot;m&quot; in choice:\n categories += &quot;Movies / &quot;\n for i in movies.readlines():\n file.write(i)\n if &quot;g&quot; in choice:\n categories += &quot;Games / &quot;\n for j in games.readlines():\n file.write(j)\n if &quot;t&quot; in choice:\n categories += &quot;TV-Shows / &quot;\n for k in tv.readlines():\n file.write(k)\n if &quot;a&quot; in choice:\n categories += &quot;Anime / &quot;\n for t in anime.readlines():\n file.write(t)\n categories = categories[0:-3] # Will go in label\n movies.close() # Close word files\n anime.close()\n tv.close()\n games.close()\n file.close()\n\n # Get lines count\n categories_file = open(&quot;temp.txt&quot;, &quot;r&quot;)\n count_lines = get_lines_count(categories_file)\n categories_file.close()\n\n # Get random word to guess\n random_num = random.randint(1, count_lines) # Get a random integer\n word_to_guess = get_word(random_num)\n word_to_guess = word_to_guess[0:-1] # Remove the &quot;\\n&quot; char\n\n # Count word chars\n chars_count = get_chars_count(list(word_to_guess))\n\n # Create a variable same length as word to guess but made from _\n under_lines_guess = hide_word(word_to_guess)\n\n play(under_lines_guess, word_to_guess, chars_count)\n\n\ndef hide_word(word):\n hidden = &quot;&quot;\n for hide in range(len(word)): # for 0 in (x-1)\n if word[hide] == &quot; &quot;:\n hidden += &quot; &quot;\n else:\n hidden += &quot;_&quot;\n return hidden\n\n\ndef get_chars_count(count_chars):\n counter_chars = 0\n for index in count_chars:\n if index != &quot; &quot;:\n counter_chars += 1\n return counter_chars\n\n\ndef get_lines_count(file):\n return sum(1 for line in file) # For each line count 1+1+...\n\n\ndef get_word(random_number):\n global count_lines\n\n f = open(&quot;temp.txt&quot;, &quot;r&quot;)\n lines = f.readlines()\n ret = lines[random_number - 1]\n f.close()\n f_new = open(&quot;temp.txt&quot;, &quot;w&quot;)\n for line in lines: # Write all lines to the file except the one with the word used\n if line != lines[random_number - 1]:\n f_new.write(line)\n f_new.close()\n\n count_lines -= 1 # Since one line is gone (used and deleted)\n\n return ret\n\n\ndef close_window():\n option_window.destroy()\n\n\ndef option_a():\n global count_lines\n global word_change\n global letter_change\n\n if word_change &lt;= 0:\n messagebox.showwarning(&quot;Used it all&quot;, &quot;You used all of your word change options!&quot;)\n option_window.destroy()\n return\n\n # Get random word to guess\n random_num = random.randint(1, count_lines) # Get a random integer\n word_to_guess = get_word(random_num)\n word_to_guess = word_to_guess[0:-1] # Remove the &quot;\\n&quot; char\n\n # Count word chars\n chars_count = get_chars_count(list(word_to_guess))\n\n # Create a variable same length as word to guess but made from _\n under_lines_guess = hide_word(word_to_guess)\n word_change -= 1\n\n play_window.destroy()\n option_window.destroy()\n\n play(under_lines_guess, word_to_guess, chars_count)\n\n\ndef option_b():\n global chars_bank\n global counter\n global letter_change\n global word_change\n\n if letter_change &lt;= 0:\n messagebox.showwarning(&quot;Used it all&quot;, &quot;You used all of your letter helper options!&quot;)\n option_window.destroy()\n return\n\n answer_b = list(wordd) # When done, do - &quot;&quot;.join(list to join as string)\n upper_word = wordd.upper()\n upper_word_list_b = list(upper_word)\n\n len_wordd = len(wordd) - 1\n used_check = True\n\n while used_check:\n random_num = random.randint(0, len_wordd)\n char_reveal = wordd[random_num]\n\n if char_reveal.upper() not in str(chars_bank).upper() and char_reveal not in &quot; &quot;:\n chars_bank += char_reveal\n while char_reveal.upper() in str(answer_b).upper():\n # print(char_reveal.upper() + str(answer_b).upper())\n i = upper_word_list_b.index(char_reveal.upper()) # Change input char and it's duplicates\n under_lines[i] = answer_b[i]\n answer_b[i] = &quot; &quot;\n upper_word_list_b[i] = &quot; &quot;\n counter -= 1\n if counter == 0:\n messagebox.showinfo(&quot;WINNER&quot;, &quot;You win!!!&quot;)\n answer_ = messagebox.askyesno(&quot;HangMan&quot;, &quot;Would you like to play again?&quot;)\n if answer_ == 0:\n quit_game()\n else:\n letter_change = 1 # Initialize after user loses\n word_change = 2\n\n if os.path.isfile(&quot;temp.txt&quot;): # In case the file was created\n os.remove(&quot;temp.txt&quot;) # Delete file (no longer needed)\n new_game_window.destroy()\n play_window.destroy()\n option_window.destroy()\n root.deiconify()\n used_check = False\n\n letter_change -= 1\n\n list_chars_bank_ = list(chars_bank)\n bank_lbl = Label(play_window, text=&quot;Used characters bank:\\n&quot; + &quot; &quot;.join(list_chars_bank_).upper())\n canvas_play.create_window(70, 270, anchor=CENTER, window=bank_lbl)\n\n underlines_lbl = Label(play_window, text=&quot; &quot;.join(under_lines))\n canvas_play.create_window(400, 310, anchor=CENTER, window=underlines_lbl)\n\n guesses_lbl = Label(play_window, text=&quot;You have &quot; + str(guesses) + &quot; guesses left&quot;)\n canvas_play.create_window(400, 340, anchor=CENTER, window=guesses_lbl)\n\n option_window.destroy()\n\n\ndef assistance():\n global word_change\n global letter_change\n\n global option_window\n\n if word_change == 0 and letter_change == 0:\n messagebox.showinfo(&quot;Assistance menu&quot;, &quot;You don't have any more assistance options to use.&quot;)\n else:\n option_window = Toplevel()\n option_window.title(&quot;Assistance menu&quot;)\n option_window.iconbitmap(&quot;images/icon.ico&quot;)\n option_window.geometry(&quot;270x219&quot;)\n option_window.resizable(width=False, height=False)\n option_window.attributes(&quot;-topmost&quot;, &quot;true&quot;)\n\n # Create canvas and add background\n canvas_option = Canvas(option_window, width=&quot;270&quot;, height=&quot;219&quot;)\n canvas_option.pack()\n\n option_bg = ImageTk.PhotoImage(Image.open(&quot;images/choosewisely.jpg&quot;).resize((270, 219), Image.ANTIALIAS))\n canvas_option.background = option_bg\n canvas_option.create_image(0, 0, anchor=NW, image=option_bg)\n\n option_text = (&quot;Choose an option:\\nA) Change word (uses left: &quot; + str(word_change)\n + &quot;)\\nB) Letter helper (uses left: &quot; + str(letter_change) + &quot;)&quot;)\n\n option_lbl = Label(option_window, text=option_text)\n canvas_option.create_window(135, 55, anchor=CENTER, window=option_lbl)\n\n option_a_btn = Button(option_window, text=&quot;Option A&quot;, borderwidth=5, command=option_a)\n canvas_option.create_window(85, 150, anchor=CENTER, window=option_a_btn)\n\n option_b_btn = Button(option_window, text=&quot;Option B&quot;, borderwidth=5, command=option_b)\n canvas_option.create_window(185, 150, anchor=CENTER, window=option_b_btn)\n\n cancel_btn = Button(option_window, text=&quot;Nah... I don't need any help&quot;, borderwidth=5,\n command=close_window)\n canvas_option.create_window(135, 195, anchor=CENTER, window=cancel_btn)\n\n\ndef my_answer():\n global chars_bank\n\n global wordd\n\n global counter\n\n global guesses\n\n global list_chars_bank\n\n global under_lines\n\n global word_change\n global letter_change\n\n if e.get()[0:1] in &quot;\\n =+-*/.`~!@#$%^&amp;*()_,';:&quot;:\n messagebox.showwarning(&quot;Illegal input&quot;,\n &quot;Input is illegal. Enter a character in the range of (a-z) and (0-9)&quot;)\n e.delete(0, &quot;end&quot;)\n return\n if e.get()[0:1] in chars_bank:\n messagebox.showwarning(&quot;Illegal input&quot;,\n &quot;Input was used before.&quot;)\n e.delete(0, &quot;end&quot;)\n return\n else:\n len_align = (len(chars_bank) + 1) % 10\n if len_align == 0:\n chars_bank += &quot;\\n&quot;\n chars_bank += e.get()[0:1]\n if e.get()[0:1].upper() in str(answer).upper(): # upper in order to ignore if the letter is written\n while e.get()[0:1].upper() in str(answer).upper(): # Check if its there more than once\n i = upper_word_list.index(e.get()[0:1].upper()) # Returns index of the letter guessed\n under_lines[i] = answer[i]\n answer[i] = &quot; &quot;\n upper_word_list[i] = &quot; &quot;\n counter -= 1\n if counter == 0:\n messagebox.showinfo(&quot;WINNER&quot;, &quot;You win!!!&quot;)\n answer_ = messagebox.askyesno(&quot;HangMan&quot;, &quot;Would you like to play again?&quot;)\n if answer_ == 0:\n quit_game()\n else:\n if os.path.isfile(&quot;temp.txt&quot;): # In case the file was created\n os.remove(&quot;temp.txt&quot;) # Delete file (no longer needed)\n new_game_window.destroy()\n play_window.destroy()\n root.deiconify()\n else:\n guesses -= 1\n if guesses == 4:\n play_bg4 = ImageTk.PhotoImage(Image.open(&quot;images/4guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS))\n canvas_play.background = play_bg4\n canvas_play.create_image(0, 0, anchor=NW, image=play_bg4)\n if guesses == 3:\n play_bg3 = ImageTk.PhotoImage(Image.open(&quot;images/3guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS))\n canvas_play.background = play_bg3\n canvas_play.create_image(0, 0, anchor=NW, image=play_bg3)\n if guesses == 2:\n play_bg2 = ImageTk.PhotoImage(Image.open(&quot;images/2guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS))\n canvas_play.background = play_bg2\n canvas_play.create_image(0, 0, anchor=NW, image=play_bg2)\n if guesses == 1:\n play_bg1 = ImageTk.PhotoImage(Image.open(&quot;images/1guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS))\n canvas_play.background = play_bg1\n canvas_play.create_image(0, 0, anchor=NW, image=play_bg1)\n if guesses == 0:\n play_bg0 = ImageTk.PhotoImage(Image.open(&quot;images/0guesses.jpg&quot;).resize((800, 450), Image.ANTIALIAS))\n canvas_play.background = play_bg0\n canvas_play.create_image(0, 0, anchor=NW, image=play_bg0)\n messagebox.showinfo(&quot;LOSER&quot;, &quot;You lose!\\nThe word was: &quot; + wordd)\n answer_ = messagebox.askyesno(&quot;HangMan&quot;, &quot;Would you like to play again?&quot;)\n if answer_ == 0:\n quit_game()\n else:\n word_change = 2\n letter_change = 1\n if os.path.isfile(&quot;temp.txt&quot;): # In case the file was created\n os.remove(&quot;temp.txt&quot;) # Delete file (no longer needed)\n new_game_window.destroy()\n play_window.destroy()\n root.deiconify()\n\n e.delete(0, &quot;end&quot;)\n\n # letters_left_lbl = Label(play_window, text=str(counter) + &quot; letters left to solve the word&quot;)\n # canvas_play.create_window(400, 370, anchor=CENTER, window=letters_left_lbl)\n #\n list_chars_bank = list(chars_bank)\n bank_lbl = Label(play_window, text=&quot;Used characters bank:\\n&quot; + &quot; &quot;.join(list_chars_bank).upper())\n canvas_play.create_window(70, 270, anchor=CENTER, window=bank_lbl)\n\n underlines_lbl = Label(play_window, text=&quot; &quot;.join(under_lines))\n canvas_play.create_window(400, 310, anchor=CENTER, window=underlines_lbl)\n\n guesses_lbl = Label(play_window, text=&quot;You have &quot; + str(guesses) + &quot; guesses left&quot;)\n canvas_play.create_window(400, 340, anchor=CENTER, window=guesses_lbl)\n\n\ndef play(hidden, word, count):\n new_game_window.withdraw()\n global play_bg\n global play_window\n global canvas_play\n\n global chars_bank\n global e\n\n global answer\n global upper_word_list\n global under_lines\n global wordd\n wordd = word\n\n global guesses\n guesses = 5\n\n global counter\n counter = count\n\n global list_chars_bank\n chars_bank = &quot;&quot;\n list_chars_bank = list(chars_bank)\n\n global word_change\n\n global letter_change\n\n play_window = Toplevel()\n play_window.title(&quot;HangMan&quot;)\n play_window.iconbitmap(&quot;images/icon.ico&quot;)\n play_window.geometry(&quot;800x400&quot;)\n play_window.resizable(width=False, height=False)\n play_window.protocol(&quot;WM_DELETE_WINDOW&quot;, disable_event) # Disable window &quot;X&quot; (close) button\n\n # Create canvas and add background\n canvas_play = Canvas(play_window, width=&quot;800&quot;, height=&quot;450&quot;)\n canvas_play.pack()\n\n play_bg = ImageTk.PhotoImage(Image.open(&quot;images/main_bg.jpg&quot;).resize((800, 450), Image.ANTIALIAS))\n canvas_play.background = play_bg\n canvas_play.create_image(0, 0, anchor=NW, image=play_bg)\n\n under_lines = list(hidden) # Will make it easier to change chars in string\n answer = list(word) # When done, do - &quot;&quot;.join(list to join as string)\n upper_word = word.upper()\n upper_word_list = list(upper_word)\n chars_bank = &quot;&quot;\n\n # letters_left_lbl = Label(play_window, text=str(counter) + &quot; letters left to solve the word&quot;)\n # canvas_play.create_window(400, 370, anchor=CENTER, window=letters_left_lbl)\n #\n underlines_lbl = Label(play_window, text=&quot; &quot;.join(under_lines))\n canvas_play.create_window(400, 310, anchor=CENTER, window=underlines_lbl)\n\n guesses_lbl = Label(play_window, text=&quot;You have &quot; + str(guesses) + &quot; guesses left&quot;)\n canvas_play.create_window(400, 340, anchor=CENTER, window=guesses_lbl)\n\n bank_lbl = Label(play_window, text=&quot;Used characters bank:\\n&quot; + &quot; &quot;.join(list_chars_bank).upper())\n canvas_play.create_window(70, 270, anchor=CENTER, window=bank_lbl)\n\n back_menu_btn_ = Button(play_window, text=&quot;Main Menu&quot;, borderwidth=5, width=15,\n command=lambda: [main_menu_(),\n play_window.destroy(),\n new_game_window.destroy()])\n canvas_play.create_window(70, 370, anchor=CENTER, window=back_menu_btn_)\n\n e = Entry(play_window, width=4, borderwidth=2)\n canvas_play.create_window(380, 250, anchor=CENTER, window=e)\n\n assistance_btn = Button(play_window, text=&quot;Other options&quot;, width=15, borderwidth=5, command=assistance)\n canvas_play.create_window(70, 30, anchor=CENTER, window=assistance_btn)\n\n input_answer = Button(play_window, text=&quot;Confirm&quot;, command=my_answer, borderwidth=5)\n canvas_play.create_window(430, 250, anchor=CENTER, window=input_answer)\n\n music_btn = Button(play_window, text=&quot;Music&quot;, command=play_music)\n canvas_play.create_window(770, 380, anchor=CENTER, window=music_btn)\n\n\ndef score_board():\n return\n\n\ndef quit_game():\n if os.path.isfile(&quot;temp.txt&quot;): # In case the file was created\n os.remove(&quot;temp.txt&quot;) # Delete file (no longer needed)\n root.destroy()\n\n\nmain_menu_() # Start game\nroot.mainloop()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T00:04:16.873", "Id": "250346", "ParentId": "250295", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T23:45:23.670", "Id": "250295", "Score": "2", "Tags": [ "python", "tkinter", "hangman" ], "Title": "Feedback HangMan game using python and tkinter for GUI" }
250295
<p>I've just spent a good hour or so developing a python script that hunts down and removes .php files depending on the regex expression the situation was a client has got several sites and got hacked recently and as a result a large portion of 8 character random php files have created, so in order to remove them all I made a python script to hunt and find the files whilst avvoiding the files needed also which are 8 characters.</p> <h3>Target:</h3> <p>n1qv0iop.php<br/> e7wo0sb8.php<br/> sdt24g9o.php<br/> 9ktrhstu.php<br/> 2cvgc7qa.php<br/> nlrgnwzt.php<br/> pyj67osr.php<br/></p> <h3>Script:</h3> <pre><code>import os import re rootdir = &quot;/ROOTDIRECTORY&quot; regex = re.compile('^((((?!absolute|abstract|accounts|activate|activity|advanced|archives|autoload|autoplay|basiccss|bookmark|calendar|captions|category|checkbox|comments|compiled|conntest|controls|counters|courierb|courieri|creative|cronview|database|defaults|disabled|document|dropcaps|elements|embedded|error404|external|facebook|features|fieldset|flamingo|flipcard|freedoms|frontend|getcombo|getnodes|groupped|gzdecode|homepage|icongrid|iconlist|igniteup|importer|includer|launcher|lazyload|licenses|lightbox|location|magazine|mailpoet|manifest|mappings|myticket|optimize|packager|password|phpthumb|platform|pointers|products|progress|promobox|radiotab|redirect|register|renderer|repeater|required|response|revision|richtext|rollback|rollover|security|services|settings|sidebars|sitemaps|switcher|taxonomy|template|testmail|textarea|thankyou|timeline|tracking|upgrader|upgrades|variable|videobox|whatsnew|payments|donation|checkout|readmore|overview|tooltips|purchase|endpoint|firewood|pagepost|jwplayer|analytic|builders|bulkedit|carousel|delivery|featured|feedback|fontello|fontpack|headline|honeypot|messages|metadata|position|registry|sendaway|sections|singular|siblings|subpages|tabgroup|thickbox|turfmail|webfonts|networks|htaccess))[a-z0-9]{8})).php$') for root, dirs, files in os.walk(rootdir): for file in files: if regex.match(file): print(os.path.join(root,file)) #os.remove(os.path.join(root,file)) print &quot;END&quot;; </code></pre> <p>My question is can this be improved? is there a better way to write the regex pattern?just looking for advice :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:54:30.237", "Id": "491089", "Score": "1", "body": "any reason for regex? glob searching for `**.php` would be easier imo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T21:16:24.420", "Id": "491385", "Score": "0", "body": "Which Python version are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T00:10:51.683", "Id": "491478", "Score": "0", "body": "@AMC I am using version 2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T00:11:15.437", "Id": "491479", "Score": "0", "body": "@hjpotter92 no reason just thought it might be easier" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T22:46:26.353", "Id": "491681", "Score": "0", "body": "_I am using version 2_ I'm guessing that's a hard requirement?" } ]
[ { "body": "<h3>Looks OK!</h3>\n<ul>\n<li><p>I guess it's just missing a <code>\\</code> near <code>.php</code>. Currently, these strings are being accepted:</p>\n<pre><code>n1qv0iopAphp\ne7wo0sb8Bphp\nsdt24g9oCphp\n9ktrhstu1php\n2cvgc7qa&amp;php\n</code></pre>\n<p><a href=\"https://regex101.com/r/WbzJfS/1/\" rel=\"nofollow noreferrer\">Current Expression</a><br />\n<a href=\"https://regex101.com/r/uSO1BW/1/\" rel=\"nofollow noreferrer\">Updated Expression 1</a></p>\n</li>\n<li><p>We can likely get ride of some of those capturing groups. <a href=\"https://regex101.com/r/8orQv5/1/\" rel=\"nofollow noreferrer\">Updated Expression 2</a></p>\n<pre><code>^(?!absolute|abstract|accounts|activate|activity|advanced|archives|autoload|autoplay|basiccss|bookmark|calendar|captions|category|checkbox|comments|compiled|conntest|controls|counters|courierb|courieri|creative|cronview|database|defaults|disabled|document|dropcaps|elements|embedded|error404|external|facebook|features|fieldset|flamingo|flipcard|freedoms|frontend|getcombo|getnodes|groupped|gzdecode|homepage|icongrid|iconlist|igniteup|importer|includer|launcher|lazyload|licenses|lightbox|location|magazine|mailpoet|manifest|mappings|myticket|optimize|packager|password|phpthumb|platform|pointers|products|progress|promobox|radiotab|redirect|register|renderer|repeater|required|response|revision|richtext|rollback|rollover|security|services|settings|sidebars|sitemaps|switcher|taxonomy|template|testmail|textarea|thankyou|timeline|tracking|upgrader|upgrades|variable|videobox|whatsnew|payments|donation|checkout|readmore|overview|tooltips|purchase|endpoint|firewood|pagepost|jwplayer|analytic|builders|bulkedit|carousel|delivery|featured|feedback|fontello|fontpack|headline|honeypot|messages|metadata|position|registry|sendaway|sections|singular|siblings|subpages|tabgroup|thickbox|turfmail|webfonts|networks|htaccess)[a-z0-9]{8}\\.php$\n</code></pre>\n</li>\n<li><p>We can also make the stopwords shorter, but I would leave it as is, because it would be more readable and it does not improve the performance. For instance <code>autoload|autoplay</code> could be one character shorter: <code>auto(?:load|play)</code>. <a href=\"https://regex101.com/r/nyPBPs/1/\" rel=\"nofollow noreferrer\">Updated Expression 3</a></p>\n<pre><code>^(?!absolute|abstract|accounts|activate|activity|advanced|archives|auto(?:load|play)|basiccss|bookmark|calendar|captions|category|checkbox|comments|compiled|conntest|controls|counters|courierb|courieri|creative|cronview|database|defaults|disabled|document|dropcaps|elements|embedded|error404|external|facebook|features|fieldset|flamingo|flipcard|freedoms|frontend|getcombo|getnodes|groupped|gzdecode|homepage|icongrid|iconlist|igniteup|importer|includer|launcher|lazyload|licenses|lightbox|location|magazine|mailpoet|manifest|mappings|myticket|optimize|packager|password|phpthumb|platform|pointers|products|progress|promobox|radiotab|redirect|register|renderer|repeater|required|response|revision|richtext|rollback|rollover|security|services|settings|sidebars|sitemaps|switcher|taxonomy|template|testmail|textarea|thankyou|timeline|tracking|upgrader|upgrades|variable|videobox|whatsnew|payments|donation|checkout|readmore|overview|tooltips|purchase|endpoint|firewood|pagepost|jwplayer|analytic|builders|bulkedit|carousel|delivery|featured|feedback|fontello|fontpack|headline|honeypot|messages|metadata|position|registry|sendaway|sections|singular|siblings|subpages|tabgroup|thickbox|turfmail|webfonts|networks|htaccess)[a-z0-9]{8}\\.php$\n</code></pre>\n</li>\n</ul>\n<p>Overall it'd best to stay as far away from the regular expression as possible. ( ˆ_ˆ )</p>\n<hr />\n<p>If you wish to simplify/update/explore the expression, it's been explained on the top right panel of <a href=\"https://regex101.com/r/nyPBPs/1/\" rel=\"nofollow noreferrer\">regex101.com</a>. You can watch the matching steps or modify them in <a href=\"https://regex101.com/r/nyPBPs/1/debugger\" rel=\"nofollow noreferrer\">this debugger link</a>, if you'd be interested. The debugger demonstrates that how <a href=\"https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines\" rel=\"nofollow noreferrer\">a RegEx engine</a> might step by step consume some sample input strings and would perform the matching process.</p>\n<hr />\n<h3>RegEx Circuit</h3>\n<p><a href=\"https://jex.im/regulex/#!flags=&amp;re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions:</p>\n<p><a href=\"https://i.stack.imgur.com/cBc4Y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cBc4Y.png\" alt=\"enter image description here\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T02:21:15.320", "Id": "250299", "ParentId": "250296", "Score": "1" } }, { "body": "<p>I think a regex is overkill here. There comes a point where evaluating all these or'ed exceptions becomes just too slow. I would instead use a simple glob and a blacklist:</p>\n<pre><code>from pathlib import Path\n\nIGNORE = {&quot;absolute&quot;, &quot;abstract&quot;, ...}\n\nroot = Path(&quot;/ROOTDIRECTORY&quot;)\nfor file in root.glob(&quot;**/*.php&quot;):\n if len(file.stem) == 8 and file.stem not in IGNORE:\n print(file)\n</code></pre>\n<p>Note that I used a <code>set</code> for a fast check with <code>in</code>.</p>\n<p>You could also use the glob <code>&quot;**/????????.php&quot;</code>, as suggested by @RootTwo in the comments, then you wouldn't have to do the length check, although that is quite fast.</p>\n<p>Indeed, what you should ideally do is not take my or anyone else's word for it, but measure. Measure how fast your approach is, how fast an optimized regex is, how fast mine is and how fast using a different glob is. Maybe it matters, or maybe all of this is premature optimization and it doesn't actually matter that one takes a millisecond and the other a second (or whatever the actual results are). That depends entirely on your use case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:44:35.340", "Id": "491168", "Score": "1", "body": "Perhaps use `\"**/????????.py\"` for the pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:49:25.207", "Id": "491169", "Score": "0", "body": "@RootTwo That's definitely also a possibility, but for that I would run tests to see which is faster in that particular use case. Actually, I would run tests either way, so let me add that to the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T00:12:28.697", "Id": "491480", "Score": "0", "body": "@RootTwo will \"**/????????.py\" avoid words tho like comment, autoload etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T01:56:17.203", "Id": "491483", "Score": "0", "body": "@MrJoshFisher No, you will still need the ignore list. It just selects filenames with eight characters without using a regex." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T08:17:03.443", "Id": "250304", "ParentId": "250296", "Score": "3" } } ]
{ "AcceptedAnswerId": "250304", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-06T23:51:07.270", "Id": "250296", "Score": "2", "Tags": [ "python" ], "Title": "How can this python regex file finder be improved?" }
250296
<p>The first &quot;method&quot; I have coded is _bigPow which can pow(x, y) on any number which is really big. And the _printBigInt prints a very big integer. Plus I have tried to comment most parts of my code to make it easier hopefully!</p> <p>I just want criticism on what I can improve upon!</p> <p>The _start you can edit the numbers to check that it works on giant numbers</p> <p>I used this resource to guide me on how to work with big numbers in x86 - <a href="http://x86asm.net/articles/working-with-big-numbers-using-x86-instructions/" rel="nofollow noreferrer">http://x86asm.net/articles/working-with-big-numbers-using-x86-instructions/</a></p> <p>Code-</p> <pre><code>bits 64 %define STDIN 0 %define STDOUT 1 %define STDERR 2 %define SYSCALL_READ 0 %define SYSCALL_WRITE 1 %define SYSCALL_EXIT 60 section .bss bigNum resq 100000 bigNumLen equ 100000 section .text global _start _start: push 1000 ;pow(1356, 1000) &lt;- edit these two to check the program! push 1356 ;pow(1356, 1000) &lt;- edit these two to check the program! push bigNumLen ;how many qwords is this storage push bigNum ;pointer to storage call _bigPow ;return pointer in rax if sucess or 0 if fail push bigNumLen ;push storage size again push rax ;pus hpointer again call _printBigInt add rsp, 48 ;clean stack mov rax, 60 ;SYSCALL_EXIT mov rdi, 0 syscall ;must reserve at leat 64 bits of space aka 1 qword. ;must increment space in 64 bits. (64, 128, 192) aka 1 qword, 2 qword, 3 qword ;(first)last thing pushed on the stack must be a pointer to where you want to store the number ;second argument must be how many qwords you have reserved (1, 2, 3) etc. ;third argument must be what number you want to pow e.g 2 ;fourth argument must be thw power e.g 3 (2^3) ;if sucessful then it will return pointer in rax ;if failer returns 0 in rax _bigPow: ;prolog push rbp mov rbp, rsp ;save registers push rbx mov rbx, [rbp + 32] ;the number to be powed (the base) mov r8, qword[rbp + 16] ;the pointer to where to store the result mov [r8], rbx ;derefrence pointer and store rbx mov rcx, [rbp + 40] ;the actual power (the exponent) test rcx, rcx jz ._expIsZero jmp ._BigPowLoopCond ._BigPowLoop: mov rax, [r8] ;derefrence pointer and move value into rax mul rbx ;multiply by base mov [r8], rax ;put the number back after derefrencing pointer mov r9, rdx ;save the carried part into r9 register push rcx ;pushing rcx (the exponent) into the stack for later use xor rcx, rcx jmp ._BigPowLoop2Cond ._BigPowLoop2: mov rax, [r8 + 8 * rcx] ;moving xth bytes into rax (8, 16, 24...) mul rbx add rax, r9 ;adding previous carried part mov [r8 + 8 * rcx], rax ;store number back into xth bytes mov r9, rdx ._BigPowLoop2Cond: inc rcx cmp rcx, [rbp + 24] ;how many qwords were reserved jl ._BigPowLoop2 pop rcx ;put the exponent back into rcx test rdx, rdx ;if rdx is not zero we dont have enough space! jnz ._overflow ;exit gracefuly ._BigPowLoopCond: loop ._BigPowLoop ._sucess: mov rax, r8 jmp ._exitBigPow ._expIsZero: mov rax, r8 mov qword[r8], 1 jmp ._exitBigPow ._overflow: mov rax, 0 ._exitBigPow: ;restore registers pop rbx ;epilog pop rbp ret ;prints only big positive numbers ;last value pushed onto stack must contain pointer to the value to be printed ;second value is how many qwords long is the number (1, 2, 3,...) _printBigInt: ;prolog push rbp mov rbp, rsp ;save registers push rbx mov rdi, rsp ;make a copy of rsp for later. plus now I dont need to clean stack!!! ;making space on the stack because ;I dont want to destroy the original number mov rcx, [rbp + 24] ;getting the second param. how many qwords long lea r8, [rcx * 8] sub rdi, r8 ;make space on the stack mov r8, [rbp + 16] ;getting the pointer jmp ._printBigIntStackLoopCond ._printBigIntStackLoop: mov rax, [r8 + 8 * rcx] ;move the most significant byte into rax mov [rdi + 8 * rcx], rax ;mov that byte into the stack ._printBigIntStackLoopCond: dec rcx cmp rcx, -1 jne ._printBigIntStackLoop ;now the bigInt has been moved into the stack so we dont mess it up mov rbx, 10 ;divisor xor r8, r8 ;will be used to keep track of how many char are in the stack mov r9, rdi ;needed to manually put char in stack ._printBigIntLoop: mov rcx, [rbp + 24] ;get how many qwords big the number is dec rcx ;decrementing because 0 based index xor rdx, rdx ;clear rdx mov rax, [rdi + 8 * rcx] ;move most sig 8 bytes into rax from the stack div rbx ;divide by 10 mov [rdi + 8 * rcx], rax ;mov the result into the stack again jmp ._printBigIntLoop2Cond ._printBigIntLoop2: mov rax, [rdi + 8 * rcx] div rbx mov [rdi + 8 * rcx], rax ._printBigIntLoop2Cond: dec rcx cmp rcx, -1 jne ._printBigIntLoop2 lea rax, [rdx + '0'] ;converting the one digit into ascii value dec r9 mov [r9], al ;pushing the remainded onto the stack inc r8 ;inc how many chars need to be printed ._printBigIntLoopCond: mov rcx, [rbp + 24] ;move how many qwords big the number is dec rcx ;dec by 1 because 0 based index ._checkIfBigIntIsZero: mov rax, [rdi + 8 * rcx] ;move most sig 8 bytes int rax test rax, rax ;check if 0 jnz ._printBigIntLoop ;jump if not zero as there is more numbers to divide dec rcx cmp rcx, -1 ;if rcx becomes -1 then there is noting less to divide jne ._checkIfBigIntIsZero ;print the number mov rax, SYSCALL_WRITE mov rdi, STDOUT mov rsi, r9 ;the string mov rdx, r8 ;length syscall ;restore registers pop rbx ;epilog pop rbp ret <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Multiplication bug</h1>\n<p>Putting aside the loop logic for a bit, the &quot;meat&quot; of the bignint-by-smallint multiplication is like this:</p>\n<blockquote>\n<pre><code> mov rax, [r8 + 8 * rcx] ;moving xth bytes into rax (8, 16, 24...)\n mul rbx\n add rax, r9 ;adding previous carried part\n mov [r8 + 8 * rcx], rax ;store number back into xth bytes\n mov r9, rdx\n</code></pre>\n</blockquote>\n<p>Of course, you followed the resource, but it's not right.\n<code>add rax, r9</code> can carry (though keeping the base low means it is unlikely to happen). When it does, the upper half would have to be incremented. That increment does not pose the same problem again: the maximum product of two 64bit numbers is 0xffffffffffffffff² = 0xfffffffffffffffe0000000000000001, the upper half is at most 0xfffffffffffffffe so it's safe to increment.</p>\n<p>For example,</p>\n<pre><code> mov rax, [r8 + 8 * rcx] ;moving xth bytes into rax (8, 16, 24...)\n mul rbx\n add rax, r9 ;adding previous carried part\n mov [r8 + 8 * rcx], rax ;store number back into xth bytes\n adc rdx, 0 ;increment upper half if the 'add' carried\n mov r9, rdx\n</code></pre>\n<h1>Unnecessarily-64-bit instructions</h1>\n<p>Several instructions can be replaced with their 32bit counterparts, typically saving code size. For example, <code>mov rax, 1</code> (7 bytes) can be <code>mov eax, 1</code> (5 bytes). <code>xor rdx, rdx</code> can be <code>xor edx, edx</code>. <code>_BigPowLoop2</code> does not need a 64bit loop count. Small changes in code size are not necessarily significant, so this is all low-priority, but it can help.</p>\n<p>Perhaps you have heard that a processor &quot;prefers&quot; operations that match its &quot;bitness&quot;, x86-64 <a href=\"https://stackoverflow.com/q/8948918/555045\">does not work like that</a>, if anything it has a small preference for 32bit operations (but 64bit memory addressing).</p>\n<h1>The <code>loop</code> instruction</h1>\n<p><code>loop</code> is not as nice as it looks. See <a href=\"https://stackoverflow.com/q/46881279/555045\">How exactly does the x86 LOOP instruction work?</a> for the details. As an extra half-strike against it, your code needed <code>push rcx / pop rcx</code> in the loop because <code>rcx</code> was used as loop counter by both loops - but of course an other way to avoid that is choosing an other register for the inner loop.</p>\n<h1>Spelling</h1>\n<p>I rarely comment on this, but there are some spelling errors in your comments, so they could be improved. For example: deref<strong>e</strong>rence, suc<strong>c</strong>essful, fail<strong>ure</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T00:59:05.027", "Id": "491186", "Score": "0", "body": "Thanks for the advice tonight i will fix it! Especially the spelling that my bad!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T00:31:34.833", "Id": "250348", "ParentId": "250297", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T00:19:16.653", "Id": "250297", "Score": "1", "Tags": [ "assembly", "x86", "nasm", "bigint" ], "Title": "Criticism on x86_64 nasm printBigInt and bigPow implementation" }
250297
<p>In Rust, I want to take an array of <code>u32</code> values, convert each to four bytes in big endian, and concatenate them to yield a <code>Vec&lt;u8&gt;</code> result. Example:</p> <pre><code>let input: [u32; 5] = [ 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; (... Do some data conversion work ...) let output: Vec&lt;u8&gt; = vec![ 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, 0x89, 0x98, 0xBA, 0xDC, 0xFE, 0x10, 0x32, 0x54, 0x76, 0xC3, 0xD2, 0xE1, 0xF0, ]; </code></pre> <p>I have several pieces of working code that all give the same answer.</p> <p>Algorithm A (for-loop):</p> <pre><code>let mut output = Vec::&lt;u8&gt;::new(); for val in &amp;input{ output.extend_from_slice(&amp;val.to_be_bytes()); } </code></pre> <p>Algorithm B (for-each):</p> <pre><code>let mut output = Vec::&lt;u8&gt;::new(); input.iter().for_each(|val| output.extend_from_slice(&amp;val.to_be_bytes())); </code></pre> <p>Algorithm C (fold-append):</p> <pre><code>let output = input.iter().fold(Vec::&lt;u8&gt;::new(), |mut acc, val| {acc.extend_from_slice(&amp;val.to_be_bytes()); acc}); </code></pre> <p>Algorithm D (flat-map):</p> <pre><code>let output: Vec&lt;u8&gt; = input.iter().flat_map(|val| val.to_be_bytes().to_vec()).collect(); </code></pre> <p>Is there an even shorter, clearer way to accomplish the task? Maybe algorithm D's <code>to_vec()</code> could be avoided somehow?</p> <p>Speed is not a concern because this code only executes a few times, and the input array length is fixed at 5.</p>
[]
[ { "body": "<p>Algorithm A seems the clearest to me. An improvement might be to use <code>Vec::with_capacity</code> to avoid the allocation. Indeed, arrays in Rust are currently somewhat cumbersome to use.</p>\n<p>My advice would be to wrap it in a function and not worry about it later on:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn to_bytes(input: &amp;[u32]) -&gt; Vec&lt;u8&gt; {\n let mut bytes = Vec::with_capacity(4 * input.len());\n\n for value in input {\n bytes.extend(&amp;value.to_be_bytes());\n }\n\n bytes\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn to_bytes() {\n use super::*;\n\n assert_eq!(to_bytes(&amp;[]), &amp;[]);\n\n let input = &amp;[0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];\n let output = &amp;[\n 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, 0x89, 0x98, 0xBA, 0xDC, 0xFE, 0x10, 0x32,\n 0x54, 0x76, 0xC3, 0xD2, 0xE1, 0xF0,\n ];\n\n assert_eq!(to_bytes(input), output);\n }\n}\n</code></pre>\n<p>(<a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=4b416f84cab0a1051cbac22ad81e03f7\" rel=\"nofollow noreferrer\">playground</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T12:32:34.240", "Id": "250318", "ParentId": "250300", "Score": "3" } }, { "body": "<p><a href=\"https://blog.rust-lang.org/2021/06/17/Rust-1.53.0.html#intoiterator-for-arrays\" rel=\"nofollow noreferrer\">Rust 1.53.0</a> (2021-06-17) introduces the <code>IntoIterator</code> for array types, which finally makes this shorter code possible:</p>\n<p><strong>Algorithm E (flat-map simpler):</strong></p>\n<pre><code>let output: Vec&lt;u8&gt; = input.iter().flat_map(|val| val.to_be_bytes()).collect();\n</code></pre>\n<p>(This is based on my algorithm D, removing <code>.to_vec()</code>. I did check that algorithm E fails to compile using Rust 1.52.0.)</p>\n<hr />\n<p>Algorithm F (not recommended, Rust 1.51.0, see <a href=\"https://doc.rust-lang.org/nightly/std/array/struct.IntoIter.html#method.new\" rel=\"nofollow noreferrer\"><code>std::array::IntoIter::new()</code></a>):</p>\n<pre><code>let output: Vec&lt;u8&gt; = input.iter().flat_map(|val|\n std::array::IntoIter::new(val.to_be_bytes())).collect();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T15:46:17.737", "Id": "263951", "ParentId": "250300", "Score": "2" } } ]
{ "AcceptedAnswerId": "263951", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T03:25:47.443", "Id": "250300", "Score": "4", "Tags": [ "array", "comparative-review", "rust", "iterator" ], "Title": "Convert array of u32 to Vec<u8> in Rust" }
250300
<p>I came across this strategy pattern implementation</p> <p><a href="https://github.com/jtortorelli/head-first-design-patterns-python/blob/master/src/python/chapter_1/adventure_game.py" rel="nofollow noreferrer">https://github.com/jtortorelli/head-first-design-patterns-python/blob/master/src/python/chapter_1/adventure_game.py</a></p> <pre><code>class Character: def __init__(self): self.weapon_behavior = None def set_weapon(self, weapon_behavior): self.weapon_behavior = weapon_behavior def fight(self): self.weapon_behavior.use_weapon() class Queen(Character): def __init__(self): super().__init__() self.weapon_behavior = KnifeBehavior() class King(Character): def __init__(self): super().__init__() self.weapon_behavior = BowAndArrowBehavior() class Troll(Character): def __init__(self): super().__init__() self.weapon_behavior = AxeBehavior() class Knight(Character): def __init__(self): super().__init__() self.weapon_behavior = SwordBehavior() class WeaponBehavior: def use_weapon(self): raise NotImplementedError class KnifeBehavior(WeaponBehavior): def use_weapon(self): print(&quot;Stabby stab stab&quot;) class BowAndArrowBehavior(WeaponBehavior): def use_weapon(self): print(&quot;Thwing!&quot;) class AxeBehavior(WeaponBehavior): def use_weapon(self): print(&quot;Whack!&quot;) class SwordBehavior(WeaponBehavior): def use_weapon(self): print(&quot;Thrust!&quot;) knight = Knight() king = King() queen = Queen() troll = Troll() knight.fight() king.fight() queen.fight() troll.fight() </code></pre> <p>Would it be correct to refactor it the following way, using an ABC?</p> <pre><code>from abc import ABC, abstractmethod class Character: def __init__(self): self.weapon_behavior = None def set_weapon(self, weapon_behavior): self.weapon_behavior = weapon_behavior def fight(self): self.weapon_behavior.use_weapon() class Queen(Character): def __init__(self): super().__init__() self.weapon_behavior = KnifeBehavior() class King(Character): def __init__(self): super().__init__() self.weapon_behavior = BowAndArrowBehavior() class Troll(Character): def __init__(self): super().__init__() self.weapon_behavior = AxeBehavior() class Knight(Character): def __init__(self): super().__init__() self.weapon_behavior = SwordBehavior() class WeaponBehavior(ABC): @abstractmethod def use_weapon(self, message): print(message) class KnifeBehavior(WeaponBehavior): def use_weapon(self): super().use_weapon(&quot;Stabby stab stab&quot;) class BowAndArrowBehavior(WeaponBehavior): def use_weapon(self): super().use_weapon(&quot;Thwing!&quot;) class AxeBehavior(WeaponBehavior): def use_weapon(self): super().use_weapon(&quot;Whack!&quot;) class SwordBehavior(WeaponBehavior): def use_weapon(self): super().use_weapon(&quot;Thrust!&quot;) knight = Knight() king = King() queen = Queen() troll = Troll() knight.fight() king.fight() queen.fight() troll.fight() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:50:09.877", "Id": "491088", "Score": "0", "body": "why not use ABC for characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T07:14:08.187", "Id": "491091", "Score": "0", "body": "@hjpotter92 I'm not entirely sure, I felt it wouldn't be ideal because each subclass of character doesn't and shouldn't define its own method for fight and set_weapon. I'm new to ABCs though, so I could be wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T07:28:15.877", "Id": "491092", "Score": "0", "body": "but you're defining the `use_weapon` for each subclass for weapon behaviour." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T07:34:58.190", "Id": "491093", "Score": "0", "body": "@hjpotter92 yeah, that's intentional - each definitoion of use_weapon is unique to the subclass. each definition of fight and set_weapon wouldn't be unique. Or am I missing something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:34:40.843", "Id": "491134", "Score": "0", "body": "Only the Character and WeaponBehaviour classes are actually useful and neither of them needs to inherit anything. The rest can be just factory functions, because only the constructors differ. If a class constructor does anything except assign arguments to properties, it is probably wrong. And btw I just learnt that behavior is prefered in american english and behaviour everywhere else :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:50:56.547", "Id": "491139", "Score": "0", "body": "@slepic Could you give a quick example of a factory function that could be used in this way? And I just learned that 'learnt' is the preferred past tense of learn outside of the US and Canada." } ]
[ { "body": "<p>Only the Character and WeaponBehaviour classes are actually useful and neither of them needs to inherit anything. The rest can be just factory functions, because only the constructors differ. If a class constructor does anything except assign arguments to properties, it is probably wrong.</p>\n<p>Strategy pattern is based on composition rather then inheritance.</p>\n<pre><code>class Character:\n def __init__(self, weapon):\n self.weapon = weapon\n\n def set_weapon(self, weapon):\n self.weapon = weapon\n\n def fight(self):\n self.weapon.use()\n\n\ndef Queen():\n return Character(Knife())\n\ndef King():\n return Character(Bow())\n\nclass Weapon:\n def __init__(self, message):\n self.message = message\n def use(self):\n print(self.message)\n\n\ndef Knife():\n return Weapon(&quot;Stabby stab stab&quot;)\n\ndef Bow():\n return Weapon(&quot;Thwing!&quot;)\n\n\nking = King()\nqueen = Queen()\nking.fight()\nqueen.fight()\nqueen.set_weapon(Bow())\nqueen.fight()\n</code></pre>\n<p>Notice that I have removed the <code>behavior</code> part of the names as it seemed a bit useless.</p>\n<p>I have also renamed <code>use_weapon()</code> to just <code>use()</code> because it is called on a <code>weapon</code> variable, and so it seemed redundant.</p>\n<p>Also notice, that unless I used the <code>set_weapon()</code> method on a constructed Character instance (ie. to switch weapon in middle of battle), the Character class would be useless, because everything could have been done with the weapons alone. Of course I know this is just a pattern demonstration code, but I wanted to point out anyway..</p>\n<p>As a bonus, here is something (not only) for the king :) Also notice how again composition is prefered over inheritance to provide flexibility.</p>\n<pre><code>class DoubleWeapon:\n def __init__(self, left, right):\n self.left = left\n self.right = right\n def use(self):\n self.left.use()\n self.right.use()\n\nking.set_weapon(DoubleWeapon(Knife(), Sword()))\nking.fight()\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T16:31:56.290", "Id": "250329", "ParentId": "250302", "Score": "4" } } ]
{ "AcceptedAnswerId": "250329", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T05:22:31.327", "Id": "250302", "Score": "3", "Tags": [ "python", "object-oriented", "design-patterns", "strategy-pattern" ], "Title": "refactor python strategy pattern to use abstract base class" }
250302
<p>I would like some advice on improving/optimizing a small program I wrote. What it does is run a random walk on a torus manifold with 8 colors that loop around.</p> <pre><code>//RTM Test Using Random Walk Fractals, WIP //Created by delta23 //This Code works on Minix, Unix, MacOSX, Linux //This Code does not work on DOS or Windows (yet...) //LICENSE OF CODE: CC0 - Public Domain #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #define TAPE_SIZE_X 672 #define TAPE_SIZE_Y 135 //Q!&gt;&lt;^V became &gt;&lt;^V : move and add char inst [ 4 ] = { '&gt;', '&lt;', '^', 'V' } ; //can be used for debugging, and for inputting code later on, when it starts in a conditional loop perhaps unsigned char tape [ TAPE_SIZE_X ] [ TAPE_SIZE_Y ] ; int x = 336 ; int y = 67 ; void main ( void ) { system ( &quot;clear&quot; ) ; //clear screen srand ( time ( NULL ) ) ; //initialize random generator; TODO: port to C++ and use TRNG instead printf ( &quot;\e[?25l&quot; ) ; //disable cursor //TODO: Implement program input and conditional commands while ( 1 ) { switch ( inst [ rand ( ) % 4 ] ) { //MOVE case '&gt;' : x = x + 1 ; break ; case '&lt;' : x = x - 1 ; break ; case '^' : y = y + 1 ; break ; case 'V' : y = y - 1 ; break ; } if ( x &gt;= TAPE_SIZE_X ) x = 0 ; //TOROID CODES FOR OOB CURSOR else if ( x &lt; 0 ) x = TAPE_SIZE_X - 1 ; if ( y &gt;= TAPE_SIZE_Y ) y = 0 ; else if ( y &lt; 0 ) y = TAPE_SIZE_Y - 1 ; tape [ x ] [ y ] = tape [ x ] [ y ] + 1 ; // ADD 1 if ( tape [ x ] [ y ] == 8 ) tape [ x ] [ y ] = 0 ; usleep ( 16667 ) ; // CAP SPEED TO 60FPS : 1/60 seconds = 16666.666... microseconds printf ( &quot;\33[%d;%dH&quot;, y, x ) ; //print @ cursor position switch ( tape [ x ] [ y ] ) { //Color Code for Mem case 0 : printf ( &quot;\x1B[40m &quot; ) ; break ; case 1 : printf ( &quot;\x1B[41m &quot; ) ; break ; case 2 : printf ( &quot;\x1B[43m &quot; ) ; break ; case 3 : printf ( &quot;\x1B[42m &quot; ) ; break ; case 4 : printf ( &quot;\x1B[46m &quot; ) ; break ; case 5 : printf ( &quot;\x1B[44m &quot; ) ; break ; case 6 : printf ( &quot;\x1B[45m &quot; ) ; break ; case 7 : printf ( &quot;\x1B[47m &quot; ) ; break ; } fflush ( stdout ) ; //flush stdout to prevent abnormal lag in printing to screen } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>General Observations</h2>\n<p>Welcome to code review, nice first question. I would leave the licensing information out since stack exchange uses the <a href=\"https://stackoverflow.com/help/licensing\">Creative Commons Attribution-ShareAlike</a> license.</p>\n<p>The comment block at the top is rather helpful otherwise. FYI, this compiles fine on Windows 10 in Visual Studio 2019 Professional, but doesn't link (<code>usleep()</code> is undefined).</p>\n<p>Some of the code is a little difficult to read as there is vertical crowding, you might want to insert a few blank lines inside <code>main()</code> between logic blocks.</p>\n<h2>Avoid Global Variables</h2>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<h2>Declare and Initialize the Variables Where They are Needed</h2>\n<p>In the original version of C variables needed to be declared at the top of the logic block where they were used, this is no longer true, declare them as necessary.</p>\n<pre><code>void main(void) {\n char inst[] =\n {\n '&gt;',\n '&lt;',\n '^',\n 'V'\n };\n\n system(&quot;clear&quot;); //clear screen\n srand(time(NULL)); //initialize random generator; TODO: port to C++ and use TRNG instead\n printf(&quot;\\e[?25l&quot;); //disable cursor\n //TODO: Implement program input and conditional commands\n\n unsigned char tape[TAPE_SIZE_X][TAPE_SIZE_Y];\n int x = 336;\n int y = 67;\n\n while (1) {\n ...\n }\n}\n</code></pre>\n<h2>Let the Compiler Do More of the Work</h2>\n<p>In the code example above there is no size defined for the array <code>inst[]</code>, the compiler will fill this in based on the number of initialization values in the array. This makes it easier to write and maintain the code since the size doesn't need to be modified each time an instruction is added.</p>\n<h2>Magic Numbers</h2>\n<p>There are Magic Numbers in the <code>main()</code> function (336 and 67), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. You already define symbolic constants for <code>TAPE_SIZE_X</code> and <code>TAPE_SIZE_Y</code> the code would be more readable and understandable if the initialization values for <code>x</code> and <code>y</code> used symbolic constants, in this case you could possibly make the initialization half of the tape size for <code>x</code> and <code>y</code>.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<h2>Complexity</h2>\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>There are at least multiple functions in <code>main()</code>.</p>\n<ul>\n<li>//TODO: Implement program input and conditional commands</li>\n<li>Set up the screen</li>\n<li>The contents of the <code>while (1)</code> loop also seem to be multiple functions</li>\n</ul>\n<h2>Default Cases for <code>switch</code> Statements</h2>\n<p>While it isn't necessary in the current code, to prevent undefined behavior it is best to have a default case for every switch statement:</p>\n<pre><code> switch (inst[rand() % 4]) { //MOVE\n case '&gt;':\n x = x + 1;\n break;\n case '&lt;':\n x = x - 1;\n break;\n case '^':\n y = y + 1;\n break;\n case 'V':\n y = y - 1;\n break;\n default :\n printf(&quot;Unknown instruction in switch\\n&quot;);\n return 1;\n }\n</code></pre>\n<h2>Possible Optimization</h2>\n<p>The second <code>switch</code> statement could be replaced with a table of values and that would improve performance.</p>\n<pre><code> char* control_sequence[] =\n {\n &quot;\\x1B[40m &quot;,\n &quot;\\x1B[41m &quot;,\n &quot;\\x1B[43m &quot;,\n &quot;\\x1B[42m &quot;,\n &quot;\\x1B[46m &quot;,\n &quot;\\x1B[44m &quot;,\n &quot;\\x1B[45m &quot;,\n &quot;\\x1B[47m &quot;,\n };\n\n printf(&quot;%s&quot;, control_sequence[tape[x][y]]);\n fflush(stdout); //flush stdout to prevent abnormal lag in printing to screen\n</code></pre>\n<h2>Readability and Maintainability</h2>\n<p>As mentioned in the general observations, this section of code is very hard to read and even harder to maintain:</p>\n<pre><code> if (x &gt;= TAPE_SIZE_X) x = 0; //TOROID CODES FOR OOB CURSOR\n else if (x &lt; 0) x = TAPE_SIZE_X - 1;\n if (y &gt;= TAPE_SIZE_Y) y = 0;\n else if (y &lt; 0) y = TAPE_SIZE_Y - 1;\n tape[x][y] = tape[x][y] + 1; // ADD 1\n if (tape[x][y] == 8) tape[x][y] = 0;\n usleep(16667); // CAP SPEED TO 60FPS : 1/60 seconds = 16666.666... microseconds\n printf(&quot;\\33[%d;%dH&quot;, y, x); //print @ cursor position\n</code></pre>\n<p>In languages like C, C++ or Java put action code such as <code>x = 0;</code> on its own line, preferably in braces, that makes the action easier to find, and with the braces easier to maintain by adding more statements later:</p>\n<pre><code> if (x &gt;= TAPE_SIZE_X)\n {\n x = 0;\n }\n else if (x &lt; 0)\n {\n x = TAPE_SIZE_X - 1;\n }\n if (y &gt;= TAPE_SIZE_Y)\n {\n y = 0;\n }\n else if (y &lt; 0)\n {\n y = TAPE_SIZE_Y - 1;\n }\n\n tape[x][y] = tape[x][y] + 1; // ADD 1\n if (tape[x][y] == 8)\n {\n tape[x][y] = 0;\n }\n\n usleep(16667); // CAP SPEED TO 60FPS : 1/60 seconds = 16666.666... microseconds\n printf(&quot;\\33[%d;%dH&quot;, y, x); //print @ cursor position\n</code></pre>\n<p>An example of how hard the original code is to read is that I missed the magic number <code>8</code> in the discussion of magic numbers above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T16:42:00.483", "Id": "250331", "ParentId": "250303", "Score": "6" } }, { "body": "<h1>Don't use <code>system()</code> for trivial tasks</h1>\n<p>Calling <code>system()</code> means starting a new shell process, which in turn has to parse the command and execute it. The <code>clear</code> command is not a built-in for Bash, so the shell in turn will start a new process to execute <code>/usr/bin/clear</code>. And it's just a program, it's not magic; <code>clear</code> itself is also written in C. And all it eventually does is just print an escape sequence, like you already do in your program. You can replace <code>system(&quot;clear&quot;)</code> with:</p>\n<pre><code>printf(&quot;\\e[1;1H\\e[2J&quot;);\n</code></pre>\n<h1>Consider using ncurses</h1>\n<p>You are relying on escape sequences that, as you already mention in the comments, don't work on every system. Luckily, there's a library that provides this functionality in a cross-platform (and cross-terminal) way: <a href=\"https://en.wikipedia.org/wiki/Ncurses\" rel=\"nofollow noreferrer\">ncurses</a>. In fact, the <code>clear</code> command you called is part of the ncurses package. But it's even better, ncurses allows you to move the cursor to arbitrary positions, change colors, and so on.</p>\n<h1>Avoid repeating yourself</h1>\n<p>Whenever you are repeating the same thing twice or more times, you should find a way to automate it. For example, you can replace the second <code>switch</code>-statement with:</p>\n<pre><code>printf(&quot;\\x1B[%dm &quot;, 40 + tape[x][y]);\n</code></pre>\n<h1>Create functions for sub-problems.</h1>\n<p>Even if you don't repeat yourself, it might make sense to create a new function to handle a small problem. This usually makes the code more easy to read. For example, you warp and clamp the <code>x</code> and <code>y</code> coordinates after moving the position, you could create functions to do this, for example:</p>\n<pre><code>static int wrap(int value, int limit) {\n if (value &lt; 0)\n return limit - 1;\n else if (value &gt;= limit)\n return 0;\n else\n return value;\n}\n</code></pre>\n<p>And use it like so:</p>\n<pre><code>switch(...) {\ncase '&gt;':\n x = wrap(x + 1, TAPE_SIZE_X);\n break;\ncase '&lt;':\n x = wrap(x - 1, TAPE_SIZE_X);\n break;\n...\n</code></pre>\n<h1>Don't hardcode the screen size</h1>\n<p>When I tried to run your program, I thought it was buggy at first, but it turns out it requires a terminal that is 672 by 135 characters big. Find some way to get the current size of the terminal. You could use <code>atoi(getenv(&quot;COLUMNS&quot;))</code> and <code>atoi(getenv(&quot;LINES&quot;))</code> on UNIX-like operating systems, but again using a library like ncurses will take care of this for you.</p>\n<h1>Complete example</h1>\n<p>Below is your program, but using <code>ncurses</code>. Since <code>ncurses</code> already tracks the contents of the screen, including the color used at each position, it no longer needs the array <code>tape[][]</code>.</p>\n<p>As pacmaninbw mentioned, also avoid hardcoding numbers, and <code>#define</code> or declare them as <code>static const int</code> instead.</p>\n<pre><code>#include &lt;ncurses.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\nstatic int clamp(int value, int limit) {\n if (value &lt; 0)\n return 0;\n else if (value &gt;= limit)\n return limit - 1;\n else\n return value;\n}\n\nstatic int wrap(int value, int limit) {\n if (value &lt; 0)\n return limit - 1;\n else if (value &gt;= limit)\n return 0;\n else\n return value;\n}\n\nvoid main(void)\n{\n srand(time(NULL));\n\n /* Initialize the screen and colors */\n\n initscr();\n curs_set(0);\n start_color();\n\n static const int max_colors = 8;\n\n for (int i = 0; i &lt; max_colors; i++)\n init_pair(i, COLOR_WHITE, i);\n\n int x = COLS / 2;\n int y = LINES / 2;\n\n /* Set the delay for keyboard input */\n\n static const int framerate_limit = 60; /* Hz */\n timeout(1000 /* ms */ / fraterate_limit);\n\n /* Main loop */\n\n while (getch() == ERR) {\n switch (rand() % 4) {\n case 0: x = wrap(x + 1, COLS); break;\n case 1: x = wrap(x - 1, COLS); break;\n case 2: y = clamp(y + 1, LINES); break;\n case 3: y = clamp(y - 1, LINES); break;\n }\n\n int cur_color = PAIR_NUMBER(mvinch(y, x));\n int new_color = wrap(cur_color + 1, max_colors);\n chgat(1, A_NORMAL, new_color, NULL);\n refresh();\n }\n\n endwin();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T09:19:52.367", "Id": "491318", "Score": "1", "body": "`timeout(1000 / 60)` lacks time units context. Perhaps `#define KDB_DELAY_ms (1000/60) timeout(KDB_DELAY_ms);` or simply `timeout(1000 /* ms */ / 60)`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T16:44:05.860", "Id": "250332", "ParentId": "250303", "Score": "6" } } ]
{ "AcceptedAnswerId": "250331", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T05:56:28.050", "Id": "250303", "Score": "5", "Tags": [ "performance", "algorithm", "c", "random", "ascii-art" ], "Title": "ASCII Random Walk Algorithm" }
250303
<p>Trying to get my first job as a developer I made an app I was extremely proud of:<br /> <a href="https://github.com/AnatolyRudenko/Crystals.Dragons" rel="nofollow noreferrer">https://github.com/AnatolyRudenko/Crystals.Dragons</a><br /> The game starts in a random room of a random maze. Some prebuilt items get randomly located all around the maze. User can see arrows (from 1 to 4 depending on directions available to move in) and items (if there are any in current room) on his screen. You can interact with the items: pick it up, use it, drop it or destroy it. Picked up items go to inventory which is a collectionView. To win you've got find a key and open a chest with it. Any time you travel from one room to another - you lose HP.<br /> But the feedback received on the app absolutely smashed me:</p> <ol> <li>Extremely poor realization of item pick-up. Everything is bad about that. Starting with creating an item in a room and ending with defining what item is in inventory. Items are rigidly bound to images, fixed number of items in the game.</li> <li>Items have no identifiers. Identification by name is a bad decision.</li> <li>OOP is weak. Some classes are there just for the sake of it. But neither polymorphism nor inheritance are used. Even though there are a lot of opportunities to do so.</li> </ol> <p>The problem is that due to lack of experience I can't even imagine another way of building this app. The most confusing point to me is 1). But if someone could give a hint on how to fix 2) and 3), that would be much appreciated.<br /> 1)-relevant code:<br /> <code>Item.swift</code>:</p> <pre><code>struct Item { let imageName: String let description: String } </code></pre> <p><code>ItemsList.swift</code>:</p> <pre><code>struct ItemsList { var items = [ Item(imageName: K.icons.chest, description: K.descriptions.chest), Item(imageName: K.icons.key, description: K.descriptions.key), Item(imageName: K.icons.rock, description: K.descriptions.rock), Item(imageName: K.icons.bone, description: K.descriptions.bone), Item(imageName: K.icons.mushroom, description: K.descriptions.mushroom), Item(imageName: K.icons.apple, description: K.descriptions.apple) ] } </code></pre> <p><code>CurrentData.swift</code>:</p> <pre><code>struct CurrentData { var itemsList = ItemsList() var items = [Item]() var maze: MazeGenerator var cell: MazeElement var size: Int var location: (x: Int, y: Int) { didSet { cell = maze.maze[location.x][location.y] } } var createdImages: [UIImageView] = [] var collectedImages: [(collectedIndex: Int, item: Int, image: UIImage)] = [] var itemLocationArray: [(Int, Int)] = [] var itemCollected: Int? var collectedImagesIndex = -1 var cellSelected: Int? init(howManyRooms: Int) { self.size = Int(ceil(sqrt(Double(howManyRooms)))) self.location = (Int.random(in: 0...self.size-1), Int.random(in: 0...self.size-1)) items = itemsList.items maze = MazeGenerator(self.size, self.size) //generate a maze cell = maze.maze[location.x][location.y] } } </code></pre> <p><code>GameplayViewController.swift</code>:</p> <pre><code>class GameplayViewController: UIViewController { private var current: CurrentData? private func startGame() { current = CurrentData.init(howManyRooms: rooms) for index in 0...current!.items.count-1 { createItems(imageName: current!.items[index].imageName) let itemLocation = (Int.random(in: 0...current!.size-1), Int.random(in: 0...current!.size-1)) //Every item gets random location current?.itemLocationArray.append(itemLocation) } } private func createItems(imageName: String) { //Create item images when launched let imageNamePNG = &quot;\(imageName).png&quot; let itemImage = UIImage(named: imageNamePNG) let itemImageView = UIImageView(image: itemImage) if let freeSpace = self.freeSpace { itemImageView.frame = CGRect( x: Int.random(in: Int(freeSpace.minX) ... Int(freeSpace.maxX)), //item images can't cover arrows or inventoryView y: Int.random(in: Int(freeSpace.minY) ... Int(freeSpace.maxY)), width: 63, height: 63) } let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) itemImageView.isUserInteractionEnabled = true itemImageView.addGestureRecognizer(tapGestureRecognizer) //item image can be tapped view.addSubview(itemImageView) current?.createdImages.append(itemImageView) } @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) { //item gets tapped let tappedImageView = tapGestureRecognizer.view as! UIImageView if let tappedImage = tappedImageView.image { if tappedImageView != current!.createdImages[0] { //can't pick up the chest tappedImageView.isHidden = true tappedImageView.isUserInteractionEnabled = false current?.collectedImagesIndex += 1 //keep track of the order in which we pick up the items current?.itemCollected = current!.createdImages.firstIndex(of: tappedImageView) //find out what item was picked if let whatItem = current!.itemCollected { current?.collectedImages.append((current!.collectedImagesIndex, whatItem, tappedImage)) } collectionView.reloadData() } else { descriptionLabel.text = current!.items[0].description //if chest was tapped } } } } // MARK: - UICollectionViewDataSource protocol extension GameplayViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int { return current?.collectedImages.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.Cell.reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell cell.inventoryImageView.image = current?.collectedImages[indexPath.item].image return cell } // MARK: - UICollectionViewDelegate protocol func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { for image in current!.collectedImages { if indexPath.item == image.collectedIndex { descriptionLabel.text = current?.items[image.item].description current?.cellSelected = indexPath.item } } } } </code></pre> <p>Any help is much appreciated! Thanks</p>
[]
[ { "body": "<p>Your problems include:</p>\n<ul>\n<li>naming</li>\n<li>not following MVC</li>\n<li>inconsistent optionality decisions</li>\n<li>having only a single view controller</li>\n<li>not keep separate things separate</li>\n<li>naming things inconsistently</li>\n</ul>\n<ol>\n<li>Naming is important. You have:</li>\n</ol>\n<ul>\n<li>var maze: MazeGenerator - A maze is not a maze generator.</li>\n<li>var cell: MazeElement - Choose cell or element and stick with one word for it.</li>\n<li>var createdImages: [UIImageView] - an image is not an imageView</li>\n</ul>\n<ol start=\"2\">\n<li><p>MVC: Model types shouldn't be aware of UI.\nWhen designing your application it might be useful to consider there will be two or more things that will use your application: the iOS UI itself, a command-line interface, and your unit tests. This means in the model, something like:</p>\n<p>var createdImages: [UIImageView]</p>\n</li>\n</ol>\n<p>obviously doesn't belong in the model, because it ties your model to your UI.</p>\n<ol start=\"3\">\n<li>Inconsistent optionality decisions</li>\n</ol>\n<p>A statement like:</p>\n<pre><code> current?.itemCollected = current!.createdImages.firstIndex(of: tappedImageView) \n</code></pre>\n<p>shows that the optionality of 'current' is not clear. You should decide whether you want to force unwrap (crash if nil) or optional-chain (do nothing if nil).</p>\n<p>Even better is to avoid the optionality altogether. When it's defined, you have:</p>\n<pre><code>private var current: CurrentData?\n</code></pre>\n<p>Clearly that's an optional model. You're saying this view controller might not have a model, and that's because you have another design issue which is that you don't split out your view controllers. The same view controller is used for three states: before, during and after gameplay. Instead, if you have, for example, a GameSetupViewController, a GameViewController and a GameFinishedViewController, now you can have 'CurrentData' as a real, genuine, non-optional 'CurrentData' on GameViewController. Splitting up to even more view controllers would be good too, an InventoryViewController, a RoomViewController etc.</p>\n<p>If you write an if condition that has (or needs) a comment that explains the if condition, then you should remove the comment, and rewrite the if condition. For example:</p>\n<pre><code>if tappedImageView != current!.createdImages[0] { //can't pick up the chest\n</code></pre>\n<p>Rewrite that as:</p>\n<pre><code>let canPickUpItem = tappedImageView != current.createdImages[0]\n\nif canPickUpItem { ... }\n</code></pre>\n<p>And then consider MVC: where should you put the code to decide if an item can be picked up? Here it is the ViewController, but this is a job for the model. Your controller method then becomes:</p>\n<pre><code>@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) { //item gets tapped\n let tappedImageView = tapGestureRecognizer.view as! UIImageView\n // Get the item associated with that image view ...\n // tell the model that the user wanted to pick up item ...\n }\n</code></pre>\n<p>The ViewController should then monitor changes in the model, so that when the item is collected, you update the UI.</p>\n<p>Then over in the model we should decide if an item is collectable or not: e.g.</p>\n<pre><code>struct Item {\n let imageName: String\n let description: String\n let isCollectable: Bool \n}\n</code></pre>\n<p>There are other ways you could do it. You could have isCollectable be a function (maybe it returns something like a reason why you can't pick it up, maybe if it is collectable depends on the GameState).</p>\n<p>For mapping between the game model's item location and your viewController's image views:\nHiding and showing imageViews is not ideal.</p>\n<p>When the room changes, I would remove all the image views and make new ones for all the items in that room.</p>\n<p>When creating your imageViews and tap gesture recognizers, one of the things you need to do is determine which item they are. One trick to do that is to recognize that the target object doesn't need to be 'self,' i.e. the ViewController. If you use a general-purpose object that can wrap any block of code that you like:</p>\n<pre><code>final class TargetAction {\n let work: () -&gt; Void\n\n init(_ work: @escaping () -&gt; Void) {\n self.work = work\n }\n\n @objc func action(_ sender: Any) {\n work()\n }\n}\n</code></pre>\n<p>Now when the room changes, and your viewController makes item image views: you can do e.g.:</p>\n<pre><code>for item in currentRoomItems {\n let imageView = ...\n\n let didWantToPickUp = TargetAction { [weak self] in\n self?.model.userDidWantToPickUp(item)\n }\n\n imageView.addTarget(didWantToPickUp, action: #selector(TargetAction.action(_:))\n}\n</code></pre>\n<p>&quot;defining what item is in inventory&quot;:\nI would expect something like an array or a set, of Item identifiers, in the model, that represents what the user has collected. If Item were a class not a struct, then an array of the objects themselves.</p>\n<p>This way you don't need something like collectedImagesIndex to keep track of the order in which we pick up the items. The model's array of collected items does that.</p>\n<p>Here's an example of code that is a problem:</p>\n<pre><code>if current?.items[image.1].imageName == K.icons.apple\n</code></pre>\n<ul>\n<li>The if statement is tricky to read</li>\n<li>Current is optional, and could be better named</li>\n<li>The testing for equality using just the imageName (and controller deciding how to test for equality)</li>\n<li>This is game logic, so it should be in the model not the viewController.</li>\n</ul>\n<p>If you make a custom type, like Item, and two items need to be able to compare themselves for equality, you should make the type conform to Swift's Equatable protocol. Your controller should then be able to say if itemA == itemB, and have the type define for itself what it means to be the same.</p>\n<p>In the 'use' function you actually want this equatability to check whether certain special logic is required. And you have an &quot;if else ladder&quot;. This kind of design is often not as good as putting the logic on the type itself. For example:</p>\n<pre><code>struct Item {\n let imageName: String\n let description: String\n let hpToAddWhenUsed: Int // How much to add or subtract on use\n let isFinalKey: Bool // means if used with chest then you win the game\n}\n</code></pre>\n<p>or more flexibly:</p>\n<pre><code>struct Item {\n let imageName: String\n let description: String\n var use: ((inout GameState) -&gt; Void)?\n}\n</code></pre>\n<p>This is saying an item can have a 'use' function that means an item can have custom logic.\nYour controller's use function then dispatches the use to the model, the model then says run any custom logic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-16T19:28:15.413", "Id": "250761", "ParentId": "250306", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T08:44:28.160", "Id": "250306", "Score": "1", "Tags": [ "object-oriented", "swift" ], "Title": "\"Pick up\" images when tapped on and keep track of it" }
250306
<p>I created a class to scrape URLS, parse and validate emails and get internal links.</p> <p>How can I achieve the SOLID principles in this class written in Javascript to make a web scraper?</p> <pre><code>const axios = require('axios'); const fs = require('fs') const { JSDOM } = require('jsdom'); class Scraper { static dangerDomains = ['loan', 'work', 'biz', 'racing', 'ooo', 'life', 'ltd', 'png']; static emailRegex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi; static domObject = null; static internalLinks = new Set(); static externalLinks = new Set(); constructor(url) { this.url = url; this.emails = new Set(); this.dangerEmails = new Set(); } async executeScraper() { const fetchedData = await this.fetchUrlAndGetDom(this.url); const links = await this.getInternalLinks(); const linksArray = Array.from(Scraper.internalLinks); const emails = await this.fetchInternalLinks(linksArray); this.addEmails(emails); this.validateEmails(); await this.writeFile(); } const result = async fetchInternalLinks(internalLink) { const result = await Promise.all(internalLink.map((link) =&gt; { return this.fetchUrlAndGetDom(`${this.url}${link}`); })); return result; } async fetchUrlAndGetDom(url) { try { const response = await axios(url); if (response.status === 200) { let htmlData = await response.data; Scraper.domObject = await new JSDOM(htmlData); let dades = this.searchForEmails(); return dades; } else if (response.status === 404) { console.log('this page doesnt exists') return process.exit(1); } } catch (error) { console.log(error) return process.exit(1); } } </code></pre> <blockquote> <p>Get all the internal links from a website to scrape them</p> </blockquote> <pre><code> getInternalLinks() { let links = Scraper.domObject.window.document.body; links = links.querySelectorAll('a[href^=&quot;/&quot;]'); Array.from(links).filter(link =&gt; Scraper.internalLinks.add(link.getAttribute('href'))); } </code></pre> <blockquote> <p>Use of a regex to find all the emails in the dom</p> </blockquote> <pre><code> searchForEmails() { let emailsInDom = Scraper.domObject.window.document.body.innerHTML; let emails = emailsInDom.toString().match(Scraper.emailRegex) return emails; } </code></pre> <blockquote> <p>Validate all the emails found in the dom</p> </blockquote> <pre><code> validateEmails() { const validatedEmails = Array.from(this.emails).filter(email =&gt; { let domainName = email.split('@')[1].split('.')[1]; if (Scraper.dangerDomains.includes(domainName)) { this.dangerEmails.add(email); this.emails.delete(email); } else return email; }); } </code></pre> <blockquote> <p>Write the emails in a file</p> </blockquote> <pre><code> async writeFile() { return new Promise((resolve, reject) =&gt; { fs.writeFile('./emails.txt', Array.from(this.emails), err =&gt; { if (err) reject('Could not write file'); resolve('success'); }); }); } </code></pre> <blockquote> <p>Add email to the propertie emails</p> </blockquote> <pre><code> addEmails(emailsInDom) { Array.from(emailsInDom).filter(el =&gt; { if(el !== null) { el.filter(el =&gt; this.emails.add(el)) } }); } } </code></pre> <blockquote> <p>This execute the scraper</p> </blockquote> <pre><code>const Scraper = require('./Scraper'); const scraper = new Scraper('any url'); (async () =&gt; { try { const dades = await scraper.executeScraper(); } catch (e) { console.log(e) } })() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T12:23:13.167", "Id": "491120", "Score": "0", "body": "Opinion: you are using a class to encapsulate a library of web scraping utility functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T13:57:01.883", "Id": "491124", "Score": "0", "body": "It looks like you never call `getExternalLinks`. Is that deliberate, or is some of the code missing? Maybe edit in an example of how the class is used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:20:37.187", "Id": "491132", "Score": "0", "body": "Scrapper != Scraper" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:50:17.590", "Id": "491137", "Score": "0", "body": "I remove getExternalLinks because I don't use it. Also correct the orthography. I add the way that I execute the scraper. It's better to use functional programing or OOP in this case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T15:36:42.097", "Id": "491149", "Score": "0", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/250307/revisions#rev-arrow-8424d5f6-62c7-4eba-9ca2-bd4d92e39507) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:08:31.323", "Id": "491161", "Score": "2", "body": "PS your email regex is woefully inadequate: https://stackoverflow.com/q/201323/4400820" } ]
[ { "body": "<p>I choose to focus on the Single Responsibility Principle in this answer.</p>\n<p>To move closer to the Single Responsibility Principle, I think some of the functionality needs to be moved around. I have decomposed the class and removed all state that is shared on the class (rhetorical question: is the class responsible for state or functionality? If it is &quot;both&quot;, then surely that violates SRP?!). Shared state like this can get tough to reason about and lead to an ever-larger class as the functionality evolves over time.</p>\n<p>How about a <code>scraper</code> object, with one method <code>run</code> that accepts a URL and returns the result for a URL (and its sub-URLs)?</p>\n<p>Usage:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>import scraper from './scraper.js'\n\nconst { emails: { valid, dangerous }, links: { internal } } = await scraper.run('http://www.example.com')\n</code></pre>\n<p>We configure a <code>result</code> object which we then pass around to populate, before it is returned:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const scraper = {\n async run(url) {\n const result = {\n emails: { valid: [], dangerous: [] },\n links: { internal: [] }\n }\n return scrape(url, result)\n }\n}\n</code></pre>\n<p>We define a <code>scrape</code> function, responsible for coordinating the scraping of a URL:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>async function scrape(url, result, visited=new Set()) {\n if (visited.has(url)) {\n return result\n }\n\n visited.add(url)\n const dom = await fetchDom(url)\n const internalLinks = findInternalLinks(dom)\n const { valid, dangerous } = validateEmails(findEmails(dom))\n\n for (let link of internalLinks) {\n await scrape(link, result, visited)\n }\n\n result.links.internal.push(...internalLinks)\n result.emails.valid.push(...valid)\n result.emails.dangerous.push(...dangerous)\n\n return result\n}\n</code></pre>\n<p>Function <code>fetchDOM</code> is responsible for retrieving the DOM from the network for a URL:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>async function fetchDOM(url) {\n try {\n const { status, data } = await axios(url)\n switch (status) {\n case 200:\n return new JSDOM(await data)\n case 404:\n console.log('this page doesnt exists')\n return process.exit(1)\n }\n } catch (error) {\n console.log(error)\n return process.exit(1)\n }\n}\n</code></pre>\n<p><code>findInternalLinks</code> is responsible for returning an array of internal links, found within the supplied DOM:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function findInternalLinks({ window: { document: body } }) {\n let links = body.querySelectorAll('a[href^=&quot;/&quot;]')\n return Array.from(links).map(link=&gt;link.getAttribute('href'))\n}\n</code></pre>\n<p><code>findEmails</code> is responsible for returning the an array of emails, found within the supplied DOM:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const EMAIL_REGEX = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)/gi\n\nfunction findEmails({ window: { document: { body: { innerHTML: html } } }) {\n return html.toString().match(EMAIL_REGEX)\n}\n</code></pre>\n<p><code>validateEmails</code> splits an array of emails into two sets: <code>valid</code> and <code>dangerous</code>:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const DANGEROUS_DOMAINS = ['loan', 'work', 'biz', 'racing', 'ooo', 'life', 'ltd', 'png']\n\nfunction validateEmails(emails) {\n const dangerous = []\n const valid = Array.from(emails).filter(email=&gt;{\n let domainName = email.split('@')[1].split('.')[1]\n if (DANGEROUS_DOMAINS.includes(domainName)) {\n dangerous.add(email)\n return false\n } else\n return true\n })\n return { valid, dangerous }\n}\n</code></pre>\n<p>The writing of a file is a wholly separate responsibility. Perhaps create an <code>emailFileWriter</code> object to encapsulate it:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const emailFileWriter = {\n write(emails) {\n return new Promise((resolve,reject)=&gt;{\n fs.writeFile('./emails.txt', emails, err=&gt;{\n if (err) {\n reject('Could not write file')\n }\n resolve('success')\n })\n })\n }\n}\n</code></pre>\n<p>I would put each of these functions and objects in a separate file. Each has its own responsibility after all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T15:18:58.123", "Id": "250326", "ParentId": "250307", "Score": "4" } }, { "body": "<h2>Bug: no assignment when calling <code>filter</code></h2>\n<p>There are places where <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.filter()</code></a> is called but not assigned to anything.</p>\n<blockquote>\n<pre><code>Array.from(links).filter(link =&gt; Scraper.internalLinks.add(link.getAttribute('href')));\n</code></pre>\n</blockquote>\n<p>and this in <code>addEmails()</code></p>\n<blockquote>\n<pre><code>Array.from(emailsInDom).filter(el =&gt; {\n if(el !== null) {\n el.filter(el =&gt; this.emails.add(el))\n }\n});\n</code></pre>\n</blockquote>\n<h2>Suggestions</h2>\n<h3>Handling Response cases</h3>\n<p>The code in <code>fetchUrlAndGetDom()</code> handles responses of <code>200</code> and <code>404</code>. What about <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status\" rel=\"nofollow noreferrer\">the other numerous cases</a>?</p>\n<p>The <code>else</code> in that <code>if</code>/<code>else</code> sequence is superfluous, since the <code>if</code> block contains a <code>return</code> statement.</p>\n<h3>Variable declarations</h3>\n<p>It is recommended to default to using <code>const</code> instead of <code>let</code> for all variables as it can <a href=\"https://softwareengineering.stackexchange.com/q/278652/244085\">cause bugs</a>. When you determine re-assignment is necessary (mostly for loop/iterator variables) then use <code>let</code>. Some variables are already declared with <code>const</code> but others could be declared with <code>const</code> instead of <code>let</code> - e.g. <code>htmlData</code> in <code>fetchUrlAndGetDom()</code>, <code>links</code> in <code>getInternalLinks()</code>, etc.</p>\n<h3>Variable naming</h3>\n<p>Some variables are inappropriately named. For example, the method <code>executeScraper</code> passes an array to the method <code>fetchInternalLinks</code>:</p>\n<blockquote>\n<p>const emails = await this.fetchInternalLinks(linksArray);</p>\n</blockquote>\n<p>Yet the signature is:</p>\n<blockquote>\n<pre><code>const result = async fetchInternalLinks(internalLink) {\n const result = await Promise.all(internalLink.map((link) =&gt; {\n return this.fetchUrlAndGetDom(`${this.url}${link}`);\n }));\n return result;\n}\n</code></pre>\n</blockquote>\n<p>Not only is <code>result</code> assigned to the function (which seems superfluous), the parameter is <code>internalLink</code>, yet it is passed an array and treated as an array (since the <code>.map()</code> method is called on it). A better name for that argument would be <code>internalLinks</code>.</p>\n<h3>NodeList to array</h3>\n<p>There are a few places where <code>Array.from()</code> is called to put elements of a NodeList to an array. Some of those can be simplified by using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a>. For example, instead of:</p>\n<blockquote>\n<pre><code>Array.from(links).filter(link =&gt; Scraper.internalLinks.add(link.getAttribute('href')));\n</code></pre>\n</blockquote>\n<p>It can be:</p>\n<pre><code>[...links].filter(link =&gt; Scraper.internalLinks.add(link.getAttribute('href')));\n</code></pre>\n<h3>Simplifying Regular Expressions</h3>\n<p>The Character class <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types\" rel=\"nofollow noreferrer\"><code>\\w</code></a> can be used instead of <code>[A-Za-z0-9_]</code>. As was mentioned in a comment, <a href=\"https://stackoverflow.com/q/201323/1575353\">validating an email address with a regular expression is not an easy feat</a>. There are packages that could be used in NodeJS - e.g. <a href=\"https://www.npmjs.com/package/email-validator\" rel=\"nofollow noreferrer\">email-validator</a>, <a href=\"https://github.com/bmshamsnahid/validate-email-address-node-js\" rel=\"nofollow noreferrer\">validate-email-address-node-js</a>, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T15:34:28.890", "Id": "250327", "ParentId": "250307", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T09:06:08.777", "Id": "250307", "Score": "4", "Tags": [ "javascript", "object-oriented", "design-patterns", "node.js", "web-scraping" ], "Title": "web scraper for emails and links" }
250307
<p>I made a simple program as an exercise in improving my code flow in Python, which does the following:</p> <ol> <li>asks user to input their name</li> <li>presents them with a choice to either print their name in reverse, or print the number of characters</li> <li>after the output is printed, the user is asked if they want to &quot;play again&quot;. if not, exits</li> </ol> <p>Have I done anything especially goofy? Any low hanging fruit? Best practice I'm unaware of?</p> <pre><code>from sys import exit def userinput(): print('Enter your name:') n = input() print('Hello, ' + n + ', would you rather (R)everse or (C)ount the letters of your name?') a = input() return (a,n) def choosef(choice,myname): while choice not in ['R','C']: print(&quot;Only 'R' or 'C' are valid. Try again:&quot;) choice = input() if choice == 'R': print(''.join(reversed(myname))) else: spaces = 0 for c in list(myname): if c == ' ': spaces = spaces + 1 print('Total # Characters: ' + str(len(myname) - spaces)) playagain() def playagain(): print(&quot;Would you like to play again, (Y)es or any other character to exit?&quot;) yn = input() if yn == 'Y': ui = userinput() choosef(ui[0],ui[1]) else: exit() ui = userinput() choosef(ui[0],ui[1]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T17:29:21.600", "Id": "491157", "Score": "0", "body": "@AryanParekh after only 11 hours, I don't see why OP would be pressed to do this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:05:28.630", "Id": "491159", "Score": "0", "body": "@BCdotWEB I had originally posted this on Stack Overflow but it was migrated here. Because the two forums serve different purposes, I don't understand how a post can maintain a fitting title after such migrations. There is a recommended edit to change the title to \"Simple Beginner Python Console Game\". But the fact the code happened to make a \"console game\" is completely irrelevant to the guidance I was seeking. I was hoping to draw the attention of people who are especially knowledgeable about code structure, not console games. Can you help me understand a bit better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T09:57:39.347", "Id": "491214", "Score": "1", "body": "Don't worry about the migration - just keep in mind to use a descriptive title if you happen to post again on Code Review in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T23:17:48.037", "Id": "491277", "Score": "0", "body": "@BCdotWEB - I read your comment and the link before I responded. To clarify, I'm less confused about title guidelines on CodeReview than I am about the rationale for migrating my post from StackExchange to CodeReview in the first place. From your link: \"If your code does not have a goal, then it is likely that...you are asking about best practices in general...such questions are off-topic for Code Review.\" In my post, I explicitly asked about any \"best practice I'm unaware of?\" Should I request a different migration (e.g. Software Engineering), or just accept the less relevant title edit?" } ]
[ { "body": "<p>You can have a better structure. Here is detailed explanation.\nData Flow Errors which you should not do in real world:</p>\n<ul>\n<li>Here, your function calls don't make sense. Whenever you define and use functions, define them in such a way that they don't call each other i. e. there should be tree structure. Main function will control all. (See Below Code to get glimpse.)</li>\n<li>Your script can have better structure. See Below Code.</li>\n</ul>\n<p>*** <strong>PROTIP: If you want to make your code more maintainable, break it into modules and put all of them in different files and import them</strong> ***</p>\n<pre><code>def take_name_input():\n print('Enter your name:')\n n = input()\n return n\n\ndef ask_choice():\n print('Hello, ' + n + ', would you rather (R)everse or (C)ount the letters of your name?')\n a = input()\n return a\n\ndef playgame(myname):\n while True:\n choice = ask_choice()\n if choice == 'R':\n print(''.join(reversed(myname)))\n elif choice == 'C':\n for c in list(myname):\n if c == ' ':\n spaces = spaces + 1\n print('Total # Characters: ' + str(len(myname) - spaces))\n else:\n break\n\nname = take_name_input()\nplaygame(name)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:26:00.073", "Id": "250310", "ParentId": "250309", "Score": "2" } }, { "body": "<p>I think the structure is quite convoluted, with calls to input() and choosef() scattered in multiple places/levels, thus the program is not super readable and not scalable (if you had to handle more user inputs).</p>\n<p>A more readable approach would be a main loop like - in pseudo code</p>\n<pre><code>while True:\n Get user input from 3 choices R / C / E(xit)\n if input = E:\n exit\n else if input = R:\n handle R case\n else \n handle C case\n</code></pre>\n<p>Also in python there is a shorter way to reverse a string with slicing syntax: &quot;abc&quot;[::-1]</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:44:09.197", "Id": "491100", "Score": "0", "body": "Looking back at my original program, it is looking more like an exercise in deliberate code obfuscation than an honest attempt at structuring a simple program. I suck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T11:20:03.897", "Id": "491218", "Score": "1", "body": "@ZeroDadeCoolMurphy - don't despair; we all have to learn. I'd been a professional programmer for years when I switched from COBOL to Visual Basic and I honestly think I'd be torn between shuddering and laughing out loud if I went back and looked at my first efforts in VB now (and it was production code too! Bonus ego-hit!); we've all been there. We learn and improve, and eventually you'll be back here helping others with exactly the same sorts of issues you're having now. If your code actually did what you wanted you're already ahead of an awful lot of programmers I've worked with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T23:21:11.657", "Id": "491278", "Score": "1", "body": "Yep, my original language is 'q\" (from kdb+), which has it's own very distinct idiomatic approach to clean programming. The switch to Python has been trying at times." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:37:26.510", "Id": "250311", "ParentId": "250309", "Score": "2" } }, { "body": "<p>There are two area's where your code could improve further.</p>\n<p>First you can run tools like flake8 or pylint to check your code for 'violations' of PEP8. PEP8 is a Python style guide that is accepted as the de facto style for Python code. I won't focus on this since this mostly an automatic process and a somewhat personal choice.</p>\n<p>Secondly you can make some improvements to your code with regards to naming and documentation. This is what we call the readability of your code. I've taken a shot at this myself and this is what I (personally) find to be better code.</p>\n<p>One thing you can improve is removing all <em>magic</em> from your code. In the two lines below you set a variable <code>ui</code> and then pass the first and second element to another function. If I see these two lines, I have no idea what you're doing.</p>\n<pre><code>ui = userinput()\nchoosef(ui[0],ui[1])\n</code></pre>\n<p>This can be simplified and made more readable by selecting better variable names and (in this case at least) using tuple unpacking:</p>\n<pre><code>action, name = get_user_input()\nhandle_user_action(action, name)\n</code></pre>\n<p>The example above can be applied throughout your code. I always judge my code (and the code I review) with the question: <em>&quot;If I show this block of code to someone, is the intention of the code clear to the person reading it, without requiring knowledge of the entire program?&quot;</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T07:04:26.453", "Id": "491101", "Score": "0", "body": "I actually did try to implement your last suggestion, but I must have screwed up the syntax because it kept giving me an error. Thanks for getting me back on the right track." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:39:33.803", "Id": "250312", "ParentId": "250309", "Score": "0" } }, { "body": "<p>Try to forget everything that you know about the code, and assume that you aren't the author. Imagine yourself to be a third person reading the code, he/she knows nothing about it and just reading it for the first time.</p>\n<pre class=\"lang-py prettyprint-override\"><code>ui = userinput()\nchoosef(ui[0],ui[1])\n</code></pre>\n<p>Alright, <code>userinput()</code> must take some input and put it into <code>ui</code>. Makes sense, but what is <code>choosef()</code>?.</p>\n<h2>Naming convention</h2>\n<p>Use <a href=\"https://medium.com/coding-skills/clean-code-101-meaningful-names-and-functions-bf450456d90c#:%7E:text=How%20meaningful%20%3F,does%20not%20reveal%20its%20intent.\" rel=\"nofollow noreferrer\">meaningful</a> names for functions and variables. take this example</p>\n<pre class=\"lang-py prettyprint-override\"><code>x = 3.14\ny = 24\n</code></pre>\n<p>what is <code>x</code> and <code>y</code> to the reader? Is that the price of something?</p>\n<pre class=\"lang-py prettyprint-override\"><code>pi_value = 3.14\nnumber_of_hours = 24\n</code></pre>\n<p>Ahhh okay, now I know exactly what <code>3.14</code> means. So If I use it somewhere the reader will also know what I exactly mean. This is an important part of writing clean code.</p>\n<p>Another aspect is the style. There are a few ways I can write <em>user input</em>*</p>\n<pre class=\"lang-py prettyprint-override\"><code>user_input()\nUSERINPUT()\nUserInput()\nuserinput()\n</code></pre>\n<p>Which one should I follow?</p>\n<p>To have a consistent naming convention, python code follows the <strong><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a></strong> naming convention. When I say follows, I mean that it is recommended that you should follow it too as other python libraries also use this. It makes the code look cleaner.</p>\n<p>Things like functions follow : <code>lower_snake_case</code></p>\n<p>Classes follow: <code>CamelCase</code></p>\n<p>You can read the link for more information.</p>\n<h1>Taking input in Python</h1>\n<pre class=\"lang-py prettyprint-override\"><code>print('Enter your name:')\nn = input()\n</code></pre>\n<p>Clearly, you want to display a message to the user before he enters something. This is why the <code>input()</code> function has something called <a href=\"https://www.w3schools.com/python/ref_func_input.asp\" rel=\"nofollow noreferrer\">input prompt</a>.</p>\n<p><code>name = input(&quot;Enter your name: &quot;)</code></p>\n<p>You can display the message between the <code>()</code>. This removes the additional line. Also note that I changed <code>n</code> to <code>name</code> for the reasons I mentioned above.</p>\n<h1>Formatting strings</h1>\n<p>From your code, I can see that you concatenated strings with <code>+</code> to form meaningful sentences. That works but there is a huge problem when you want to use variables of different types.</p>\n<pre class=\"lang-py prettyprint-override\"><code>name = &quot;Eric&quot;\nage = 14\njob = &quot;Comedian&quot;\nprint(&quot;Hello &quot; + name + &quot;You are &quot; + age + &quot; years old and you are a &quot; + comedian)\n</code></pre>\n<blockquote>\n<p>TypeError: can only concatenate str (not &quot;int&quot;) to str</p>\n</blockquote>\n<p>Simply use Python 3's <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a>. Place the letter <strong>'f'</strong> before <code>&quot;</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>print(f&quot;Hello {name}, you are {age} years old &quot;)\n</code></pre>\n<p>Cleaner.</p>\n<h2>return value from <code>userinput()</code></h2>\n<p>What you are currently doing is returning a tuple of <code>choice</code> and <code>name</code>. It's better that you keep them as they are because later on, you slice from it just to get them again.\nThis means you directly do</p>\n<pre class=\"lang-py prettyprint-override\"><code>return name, choice\n\n# Calling the function\n\n\nname, choice = userinput()\n</code></pre>\n<hr />\n<h2>Code structure</h2>\n<p>Couple of points</p>\n<ul>\n<li><p>Do not ask <code>&quot;Do you want to play again? &quot;</code> in the <code>play_again()</code> function. The reason you called that function should be because the user wants to play again. Move that to a <code>playgame()</code> function which will call <code>user_input()</code> every time the user wants to play the game, and break from the loop only if the user enters <code>'n'</code> or <code>&quot;no&quot;</code></p>\n</li>\n<li><p><code>spaces = spaces + 1</code> can be simplified into <code>spaces += 1</code></p>\n</li>\n<li><p>Move the part where you count the number of characters into a separate function which will return an integer. So your <code>play_game()</code> function doesn't do anything other than <em><strong>play the game</strong></em>. When you need the characters , <code>number_of_char = character_len( name )</code>.</p>\n</li>\n<li><p>Use <a href=\"https://docs.python.org/3.4/library/enum.html\" rel=\"nofollow noreferrer\">enum</a> for clarity.</p>\n</li>\n</ul>\n<p>An improved version of the code</p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\nclass PrintChoices(Enum):\n number_of_char = 'c'\n reversed_name = 'r'\n exit_choice = 'e'\n\n\ndef find_num_of_char(name):\n return len(name) - name.count(' ') \n\ndef reverse_name(name):\n return name[::-1]\n\ndef user_input():\n name = input(&quot;Enter your name: &quot; )\n choice = input(&quot;Would you like to (r)everse your name\\n or would you like to print the number of (c)haracters or (e)xit?: &quot;)\n return name, choice\n\ndef clear_screen():\n print(chr(27) + &quot;[2J&quot;)\n\ndef play_game():\n while True:\n clear_screen()\n name, choice = user_input()\n if choice == PrintChoices.reversed_name.value:\n print(reverse_name(name))\n input(&quot;Press any key to continue...&quot;)\n elif choice == PrintChoices.number_of_char.value:\n print(find_num_of_char(name))\n input(&quot;Press any key to continue...&quot;)\n elif choice == PrintChoices.exit_choice.value:\n break\n else:\n input(&quot;Invalid input, Press any key to continue...&quot;)\n\n\n\nplay_game()\n</code></pre>\n<p>Note: I have also added <code>print(chr(27) + &quot;[2J&quot;)</code> to clear the screen.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:12:00.437", "Id": "491163", "Score": "13", "body": "Wow, your answer was more instructive than hours I've spent watching YouTube videos and reading blog posts on Python. Really appreciate the thoroughness....super insightful for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:14:52.127", "Id": "491164", "Score": "1", "body": "I am so happy that you found it useful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T06:08:40.667", "Id": "491196", "Score": "1", "body": "As a nitpick, perhaps `len(name) - name.count(\" \")` over `len(name.replace(\" \", \"\")`, no need for a new string" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T06:11:46.263", "Id": "491197", "Score": "0", "body": "@Cireo, not a nitpick, but a useful optimization tactic, Do you mind if I edit my answer to add it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T06:16:30.290", "Id": "491198", "Score": "0", "body": "Not at all, please do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T07:13:56.880", "Id": "491201", "Score": "10", "body": "I'd move `print(chr(27) + \"[2J\")` into a separate function `clear_screen` because it wasn't clear until I read your explanation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T00:06:59.713", "Id": "491286", "Score": "0", "body": "Excellent answer, but I don't like the `continue` on the `else:`. If you want to use it, why not also use it with the `if:` and first `elif:`? Second, `input(\"Press any key to continue...\")` should be `input(\"Press ENTER to continue...\")`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T07:25:53.967", "Id": "491309", "Score": "2", "body": "@KenY-N yeah i don't know why I added the continue there, It doesn't serve any purpose. About the input thing, for me, it works with any key, and not just ENTER" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T10:55:00.310", "Id": "250315", "ParentId": "250309", "Score": "31" } } ]
{ "AcceptedAnswerId": "250315", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T06:10:49.283", "Id": "250309", "Score": "12", "Tags": [ "python" ], "Title": "Simple Python Console Game With Inefficient Code Flow" }
250309
<p>I'm fairly new to R. I have used the 'r2excel' package to create an excel workbook from a subset of my R data. This should have 3 sheets for the three different subsets. What I have written works fine, but its a lot of code and is very clunky, just re written three times.</p> <p>If there is a better way of framing my question/best practice tips, I'd love to learn.</p> <pre><code> # Create an Excel workbook. filename &lt;- &quot;validitycheck.xlsx&quot; #The name of the file that will be saved wb &lt;- createWorkbook(type=&quot;xlsx&quot;) #Creating an excel workbook # Create a sheet in that workbook to contain the data table sheet1 &lt;- createSheet(wb, sheetName = &quot;prime1&quot;) sheet2 &lt;- createSheet(wb, sheetName = &quot;prime2&quot;) sheet3 &lt;- createSheet(wb, sheetName = &quot;prime3&quot;) # Add header for sheet 1 xlsx.addHeader(wb, sheet1, value=&quot;Prime 1&quot;,level=1, color=&quot;black&quot;, underline=1) xlsx.addLineBreak(sheet1, 1) # Add header for sheet 2 xlsx.addHeader(wb, sheet2, value=&quot;Prime 2&quot;,level=1, color=&quot;black&quot;, underline=1) xlsx.addLineBreak(sheet2, 1) # Add header for sheet 3 xlsx.addHeader(wb, sheet3, value=&quot;Prime 3&quot;,level=1, color=&quot;black&quot;, underline=1) xlsx.addLineBreak(sheet3, 1) # Add a paragraph : Author author=paste(&quot;Author : Gabriella. \n&quot;, &quot;20% randomly chosen validity check.&quot;, &quot;\n Source: filename&quot;, sep=&quot;&quot;) #Add author for sheet 1 xlsx.addParagraph(wb, sheet1,value=author, isItalic=TRUE, colSpan=5, rowSpan=4, fontColor=&quot;darkgray&quot;, fontSize=14) #Add author para for sheet 2 xlsx.addParagraph(wb, sheet2,value=author, isItalic=TRUE, colSpan=5, rowSpan=4, fontColor=&quot;darkgray&quot;, fontSize=14) #Add author para for sheet 3 xlsx.addParagraph(wb, sheet3,value=author, isItalic=TRUE, colSpan=5, rowSpan=4, fontColor=&quot;darkgray&quot;, fontSize=14) xlsx.addLineBreak(sheet1, 3) xlsx.addLineBreak(sheet2, 3) xlsx.addLineBreak(sheet3, 3) # Add table : add a data frame for sheet 1 xlsx.addHeader(wb, sheet1, value=&quot;Validty for prime 1&quot;) xlsx.addLineBreak(sheet1, 1) xlsx.addTable(wb, sheet1, sample_prime1, fontColor=&quot;darkblue&quot;, fontSize=14, rowFill=c(&quot;white&quot;, &quot;lightblue&quot;), startCol=2, row.names=FALSE, col.names = TRUE) # Add table : add a data frame for sheet 2 xlsx.addHeader(wb, sheet2, value=&quot;Validty for prime 2&quot;) xlsx.addLineBreak(sheet2, 1) xlsx.addTable(wb, sheet2, sample_prime2, fontColor=&quot;darkblue&quot;, fontSize=14, rowFill=c(&quot;white&quot;, &quot;lightblue&quot;), startCol=2, row.names=FALSE, col.names = TRUE) # Add table : add a data frame for sheet 3 xlsx.addHeader(wb, sheet3, value=&quot;Validty for prime 3&quot;) xlsx.addLineBreak(sheet3, 1) xlsx.addTable(wb, sheet3, sample_prime3, fontColor=&quot;darkblue&quot;, fontSize=14, rowFill=c(&quot;white&quot;, &quot;lightblue&quot;), startCol=2, row.names=FALSE, col.names = TRUE) # save the workbook to an Excel file saveWorkbook(wb, filename, password = &quot;secret&quot;) xlsx.openFile(filename)# View the file <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:45:08.057", "Id": "491136", "Score": "1", "body": "Welcome to Code Review. You have done a pretty good job of asking your question, if you want to improve it more or for future use see the [asking section of our help center](https://codereview.stackexchange.com/help/asking)." } ]
[ { "body": "<p>@Duck from Stack overflow provided the answer. Pasting it here. Its is essentially writing a function:</p>\n<pre><code>library(r2excel)\n#Data\nsample_prime1 &lt;- 1:4\nsample_prime2 &lt;- 10:14\nsample_prime3 &lt;- 22:26\n#Store in a list\nList &lt;- list(sample_prime1,sample_prime2,sample_prime3)\n#Function\nmyfun &lt;- function(wb,name,df) {\n # Create object\n sheet &lt;- createSheet(wb, sheetName = name)\n # Add headers\n xlsx.addHeader(wb, sheet, value=paste0('Validty for prime ',name))\n xlsx.addLineBreak(sheet, 1)\n xlsx.addTable(wb, sheet, data.frame(df),\n fontColor=&quot;darkblue&quot;, fontSize=14,\n rowFill=c(&quot;white&quot;, &quot;lightblue&quot;),\n startCol=2, \n row.names=FALSE, \n col.names = FALSE)\n}\n#Create workbook\nfilename &lt;- &quot;validitycheck.xlsx&quot; \nwb &lt;- createWorkbook(type=&quot;xlsx&quot;)\n#Loop\n#Vector for names\nvnames &lt;- paste0('prime',1:length(List))\n#Code\nfor(i in 1:length(List))\n{\n myfun(wb,vnames[i],List[i])\n}\n \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T15:43:36.107", "Id": "250427", "ParentId": "250316", "Score": "1" } } ]
{ "AcceptedAnswerId": "250427", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T11:48:25.793", "Id": "250316", "Score": "2", "Tags": [ "beginner", "r" ], "Title": "Writing an excel doc with a subset of my data in R. Currently the code is excessively long" }
250316
<p>I'm writing a library which simplifies the usage of intrinsics in C#. It's a generic library which supports all numeric types. The goal of this library is to perform these operations at the highest performance possible.<br /> I'll gladly head any suggestions / tips which might improve the performance. All feedback is welcome.</p> <p>The whole library could be viewed at <a href="https://github.com/giladfrid009/SimpleSIMD" rel="noreferrer">https://github.com/giladfrid009/SimpleSIMD</a></p> <pre><code>using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace SimpleSimd { // For value delegate pattern, which will allow to inline delegates. // The performance benefits of this pattern is quite massive (up to 5x) public interface IFunc&lt;T, TResult&gt; { TResult Invoke(T param); } // Example usage of value delegate pattern. These structs will be passed to the method // instead of regular delegates. // We use structs to prevent heap allocations struct Pred : IFunc&lt;int, bool&gt; { int num; public Pred(int num) { this.num = num; } public bool Invoke(int param) { return param == num; } } struct VPred : IFunc&lt;Vector&lt;int&gt;, bool&gt; { public Vector&lt;int&gt; vec; public VPred(Vector&lt;int&gt; vec) { this.vec = vec; } public bool Invoke(Vector&lt;int&gt; param) { return param == vec; } } internal static class SimdOps { // Helper method to offset a ref, to eliminate bound checks when accessing an index internal static ref U Offset&lt;U&gt;(this ref U source, int count) where U : struct { return ref Unsafe.Add(ref source, count); } } public static partial class SimdOps&lt;T&gt; where T : unmanaged { // Helper method to get a ref to the first element of a span, without bound checks. // Also, by getting a ref instead of a pointer, we no longer need to fix the object private static ref U GetRef&lt;U&gt;(ReadOnlySpan&lt;U&gt; span) where U : unmanaged { return ref MemoryMarshal.GetReference(span); } // Helper method to convert ref type private static ref Vector&lt;U&gt; AsVector&lt;U&gt;(in U value) where U : unmanaged { return ref Unsafe.As&lt;U, Vector&lt;U&gt;&gt;(ref Unsafe.AsRef(value)); } // The actual method public static int IndexOf&lt;F1, F2&gt;(in ReadOnlySpan&lt;T&gt; span, F1 vPredicate, F2 predicate) where F1 : struct, IFunc&lt;Vector&lt;T&gt;, bool&gt; where F2 : struct, IFunc&lt;T, bool&gt; { ref var rSpan = ref GetRef(span); int i = 0; if (Vector.IsHardwareAccelerated) { ref var vrSpan = ref AsVector(rSpan); int length = span.Length / Vector&lt;T&gt;.Count; for (; i &lt; length; i++) { if (vPredicate.Invoke(vrSpan.Offset(i))) { int j = i * Vector&lt;T&gt;.Count; int l = j + Vector&lt;T&gt;.Count; for (; j &lt; l; j++) { if (predicate.Invoke(rSpan.Offset(j))) { return j; } } } } i *= Vector&lt;T&gt;.Count; } for (; i &lt; span.Length; i++) { if (predicate.Invoke(rSpan.Offset(i))) { return i; } } return -1; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:29:40.657", "Id": "491166", "Score": "1", "body": "Not worth an actual answer... you should make `Pred` and `VPred` readonly structs. It opens up some additional optimisation opportunities for the compiler (e.g. preventing defensive copies) which _may_ be beneficial." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T07:45:40.853", "Id": "491203", "Score": "1", "body": "This isn't enough for an answer, so I'll post a comment instead: Naming guidelines. .NET favours readability over brevity. Instead of `struct VPred` it should (probably) be `struct VectorPredicate`, instead of `SimdOps` it should be `SimdOperations`. You should also not use abbreviations, so instead of `GetRef` it should be `GetReference`. .NET itself breaks some of these guidelines at some points (e.g `IPAddress`), but it's good to stick to them yourself. [source](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T12:23:23.693", "Id": "250317", "Score": "6", "Tags": [ "c#", "performance", "generics", "vectorization" ], "Title": "C# Generic high performance vectorized math operations" }
250317
<p>Here is the sample <code>Students json</code> am processing</p> <pre><code>{ &quot;students&quot;: [ { &quot;firstName&quot;: &quot;Veena&quot;, &quot;lastName&quot;: &quot;Butteris&quot;, &quot;email&quot;: &quot;vbutteris@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-29&quot;, &quot;2020-06-03&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot; ] }, { &quot;firstName&quot;: &quot;Edward&quot;, &quot;lastName&quot;: &quot;Nogueras&quot;, &quot;email&quot;: &quot;enogueras@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-26&quot;, &quot;2020-05-30&quot;, &quot;2020-05-31&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-09&quot;, &quot;2020-06-10&quot; ] }, { &quot;firstName&quot;: &quot;Oterman&quot;, &quot;lastName&quot;: &quot;Chheang&quot;, &quot;email&quot;: &quot;ochheang@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-30&quot;, &quot;2020-05-31&quot;, &quot;2020-06-01&quot;, &quot;2020-06-03&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-06&quot;, &quot;2020-06-07&quot;, &quot;2020-06-10&quot; ] }, { &quot;firstName&quot;: &quot;Jack&quot;, &quot;lastName&quot;: &quot;Eclarinal&quot;, &quot;email&quot;: &quot;jeclarinal@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-28&quot;, &quot;2020-05-31&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot; ] }, { &quot;firstName&quot;: &quot;Cindy&quot;, &quot;lastName&quot;: &quot;Macallister&quot;, &quot;email&quot;: &quot;cmacallister@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-26&quot;, &quot;2020-06-02&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-06&quot;, &quot;2020-06-13&quot; ] }, { &quot;firstName&quot;: &quot;Cloe&quot;, &quot;lastName&quot;: &quot;Handrick&quot;, &quot;email&quot;: &quot;chandrick@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-29&quot;, &quot;2020-06-01&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-09&quot;, &quot;2020-06-10&quot; ] }, { &quot;firstName&quot;: &quot;Briane&quot;, &quot;lastName&quot;: &quot;Cutchall&quot;, &quot;email&quot;: &quot;bcutchall@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-29&quot;, &quot;2020-05-30&quot;, &quot;2020-05-31&quot;, &quot;2020-06-03&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-14&quot; ] }, { &quot;firstName&quot;: &quot;Mark&quot;, &quot;lastName&quot;: &quot;Heyer&quot;, &quot;email&quot;: &quot;mheyer@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-23&quot;, &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-26&quot;, &quot;2020-05-29&quot;, &quot;2020-05-31&quot;, &quot;2020-06-01&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-06&quot;, &quot;2020-06-10&quot; ] }, { &quot;firstName&quot;: &quot;Chau&quot;, &quot;lastName&quot;: &quot;Rundstrom&quot;, &quot;email&quot;: &quot;crundstrom@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-26&quot;, &quot;2020-05-27&quot;, &quot;2020-05-29&quot;, &quot;2020-05-31&quot;, &quot;2020-06-02&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot; ] }, { &quot;firstName&quot;: &quot;Francis&quot;, &quot;lastName&quot;: &quot;Haywood&quot;, &quot;email&quot;: &quot;fhaywood@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-26&quot;, &quot;2020-05-27&quot;, &quot;2020-05-29&quot;, &quot;2020-06-03&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-09&quot; ] }, { &quot;firstName&quot;: &quot;Maria&quot;, &quot;lastName&quot;: &quot;Seiple&quot;, &quot;email&quot;: &quot;mseiple@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-23&quot;, &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-06-01&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-06&quot;, &quot;2020-06-08&quot;, &quot;2020-06-09&quot; ] }, { &quot;firstName&quot;: &quot;Dan&quot;, &quot;lastName&quot;: &quot;Scavona&quot;, &quot;email&quot;: &quot;dscavona@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-29&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-07&quot;, &quot;2020-06-09&quot; ] }, { &quot;firstName&quot;: &quot;Mark&quot;, &quot;lastName&quot;: &quot;Kuehler&quot;, &quot;email&quot;: &quot;mkuehler@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-06-01&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-06&quot;, &quot;2020-06-09&quot;, &quot;2020-06-10&quot; ] }, { &quot;firstName&quot;: &quot;Dang&quot;, &quot;lastName&quot;: &quot;Come&quot;, &quot;email&quot;: &quot;dcome@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-31&quot;, &quot;2020-06-04&quot;, &quot;2020-06-05&quot;, &quot;2020-06-10&quot;, &quot;2020-06-15&quot; ] }, { &quot;firstName&quot;: &quot;Neha&quot;, &quot;lastName&quot;: &quot;Torchia&quot;, &quot;email&quot;: &quot;ntorchia@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-06-03&quot;, &quot;2020-06-06&quot; ] }, { &quot;firstName&quot;: &quot;Anita&quot;, &quot;lastName&quot;: &quot;Pujals&quot;, &quot;email&quot;: &quot;apujals@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-26&quot;, &quot;2020-05-30&quot;, &quot;2020-06-01&quot;, &quot;2020-06-06&quot; ] }, { &quot;firstName&quot;: &quot;Lorry&quot;, &quot;lastName&quot;: &quot;Loots&quot;, &quot;email&quot;: &quot;lloots@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-26&quot;, &quot;2020-06-01&quot;, &quot;2020-06-08&quot;, &quot;2020-06-12&quot; ] }, { &quot;firstName&quot;: &quot;Derik&quot;, &quot;lastName&quot;: &quot;Binner&quot;, &quot;email&quot;: &quot;dbinner@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-23&quot;, &quot;2020-05-26&quot;, &quot;2020-05-31&quot;, &quot;2020-06-03&quot;, &quot;2020-06-10&quot; ] }, { &quot;firstName&quot;: &quot;Lasha&quot;, &quot;lastName&quot;: &quot;Grybel&quot;, &quot;email&quot;: &quot;lgrybel@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-23&quot;, &quot;2020-05-26&quot;, &quot;2020-05-29&quot;, &quot;2020-06-01&quot;, &quot;2020-06-07&quot;, &quot;2020-06-10&quot; ] }, { &quot;firstName&quot;: &quot;Bobby&quot;, &quot;lastName&quot;: &quot;Shekels&quot;, &quot;email&quot;: &quot;bshekels@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-23&quot;, &quot;2020-05-26&quot;, &quot;2020-05-29&quot;, &quot;2020-05-30&quot;, &quot;2020-06-03&quot;, &quot;2020-06-06&quot; ] }, { &quot;firstName&quot;: &quot;Linc&quot;, &quot;lastName&quot;: &quot;Dorch&quot;, &quot;email&quot;: &quot;ldorch@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-27&quot;, &quot;2020-06-01&quot;, &quot;2020-06-09&quot; ] }, { &quot;firstName&quot;: &quot;Larsha&quot;, &quot;lastName&quot;: &quot;Terrey&quot;, &quot;email&quot;: &quot;lterrey@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-27&quot;, &quot;2020-05-29&quot;, &quot;2020-05-31&quot;, &quot;2020-06-06&quot; ] }, { &quot;firstName&quot;: &quot;Dunk&quot;, &quot;lastName&quot;: &quot;Dettmann&quot;, &quot;email&quot;: &quot;ddettmann@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-23&quot;, &quot;2020-05-27&quot;, &quot;2020-05-31&quot;, &quot;2020-06-01&quot;, &quot;2020-06-09&quot;, &quot;2020-06-13&quot; ] }, { &quot;firstName&quot;: &quot;Pearle&quot;, &quot;lastName&quot;: &quot;Laker&quot;, &quot;email&quot;: &quot;plaker@xyz.com&quot;, &quot;country&quot;: &quot;Wales&quot;, &quot;availableDates&quot;: [ &quot;2020-05-27&quot;, &quot;2020-05-29&quot;, &quot;2020-05-31&quot;, &quot;2020-06-03&quot;, &quot;2020-06-06&quot;, &quot;2020-06-08&quot;, &quot;2020-06-12&quot; ] }, { &quot;firstName&quot;: &quot;Derek&quot;, &quot;lastName&quot;: &quot;Lessenberry&quot;, &quot;email&quot;: &quot;llessenberry@xyz.com&quot;, &quot;country&quot;: &quot;France&quot;, &quot;availableDates&quot;: [ &quot;2020-04-14&quot;, &quot;2020-04-15&quot;, &quot;2020-04-21&quot;, &quot;2020-04-22&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-26&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-04-30&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Kobe&quot;, &quot;lastName&quot;: &quot;Carwile&quot;, &quot;email&quot;: &quot;lcarwile@xyz.com&quot;, &quot;country&quot;: &quot;France&quot;, &quot;availableDates&quot;: [ &quot;2020-04-21&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Judy&quot;, &quot;lastName&quot;: &quot;Vala&quot;, &quot;email&quot;: &quot;jvala@xyz.com&quot;, &quot;country&quot;: &quot;France&quot;, &quot;availableDates&quot;: [ &quot;2020-04-13&quot;, &quot;2020-04-15&quot;, &quot;2020-04-18&quot;, &quot;2020-04-22&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-05-02&quot;, &quot;2020-05-04&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Rhian&quot;, &quot;lastName&quot;: &quot;Hirkaler&quot;, &quot;email&quot;: &quot;ghirkaler@xyz.com&quot;, &quot;country&quot;: &quot;France&quot;, &quot;availableDates&quot;: [ &quot;2020-04-15&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-05-01&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Shayna&quot;, &quot;lastName&quot;: &quot;Salsberg&quot;, &quot;email&quot;: &quot;msalsberg@xyz.com&quot;, &quot;country&quot;: &quot;France&quot;, &quot;availableDates&quot;: [ &quot;2020-04-14&quot;, &quot;2020-04-15&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Kate&quot;, &quot;lastName&quot;: &quot;Mataalii&quot;, &quot;email&quot;: &quot;smataalii@xyz.com&quot;, &quot;country&quot;: &quot;France&quot;, &quot;availableDates&quot;: [ &quot;2020-04-16&quot;, &quot;2020-04-18&quot;, &quot;2020-04-22&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Zidan&quot;, &quot;lastName&quot;: &quot;Sefcovic&quot;, &quot;email&quot;: &quot;zsefcovic@xyz.com&quot;, &quot;country&quot;: &quot;France&quot;, &quot;availableDates&quot;: [ &quot;2020-04-13&quot;, &quot;2020-04-15&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-26&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-04-30&quot;, &quot;2020-05-02&quot;, &quot;2020-05-04&quot;, &quot;2020-05-06&quot;, &quot;2020-05-07&quot; ] }, { &quot;firstName&quot;: &quot;Mario&quot;, &quot;lastName&quot;: &quot;Centner&quot;, &quot;email&quot;: &quot;tcentner@xyz.com&quot;, &quot;country&quot;: &quot;France&quot;, &quot;availableDates&quot;: [ &quot;2020-04-13&quot;, &quot;2020-04-16&quot;, &quot;2020-04-18&quot;, &quot;2020-04-21&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-25&quot;, &quot;2020-04-27&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-04-30&quot;, &quot;2020-05-04&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Nayan&quot;, &quot;lastName&quot;: &quot;Mires&quot;, &quot;email&quot;: &quot;jmires@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-17&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Hadiya&quot;, &quot;lastName&quot;: &quot;Delsoin&quot;, &quot;email&quot;: &quot;odelsoin@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-14&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-04-30&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Lacey&quot;, &quot;lastName&quot;: &quot;Bustos&quot;, &quot;email&quot;: &quot;sbustos@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-14&quot;, &quot;2020-04-15&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-04-30&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Harrison&quot;, &quot;lastName&quot;: &quot;Bugett&quot;, &quot;email&quot;: &quot;sbugett@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-14&quot;, &quot;2020-04-17&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Connor&quot;, &quot;lastName&quot;: &quot;Schlembach&quot;, &quot;email&quot;: &quot;lschlembach@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-13&quot;, &quot;2020-04-14&quot;, &quot;2020-04-16&quot;, &quot;2020-04-17&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-04-30&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Clarissa&quot;, &quot;lastName&quot;: &quot;Stolebarger&quot;, &quot;email&quot;: &quot;cstolebarger@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-14&quot;, &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-04-30&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Phoebe&quot;, &quot;lastName&quot;: &quot;Mcrea&quot;, &quot;email&quot;: &quot;mmcrea@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-23&quot;, &quot;2020-04-24&quot;, &quot;2020-04-26&quot;, &quot;2020-04-28&quot;, &quot;2020-04-29&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Avni&quot;, &quot;lastName&quot;: &quot;Vanzant&quot;, &quot;email&quot;: &quot;kvanzant@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-15&quot;, &quot;2020-04-26&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Fenella&quot;, &quot;lastName&quot;: &quot;Daughton&quot;, &quot;email&quot;: &quot;pdaughton@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-27&quot;, &quot;2020-05-01&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Yaqub&quot;, &quot;lastName&quot;: &quot;Kokesh&quot;, &quot;email&quot;: &quot;mkokesh@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-14&quot;, &quot;2020-04-15&quot;, &quot;2020-05-01&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Jeane&quot;, &quot;lastName&quot;: &quot;Haight&quot;, &quot;email&quot;: &quot;jhaight@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-13&quot;, &quot;2020-04-14&quot;, &quot;2020-04-15&quot;, &quot;2020-04-18&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Grant&quot;, &quot;lastName&quot;: &quot;Paleaae&quot;, &quot;email&quot;: &quot;cpaleaae@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-21&quot;, &quot;2020-04-22&quot;, &quot;2020-05-01&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Sanjeev&quot;, &quot;lastName&quot;: &quot;Schrupp&quot;, &quot;email&quot;: &quot;rschrupp@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-14&quot;, &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Holli&quot;, &quot;lastName&quot;: &quot;Bouley&quot;, &quot;email&quot;: &quot;kbouley@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-26&quot;, &quot;2020-05-06&quot;, &quot;2020-05-07&quot; ] }, { &quot;firstName&quot;: &quot;Preston&quot;, &quot;lastName&quot;: &quot;Dilbeck&quot;, &quot;email&quot;: &quot;ldilbeck@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-30&quot;, &quot;2020-05-01&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Ceri&quot;, &quot;lastName&quot;: &quot;Gruening&quot;, &quot;email&quot;: &quot;dgruening@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-05-02&quot;, &quot;2020-05-06&quot; ] }, { &quot;firstName&quot;: &quot;Shannan&quot;, &quot;lastName&quot;: &quot;Purkiss&quot;, &quot;email&quot;: &quot;npurkiss@xyz.com&quot;, &quot;country&quot;: &quot;Germany&quot;, &quot;availableDates&quot;: [ &quot;2020-04-15&quot;, &quot;2020-04-21&quot;, &quot;2020-04-22&quot;, &quot;2020-05-06&quot; ] } ] } </code></pre> <p>The above Json has list of Students with multiple available dates for training, I need to transform the json such a way that output Json should have a list of countries with maximum Students who are available on earliest adjacent dates and produces Json as</p> <pre><code>{ &quot;countries&quot;: [ { &quot;attendeeCount&quot;: 15, &quot;attendees&quot;: [ &quot;llessenberry@xtz.com&quot;, &quot;lcarwile@xtz.com&quot;, &quot;jvala@xtz.com&quot;, &quot;ghirkaler@xtz.com&quot;, &quot;msalsberg@xtz.com&quot;, &quot;smataalii@xtz.com&quot;, &quot;zsefcovic@xtz.com&quot;, &quot;tcentner@xtz.com&quot;, &quot;jmires@xtz.com&quot;, &quot;odelsoin@xtz.com&quot;, &quot;sbustos@xtz.com&quot;, &quot;sbugett@xtz.com&quot;, &quot;lschlembach@xtz.com&quot;, &quot;cstolebarger@xtz.com&quot;, &quot;mmcrea@xtz.com&quot; ], &quot;name&quot;: &quot;Germany&quot;, &quot;startDate&quot;: &quot;2020-04-23&quot; }, { &quot;attendeeCount&quot;: 14, &quot;attendees&quot;: [ &quot;vbutteris@xtz.com&quot;, &quot;enogueras@xtz.com&quot;, &quot;ochheang@xtz.com&quot;, &quot;jeclarinal@xtz.com&quot;, &quot;cmacallister@xtz.com&quot;, &quot;chandrick@xtz.com&quot;, &quot;bcutchall@xtz.com&quot;, &quot;mheyer@xtz.com&quot;, &quot;crundstrom@xtz.com&quot;, &quot;fhaywood@xtz.com&quot;, &quot;mseiple@xtz.com&quot;, &quot;dscavona@xtz.com&quot;, &quot;mkuehler@xtz.com&quot;, &quot;dcome@xtz.com&quot; ], &quot;name&quot;: &quot;Wales&quot;, &quot;startDate&quot;: &quot;2020-05-24&quot; } ] } </code></pre> <p>Below are my DTO classes</p> <pre><code>public class Students { private List&lt;Student&gt; Students; //getter setter } public class Student { String firstName; String lastName; String email; String country; List&lt;String&gt; availableDates; } public class CountryStudent { private Integer count; private List&lt;String&gt; attendees; private String name; private String startDate; } </code></pre> <p>Below is the <em>StudentsService</em> class which fetcheds <code>Students</code> json data and transforms it.</p> <pre><code>public class StudentsService{ public String processStudents(){ Students students = StudentsPayloadGenerator.getPayload(); // fetches the Students json data Map&lt;String,Map&lt;String,List&lt;String&gt;&gt;&gt; countryDatesStudents = new HashMap&lt;&gt;(); List&lt;Student&gt; StudentsList = students.getStudents(); for (Student student : StudentsList){ Map&lt;String,Integer&gt; consecutiveDates = getConsecutiveDatesForPartner(student); consecutiveDates.entrySet().forEach(computeStudentsAvailableOnConsecutiveDates(countryDatesStudents, student)); } List&lt;CountryStudent&gt; countryStudents = new ArrayList&lt;&gt;(); CountriesPayload countriesPayload = new CountriesPayload(); countriesPayload.setCountries(countryStudents); countryDatesStudents.entrySet().forEach(countryDatesPartner-&gt; { Map.Entry&lt;String, List&lt;String&gt;&gt; earliestAvailablePartner = countryDatesPartner.getValue().entrySet().stream().sorted((a, b) -&gt; b.getValue().size() - a.getValue().size()).findFirst().get(); CountryStudent countryAttendee = buildCountryPayload(countryDatesPartner.getKey(), earliestAvailablePartner); countryStudents.add(countryAttendee); }); return getJson(countriesPayload); } private String getJson(CountriesPayload countriesPayload) { ObjectMapper objectMapper = new ObjectMapper(); String countriesPayloadJson = null; try { countriesPayloadJson = objectMapper.writeValueAsString(countriesPayload); } catch (JsonProcessingException e) { e.printStackTrace(); } return countriesPayloadJson; } private CountryStudent buildCountryPayload(String country, Map.Entry&lt;String, List&lt;String&gt;&gt; attendeesEntry) { String adjacentDatePair = attendeesEntry.getKey(); String earliestDate = adjacentDatePair.substring(0,adjacentDatePair.indexOf(&quot;_&quot;)); CountryStudent countryAttendee = new CountryStudent(); countryAttendee.setName(country); countryAttendee.setAttendeeCount(attendeesEntry.getValue().size()); countryAttendee.setAttendees(attendeesEntry.getValue()); countryAttendee.setStartDate(earliestDate); return countryAttendee; } private Consumer&lt;Map.Entry&lt;String, Integer&gt;&gt; computeStudentsAvailableOnConsecutiveDates(Map&lt;String, Map&lt;String, List&lt;String&gt;&gt;&gt; countryDatesStudents, Student partner) { return entry -&gt; { countryDatesStudents.computeIfAbsent(partner.getCountry(), v -&gt; new TreeMap&lt;String, List&lt;String&gt;&gt;()); Map&lt;String, List&lt;String&gt;&gt; datesStudents = countryDatesStudents.get(partner.getCountry()); datesStudents.computeIfAbsent(entry.getKey(), v -&gt; new ArrayList&lt;&gt;()); datesStudents.get(entry.getKey()).add(partner.getEmail()); }; } private Map&lt;String, Integer&gt; getConsecutiveDatesForPartner(Student partner) { Map&lt;String,Integer&gt; consecutiveDates = new TreeMap&lt;&gt;(); List&lt;LocalDate&gt; availableDates = partner.getAvailableDates().stream().map(this::convertToLocalDate).collect(Collectors.toList()); Collections.sort(availableDates,(a,b) -&gt;{ if(a.isAfter(b)) return 1; else if(a.isBefore(b)) return -1; else return 0; }); tupleIterator(availableDates, (date1, date2) -&gt; { if(isConsecutive(date1,date2)) consecutiveDates.put(date1+&quot;_&quot;+date2,1); }); return consecutiveDates; } private LocalDate convertToLocalDate(String date){ DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-d&quot;); return LocalDate.parse(date, formatter); } private boolean isConsecutive(LocalDate date1, LocalDate date2) { return DAYS.between(date1,date2) == 1; } public static &lt;T&gt; void tupleIterator(Iterable&lt;T&gt; iterable, BiConsumer&lt;T, T&gt; consumer) { Iterator&lt;T&gt; it = iterable.iterator(); if(!it.hasNext()) return; T first = it.next(); while(it.hasNext()) { T next = it.next(); consumer.accept(first, next); first = next; } } } </code></pre> <p>My code is not performing optimal if the input json is huge like millions of students, Am wondering if the above code can be optimized any further in terms of memory consumption and to achieve less run time, please provide your valuable feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T13:39:06.587", "Id": "491123", "Score": "2", "body": "Have you profiled the code to understand where the time is spent?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:11:46.097", "Id": "491125", "Score": "0", "body": "No I did not since its not in production yet and I dont have that much data available now to test, on a high level I feel it can be optimized further since nested and operating on whole initial data set, am wondering whether it can be done using parallel streams or any other Java 8 stream api features" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:43:18.810", "Id": "491135", "Score": "1", "body": "Please embed the input and output from the links directly into your post. If they are too large, copy a representable piece of it and keep the links to full version. Nobody should be forced to open those links to understand your post. Links can rot and your post must be self-contained." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:53:42.637", "Id": "491140", "Score": "1", "body": "It is better to post the expected input and output in the question instead of via links. Then why the output json has start date 2017 but there is no such year in the input? Please provide a consistent example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T15:46:25.803", "Id": "491152", "Score": "0", "body": "@Marc Since its a big json I created a link, I have updated the question with the valid output json link, please check" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:04:18.437", "Id": "491241", "Score": "1", "body": "Well, if you have enough data to run it with to determine that is slow, you have enough data to profile where it's slow." } ]
[ { "body": "<p>I noticed you wrote the following method:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private LocalDate convertToLocalDate(String date){\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-d&quot;);\n return LocalDate.parse(date, formatter);\n}\n</code></pre>\n<p>You are instantianting a new <code>DateTimeFormatter</code> object everytime you calls this method and this is expensive, you could create one <code>DateTimeFormatter</code> static object:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-d&quot;);\n\n//you could directly invoke LocalDate.parse(date, formatter) in your code instead\n//of this function\nprivate LocalDate convertToLocalDate(String date){\n return LocalDate.parse(date, formatter);\n}\n</code></pre>\n<p>Second thing is the the following code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Collections.sort(availableDates,(a,b) -&gt;{\n if(a.isAfter(b)) return 1;\n else if(a.isBefore(b)) return -1;\n else return 0;\n});\n</code></pre>\n<p>If you have arrays of ascending dates like <code>&quot;2020-05-24&quot;, &quot;2020-05-25&quot;, &quot;2020-05-30&quot;</code> like in your json file for every element <code>a.isAfter(b)</code> will be always checked and will always return <code>false</code> and then <code>a.isBefore(b)</code> will be checked and return <code>true</code> ending the method. This is expensive, you could just the natural order of <code>Collections.sort</code> method like below:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Collections.sort(availableDates);\n</code></pre>\n<p>Or better, if you are sure the arrays are always already ascending ordered like your example, there is no need of using a sorting method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T11:09:47.667", "Id": "250363", "ParentId": "250319", "Score": "2" } }, { "body": "<p>Nice implementation, it's already efficient but I noticed something that can be improved, find my suggestion below.</p>\n<h2>Time complexity</h2>\n<pre><code>public String processStudents(){ \n //...\n // O(s) where s is the number of students \n for (Student student : StudentsList){\n // O(d*log(d)) d is the number of dates of the student with most available dates\n Map&lt;String,Integer&gt; consecutiveDates = getConsecutiveDatesForPartner(student);\n // O(d)\n consecutiveDates.entrySet().forEach(computeStudentsAvailableOnConsecutiveDates(countryDatesStudents, student));\n }\n //...\n // O(c) c is number of countries\n countryDatesStudents.entrySet().forEach(countryDatesPartner-&gt; {\n // O(D*log(D)) D is the number of all the dates of the students in a country\n Map.Entry&lt;String, List&lt;String&gt;&gt; earliestAvailablePartner = countryDatesPartner.getValue().entrySet().stream().sorted((a, b) -&gt; b.getValue().size() - a.getValue().size()).findFirst().get();\n //...\n });\n return getJson(countriesPayload);\n}\n</code></pre>\n<p>So the total complexity is approximately <span class=\"math-container\">\\$O(s*d*log(d) + c*D*log(D))\\$</span>. If the input JSON doesn't come with sorted dates then the fist factor cannot be improved.</p>\n<p>The second factor can be improved by creating a map with adjacent dates in advance. For example:</p>\n<ul>\n<li>2019-01-01_2019-01-02 -&gt; students</li>\n<li>2019-01-02_2019-01-03 -&gt; students</li>\n<li>...</li>\n<li>2020-10-07_2020-10-08 (today) -&gt; students</li>\n</ul>\n<p>A method to create the map:</p>\n<pre><code>private Map&lt;String,List&lt;Student&gt;&gt; buildDateStudentsMap() {\n Map&lt;String,List&lt;Student&gt;&gt; datesStudents = new HashMap&lt;&gt;();\n LocalDate start = LocalDate.parse(&quot;2019-01-01&quot;);\n LocalDate end = LocalDate.now();\n while(start.isBefore(end)) {\n LocalDate nextDay = start.plusDays(1);\n datesStudents.put(start+&quot;_&quot;+nextDay, new ArrayList&lt;&gt;());\n start = nextDay;\n }\n return datesStudents;\n}\n</code></pre>\n<p>Once the dates of the students are sorted, it's enough to add the student to the map.</p>\n<p>The second improvement is <strong>parallelization</strong>. If the students are divided by country, the successive operations can run in parallel:</p>\n<ol>\n<li>Group the students by country. <span class=\"math-container\">\\$O(s)\\$</span></li>\n<li>Create map with adjacent dates (as explained before) <span class=\"math-container\">\\$O(days)\\$</span></li>\n<li>Fill map with students. <span class=\"math-container\">\\$O(s*d*log(d))\\$</span></li>\n<li>Get the entry of the map with most students <span class=\"math-container\">\\$O(days)\\$</span></li>\n<li>Generate the result</li>\n</ol>\n<p>So the complexity would be <span class=\"math-container\">\\$O(s*d*log(d))\\$</span> and the steps 2-5 can run in parallel. If you can get the dates in the input JSON sorted the complexity would basically be <span class=\"math-container\">\\$O(s)\\$</span>.</p>\n<p>By running the two solution I got the following runtimes:</p>\n<pre><code>Initial solution: 209.4444 ms\nOptimized solution: 61.7075 ms \n</code></pre>\n<p>Its more than three time faster which follows by the fact that there are are 3 countries in the example and it uses the precomputed map to avoid the second sort.</p>\n<p>Optimized solution:</p>\n<pre><code>public List&lt;CountryStudent&gt; processStudents(List&lt;Student&gt; students) throws Exception{\n Map&lt;String, List&lt;Student&gt;&gt; countryStudents = students.stream()\n .collect(Collectors.groupingBy(Student::getCountry));\n return countryStudents.entrySet()\n .parallelStream()\n .map(k -&gt; this.toCountryStudent(k.getKey(), k.getValue()) )\n .collect(Collectors.toList());\n}\n\nprivate CountryStudent toCountryStudent(String country, List&lt;Student&gt; students) {\n // Build map with adjacent dates\n Map&lt;String,List&lt;Student&gt;&gt; datesStudents = buildDateStudentsMap();\n \n // Fill map with students.\n for(Student s: students) {\n List&lt;LocalDate&gt; availableDates = s.getAvailableDates().stream()\n .map(this::convertToLocalDate).collect(Collectors.toList());\n // If availableDates are already sorted this can be removed\n Collections.sort(availableDates);\n tupleIterator(availableDates, (date1, date2) -&gt; {\n if(isConsecutive(date1,date2))\n datesStudents.get(date1+&quot;_&quot;+date2).add(s);\n });\n }\n String dates = getMostPopularDates(datesStudents);\n String startDate = dates.substring(0,dates.indexOf(&quot;_&quot;));\n return new CountryStudent(country,datesStudents.get(dates), startDate);\n}\n\nprivate String getMostPopularDates(Map&lt;String,List&lt;Student&gt;&gt; datesStudents) {\n int max=0;\n String key=null;\n // Get most popular adjacent dates. O(days) \n for(Map.Entry&lt;String,List&lt;Student&gt;&gt; entry : datesStudents.entrySet()) {\n if(entry.getValue().size()&gt;=max) {\n key = entry.getKey();\n max = entry.getValue().size();\n }\n }\n return key;\n}\n</code></pre>\n<p>Notice how I removed the class <code>Students</code> and the JSON serialization/deserialization, motivations below.</p>\n<h2>Minor changes</h2>\n<ul>\n<li>The class <code>Students</code> is literally a container for the list of students with no additional methods, so it can be replaced by <code>List&lt;Student&gt;</code>. Same for <code>CountriesPayload</code>.</li>\n<li>For testing and reusability is better to have a defined input and output, therefore I would remove the JSON serialization/deserialization in that method.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:30:25.020", "Id": "491243", "Score": "0", "body": "Really appreciate for improving the run time, can you please share the implementation of `getMostPopularDates()` as well" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:36:42.420", "Id": "491245", "Score": "0", "body": "@RanPaul glad I could help. That method it's nothing special, but I added it to the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T04:13:55.397", "Id": "491395", "Score": "0", "body": "`private String getMostPopularDates(Map<String,List<Student>> datesStudents) {\n\n Map<String,List<String>> map = new TreeMap<>();\n datesStudents.entrySet().forEach(entry -> map.put(entry.getKey(),entry.getValue().stream().map(student -> student.getEmail()).collect(Collectors.toList())));\n Map.Entry<String, List<String>> stringListEntry = map.entrySet().stream().sorted((a, b) -> b.getValue().size() - a.getValue().size()).findFirst().get();\n return stringListEntry.getKey();\n }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T04:14:03.703", "Id": "491396", "Score": "0", "body": "looks like your `getMostPopularDates` is not sorting and fetching the earliest date, I changed it as above to make it work" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T10:04:32.950", "Id": "491405", "Score": "0", "body": "@RanPaul my bad, I used an `HashMap` in `buildDateStudentsMap`. Changing it to `LinkedHashMap` should do the trick. But good that you solved." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:22:26.147", "Id": "250370", "ParentId": "250319", "Score": "3" } } ]
{ "AcceptedAnswerId": "250370", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T12:52:01.400", "Id": "250319", "Score": "3", "Tags": [ "java", "performance", "json", "memory-optimization" ], "Title": "Java 8: Memory/Run-time Performance optimization to transform Json structure" }
250319
<p>Newbie here. I have this <code>gqlgen</code> api with <code>sqlc</code> update code, which updates the user by given id with provided fields:</p> <pre class="lang-golang prettyprint-override"><code>// graph/schema.resolvers.go ... func (r *mutationResolver) UserUpdate(ctx context.Context, id string, input model.EditUser) (bool, error) { // Validate v := validator.New() if err := v.Struct(input); err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Println(err) } return false, errors.New(err.Error()) } pg := db.ConnectPg() defer pg.Close() // Parse string id to int64 parsedId, _ := strconv.ParseInt(id, 10, 64) u := db.User{} var err error // GetUserById is generated by sqlc if u, err = db.NewPg(pg).GetUserById(ctx, parsedId); err != nil { return false, err } // Confirm ownership or admin user := auth.ForContext(ctx) if user != nil || user.ID == parsedId || user.IsAdmin { if input.EmailVerified != nil { u.EmailVerified = *input.EmailVerified } if input.MobileVerified != nil { u.MobileVerified = *input.MobileVerified } if input.IsActive != nil { u.IsActive = *input.IsActive } if input.Name != nil { u.Name = sql.NullString{String: *input.Name, Valid: true} } if input.Avatar != nil { u.Name = sql.NullString{String: *input.Avatar, Valid: true} } if input.Email != nil { u.Email = sql.NullString{String: *input.Email, Valid: true} } if input.Mobile != nil { u.Mobile = sql.NullString{String: *input.Mobile, Valid: true} } if input.Password != nil { bytes, _ := bcrypt.GenerateFromPassword([]byte(*input.Password), 14) hashedPassword := string(bytes) u.Password = hashedPassword } if input.IsAdmin != nil { if user.IsAdmin { u.IsAdmin = *input.IsAdmin } else { return false, fmt.Errorf(&quot;Access denied&quot;) } } // UpdateUser and UpdateUserParams are generated by sqlc if _, err := db.NewPg(pg).UpdateUser(ctx, db.UpdateUserParams{ ID: u.ID, Name: u.Name, Avatar: u.Avatar, Email: u.Email, EmailVerified: u.EmailVerified, Mobile: u.Mobile, MobileVerified: u.MobileVerified, Password: u.Password, IsAdmin: u.IsAdmin, IsActive: u.IsActive, UpdatedAt: time.Now(), }); err != nil { return false, err } return true, nil } return false, fmt.Errorf(&quot;Access denied&quot;) } ... </code></pre> <p>And it is working correctly. However coming from Node land, I feel like it is too verbose. Or is this just how Golang does it? What if I have like more than 10 columns, do I have to check <code>nil</code> for each of them?</p> <p>I tried searching some Golang tutorials but couldn't find much out there like Node. How would an experienced Gopher write this code in neat?</p> <hr /> <p>Other information you may need.</p> <p>This is <code>EditUser</code> struct &quot;generated&quot; by <code>gqlgen</code> but can be edited:</p> <pre class="lang-golang prettyprint-override"><code>// graph/models/user.go type EditUser struct { Name *string `json:&quot;name,omitempty&quot; validate:&quot;omitempty,max=100&quot;` Avatar *string `json:&quot;avatar,omitempty&quot;` Email *string `json:&quot;email,omitempty&quot; validate:&quot;omitempty,email&quot;` EmailVerified *bool `json:&quot;emailVerified,omitempty&quot;` Mobile *string `json:&quot;mobile,omitempty&quot; validate:&quot;omitempty,min=2,max=55&quot;` MobileVerified *bool `json:&quot;mobileVerified,omitempty&quot;` Password *string `json:&quot;password,omitempty&quot;` IsAdmin *bool `json:&quot;is_admin,omitempty&quot;` IsActive *bool `json:&quot;isActive,omitempty&quot;` } </code></pre> <p>This is <code>User</code> struct &quot;generated&quot; by <code>sqlc</code>:</p> <pre><code>// db/models.go // Code generated by sqlc. DO NOT EDIT. package db type User struct { ID int64 `json:&quot;id&quot;` Name sql.NullString `json:&quot;name&quot;` Avatar sql.NullString `json:&quot;avatar&quot;` Email sql.NullString `json:&quot;email&quot;` EmailVerified bool `json:&quot;email_verified&quot;` Mobile sql.NullString `json:&quot;mobile&quot;` MobileVerified bool `json:&quot;mobile_verified&quot;` // is required Password string `json:&quot;password&quot;` IsAdmin bool `json:&quot;is_admin&quot;` IsActive bool `json:&quot;is_active&quot;` CreatedAt time.Time `json:&quot;created_at&quot;` UpdatedAt time.Time `json:&quot;updated_at&quot;` LastSignin sql.NullTime `json:&quot;last_signin&quot;` } </code></pre> <p>This is <code>UpdateUserParams</code> &quot;genearted&quot; by <code>sqlc</code>:</p> <pre class="lang-golang prettyprint-override"><code>// db/user.sql.go // Code generated by sqlc. DO NOT EDIT. // source: user.sql type UpdateUserParams struct { ID int64 `json:&quot;id&quot;` Name sql.NullString `json:&quot;name&quot;` Avatar sql.NullString `json:&quot;avatar&quot;` Email sql.NullString `json:&quot;email&quot;` EmailVerified bool `json:&quot;email_verified&quot;` Mobile sql.NullString `json:&quot;mobile&quot;` MobileVerified bool `json:&quot;mobile_verified&quot;` Password string `json:&quot;password&quot;` IsAdmin bool `json:&quot;is_admin&quot;` IsActive bool `json:&quot;is_active&quot;` UpdatedAt time.Time `json:&quot;updated_at&quot;` } </code></pre> <hr /> <p>go (v1.15), sqlc (v1.5.0), gqlgen (v0.13.0)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:15:42.940", "Id": "491126", "Score": "0", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T13:05:10.237", "Id": "250321", "Score": "3", "Tags": [ "go" ], "Title": "How can I make this code less verbose?" }
250321
<p>I'm trying to getting integer keyboard input to call the corresponding method.</p> <p>invalid input works, keyboard input 3 works, input 2 exits, input 1 calls the wrong method. I've not yet worked on the subtring and points problem method yet.</p> <p>Regards, and I appreciate your feedback.</p> <pre><code>import java.io.File; import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.InputMismatchException; public class WordGames { public static void main(String[] args) throws FileNotFoundException { getSelection(); File file = new File(&quot;DICTIONARY.txt&quot;); if (file.isFile() == true) { } else { System.out.println(&quot;File doesn't exist. Exiting.&quot;); System.exit(0); } subStringProblem(); pointsProblem(); } static String getSelection() { Scanner keyboardInput = new Scanner(System.in); System.out.println(&quot;Welcome to the Word Games program menu.&quot;); System.out.println(&quot;Select from one of the following options.&quot;); System.out.println(&quot;1. Substring problem.&quot;); System.out.println(&quot;2. Points problem.&quot;); System.out.println(&quot;3. Exit.&quot;); System.out.println(&quot;Enter your selections: &quot;); if ( ! keyboardInput.hasNextInt()) { System.out.println(&quot;Invalid option. Try again.&quot;); getSelection(); } else if (keyboardInput.hasNextInt(1)){ subStringProblem(); getSelection(); } else if (keyboardInput.hasNextInt(2)){ pointsProblem(); getSelection(); } else if (keyboardInput.hasNextInt(3)){ } System.out.println(&quot;Good Bye!&quot;); System.exit(0); return null; } static String subStringProblem() { System.out.println(&quot;Substring problem.&quot;); System.out.println(&quot;Enter a Substring:&quot;); return null; } static String pointsProblem() { System.out.println(&quot;Points problem.&quot;); return null; } } </code></pre>
[]
[ { "body": "<p><code>getSelection</code> is a recursive method that also terminate the program. There is no need to return anything.\nAll the code behind that call in your main method will never be executed and is useless.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T10:54:40.233", "Id": "250411", "ParentId": "250322", "Score": "2" } }, { "body": "<p><strong>1. Proper indentation</strong></p>\n<p>Please have a look at a <a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"noreferrer\">style guide</a>. One important topic of style guides is how to &quot;correctly&quot; indent your code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.File;\nimport java.util.Scanner;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.util.InputMismatchException;\n\npublic class WordGames {\n\n public static void main(String[] args) throws FileNotFoundException {\n getSelection();\n File file = new File(&quot;DICTIONARY.txt&quot;);\n if (file.isFile() == true) {\n }\n else {\n System.out.println(&quot;File doesn't exist. Exiting.&quot;);\n System.exit(0); \n }\n\n subStringProblem();\n pointsProblem();\n }\n \n static String getSelection() {\n Scanner keyboardInput = new Scanner(System.in);\n System.out.println(&quot;Welcome to the Word Games program menu.&quot;);\n System.out.println(&quot;Select from one of the following options.&quot;);\n System.out.println(&quot;1. Substring problem.&quot;);\n System.out.println(&quot;2. Points problem.&quot;);\n System.out.println(&quot;3. Exit.&quot;);\n System.out.println(&quot;Enter your selections: &quot;);\n \n if (!keyboardInput.hasNextInt()) {\n \n System.out.println(&quot;Invalid option. Try again.&quot;);\n getSelection();\n \n } else if (keyboardInput.hasNextInt(1)) {\n subStringProblem(); \n getSelection();\n \n } else if (keyboardInput.hasNextInt(2)) {\n pointsProblem();\n getSelection();\n \n } else if (keyboardInput.hasNextInt(3)) {\n System.out.println(&quot;Good Bye!&quot;);\n System.exit(0);\n } \n return null;\n }\n \n static String subStringProblem() {\n System.out.println(&quot;Substring problem.&quot;);\n System.out.println(&quot;Enter a Substring:&quot;);\n return null;\n }\n \n static String pointsProblem() {\n System.out.println(&quot;Points problem.&quot;); \n return null;\n }\n}\n</code></pre>\n<p><strong>2. Empty if</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (file.isFile() == true) {\n}\nelse {\n System.out.println(&quot;File doesn't exist. Exiting.&quot;);\n System.exit(0); \n}\n</code></pre>\n<p>This is not necessary. Just use</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (file.isFile()) {\n}\nelse {\n System.out.println(&quot;File doesn't exist. Exiting.&quot;);\n System.exit(0); \n}\n</code></pre>\n<p>Without an <code>==</code> the <code>if</code> will automatically check if the value is true.\nEven better:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if(!file.isFile()) {\n System.out.println(&quot;File doesn't exist. Exiting.&quot;);\n System.exit(0); \n}\n</code></pre>\n<p>Empty <code>if</code>-statements should be avoided.</p>\n<p><strong>3.Input validation</strong></p>\n<p>In <code>getSelection()</code>, your program doesn't crash when the user enters a letter instead of a number. That is good. But your program does crash, when the user enters a number not equal to 1, 2 or 3. This problem can be avoided like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int sel = 0;\ntry{\n sel = keyboardInput.nextInt();\n} catch (InputMismatchException e){\n keyboardInput.next();\n System.out.println(&quot;Invalid option. Try again.&quot;);\n getSelection();\n}\n\nif (sel == 1) {\n subStringProblem(); \n getSelection();\n}\nelse if (sel == 2) {\n pointsProblem();\n getSelection();\n} \nelse if (sel == 3) {\n System.out.println(&quot;Good Bye!&quot;);\n System.exit(0);\n}\nelse {\n System.out.println(&quot;Invalid option. Try again.&quot;);\n getSelection();\n}\n</code></pre>\n<p>If you are not familiar with <code>try-catch</code> yet, I suggest reading the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html\" rel=\"noreferrer\">documentation</a>.</p>\n<p><strong>4.Unnecessary returns</strong></p>\n<p>If you don't want to return something in your methods, you can use <code>void</code> as return type instead of <code>String</code>.\nFor example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>static String subStringProblem() {\n System.out.println(&quot;Substring problem.&quot;);\n System.out.println(&quot;Enter a Substring:&quot;);\n return null;\n}\n</code></pre>\n<p>should be replaced with</p>\n<pre class=\"lang-java prettyprint-override\"><code>static void subStringProblem() {\n System.out.println(&quot;Substring problem.&quot;);\n System.out.println(&quot;Enter a Substring:&quot;);\n}\n</code></pre>\n<p><strong>5. Access modifiers</strong></p>\n<p>It is considered good practice to always add Access modifiers to your methods. Instead of</p>\n<pre class=\"lang-java prettyprint-override\"><code>static void getSelection() {\n</code></pre>\n<p>it should be</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static void getSelection() {\n</code></pre>\n<p><strong>6. throws</strong></p>\n<p>The <code>throws</code>-keyword in the main-method is not necessary.</p>\n<p><strong>Code</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.File;\nimport java.util.Scanner;\nimport java.io.FileInputStream;\nimport java.util.InputMismatchException;\n\npublic class WordGames {\n\n public static void main(String[] args) {\n getSelection();\n File file = new File(&quot;DICTIONARY.txt&quot;);\n if(!file.isFile()) {\n System.out.println(&quot;File doesn't exist. Exiting.&quot;);\n System.exit(0); \n }\n subStringProblem();\n pointsProblem();\n }\n \n private static void getSelection() {\n Scanner keyboardInput = new Scanner(System.in);\n System.out.println(&quot;Welcome to the Word Games program menu.&quot;);\n System.out.println(&quot;Select from one of the following options.&quot;);\n System.out.println(&quot;1. Substring problem.&quot;);\n System.out.println(&quot;2. Points problem.&quot;);\n System.out.println(&quot;3. Exit.&quot;);\n System.out.println(&quot;Enter your selections: &quot;);\n \n int sel = 0;\n try{\n sel = keyboardInput.nextInt();\n } catch (InputMismatchException e){\n keyboardInput.next();\n System.out.println(&quot;Invalid option. Try again.&quot;);\n getSelection();\n }\n \n if (sel == 1) {\n subStringProblem(); \n getSelection();\n }\n else if (sel == 2) {\n pointsProblem();\n getSelection();\n } \n else if (sel == 3) {\n System.out.println(&quot;Good Bye!&quot;);\n System.exit(0);\n }\n else {\n System.out.println(&quot;Invalid option. Try again.&quot;);\n getSelection();\n }\n }\n \n private static void subStringProblem() {\n System.out.println(&quot;Substring problem.&quot;);\n System.out.println(&quot;Enter a Substring:&quot;);\n }\n\n private static void pointsProblem() {\n System.out.println(&quot;Points problem.&quot;); \n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:19:05.920", "Id": "250417", "ParentId": "250322", "Score": "5" } }, { "body": "<blockquote>\n<pre><code> Scanner keyboardInput = new Scanner(System.in);\n</code></pre>\n</blockquote>\n<p>You call this on each recursive call to <code>getSelection</code>. That's unnecessary. You could simply create one <code>Scanner</code> and use it for the entire program. That could be as simple as adding a class variable:</p>\n<pre><code> private static Scanner keyboardInput = new Scanner(System.in);\n</code></pre>\n<p>Or you could use a <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\"><code>try</code>-with-resources</a> and pass it into a constructor for your <code>WordGames</code> object.</p>\n<pre><code> try (Scanner keyboardInput = new Scanner(System.in)) {\n WordGames game = new WordGames(keyboardInput);\n game.play();\n }\n</code></pre>\n<p>Now the <code>Scanner</code> will be automatically closed when finished.</p>\n<p>The static version will automatically close the <code>Scanner</code> when the program finishes. Not quite as clean as using the <code>try</code>-with-resources but acceptable for a <code>Scanner</code>.</p>\n<p>Your original code will keep opening new <code>Scanner</code> instances for each invalid entry and never closes any of them. With enough entries, it would be possible to crash the program that way.</p>\n<p>Of course, even without multiple copies, the recursive calls themselves use an ever increasing number of call stacks. So you can still crash the program just from the recursion. But that will take longer if you only have a single <code>Scanner</code>. Regardless, it would be better to rewrite your program's logic as a loop (<code>while</code>, <code>for</code>, etc.) rather than recursively. Recursion is used when you care about the state. But in this case, you don't.</p>\n<p>As a practical matter, it would be difficult to crash this simple program by entering an endless stream of 4s. But it wouldn't be impossible. And it's probably a bad pattern to get in the habit of using, because if the program is less I/O based, the computer can more easily overrun its limits.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T05:54:03.667", "Id": "250497", "ParentId": "250322", "Score": "1" } } ]
{ "AcceptedAnswerId": "250417", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T14:26:47.087", "Id": "250322", "Score": "3", "Tags": [ "java" ], "Title": "Exercise for playing wordgames with user input" }
250322
<pre class="lang-cpp prettyprint-override"><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;string&gt; class Website { int status, sock; struct addrinfo hints; struct addrinfo *servinfo; public: int init(std::string url){ memset(&amp;hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if((status = getaddrinfo(url.c_str(), &quot;80&quot;, &amp;hints, &amp;servinfo)) != 0){ return status; } if((sock = socket(servinfo-&gt;ai_family, servinfo-&gt;ai_socktype, servinfo-&gt;ai_protocol)) == -1){ return -1; } return 0; } int connectToSite(){ return connect(sock, servinfo-&gt;ai_addr, servinfo-&gt;ai_addrlen); } int sendToSite(std::string request){ return send(sock, request.c_str(), strlen(request.c_str()), 0); } int recvFromSite(char buf[], int maxsize){ return recv(sock, buf, maxsize, 0); } void closeSocket(){ close(sock); freeaddrinfo(servinfo); } }; </code></pre> <p>I have a networking class that implements low level c functions in a simple class. I am looking to make my code more efficient</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:08:22.113", "Id": "491160", "Score": "1", "body": "Is this the real indentation you are using, or was there a copy and paste error (where there some tabs in your code)? It might also be helpful if you provided a test case." } ]
[ { "body": "<h2>Observation:</h2>\n<p>I don't like the design.</p>\n<p>You are using a two phase initialization. You construct the object (thus constructor) and then call an <code>init()</code> function. Two phase initialization is a bad idea as you can't tell (or have to validate) the state of the object before it can be used.</p>\n<p>A better technique is to simply use the constructor to initialize the object. If the constructor fails then the throw so the object never exists and can't be used incorrectly.</p>\n<p>You also have an explicit close (<code>closeSocket()</code>) which is fine to an extent but you are forcing people to remember to call this function when you are done with the object. This is what a destructor is for.</p>\n<p>You need to look up the concept of RAII.</p>\n<pre><code>{\n Website site(&quot;Stuff&quot;); // All resources allocated\n}\n// All resources for `site` are now released.\n</code></pre>\n<h2>Design</h2>\n<p>What is the use of <code>connectToSite()</code>, is that not the init? Can you call read/write before calling this? If not then read/write are on the wrong object and connect should return you the appropriate object that has the read/write interface.</p>\n<hr />\n<p>This is how I would want to use an object called &quot;WebSite&quot;</p>\n<pre><code>{\n // An abstract object that represents the site.\n // No actual underlying connection as connections are\n // usually to resources on the site not the actual site.\n Website site(&quot;thorsanvil.com&quot;, 80);\n\n // Create a connection to a specific resource on the site.\n Connection c = site.open(&quot;Path&quot;);\n\n // Object was created successfully so we have\n // a valid connection to a server we can not communicate with.\n c.writeData(&quot;This is a message&quot;);\n std::string resp = c.read();\n }\n</code></pre>\n<p>From your interface. I would look to rename your class to &quot;Connection&quot; then the expectations for how to use the object may be more like.</p>\n<pre><code> {\n // Create the socket and connect to the site.\n Connection c(&quot;https://thorsanvil.com/MyResource&quot;);\n\n // Object was created successfully so we have\n // a valid connection to a server we can not communicate with.\n c.writeData(&quot;This is a message&quot;);\n std::string response = c.readData();\n }\n</code></pre>\n<h2>Code Review:</h2>\n<p>You don't want to use C++ strings?</p>\n<pre><code>#include &lt;string.h&gt;\n</code></pre>\n<hr />\n<p>A URL?</p>\n<pre><code> int init(std::string url)\n</code></pre>\n<p>Sure but the name of the class is &quot;Website&quot;. A url is a lot more than just a website. There is a schema/host(hostname/port/user/password)/path/query/fragment. Would you not just pass a host and for the connection maybe a port.</p>\n<p>Or you could pass the whole url but each new connection needs a new URL not just the website.</p>\n<hr />\n<p>You are returning the status code here (on error):</p>\n<pre><code> if((status = getaddrinfo(url.c_str(), &quot;80&quot;, &amp;hints, &amp;servinfo)) != 0){\n return status;\n }\n</code></pre>\n<p>But here you are retuning -1</p>\n<pre><code> if((sock = socket(servinfo-&gt;ai_family, servinfo-&gt;ai_socktype, servinfo-&gt;ai_protocol)) == -1){\n return -1;\n }\n</code></pre>\n<p>Are you sure those error ranges do not overlap?</p>\n<p>I think a better interface would be to throw an exception if something goes wrong.</p>\n<hr />\n<p>This is not going to work for the generic URL.</p>\n<pre><code> status = getaddrinfo(url.c_str(), &quot;80&quot; ....\n</code></pre>\n<ol>\n<li>The port is not always 80.</li>\n<li>The default port is defined by the schema &quot;http/https ...&quot;</li>\n<li>The default can be overridden by the url itself.</li>\n</ol>\n<p>Example:</p>\n<pre><code> https://thorsanvil.com:1222/Work\n\n Schema: https\n Site: thorsanvil.com\n Port: 1222 overrides default 443 for https\n Path: /Work\n Query: Empty\n Fragment: Empty\n</code></pre>\n<p>Really the above code should be:</p>\n<pre><code> status = getaddrinfo(getHost(url), getPort(url), ....\n</code></pre>\n<hr />\n<p>What happens of <code>connect()</code> fails? Are you expecting the user to check the error code?</p>\n<pre><code> int connectToSite(){\n return connect(sock, servinfo-&gt;ai_addr, servinfo-&gt;ai_addrlen);\n }\n</code></pre>\n<p>That's very C like interface and very error prone to use. We know that users of API don't always check error codes. Don't leak this ingormation. Make it explicit with an exception.</p>\n<hr />\n<p>This is not how you use <code>send()</code> and <code>recv()</code> the return value indicates how much of the message was sent/recved. You need to repeatedly call this functions until the message is sent or there is an error.</p>\n<pre><code> int sendToSite(std::string request){\n return send(sock, request.c_str(), strlen(request.c_str()), 0);\n }\n int recvFromSite(char buf[], int maxsize){\n return recv(sock, buf, maxsize, 0);\n }\n</code></pre>\n<h2>Research</h2>\n<p>Have a look at this class:</p>\n<p><a href=\"https://github.com/Loki-Astari/ThorsSocket/blob/master/src/ThorsSocket/Socket.h\" rel=\"nofollow noreferrer\">https://github.com/Loki-Astari/ThorsSocket/blob/master/src/ThorsSocket/Socket.h</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T14:46:10.297", "Id": "491239", "Score": "0", "body": "Thank you very much. This is very useful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T00:05:02.670", "Id": "250347", "ParentId": "250330", "Score": "3" } } ]
{ "AcceptedAnswerId": "250347", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T16:37:01.523", "Id": "250330", "Score": "1", "Tags": [ "c++", "networking", "library" ], "Title": "Networking library for c++ linux" }
250330
<p>I have created a PowerShell script that will call a REST API and then for each node returned, add the data into a database table. This particular endpoint only returns ~600 records worth of data, however this is the method I will be using for a bunch of other API endpoints.</p> <p>There are a couple things I think would help with this script:</p> <ul> <li>Bulk add the records into the database rather than one by one</li> <li>For the <code>ON DUPLICATE KEY UPDATE</code> only change fields that are different.</li> </ul> <p>My understanding of <code>ON DUPLICATE KEY UPDATE</code> it will check if the ScryId exists, and if it does then update the fields listed below. I would like to only update the fields that are different.</p> <p>Script:</p> <pre><code>If ( Get-Module -ListAvailable -Name SimplySQL ) { Import-Module -Name SimplySQL } Else { Install-Module -Name SimplySQL -Force } Write-Host &quot;---------------------------------------------------------------------------&quot; -ForegroundColor DarkGray Write-Host &quot;Update Production.Set' Table: &quot; -ForegroundColor Gray -NoNewline $StartTime = $(Get-Date) $Response = Invoke-RestMethod -Uri &quot;https://api.scryfall.com/sets&quot; -Method GET -UseBasicParsing $ResponseSorted = $Response.data | Sort-Object -Property @{Expression = &quot;released_at&quot;; Descending = $False} $username = &quot;&quot; $password = ConvertTo-SecureString &quot;&quot; -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential ($username, $password) Open-MySQLConnection -Server &quot;&quot; -Port 1234 -Database &quot;Production&quot; -Credential $credential Foreach ( $Record in $ResponseSorted ) { $ScryID = $Record.id $Code = Try{ ($Record.code).ToUpper() } Catch {} $Name = Try{ ($Record.name) -replace &quot;'&quot;,&quot;&quot; } Catch {} $SetType = $Record.set_type $ReleaseDate = $Record.released_at $CardCount = $Record.card_count $BlockCode = Try{ ($Record.block_code).ToUpper() } Catch {} $BlockName = $Record.block $ParentSetCode = Try{ ($Record.parent_set_code).ToUpper() } Catch {} $Digital = $Record.digital $NonFoil = $Record.nonfoil_only $Foil = $Record.foil_only $Icon = $Record.icon_svg_uri $Status = 0 Invoke-SQLUpdate -query &quot; INSERT INTO Production.`Set` (ScryID, Code, Name, SetType, ReleaseDate, CardCount, BlockCode, BlockName, ParentSetCode, Digital, NonFoil, Foil, Icon, Status) VALUES ( '$ScryID', '$Code', '$Name', '$SetType', '$ReleaseDate', $CardCount, '$BlockCode', '$BlockName', '$ParentSetCode', $Digital, $NonFoil, $Foil, '$Icon', $Status ) ON DUPLICATE KEY UPDATE Code = '$Code', Name = '$Name', SetType = '$SetType', ReleaseDate = '$ReleaseDate', CardCount = $CardCount, BlockCode = '$BlockCode', BlockName = '$BlockName', ParentSetCode = '$ParentSetCode', Digital = $Digital, NonFoil = $NonFoil, Foil = $Foil, Icon = '$Icon' &quot; | Out-Null } Close-SQLConnection $ElapsedTime = $(Get-Date) - $StartTime $TotalTime = &quot;{0:HH:mm:ss.fff}&quot; -f ([datetime]$ElapsedTime.Ticks) Write-Host $TotalTime -ForegroundColor Cyan </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T18:45:48.897", "Id": "250333", "Score": "3", "Tags": [ "sql", "mysql", "database", "powershell" ], "Title": "PowerShell Script to get data from Third Party API and insert into database" }
250333
<p>I wrote a program that read a csv file that contain 100 rows that look like:</p> <pre><code>1;S****L;SCHOOL 2;*A*G*A*;HANGMAN </code></pre> <p>then try to guess the letters like in a hangman game. My scope is to count every right and wrong letters and then sum them up. The code works fine, I get around 1670 right + wrong attempts to guess the letters. My approach was to create a dictionary in which I store all the letters from the alphabet and read every words from the file then sum every appearance of a letter and store them in the dictionary. Somethin like</p> <pre><code>{ &quot;A&quot; : 30, &quot;B&quot; : 40 } </code></pre> <p>Then I sort the dict based on every letter occurrence and first try to guess the letter with the most apparace.</p> <p>My question. Is something that I can improve in order to get a smaller number of attempts?</p> <pre><code>import csv INPUT_FILE = &quot;words.csv&quot; def oppenFile(): # function to read the file with open(INPUT_FILE, &quot;r&quot;, encoding=&quot;utf-8&quot;) as words: reader = list(csv.reader(words, delimiter=&quot;;&quot;)) return reader def letterCount(): # function that count every the letter in the file and return a dict: {A : 2} letters = dict.fromkeys(&quot;QWERTYUIOPĂÎASDFGHJKLȘȚÂZXCVBNM&quot;, 0) words = oppenFile() for w in range(len(words)): for l in list(words[w][2]): if l not in list(words[w][1]): letters[l] += 1 return letters def checkLetters(word, wholeWord, letters): # function that solve a word return the number of right + wrong attempts attempts = 0 for letter, key in letters.items(): if letter in wholeWord and letter not in word: attempts += 1 index = [i for i, lit in enumerate(wholeWord) if lit == letter] letters[letter] -= len(index) for j in range(len(index)): word = word[:index[j]] + letter + word[(index[j] + 1):] elif '*' not in word: break else: attempts += 1 return attempts def hangman(): words = oppenFile() numberOfAttempts = 0 letters = letterCount() for i in range(len(words)): letters = dict(sorted(letters.items(), key=lambda x: x[1], reverse=True)) # sort the dict numberOfAttempts += checkLetters(words[i][1], words[i][2], letters) print(f&quot;{numberOfAttempts} right + wrong attempts&quot;) if __name__ == &quot;__main__&quot;: hangman() </code></pre>
[]
[ { "body": "<p>Welcome to Code Review!</p>\n<h2>PEP-8</h2>\n<p>In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.</p>\n<p>Functions and variables should be named in a <code>lower_snake_case</code>, classes as <code>UpperCamelCase</code>, and constants as <code>UPPER_SNAKE_CASE</code>.</p>\n<h2>Type hinting</h2>\n<p>With newer python versions, you can make use of type hinting to give a brief overview of the type of variables and function parameters.</p>\n<h2>Counting letters</h2>\n<p>Python provides an inbuilt <code>collections.Counter</code> for you to make use of.</p>\n<h2>Comments</h2>\n<p>The comments don't really help here. Also, prefer writing docstring over comments for functions.</p>\n<h2>Variable names</h2>\n<p>You open a file, and name its pointer as <code>words</code>, whereas the function is returning a list of words; called <code>reader</code>, which in turn is stored in a variable called <code>words</code>?</p>\n<h2>Weird conversions</h2>\n<p>You generate a mapping of letters to their respective counts, as a dictionary (hash-map/table/lookup), then convert it to list of 2-valued tuple, sort that, and convert back to dictionary. Why? <code>dict</code> has <span class=\"math-container\">\\$ O(1) \\$</span> lookup and sorting makes no sense in your case.</p>\n<h2>Iteration with index</h2>\n<p>You use the following loop structure:</p>\n<pre><code>for i in range(len(words)):\n</code></pre>\n<p>where, <code>i</code> in itself is serving no purpose. Every occurrence of usage of <code>i</code> is of the form <code>words[i]</code>. You can just iterate over the values of <code>words</code> list itself:</p>\n<pre><code>for word in words:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T21:07:28.360", "Id": "250340", "ParentId": "250337", "Score": "4" } } ]
{ "AcceptedAnswerId": "250340", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T20:00:28.423", "Id": "250337", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "python hangman solver" }
250337
<p>I made a simple program in Python</p> <ul> <li>stores tasks in the file</li> <li>allows the user to manage them.</li> </ul> <p>I'm interested if my implementation is efficient and could I do something better. I'm not sure whether loading all data from file to memory and again saving it in the file is a good way to implement list saving tasks.</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os CHOICE_LIST_TASKS = 1 CHOICE_ADD_TASK = 2 CHOICE_REMOVE_TASK = 3 CHOICE_QUIT = 4 def read_int(prompt='&gt; ', errmsg='Invalid number!'): num = None while num is None: try: num = int(input(prompt)) except ValueError: print(errmsg) return num def display_menu(): print('What do you want to do?') print('[1] List all tasks') print('[2] Add a new task') print('[3] Delete task') print('[4] Quit') choice = None file = None if not os.path.exists('tasks'): file = open('tasks', 'w+') else: file = open('tasks', 'r+') tasks = [] for line in file.readlines(): tasks.append(line.strip()) while choice != CHOICE_QUIT: display_menu() choice = read_int() if choice == CHOICE_LIST_TASKS: if len(tasks) == 0: print('Task list is empty!') else: print('Tasks:') for x in tasks: print(x) elif choice == CHOICE_ADD_TASK: desc = input('Which task do you want to do? ') index = tasks.append(desc) print('Successfully added a new task!') elif choice == CHOICE_REMOVE_TASK: if len(tasks) == 0: print('Task list is empty!') else: for x in tasks: print(tasks.index(x), x) index = read_int('Which task do you want to delete? ') try: tasks.pop(index) print('Successfully deleted task!') except IndexError: print('Please enter proper task number') elif choice == CHOICE_QUIT: print('Good bye!') else: print('Invalid choice!') file = open('tasks', 'w+') for x in tasks: file.write(x + '\n') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T21:09:47.990", "Id": "491175", "Score": "3", "body": "you started off strong with functions, and then its all one big blob of code segment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-13T18:27:25.507", "Id": "492830", "Score": "0", "body": "consider accepting an answer" } ]
[ { "body": "<p>Let's start from the very top.</p>\n<pre class=\"lang-py prettyprint-override\"><code>CHOICE_LIST_TASKS = 1\nCHOICE_ADD_TASK = 2\nCHOICE_REMOVE_TASK = 3\nCHOICE_QUIT = 4\n</code></pre>\n<p>It's clear to me that you want to create variables and assign them certain integers so you don't have to use magic numbers anywhere, kudos to you for this. There is a much better way to implement this idea in python</p>\n<h1>Enumerations : <code>Enum</code></h1>\n<p><strong><a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">Enumerations in Python</a></strong> <br></p>\n<blockquote>\n<p>An enumeration is a set of symbolic names <br>\n(members) bound to unique, constant values</p>\n</blockquote>\n<h2>creating an <code>Enum</code></h2>\n<pre class=\"lang-py prettyprint-override\"><code>class Choices(Enum):\n list_task = 1\n add_task = 2 \n remove_task = 3\n quit = 4\n</code></pre>\n<p>This already looks much clearer than random global variables. You can also <a href=\"https://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-data-structure-exercise-2.php\" rel=\"nofollow noreferrer\">iterate through the enumeration and display its values with names </a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(Choices.add_task.name)\n</code></pre>\n<blockquote>\n<p>add_task</p>\n</blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>print(Choices.add_task.value) \n</code></pre>\n<blockquote>\n<p>1</p>\n</blockquote>\n<h1>Use more functions</h1>\n<pre class=\"lang-py prettyprint-override\"><code>file = None\nif not os.path.exists('tasks'):\n file = open('tasks', 'w+')\nelse:\n file = open('tasks', 'r+')\ntasks = []\n\nfor line in file.readlines():\n tasks.append(line.strip())\n</code></pre>\n<p>Why can't we move this into a function called <code>read_task_file()</code>?<br>\nThis way it is extremely clear to me, you, you after a year reading old projects, and anybody else who will ever read this code that those few lines of code <strong>will read the task file</strong>. Without that, one must read the code thoroughly and understand its purpose.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def read_task_file():\n file = None\n if not os.path.exists('tasks'):\n file = open('tasks', 'w+')\n else:\n file = open('tasks', 'r+')\n tasks = []\n for line in file.readlines():\n tasks.append(line.strip())\n return tasks\n</code></pre>\n<p>now getting the tasks is</p>\n<pre class=\"lang-py prettyprint-override\"><code>tasks = read_task_file()\n</code></pre>\n<p>This exact same applies to the next set of code, which will let the user enter their choice so we can perform it.</p>\n<p>Factoring out the part where we read a choice from the user and perform into a function would look like</p>\n<pre class=\"lang-py prettyprint-override\"><code>def read_task_choice():\n display_menu()\n choice = read_int()\n if choice not in Choices._value2member_map_:\n print(&quot;Invalid input! Please enter a correct choice\\n&quot;)\n read_task_choice()\n</code></pre>\n<p>Note: <code>Choices._value2member_map_</code> will be all the values in an enumeration.</p>\n<p>This already looks much cleaner! We eliminate the need of having it in a loop where it will check all the cases, the function only returns <code>choice</code> when there is a valid input.</p>\n<p>As I said, factor out the work into functions and all them when required. I have done the same for the 4 main jobs ( the 4 choices ).</p>\n<hr />\n<h2>List tasks</h2>\n<pre class=\"lang-py prettyprint-override\"><code>def list_tasks(tasks):\n if len(tasks) == 0:\n print(&quot;Task list is empty!&quot;)\n return None\n\n\n for i in range(len(tasks)):\n print(f&quot;{i} {tasks[i]}&quot;)\n</code></pre>\n<h2>Add new task</h2>\n<pre class=\"lang-py prettyprint-override\"><code>def add_new_task(tasks):\n return input(&quot;What task would you like to finish ?: &quot;)\n tasks.append(task)\n</code></pre>\n<h2>Remove task</h2>\n<pre class=\"lang-py prettyprint-override\"><code>def remove_task(tasks):\n if len(tasks) == 0:\n print(&quot;Task list is already empty!&quot;)\n return None\n\n list_tasks(tasks)\n task = int(input((&quot;Which task would you like to remove: ?&quot;)))\n\n if task &lt; 0 or task &gt;= len(tasks):\n print(&quot;Invalid input! Please select an appropriate task&quot;)\n remove_task(tasks)\n tasks.pop(task)\n</code></pre>\n<p>And finally</p>\n<h2>Update task file</h2>\n<pre class=\"lang-py prettyprint-override\"><code>def update_task_file(tasks):\n file = open('tasks', 'w+')\n for x in tasks:\n file.write(x + '\\n')\n</code></pre>\n<p>What is the point of having millions of functions when I can put everything like I have already done?\nNow when you have to play the game</p>\n<pre class=\"lang-py prettyprint-override\"><code>tasks = read_task_file()\n\nwhile True:\n choice = read_task_choice()\n if choice == Choices.list_task.value:\n list_tasks(tasks)\n\n elif choice == Choices.add_task.value:\n add_new_task(tasks)\n \n\n elif choice == Choices.remove_task.value:\n remove_task(tasks)\n\n else:\n break\n\n update_task_file(tasks)\n</code></pre>\n<p>This is the main advantage of having strongly typed functions.</p>\n<h1>Clearing the screen and waiting for input</h1>\n<p>Due to the absence of Graphics, we can see that after a few choices the terminal looks a little strange<a href=\"https://i.stack.imgur.com/xuB17.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xuB17.png\" alt=\"terminal\" /></a></p>\n<p>We can improve this by simply clearing the screen after each choice, and then wait for the user to press a key</p>\n<h2>Clearing the terminal</h2>\n<p>There are a few ways. A popular way is to use <code>os.system(&quot;cls&quot;)</code> if you're on windows, but calling this is quite expensive and also makes your program more platform dependant.</p>\n<p>You can do</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(chr(27) + &quot;[2J&quot;)\n</code></pre>\n<p>And this will also work.</p>\n<h2>Waiting for input</h2>\n<p>Adding this line <code>input(&quot;Press any key to continue...&quot;)</code> will wait for the user's response before displaying all the choices again, making the experience better.</p>\n<h2>Final</h2>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nfrom enum import Enum\n\nclass Choices(Enum):\n list_task = 1\n add_task = 2\n remove_task = 3\n quit = 4\n\ndef read_int(prompt='&gt; ', errmsg='Invalid number!'):\n num = None\n while num is None:\n try:\n num = int(input(prompt))\n except ValueError:\n print(errmsg)\n return num\n\ndef display_menu():\n print('What do you want to do?')\n print('[1] List all tasks')\n print('[2] Add a new task')\n print('[3] Delete task')\n print('[4] Quit')\n\ndef read_task_file():\n file = None\n if not os.path.exists('tasks'):\n file = open('tasks', 'w+')\n else:\n file = open('tasks', 'r+')\n tasks = []\n for line in file.readlines():\n tasks.append(line.strip())\n return tasks\n\ndef update_task_file(tasks):\n file = open('tasks', 'w+')\n for x in tasks:\n file.write(x + '\\n')\n\ndef read_task_choice():\n display_menu()\n choice = read_int()\n if choice not in Choices._value2member_map_:\n print(&quot;Invalid input! Please enter a correct choice\\n&quot;)\n read_task_choice()\n return choice\n\ndef add_new_task(tasks):\n task = input(&quot;What task would you like to do: &quot;)\n tasks.append(task)\n\ndef list_tasks(tasks):\n if len(tasks) == 0:\n print(&quot;Task list is empty!&quot;)\n return None\n\n\n for i in range(len(tasks)):\n print(f&quot;{i} {tasks[i]}&quot;)\n\ndef remove_task(tasks):\n if len(tasks) == 0:\n print(&quot;Task list is already empty!&quot;)\n return None\n\n list_tasks(tasks)\n task = int(input((&quot;Which task would you like to remove: ?&quot;)))\n\n if task &lt; 0 or task &gt;= len(tasks):\n print(&quot;Invalid input! Please select an appropriate task&quot;)\n remove_task(tasks)\n tasks.pop(task)\n\ndef clear_screen():\n print(chr(27) + &quot;[2J&quot;)\n\ndef pause():\n input(&quot;Press any key to continue...&quot;)\n\ntasks = read_task_file()\n\nwhile True:\n clear_screen()\n choice = read_task_choice()\n if choice == Choices.list_task.value:\n list_tasks(tasks)\n\n elif choice == Choices.add_task.value:\n add_new_task(tasks)\n\n\n elif choice == Choices.remove_task.value:\n remove_task(tasks)\n\n else:\n break\n\n update_task_file(tasks)\n pause()\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T13:53:30.950", "Id": "250365", "ParentId": "250339", "Score": "3" } } ]
{ "AcceptedAnswerId": "250365", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T20:25:02.510", "Id": "250339", "Score": "4", "Tags": [ "python" ], "Title": "Task management program in Python" }
250339
<p>I am trying to implement a network server application in C++ using Boost.Asio.</p> <p>Here are the requirements I am trying to meet:</p> <ul> <li>The Application creates only one instance of <code>boost::io_context</code>.</li> <li>Single <code>io_context</code> is being <code>run()</code> by a shared Thread Pool. The number of threads is not defined.</li> <li>Application can instantiate multiple Server objects. New Servers can be spawned and killed at any time.</li> <li>Each Server can handle connections from multiple clients.</li> </ul> <p>I am trying to implement RAII pattern for the Server class. What I want to guarantee is that when Server gets deallocated all of its connections are completely closed. There are 3 ways each connection can be closed:</p> <ol> <li>Client responds and there is no more work to be done in a connection.</li> <li>Server is being deallocated and causes all alive connections to close.</li> <li>Connection is killed manually by invoking <code>stop()</code> method.</li> </ol> <p>I have arrived to a solution that seems to meet all of the criteria above but since Boost.Asio is still quite new to me I wanted to verify that what I am doing is correct. Also there are couple of things that I was specifically not 100% sure about:</p> <ul> <li>I was trying to remove the <code>mutex</code> from the Server class and instead use a <code>strand</code> for all of the synchronisation but I couldn't find a clear way to do it.</li> <li>Because Thread Pool can consist of only 1 thread and this thread may be what's calling a Server destructor I had to invoke <code>io_context::poll_one()</code> from the destructor to give a chance for all of the pending connections to complete the shutdown and prevent a potential deadlock.</li> <li>I would welcome any other suggestions for improvements you could think of.</li> </ul> <p>Anyways, here's the code with some unit tests ( live version on Coliru: <a href="http://coliru.stacked-crooked.com/a/1afb0dc34dd09008" rel="nofollow noreferrer">http://coliru.stacked-crooked.com/a/1afb0dc34dd09008</a> ):</p> <pre><code>#include &lt;boost/asio/io_context.hpp&gt; #include &lt;boost/asio/io_context_strand.hpp&gt; #include &lt;boost/asio/executor.hpp&gt; #include &lt;boost/asio/deadline_timer.hpp&gt; #include &lt;boost/asio/dispatch.hpp&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;memory&gt; #include &lt;list&gt; using namespace std; using namespace boost::asio; using namespace std::placeholders; class Connection; class ConnectionDelegate { public: virtual ~ConnectionDelegate() { } virtual class executor executor() const = 0; virtual void didReceiveResponse(shared_ptr&lt;Connection&gt; connection) = 0; }; class Connection: public enable_shared_from_this&lt;Connection&gt; { public: Connection(string name, io_context&amp; ioContext) : _name(name) , _ioContext(ioContext) , _timer(ioContext) { } const string&amp; name() const { return _name; } void setDelegate(ConnectionDelegate *delegate) { _delegate = delegate; } void start() { // Simulate a network request _timer.expires_from_now(boost::posix_time::seconds(3)); _timer.async_wait(bind(&amp;Connection::handleResponse, shared_from_this(), _1)); } void stop() { _timer.cancel(); } private: string _name; io_context&amp; _ioContext; boost::asio::deadline_timer _timer; ConnectionDelegate *_delegate; void handleResponse(const boost::system::error_code&amp; errorCode) { if (errorCode == error::operation_aborted) { return; } dispatch(_delegate-&gt;executor(), bind(&amp;ConnectionDelegate::didReceiveResponse, _delegate, shared_from_this())); } }; class Server: public ConnectionDelegate { public: Server(string name, io_context&amp; ioContext) : _name(name) , _ioContext(ioContext) , _strand(_ioContext) { } ~Server() { stop(); assert(_connections.empty()); assert(_connectionIterators.empty()); } weak_ptr&lt;Connection&gt; addConnection(string name) { auto connection = shared_ptr&lt;Connection&gt;(new Connection(name, _ioContext), bind(&amp;Server::deleteConnection, this, _1)); { lock_guard&lt;mutex&gt; lock(_mutex); _connectionIterators[connection.get()] = _connections.insert(_connections.end(), connection); } connection-&gt;setDelegate(this); connection-&gt;start(); return connection; } vector&lt;shared_ptr&lt;Connection&gt;&gt; connections() { lock_guard&lt;mutex&gt; lock(_mutex); vector&lt;shared_ptr&lt;Connection&gt;&gt; connections; for (auto weakConnection: _connections) { if (auto connection = weakConnection.lock()) { connections.push_back(connection); } } return connections; } void stop() { auto connectionsCount = 0; for (auto connection: connections()) { ++connectionsCount; connection-&gt;stop(); } while (connectionsCount != 0) { _ioContext.poll_one(); connectionsCount = connections().size(); } } // MARK: - ConnectionDelegate class executor executor() const override { return _strand; } void didReceiveResponse(shared_ptr&lt;Connection&gt; connection) override { // Strand to protect shared resourcess to be accessed by this method. assert(_strand.running_in_this_thread()); // Here I plan to execute some business logic and I need both Server &amp; Connection to be alive. std::cout &lt;&lt; &quot;didReceiveResponse - server: &quot; &lt;&lt; _name &lt;&lt; &quot;, connection: &quot; &lt;&lt; connection-&gt;name() &lt;&lt; endl; } private: typedef list&lt;weak_ptr&lt;Connection&gt;&gt; ConnectionsList; typedef unordered_map&lt;Connection*, ConnectionsList::iterator&gt; ConnectionsIteratorMap; string _name; io_context&amp; _ioContext; io_context::strand _strand; ConnectionsList _connections; ConnectionsIteratorMap _connectionIterators; mutex _mutex; void deleteConnection(Connection *connection) { { lock_guard&lt;mutex&gt; lock(_mutex); auto iterator = _connectionIterators[connection]; _connections.erase(iterator); _connectionIterators.erase(connection); } default_delete&lt;Connection&gt;()(connection); } }; void testConnectionClosedByTheServer() { io_context ioContext; auto server = make_unique&lt;Server&gt;(&quot;server1&quot;, ioContext); auto weakConnection = server-&gt;addConnection(&quot;connection1&quot;); assert(weakConnection.expired() == false); assert(server-&gt;connections().size() == 1); server.reset(); assert(weakConnection.expired() == true); } void testConnectionClosedAfterResponse() { io_context ioContext; auto server = make_unique&lt;Server&gt;(&quot;server1&quot;, ioContext); auto weakConnection = server-&gt;addConnection(&quot;connection1&quot;); assert(weakConnection.expired() == false); assert(server-&gt;connections().size() == 1); while (!weakConnection.expired()) { ioContext.poll_one(); } assert(server-&gt;connections().size() == 0); } void testConnectionClosedManually() { io_context ioContext; auto server = make_unique&lt;Server&gt;(&quot;server1&quot;, ioContext); auto weakConnection = server-&gt;addConnection(&quot;connection1&quot;); assert(weakConnection.expired() == false); assert(server-&gt;connections().size() == 1); weakConnection.lock()-&gt;stop(); ioContext.run(); assert(weakConnection.expired() == true); assert(server-&gt;connections().size() == 0); } void testMultipleServers() { io_context ioContext; auto server1 = make_unique&lt;Server&gt;(&quot;server1&quot;, ioContext); auto server2 = make_unique&lt;Server&gt;(&quot;server2&quot;, ioContext); auto weakConnection1 = server1-&gt;addConnection(&quot;connection1&quot;); auto weakConnection2 = server2-&gt;addConnection(&quot;connection2&quot;); server1.reset(); assert(weakConnection1.expired() == true); assert(weakConnection2.expired() == false); } void testDeadLock() { io_context ioContext; auto server = make_unique&lt;Server&gt;(&quot;server1&quot;, ioContext); auto weakConnection = server-&gt;addConnection(&quot;connection1&quot;); assert(weakConnection.expired() == false); assert(server-&gt;connections().size() == 1); auto connection = weakConnection.lock(); server.reset(); // &lt;-- deadlock, but that's OK, i will try to prevent it by other means } int main() { testConnectionClosedByTheServer(); testConnectionClosedAfterResponse(); testConnectionClosedManually(); // testDeadLock(); } </code></pre> <p>Kind Regards, Marek</p>
[]
[ { "body": "<p>I don't know enough Asio to give the kind of feedback I know you want, but here are some minor cleanups you could do:</p>\n<ul>\n<li><p>Don't <code>using namespace std</code>. You should probably avoid <code>using namespace</code> anything else, too, just for clarity.</p>\n</li>\n<li><p><code>virtual ~ConnectionDelegate() { }</code> could be <code>virtual ~ConnectionDelegate() = default;</code> instead. This represents your intent a little better.</p>\n</li>\n<li><p><code>~Server()</code> should be <code>~Server() override</code>, to indicate that it overrides a virtual member function. In general, you should use <code>override</code> wherever it's physically allowed by the language. (I think you do it right everywhere <em>except</em> on the destructors.)</p>\n</li>\n<li><p><code>Connection(string name,</code> and <code>Server(string name,</code> both unnecessarily makes a copy of <code>string name</code>.</p>\n</li>\n<li><p>All your constructors should be <code>explicit</code>, to tell the compiler that e.g. the braced pair <code>{&quot;hello world&quot;, myIOContext}</code> should not be implicitly treated as (or implicitly converted to) a <code>Server</code> object, not even by accident.</p>\n</li>\n<li><p>Personally, I find the use of typedefs for <code>ConnectionsList</code> and <code>ConnectionsIteratorMap</code> to be an unnecessary layer of indirection. I would rather see <code>std::list&lt;std::weak_ptr&lt;Connection&gt;&gt; _connections;</code> right there in-line. If I need a name for that type, I can just say <code>decltype(_connections)</code>.</p>\n</li>\n<li><p><code>default_delete&lt;Connection&gt;()(connection)</code> is a verbose way of saying <code>delete connection</code>. Be direct.</p>\n</li>\n<li><p><code>class executor executor()</code> is hella confusing. The fact that you had to say <code>class</code> there should have been a red flag that either <code>executor</code> is not the right name for the class, or <code>executor()</code> is not the right name for this method. Consider changing the name of the method to <code>get_executor()</code>, for example. I assume that you can't change the name of <code>class executor</code> because it isn't declared in this file; it must be coming from some Boost namespace that you <code>using</code>'ed, right? (Don't <code>using</code> namespaces!)</p>\n</li>\n</ul>\n<hr />\n<p>You skip a lot of opportunities to avoid copies via references and/or move semantics. For example, in <code>Server::connections()</code>, I would have written:</p>\n<pre><code>std::vector&lt;std::shared_ptr&lt;Connection&gt;&gt; connections() {\n std::lock_guard&lt;std::mutex&gt; lock(_mutex);\n std::vector&lt;std::shared_ptr&lt;Connection&gt;&gt; result;\n for (const auto&amp; weakConnection : _connections) {\n if (auto sptr = weakConnection.lock()) {\n result.push_back(std::move(sptr));\n }\n }\n return result;\n}\n</code></pre>\n<p>This avoids bumping the weak refcount by making <code>weakConnection</code> a reference instead of a copy, and then avoids bumping the strong refcount by using move instead of copy in <code>push_back</code>. Four atomic ops saved! (Not that this matters in real life, probably, but hey, welcome to Code Review.)</p>\n<hr />\n<pre><code>dispatch(_delegate-&gt;executor(),\n bind(&amp;ConnectionDelegate::didReceiveResponse, _delegate, shared_from_this()));\n</code></pre>\n<p>I find the use of <code>bind</code> confusing, but I don't know for sure (and actually hope someone will comment and enlighten me) — is <code>bind</code> <em>needed</em> here? It would certainly be clearer-to-read, faster-to-compile, and no-slower-at-runtime to write</p>\n<pre><code>dispatch(\n _delegate-&gt;executor(),\n [self = shared_from_this(), d = _delegate]() {\n d-&gt;didReceiveResponse(self);\n }\n);\n</code></pre>\n<p>This would make it a bit clearer what's actually being copied (one <code>shared_ptr</code> keeping <code>*this</code> alive, and one raw pointer). In fact, I wonder whether we even need to stash the copy of the raw pointer; could we get away with this instead?</p>\n<pre><code>dispatch(\n _delegate-&gt;executor(),\n [self = shared_from_this()]() {\n self-&gt;_delegate-&gt;didReceiveResponse(self);\n }\n);\n</code></pre>\n<p>Or do you expect that sometimes you'll get into the body of that lambda with <code>d != self-&gt;_delegate</code> and that's why you need the extra pointer?</p>\n<hr />\n<p>I also wonder whether it'd be possible to use <code>std::chrono::seconds</code> instead of <code>boost::posix_time::seconds</code>. Can Boost.Asio interoperate with C++11 <code>std::chrono</code> these days?</p>\n<hr />\n<pre><code>_connectionIterators[connection.get()] = _connections.insert(_connections.end(), connection);\n</code></pre>\n<p>I feel like the &quot;cleverness&quot; here is on the wrong side of the equals sign. <code>_connections.insert(_connections.end(), connection)</code> seems like a verbose way of writing <code>_connections.push_back(connection)</code>. Vice versa, I'm used to seeing people replace <code>map[k] = v</code> with <code>map.emplace(k, v)</code> for performance and clarity. Remember that <code>map[k] = v</code> first <em>default-constructs</em> <code>map[k]</code>, and then <em>assigns</em> a new value into it.</p>\n<p>Ah, I see, you need to use <code>insert</code> because <code>insert</code> returns an iterator and <code>push_back</code> doesn't.</p>\n<p>But that just raises the question: Why are you trying to shoehorn <em>two</em> side-effects into <em>one</em> line? If we're allowed two lines, we just do <code>push_back</code> and then set <code>map.emplace(connection.get(), std::prev(_connections.end()))</code>. Or, heck, at that point I wouldn't really complain about</p>\n<pre><code>auto it = _connections.insert(_connections.end(), connection);\n_connectionIterators.emplace(connection.get(), it);\n</code></pre>\n<p>Having spotted the red flag, dig deeper: what's the <em>difference</em> between the one-liner and the clearer two-liner? Aha! The difference is what happens if <code>_connections.insert(...)</code> runs out of memory and throws. With the two-liner, <code>_connectionIterators</code> remains untouched. With the one-liner, you <em>first</em> default-construct some dangerous garbage in <code>_connectionIterators[connection.get()]</code> and <em>then</em> propagate the exception.</p>\n<p>So I think there's a reasonable argument to be made in favor of the two-liner, just on general principles.</p>\n<hr />\n<p>Again, this answer doesn't really address your main concern about RAII, but I hope it gives some food for thought anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T20:36:13.007", "Id": "491670", "Score": "0", "body": "Thank you very much for your response. You're right that I am mostly interested in someone reviewing my Asio usage and handling of the lifetime of the connections. Nevertheless I still find your comments valuable, especially the points about explicit constructors, default destructors and executor() method. I will keep this question open in case some Asio expert will come across it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T22:16:05.087", "Id": "250450", "ParentId": "250341", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T21:34:56.647", "Id": "250341", "Score": "4", "Tags": [ "c++", "networking", "server", "boost", "raii" ], "Title": "Boost.Asio Server and RAII" }
250341
<p>Hi I just finished a VERY Basic airline reservation system. Wanted some feedback please let me know what you all think, if I am obfuscating information or passing parameters where I shouldn't or if things don't make sense</p> <p>Airline Class: handles booking and refunds<br /> Passenger: Has a seat assignment, and a balance to pay for ticket<br /> Seat:<br /> Firstclass and Coach<br /> Plane:<br /> a dictionary object holding seats and passengers get passed as values to those seats</p> <p>here is my code:</p> <pre><code>class Airline: def __init__(self, name=None): self._name = name self._booked = [] def get_name(self): return self._name def set_name(self, name): self._name = name def book(self, passenger, plane, cls=None): while cls not in ['first class', 'coach']: cls = input(&quot;Please pick a seat: First class or Coach &quot;).lower() if cls not in ['first class', 'coach']: print(&quot;Please select either from 'first class' or 'coach'&quot;) pass if cls == 'first class': first_class = ([(number, seat) for number, seat in enumerate(plane.capacity)][0:10]) choice = None while choice not in range(10): try: choice = int(input(f&quot;Please select a number between 0 and 9 for your seats: &quot;)) except ValueError: print(&quot;Please select a valid number between 0 and 9&quot;) if choice in self._booked: print(f&quot;That seat is taken please choose another seat\n&quot; f&quot;These seats are booked: {self._booked}&quot;) choice = None for seat in first_class: if seat[0] == choice: plane.capacity[seat[1]] = passenger passenger._balance = passenger._balance - seat[1].price self._booked.append(seat[0]) passenger._assignment = seat[1].tier + f&quot; seat {seat[0]}&quot; else: coach = ([(number, seat) for number, seat in enumerate(plane.capacity)][10:50]) choice = None while choice not in range(10, 50): try: choice = int(input(f&quot;Please select a number between 10 and 50 for your seats: &quot;)) except ValueError: print(&quot;Please select a valid number between 10 and 50&quot;) if choice in self._booked: print(f&quot;That seat is taken please choose another seat\n&quot; f&quot;These seats are booked: {self._booked}&quot;) choice = None for seat in coach: if seat[0] == choice: plane.capacity[seat[1]] = passenger passenger._balance = passenger._balance - seat[1].price self._booked.append(seat[0]) passenger._assignment = seat[1].tier + f&quot; seat {seat[0]}&quot; def refund(self, passenger, plane): for i, (seat, person) in enumerate(plane.capacity.items()): if person == passenger: plane.capacity[seat] = None passenger._balance = passenger._balance + seat.price passenger._assignment = None self._booked.remove(i) class Passenger: def __init__(self, balance=1000, assignment=None): self._balance = balance self._assignment = assignment def get_balance(self): return self._balance def get_assignment(self): return self._assignment class Seat: def __init__(self): pass class FirstClass(Seat): def __init__(self): super().__init__() self.tier = 'First Class' self.price = 500 class Coach(Seat): def __init__(self): super().__init__() self.tier = 'Coach' self.price = 100 class Plane: def __init__(self): self.capacity = {} temp_capacity = [] # Create a temporary list to append seats into ( this will be the seats in the airplane) for i in range(10): # first 10 seats are first class temp_capacity.append(FirstClass()) for i in range(10, 50): # last 40 seats are coach class temp_capacity.append(Coach()) for seat in temp_capacity: self.capacity[seat] = None # Each seat has no value(person) assigned def view_plane(self): for i, k in self.capacity.items(): print(f&quot;{i} : {k}&quot;) def get_available_seats(self): count = 0 for value in self.capacity.values(): if value is None: count += 1 return count </code></pre> <p>Running this below: (Will output how I envisioned the plane to be built and how seats are assigned to passengers, etc.)</p> <pre><code>plane = Plane() p = Passenger() p2 = Passenger() p3 = Passenger() airline = Airline() plane.view_plane() airline.book(p, plane) airline.book(p2, plane) print(airline._booked) print(f&quot;passenger 1 balance: {p.get_balance()}\n&quot; f&quot;passenger 1 assignment: {p.get_assignment()}\n&quot; f&quot;passenger 2 balance: {p2.get_balance()}\n&quot; f&quot;passenger 2 assignment: {p2.get_assignment()}\n&quot; f&quot;Number of seats available: {plane.get_available_seats()}\n&quot; f&quot;Number of seats booked: {len(airline._booked)}&quot;) plane.view_plane() airline.book(p3, plane) plane.view_plane() print(&quot;--------------&quot;) print(airline._booked) print(f&quot;passenger 1 balance: {p.get_balance()}\n&quot; f&quot;passenger 1 assignment: {p.get_assignment()}\n&quot; f&quot;passenger 2 balance: {p2.get_balance()}\n&quot; f&quot;passenger 2 assignment: {p2.get_assignment()}\n&quot; f&quot;passenger 3 balance: {p3.get_balance()}\n&quot; f&quot;passenger 3 assignment: {p3.get_assignment()}\n&quot; f&quot;Number of seats available: {plane.get_available_seats()}\n&quot; f&quot;Number of seats booked: {len(airline._booked)}&quot;) print(&quot;----------------&quot;) airline.refund(p2, plane) print(airline._booked) print(f&quot;passenger 1 balance: {p.get_balance()}\n&quot; f&quot;passenger 1 assignment: {p.get_assignment()}\n&quot; f&quot;passenger 2 balance: {p2.get_balance()}\n&quot; f&quot;passenger 2 assignment: {p2.get_assignment()}\n&quot; f&quot;passenger 3 balance: {p3.get_balance()}\n&quot; f&quot;passenger 3 assignment: {p3.get_assignment()}\n&quot; f&quot;Number of seats available: {plane.get_available_seats()}\n&quot; f&quot;Number of seats booked: {len(airline._booked)}&quot;) </code></pre> <p>Please let me know better ways to do this or better interfaces etc. I will be slowly adding more complexity but my main goal was having the airline be able to book and place passengers in the plane and refund them from their seat while updating the planes capacity during these changes.</p> <p>Will be adding multiple planes per airline which will undoubtedly change the structure of some of the classes but for right now let me know if what I have allows for the basic booking and refunding operations to work efficiently and if the classes are setup properly or what improvements can be made.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T12:33:59.413", "Id": "491230", "Score": "1", "body": "Nicely written code, very easy to follow. Good job" } ]
[ { "body": "<p>Nice implementation, it's easy to understand and well structured. Few suggestions:</p>\n<h2>Seat class</h2>\n<pre><code>class Seat:\n def __init__(self):\n pass\n\nclass FirstClass(Seat):\n def __init__(self):\n super().__init__()\n self.tier = 'First Class'\n self.price = 500\n\nclass Coach(Seat):\n def __init__(self):\n super().__init__()\n self.tier = 'Coach'\n self.price = 100\n</code></pre>\n<p>A <code>Seat</code> is supposed to have a tier and a price, but this information is not in the main class, only in the subclasses.</p>\n<p>Consider to add <code>tier</code> and <code>price</code> in the <code>Seat</code> constructor. I also suggest to add a number for the <code>Seat</code> class.</p>\n<p>Typically, the price of the seat is not bound to a tier forever. The price of a seat depends on the flight. For example, the same seat can have two different prices for two flights on the same day. Consider this when you will expand the design.</p>\n<h2>Passenger class</h2>\n<pre><code>class Passenger:\n\n def __init__(self, balance=1000, assignment=None):\n self._balance = balance\n self._assignment = assignment\n</code></pre>\n<ul>\n<li>A passenger should have at least a name, but most importantly an <code>id</code>.</li>\n<li>I am not sure why you use underscore variables here. Is because they are for internal use? But the class <code>Airline</code> uses them in the <code>book</code> method like <code>passenger._balance = ..</code>. Also the class <code>Seat</code> does not use underscore variables so I am a bit confused. Consider to use them consistently.</li>\n</ul>\n<h2>Book method</h2>\n<ul>\n<li><code>if choice in self._booked</code>: here <code>_booked</code> is a list that contains all the reserved seats for all the planes. What happens if there is a reservation for the same seat number of two different planes? Consider to associate the reservations to a plane or better to a <strong>flight</strong>.</li>\n<li><strong>Performance</strong>: at every reservation, a new <code>first_class</code> is created:\n<pre><code>if cls == 'first class':\n first_class = ([(number, seat) for number, seat in enumerate(plane.capacity)][0:10])\n</code></pre>\nThis is an expensive operation that can be avoided. Consider to create the first class in the plane and then request the result with a method.</li>\n<li><strong>Magic numbers and duplication</strong>:\n<pre><code>if cls == 'first class':\n first_class = ([(number, seat) for number, seat in enumerate(plane.capacity)][0:10])\n choice = None\n while choice not in range(10):\n try:\n choice = int(input(f&quot;Please select a number between 0 and 9 for your seats: &quot;))\n #...\nelse:\n coach = ([(number, seat) for number, seat in enumerate(plane.capacity)][10:50])\n choice = None\n while choice not in range(10, 50):\n try:\n choice = int(input(f&quot;Please select a number between 10 and 50 for your seats: &quot;))\n #...\n</code></pre>\nThe code to ask the user about tier and seat number is duplicated and there are some &quot;magic numbers&quot; like <code>while choice not in range(10)</code>. In this case 10 is the number of seats in the first class of the given plane. I think it should be a property of the <code>plane</code> that has a first class with a certain number of seats.\nYou can consider something like this:\n<pre><code>tier = plane.get_tier(cls) # tier is first class or coach\nchoice = None\nwhile choice not in tier.get_seats_range():\n try:\n choice = int(input(f&quot;Please select a number between {tier.get_seats_range()[0]} and {tier.get_seats_range()[1]} for your seats: &quot;)) \n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T06:28:16.150", "Id": "250352", "ParentId": "250343", "Score": "2" } }, { "body": "<p>Here is some minor things on the class Airline</p>\n<pre><code>class Airline:\n\n def __init__(self, name=None):\n self._name = name\n self._booked = []\n\n def get_name(self):\n return self._name\n\n def set_name(self, name):\n self._name = name\n</code></pre>\n<p>Is strange to me that you can have an airline that have no name, so I would recommend to make the argument name mandatory. Conceptually is more correct from my point of view.</p>\n<p>The other thing is that in python there is no concept of getters and setters, instead of that there is properties.</p>\n<pre><code>class Airline:\n\n def __init__(self, name):\n self._name = name\n self._booked = []\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T13:58:50.217", "Id": "250366", "ParentId": "250343", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-07T22:11:13.313", "Id": "250343", "Score": "3", "Tags": [ "python", "beginner", "object-oriented", "programming-challenge" ], "Title": "Beginner - OOP Project - Airline reservation system" }
250343
<p><em>for clarity: moved here from stackoverflow after being pointed to Code Review being the better place for this question</em></p> <p>I love async/await and Promises since I got my hands on them. And I might be overdoing it, but it feels like there should be a good and readable way to utilize async/await to get a little closer to a flow like, functionalISH programming style.</p> <p>I would love to not have to only use async/await to wait for web resources to come back but also to wait for user input when I await it.</p> <p>So far i have some code working similar to this shortened demo where I wrap a one time only EventListener into a Promise:</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>//// MAIN /////// (async function(){ //...do some async await stuff here... fetching stuff from a server // let services = await fetch(...) for example let services = [{url:"x",label:"1"},{url:"y",label:"2"},{url:"z",label:"3"}] let service_chosen = await showServicesToUserAndAwaitInput(services); console.log("service_chosen:",service_chosen); // ... go on.... })() //// END MAIN ///// async function showServicesToUserAndAwaitInput(services){ if (services.length &lt; 1){return null} let choice = null; let serviceList = document.querySelector("#serviceList"); // show list element serviceList.classList.remove("hidden") // create some elements for the user to interact with for (let service of services){ let button = document.createElement("BUTTON"); button.innerHTML = service.label; button.addEventListener("click",function(){ document.dispatchEvent( new CustomEvent('serviceChosen', { detail:service }) ) }); serviceList.appendChild(button); } // returns promise with one time only event listener return new Promise((resolve,reject)=&gt;{ document.addEventListener("serviceChosen",function(e){ serviceList.classList.add("hidden") // hide again for we are done resolve(e.detail) },{ once: true }) }) }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden{ visibility: hidden }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="serviceList" class="hidden"&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>But something about this use of the EventListener bugs me. Also: I use a promise that always resolves, which also seems strange.</p> <p>On the upside: I get to read the code top to bottom and can follow the user flow within the MAIN without having to chase down events, callbacks and so on.</p> <p>Yet, it feels like I am reinventing something somebody else might have already normed. So:</p> <p>Is there a better way to achieve this? Are there best practices to work with user interactions or other DOM events in a async and/or thenable way?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T07:05:22.123", "Id": "491200", "Score": "2", "body": "Usually events are not a good match for one-shot promises. If trying to make them work together, then you should be removing your event handler after it fires and you resolve the promise so it won't just accumulate and won't run this event handler code again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T09:12:53.370", "Id": "491207", "Score": "0", "body": "thank you! Good to know, yet: as mentioned in my comment to MauriceNino's answer:\nWhat is a good-match for DOM events and trying a more functional(ish) style code? Promises always seemed to me kinda better in that regard. e.g. in order to avoid too many side effects (as in cb hell or multiple EventListeners being open. Also: I thought the { once:true } parameter in my EventListener would do what you describe: close the listener after first call. Am I wrong with that, too? oh my..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T20:01:37.957", "Id": "491258", "Score": "0", "body": "Asynchronous event driven things do not translate to functional code. They just don't. And, trying to force a square peg into a round hole will just create a mess. Learn to use event driven programming for handling event driven stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T07:00:18.560", "Id": "491305", "Score": "0", "body": "@jfriend00 i understand your comments trajectory. But am left with a: What does learning event driven programming mean when I have to keep track with a very distinct and clear user flow (aka one thing after another) but have to solve it in an environment like javascript that is all about handling things async? Any suggestions, references what would be an orderly approach to event based programming?" } ]
[ { "body": "<p>First of all, I would not use Promises to do event based programming.\nIt is not used like that, so your code will get harder to follow.</p>\n<p>Also, I would advise you to split up your functions more and omit some comments that way.</p>\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>//// MAIN ///////\n\nlet services = [\n { url: \"x\", label: \"1\" },\n { url: \"y\", label: \"2\" },\n { url: \"z\", label: \"3\" },\n];\n\nshowServicesToUser(services);\n\n//// END MAIN /////\n\nconst serviceList = document.querySelector(\"#serviceList\");\n\nfunction createButtonFromService(service) {\n let button = document.createElement(\"BUTTON\");\n button.innerHTML = service.label;\n button.addEventListener(\"click\", function () {\n document.dispatchEvent(\n new CustomEvent(\"serviceChosen\", { detail: service })\n );\n });\n serviceList.appendChild(button);\n}\n\nfunction showServicesToUser(services) {\n if (services.length &lt; 1) return;\n\n serviceList.classList.remove(\"hidden\");\n\n for (let service of services) {\n createButtonFromService(service);\n }\n}\n\nfunction chooseService(service) {\n console.log(\"service_chosen:\", service);\n // ... go on....\n}\n\ndocument.addEventListener(\"serviceChosen\", function (e) {\n serviceList.classList.add(\"hidden\"); // hide again for we are done\n chooseService(e.detail);\n}, { once: true });</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.hidden{\n visibility: hidden\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"serviceList\" class=\"hidden\"&gt;\n\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>My proposed code above is written in a scripted kind of way, with a global variable (<code>serviceList</code>), but you could also write this all in a class (especially if you have more code), to make it more readable and reusable.</p>\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>class ServiceChooser {\n serviceListSelector;\n serviceList;\n services;\n\n constructor(serviceListSelector, services) {\n this.serviceListSelector = serviceListSelector;\n this.services = services;\n\n this.serviceList = document.querySelector(serviceListSelector);\n \n document.addEventListener(`serviceChosen${this.serviceListSelector}`, (e) =&gt; this.chooseService(e.detail), { once: true });\n }\n\n createButtonFromService(service) {\n let button = document.createElement(\"BUTTON\");\n\n button.innerHTML = service.label;\n button.addEventListener(\"click\", () =&gt; {\n const event = new CustomEvent(`serviceChosen${this.serviceListSelector}`, { detail: service });\n document.dispatchEvent(event);\n });\n\n this.serviceList.appendChild(button);\n }\n\n chooseService(service) {\n this.serviceList.classList.add(\"hidden\");\n console.log(\"service_chosen:\", service);\n // ... go on....\n }\n \n showServicesToUser() {\n if (this.services.length &lt; 1) return;\n\n this.serviceList.classList.remove(\"hidden\");\n\n for (let service of this.services) {\n this.createButtonFromService(service);\n }\n }\n}\n\n//// MAIN ///////\n\nlet services = [\n { url: \"x\", label: \"1\" },\n { url: \"y\", label: \"2\" },\n { url: \"z\", label: \"3\" },\n];\n\nconst sc = new ServiceChooser('#serviceList', services);\nsc.showServicesToUser();\n\n// now you could add 2 service choosers, sperate from each other\nconst sc2 = new ServiceChooser('#serviceList2', services);\nsc2.showServicesToUser();\n\n//// END MAIN /////</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.hidden{\n visibility: hidden\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"serviceList\" class=\"hidden\"&gt;\n\n&lt;/div&gt;\n&lt;div id=\"serviceList2\" class=\"hidden\"&gt;\n\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T09:08:41.487", "Id": "491206", "Score": "0", "body": "thank you. the splitting up makes a lot of sense to me. \nthe issue with the readability and clarity of the code does as well in some way but i wonder: How do I force myself within javascript to a more or less functional style (i mean: being able to read the main part of the code top to bottom with no side effects) considering DOM events being a thing in html and js?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T09:22:29.297", "Id": "491208", "Score": "1", "body": "it really depends on the size of the site you are working on and the kind of framework. I rarely use vanilla JS to write sites, but if I would, I would organize them into smaller scripts and build them together into one script. Then you would maybe have your event-handlers in one script and your functions for the service chooser in another one. I also really like the angular approach, where everything is bundled together per component. You could also emulate this, but with a bit more template code. @gauguerilla" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T07:01:19.887", "Id": "250354", "ParentId": "250351", "Score": "5" } }, { "body": "<p>You should use observables and the <a href=\"https://www.learnrxjs.io/learn-rxjs/operators\" rel=\"nofollow noreferrer\">myriad of functions</a> available for them. It's called <a href=\"https://gist.github.com/staltz/868e7e9bc2a7b8c1f754\" rel=\"nofollow noreferrer\">reactive programming</a>, but I think it might fall into the category of functional<em>ish</em>.</p>\n<p>An example from memory:</p>\n<pre><code>import { fromEvent, takeUntil } from 'rxjs';\n\n...\n\nconst eventListener = document.addEventListener('serviceChosen', () =&gt; console.log('chosen'));\n\nconst unsubscribe = new Subject();\n\nfromEvent(eventListener)\n .pipe(takeUntil(unsubscribe))\n .subscribe({\n next: event =&gt; {\n serviceList.classList.add('hidden');\n unsubscribe.next();\n unsubscribe.complete();\n }\n });\n</code></pre>\n<p>It may look a little bit overkill for a one-time action, however I think it's better than a promise, and in general you should use observables over promises. I would describe the difference as promises being &quot;active&quot; listeners as they expect to complete, while observable subscriptions are more &quot;passive&quot; since they may never get fired and don't expect to be, they're just setup to fire when they are needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T10:38:17.720", "Id": "491217", "Score": "1", "body": "wow. thank you so much. i never heard about reactive programming but it indeed seems to be what I am actually looking for and trying to describe with \"flow\", \"await\", \"functional(ish)\". that is indeed very helpful. Is rxjs the only implementation of observables in js? I think i stumbled upon the term first in the vue landscape but am not sure if it means the same thing or just happens to be a similar terminology (also never got it within using vue)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T13:02:16.790", "Id": "491232", "Score": "1", "body": "@gauguerilla I think Observables were originally made by rxjs. At this point rxjs is practically synonymous with javascript for any medium-sized to enterprise application. Even small applications benefit from some of its features. Many (all?) of the popular frameworks use rxjs under the hood in some capacity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T14:54:48.297", "Id": "491240", "Score": "1", "body": "checking rxjs now (and loosing a lot of time on it, oups), I must say: This is EXACTLY what I was looking for (and a lot more I dont quite grasp yet). So I will accept this as the answer to my question yet hoping that there are more people who have tipps/ best practises on this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:20:59.213", "Id": "491242", "Score": "0", "body": "@gauguerilla It is quite a hefty learning curve but in the end it's so worth it; so don't give up if you get stuck, keep looking to understand it deeper." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T17:01:34.000", "Id": "491251", "Score": "3", "body": "@gauguerilla To answer the question: Functional Reactive Programming was created by Conal Elliott and Paul Hudak for the Fran Functional Reactive Animation system in Haskell in 1997. Flapjax was a language for Functional Reactive Ajax that compiled to JavaScript. There were a couple of other languages and frameworks as well, but what we now understand as \"Reactive X\" or \"RxX\" (sort of \"OORP\" instead of \"FRP\") was first implemented by Erik Meijer and his team at Microsoft as \"Rx.NET\", shortly thereafter came RxJS (not sure if that also came out of Microsoft), and then many other." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T17:03:48.383", "Id": "491252", "Score": "0", "body": "There is a brilliant video with Rx.NET's creator Erik Meijer, which is actually not at all specific to .NET: https://channel9.msdn.com/Shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx It explains the *deep* mathematical relationship between looping over a collection and reacting to an event stream. (Spoiler: they are category theoretical duals, but both are monads, and thus they can be treated the same.) In the \"related videos\" section, there is also a video about the afore-mentioned Flapjax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T17:06:32.123", "Id": "491253", "Score": "1", "body": "And here's the original paper on FRP and Fran: http://conal.net/papers/icfp97/icfp97.pdf" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T21:19:13.273", "Id": "491264", "Score": "1", "body": "@gauguerilla do yourself a favor and never introduce rx.js into any project you want to work on with multiple people. The fact that there are \"a myriad\" of operators for rx observables is not a good thing. It means, whenever some of your colleagues finds a new smart way of solving one very particular problem with a fancy rx operator like `distinctUntilKeyChanged`, you'll have to read up on the documentation. Let alone the ridiculous bugs you'll get when people change the caching behavior of any subscriptions with things like `publishReplay`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T21:21:49.243", "Id": "491265", "Score": "1", "body": "Basically, whenever you want to onboard somebody new into your team, you'll have to explain to them that sadly, all their JS experience is essentially worthless because somebody decided to use rx.js and they will now have to spend hours and hours understanding your control flow from a badly documented complexity hell, which doesn't really solve anything you can't solve with vanilla js. \n\nAnd if you are ever forced to use rx.js, maybe because you inherited an angular project from someone, I'd strongly recommend to use e.g. eslint to forbid almost all operators except `map`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T07:01:26.510", "Id": "491306", "Score": "1", "body": "@FinnPoppinga i hear you. Writing \"exactly what I was looking for\" does (sadly) not translate in me using it in the project I came upon the issue. For exactly that reason: I am since yesterday going through some tutorials and would say: rxjs is a great tool, but it looks too complex and has too many impacts on the style of code that I would only use it in a project where I can make it front and center for all team members. It is sad in a way. The very basic concept of observables I find intriguing. But rxjs is indeed too mighty to be easy to (be) train(ed) in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:24:03.870", "Id": "491337", "Score": "1", "body": "@FinnPoppinga indeed, it's a skill unto itself, but I completely disagree with your assessment that it's bad for teams. It's bad for teams of weak developers under strict deadlines that don't have the time or the desire to develop their skills beyond basic imperative and functional programming. Like everything, it can be misused and done badly. I've seen my fair share of horrendous imperative and functional programming; no tool/framework/paradigm can account for poor judgement in programming." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T09:36:48.530", "Id": "250357", "ParentId": "250351", "Score": "4" } }, { "body": "<p>I agree it doesn't make sense to use promises with event-based programming and using observables is a good solution.</p>\n<p>On another note, it is recommended to default to using <code>const</code> instead of <code>let</code> for all variables as it can <a href=\"https://softwareengineering.stackexchange.com/q/278652/244085\">cause bugs</a>. When you determine re-assignment is necessary (mostly for loop/iterator variables) then use <code>let</code>.</p>\n<p>Another suggestion is to use a linter - e.g. <a href=\"https://eslint.org/\" rel=\"nofollow noreferrer\">ESLint</a>, <a href=\"https://jslint.com/\" rel=\"nofollow noreferrer\">JSLint</a>, etc. For example: lines like this would be caught for the ESLint rule <a href=\"https://eslint.org/docs/rules/key-spacing\" rel=\"nofollow noreferrer\"><em>key-spacing</em></a>:</p>\n<blockquote>\n<pre><code>new CustomEvent('serviceChosen', { detail:service })\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T14:07:50.390", "Id": "250367", "ParentId": "250351", "Score": "4" } } ]
{ "AcceptedAnswerId": "250357", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T06:18:48.750", "Id": "250351", "Score": "6", "Tags": [ "javascript", "functional-programming", "async-await", "promise", "ecmascript-8" ], "Title": "await user input with async/await syntax" }
250351
<p>I need to design a <a href="https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/generics/" rel="nofollow noreferrer">generic</a> &quot;<a href="https://martinfowler.com/eaaCatalog/unitOfWork.html" rel="nofollow noreferrer">Unit Of Work</a>&quot;, basically so that I can &quot;change the context of the Database&quot; only changing the implementation of <code>IUnitOfWork</code> on my DI container. I will exemplify below.</p> <p>So far, I have following solution:</p> <p><strong>IUnitOfWork.cs</strong></p> <pre><code>public interface IUnitOfWork { TTransactionType GetCurrentTransaction&lt;TTransactionType&gt;(); Task CommitAsync(CancellationToken cancellationToken); Task BeginTransactionAsync(CancellationToken cancellationToken); } </code></pre> <p><strong>UnitOfWorkMongoDB.cs</strong></p> <pre><code>public class UnitOfWorkMongoDB : IUnitOfWork { IClientSessionHandle _session; readonly IMongoDbContext _mongoDbContext; public UOLMongoDB(IMongoDbContext mongoDbContext) { _mongoDbContext = mongoDbContext; } public TTransactionType GetCurrentTransaction&lt;TTransactionType&gt;() =&gt; (TTransactionType)_session; public async Task CommitAsync(CancellationToken cancellationToken) { await _session.CommitTransactionAsync(); } public async Task BeginTransactionAsync(CancellationToken cancellationToken) { _session = await _mongoDbContext.MongoClient.StartSessionAsync(cancellationToken: cancellationToken); _session.StartTransaction(); } } </code></pre> <p><em><strong>DI Resolution</strong></em></p> <pre><code> services.AddScoped&lt;IUnitOfWork, UnitOfWorkMongoDB&gt;(); </code></pre> <p><em><strong>Using the solution</strong></em></p> <pre><code>public class MyServiceA { public MyServiceA(IUnitOfWork unitOfWork) { /*...*/ } } public class MyServiceB { public MyService(IUnitOfWork unitOfWork) { /*...*/ } } </code></pre> <p><strong>Considerations</strong></p> <ul> <li><p>The <code>IUnitOfWork</code> interface is not really generic, the only &quot;generic thing&quot; used, was <code>TTransactionType</code>, since each Database driver manufacturer has a different implementation of transaction handling. Like:</p> <ul> <li>MongoDB = <code>IClientSessionHandler.cs</code></li> <li>MySql = <code>MySqlTransaction.cs</code></li> <li>Oracle = <code>OracleTransaction.cs</code></li> </ul> </li> <li><p>The <code>IUnitOfWork</code> interface is non generic in attempt to avoid refactoring code when we change his implementation on D.I resolution.</p> </li> </ul> <p><em>Samples with non generic <code>IUnitOfWork</code>:</em></p> <pre><code> services.AddScoped&lt;IUnitOfWork, UnitOfWorkPostgreSQL&gt;(); //OR services.AddScoped&lt;IUnitOfWork, UnitOfWorkOracle&gt;(); //OR services.AddScoped&lt;IUnitOfWork, UnitOfWorkMySQL&gt;(); //OR </code></pre> <p>Dependencies not break:</p> <pre><code>public class MyServiceA { public MyServiceA(IUnitOfWork unitOfWork) { /*...*/ } } </code></pre> <ol start="3"> <li>&quot;Problems&quot; with with a generic <code>IUnitOfWork&lt;TUnitOfWork&gt;</code>.</li> </ol> <p>If we change the resolution on D.I, all services dependecies will break, like:</p> <pre><code>services.AddScoped&lt;IUnitOfWork&lt;UnitOfWorkPostgreSQL&gt;, UnitOfWorkPostgreSQL&gt;(); </code></pre> <p>On <code>MyServiceB.cs</code> for example, before he depends of <code>IUnitOfWork&lt;UnitOfWorkMongoDB&gt;</code> and now, my D.I container not solves it. This can cause several changes on application code base.</p> <pre><code>public class MyServiceB { public MyServiceB(IUnitOfWork&lt;UnitOfWorkMongoDB&gt; unitOfWork) { /*...*/ } } </code></pre> <p>I still feel uncomfortable with the explicit conversion <code>(TTransactionType)_session;</code> on <code>GetCurrentTransaction&lt;TTransactionType&gt;()</code> method, is there any other approach to make this method? Or am I worrying too much?</p> <p>What do you think can be improved in this solution? Any evaluation/improvement is welcome!</p> <p>P.S I created a little repo with this implementation <a href="https://github.com/igorgomeslima/MongoDB.RepositoryPattern.With.Transaction" rel="nofollow noreferrer">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T08:54:09.680", "Id": "491204", "Score": "0", "body": "This looks very abstract. Have you used this in an actual project yet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:53:08.967", "Id": "491248", "Score": "0", "body": "@Mast I'm beggining an project with this now. When you say \"This looks very abstract\" it's a good or bad point?(rofl) Thanks for your comment! :)" } ]
[ { "body": "<p>I have some doubts about the way you choose to implement &quot;unit of work&quot;. By definition, this pattern is an abstraction <em>between</em> the database access layer and business logic. Which means that the &quot;unit of work&quot; should not have database code. Having database-specific implementation of the &quot;unit of work&quot; is an indication of wrong approach.</p>\n<p><a href=\"https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application</a></p>\n<blockquote>\n<p>The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store ...</p>\n</blockquote>\n<p>Means that you change the data store and keep the business logic and &quot;unit of work&quot; intact.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T02:45:36.950", "Id": "491296", "Score": "0", "body": "The `Unit Of Work` not contains any bussiness logic. The question is specific to `Unit Of Work`, and this implementation not contais any business logic. The repositories they are treated at another level of abstraction. Implementations only solves a \"driver transactions\" questions, like: `BeginTransaction`, `Commit`, etc. Please, see the link that I had put on question: UoW: \"Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.\" - https://martinfowler.com/eaaCatalog/unitOfWork.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T09:46:54.097", "Id": "491319", "Score": "0", "body": "> \"The Unit Of Work not contains any bussiness logic.\"\n\nExactly. But it does not contain any DB-specific code either. It is like a staging section in git - these files are selected for commit but not yet committed.\n\n> \"Maintains a list of objects affected by a business transaction\"\n\nso where is this list of objects in your implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T22:51:16.487", "Id": "491387", "Score": "0", "body": "\"so where is this list of objects in your implementation?\" The \"Transaction Scope\" has this objects. Created a repository and now put it on question. Please, see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T22:56:27.697", "Id": "491389", "Score": "0", "body": "And please, not down vote the question!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T01:48:36.707", "Id": "250388", "ParentId": "250353", "Score": "0" } }, { "body": "<p>This is pretty abstract and might be a better fit over in Software Engineering or Stack Overflow.</p>\n<p>I'm going to leave out if this is a good idea. I don't use repos hardly anymore but only you know if that's required. I think for simple projects they are fine but there are better patterns for more complex projects, IMO.</p>\n<p>I don't like the generic as there is no guard on what I can cast it to. What I can't tell from your code is how having this generic wouldn't also prevent code changes needing to happen. For example if injecting IUnitOfWork then in middle of save I have a call to GetCurrentTransaction and now I'm switching to SQL that line of code needs to change and what's worst right now is the compiler wouldn't tell you that and would just get an exception at runtime. Yuck.</p>\n<p>I think you need to think about what you all need from each implementation of their transaction and create a common interface and adapt each one to that interface and not directly interact with the providers interface directly in your unit of work. If you need RollBack then add that to the interface and adapt each one to that interface.</p>\n<p>You can look at lots of ORMs they do this exact same thing where they work with multiple db engines but have a common way to deal with saving/updating and transactions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T02:53:26.670", "Id": "491583", "Score": "0", "body": "Hey @Charles! You read the [READ.md](https://github.com/igorgomeslima/MongoDB.RepositoryPattern.With.Transaction#-final-considerations) of git repo question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T02:53:52.037", "Id": "491584", "Score": "0", "body": ">`For example if injecting IUnitOfWork then in middle of save I have a call to GetCurrentTransaction and now I'm switching to SQL that line of code needs to change`< Your affirmation is wrong. If we switched the implementation from IUnitOfWork to a new database type we would not need to change the `GetCurrentTransaction` method because the one who calls it are the [`repositories`](https://bit.ly/3nFfZDz) and each database has a different implementation over the commands, that is, each has its own syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T02:57:15.203", "Id": "491585", "Score": "0", "body": "First no I didn’t. A good question on code review should not have to follow links to get understanding. Second even so that doesn’t invalidate that there is no constraints and looking at what other ORNs do." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T00:50:28.993", "Id": "250492", "ParentId": "250353", "Score": "0" } }, { "body": "<p>Trying to not promote low-level transaction implementation in initial design,\nIDbContext is the place for db-transactions.</p>\n<pre><code> public interface IDbContext \n {\n void Commit();\n void Rollback(); \n } \n</code></pre>\n<blockquote>\n<p>Using “Generics” to implement “Unit Of Work”</p>\n</blockquote>\n<pre><code>public interface IUnitOfWork&lt;T&gt; where T: IDbContext\n{\n T DbContext { get; }\n}\n</code></pre>\n<p>Now the async version of IUnitOfWork</p>\n<pre><code>public interface IAsyncUnitOfWork: IUnitOfWork&lt;IDbContext&gt; \n{ \n Task CommitAsync(CancellationToken cancellationToken);\n Task BeginTransactionAsync(CancellationToken cancellationToken);\n}\n</code></pre>\n<p>Trying to implement abstract system with our setup.</p>\n<pre><code>public abstract class AbstractUnitOfWork: IAsyncUnitOfWork \n{\n public abstract IDbContext DbContext {get; set; }\n \n public AbstractUnitOfWork(IDbContext context)\n {\n DbContext = context;\n }\n \n public abstract Task BeginTransactionAsync(CancellationToken cancellationToken);\n public abstract Task CommitAsync(CancellationToken cancellationToken);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T03:05:00.440", "Id": "491587", "Score": "0", "body": "Thanks for your answer! In the GitHub link solution, I tried to bring the responsibility of managing a transaction to my [`DbContext`](https://bit.ly/2GXTyso) Please see it. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T01:08:38.483", "Id": "250493", "ParentId": "250353", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T06:48:50.730", "Id": "250353", "Score": "0", "Tags": [ "c#", "generics", "interface" ], "Title": "Using \"Generics\" to implement \"Unit Of Work\"" }
250353
<p>I've written a function that reads and returns one UTF-8 code point from an istream. I am wondering if the code is efficient or if there are some obvious problems with the implementation.</p> <pre class="lang-cpp prettyprint-override"><code>chr_t utf32::get_utf32_char(std::istream &amp;in_stream) { int next; chr_t out = in_stream.get(); if (out == -1 || out &lt; 0x80) { return out; } else if ((out &amp; 0xe0) == 0xc0) { out &amp;= 0x1f; out &lt;&lt;= 6; next = in_stream.get(); if (next == -1) goto invalid_seq; out |= next &amp; 0x3F; return out; } else if ((out &amp; 0xf0) == 0xe0) { out &amp;= 0x0f; out &lt;&lt;= 12; next = in_stream.get(); if (next == -1) goto invalid_seq; out |= (next &amp; 0x3F) &lt;&lt; 6; next = in_stream.get(); if (next == -1) goto invalid_seq; out |= next &amp; 0x3F; return out; } else if ((out &amp; 0xf8) == 0xf0) { out &amp;= 0x07; out &lt;&lt;= 18; next = in_stream.get(); if (next == -1) goto invalid_seq; out |= (next &amp; 0x3F) &lt;&lt; 12; next = in_stream.get(); if (next == -1) goto invalid_seq; out |= (next &amp; 0x3F) &lt;&lt; 6; next = in_stream.get(); if (next == -1) goto invalid_seq; out |= next &amp; 0x3F; return out; } else { throw std::runtime_error(&quot;invalid utf8 character&quot;); } invalid_seq: throw std::runtime_error(&quot;unexpected end of utf8 sequence&quot;); } </code></pre>
[]
[ { "body": "<h2>Overview</h2>\n<p>There is a lot of repeated code that could be removed by use of functions.</p>\n<p>When bittwiddling like this it would be nice for a human readable explanation of what you are doing. I had to look up the unicode spec to make sure you were doing it correctly.</p>\n<p>A lot of UTF-8 files (stream) contain a BOM marker <code>0xEF, 0xBB, 0xBF</code> as the first code point. This is not part of the text stream and should be discarded if it exists. Though you may do this at the layer of abstraction above this in which case a comment pointing out that the BOM marker is not removed should be added.</p>\n<p>You don't validate that the bytes 2 through 4 have the correct pattern for UTF-8 you just make that assumption.</p>\n<p>You use exceptions on streams. Normally you would mark the stream as bad and return. The user of the stream is supposed to check the state of the stream before using any output (and further reading will fail).</p>\n<p>C++ uses <code>operator&gt;&gt;</code> to read from a stream. It would be nice to be able to read your characters using this operator.</p>\n<h2>Code Review</h2>\n<p>The name of the function is not quite correct:</p>\n<pre><code>chr_t utf32::get_utf32_char(std::istream &amp;in_stream)\n</code></pre>\n<p>Code points are distinct from there encoding. You are converting an code point that was encoding UTF-8 into UCS-4 (not UTF-32). UTF-32 is another encoding format used for transportation. I would note that UCS-4 and UTF-32 look the same but they are not the same thing.</p>\n<hr />\n<p>You read into <code>next</code> (an int) in all locations apart from here:</p>\n<pre><code> int next;\n chr_t out = in_stream.get();\n</code></pre>\n<p>Why not be consistent. I especially worry about corner case and auto conversions with characters and integers. Can't think of anything that would go wrong but why risk it. Read into <code>next</code> (the int) check for EOF then convert to your character representation.</p>\n<hr />\n<p>Don't use magic numbers. In this context you should use EOF (not -1).</p>\n<pre><code> if (out == -1 || out &lt; 0x80) {\n return out;\n</code></pre>\n<hr />\n<p>I hate <code>else</code> on the same line as <code>}</code>.</p>\n<pre><code> } else if ((out &amp; 0xe0) == 0xc0) {\n</code></pre>\n<p>But your code your style.<br />\nVery few coding standards use this system.</p>\n<p>In my opinion (so ignorable) you don't need to crush the code together that much. Extra vertical spacing will make the code easier to read.</p>\n<hr />\n<p>Questionablt use of <code>goto</code>:</p>\n<pre><code> if (next == -1) goto invalid_seq;\n</code></pre>\n<p>Why not simply:</p>\n<pre><code> if (next == EOF) {\n throw std::runtime_error(unexpectedESFMessage);\n }\n</code></pre>\n<hr />\n<h2>Redesign:</h2>\n<p>I would have used a more data driven approach:</p>\n<pre><code>struct Encoding\n{\n char mask;\n char value;\n int extra;\n};\nEncoding const utf8Info[] = { \n {0x80, 0x00, 0}\n {0xE0, 0xC0, 1}\n {0xF0, 0xE0, 2}\n {0xF8, 0xF0, 3}\n };\nchr_t decodeUtf(std::istream&amp; stream, chr_t result, int count)\n{\n for(; count; --count) {\n int next = stream.get();\n if (next &amp; 0xC0 != 0x80) {\n // Not a valid continuation character\n stream.setstate(std::ios::badbit)\n return -1;\n }\n result = (result &lt;&lt; 6) | (next &amp; 0x3F);\n }\n return result;\n} \nchr_t getCodePoint(std::istream&amp; stream)\n{\n // NOTE: Does not remove any initial BOM marker.\n\n int next = stream.get();\n if (next == EOF) {\n return -1;\n }\n for(auto const&amp; type: utf8Info) {\n if ( next &amp; type.mask == type.value ) {\n return decodeUtf(stream, next &amp; ~type.mask, type.extra);\n }\n }\n // Not a valid first character\n stream.setstate(std::ios::badbit)\n return -1;\n}\n\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; str, chr_t&amp; out)\n{\n chr_t tmp = getCodePoint(str);\n if (str) {\n out = tmp;\n }\n return str;\n}\n</code></pre>\n<p>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T12:09:35.847", "Id": "491226", "Score": "0", "body": "One small mistake i noticed was that `decodeUtf(stream, next & type.mask, type.extra)` would first need to negate the mask (`~type.mask`) cause otherwise you're taking the encoding bits instead of the data bits. other than that, this works perfectly! thank you very much :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T20:44:07.377", "Id": "491261", "Score": "1", "body": "@IanRehwinkel Fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T11:36:00.583", "Id": "250364", "ParentId": "250359", "Score": "2" } } ]
{ "AcceptedAnswerId": "250364", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T09:53:41.137", "Id": "250359", "Score": "2", "Tags": [ "c++", "utf-8" ], "Title": "A C++ function to read Code Points from an UTF-8 Stream" }
250359
<p>Discovering sk-learn pipelines (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html</a>) made me wonder why weren't I using the same idea for any set of functions applied to a single main argument. Based on this idea I developed the following code (Using kwargs treatment from <a href="https://stackoverflow.com/a/58543357">https://stackoverflow.com/a/58543357</a>):</p> <pre><code>import inspect def create_sequential_pipe(func_list): &quot;&quot;&quot; Create a pipeline for a series of functions to be applied to a single main argument Args: func_list: List of functions &quot;&quot;&quot; def sequential_pipe(main_arg, **kwargs): for func in sequential_pipe._func_list: func_args = [k for k, v in inspect.signature(func).parameters.items()] func_dict = {k: kwargs.pop(k) for k in dict(kwargs) if k in func_args} main_arg = func(main_arg, **func_dict) return main_arg sequential_pipe._func_list = func_list return sequential_pipe def example_func_1(n, power=1): return n ** power def example_func_2(n, sum=0): return n + sum def example_func_3(n, divide=1): return n / divide if __name__ == &quot;__main__&quot;: example_pipe= create_sequential_pipe([example_func_1, example_func_2, example_func_3]) out = example_pipe(2) print(out) # 2.0 out = example_pipe(2, power=2, sum=1, divide=5) print(out) # 1.0 </code></pre> <p>I feel I could get used to its use, but I couldn't find something similar already implemented in Python, so I feel there must be a downside I am not seeing.</p> <p>I could just create a wrapper function for the pipeline of functions, but I'm not sure it would be as simple. Is there something similar commonly used in other languages? Do you think it's obfuscates the code? Are there clear downsides to using this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T10:36:05.013", "Id": "491215", "Score": "0", "body": "Hi, I would appreciate if I could know the reason for the downvote, so I might update the question and make it more adequate. Receiving a silent downvote isn't useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T12:09:45.390", "Id": "491227", "Score": "3", "body": "Welcome to Code Review, you are correct, whoever down voted should have left a comment. I'm only guessing about why they down voted but there could be 2 reasons, the first is the title and the second is the question seems a little hypothetical due to the function names used. The answer to the question `What does the code do?` should be clearly stated in either the title or in a text section above the code, then follow that with your concerns about the code. Please see [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask) for more ideas on improvements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T13:32:55.877", "Id": "491235", "Score": "3", "body": "That's useful, thanks! I'll try to improve those points" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T16:00:37.363", "Id": "491363", "Score": "0", "body": "I think your self-answer can safely be un-deleted - any answer that contains at least one material piece of feedback is on-topic. Also, though your question is on the precipice of being closed, I think you've done a good enough job of editing it that it's now basically on-topic." } ]
[ { "body": "<p>Without being familiar in use of <code>sklearn</code>, there are still some Python fundamentals that can be improved:</p>\n<h2>Superfluous comprehension</h2>\n<pre><code>func_args = [k for k, v in inspect.signature(func).parameters.items()]\n</code></pre>\n<p>can probably be</p>\n<pre><code>func_args = inspect.signature(func).parameters.keys()\n</code></pre>\n<p>assuming that <code>parameters</code> has the interface of a regular dictionary. Also, since you're only using it to test membership, wrap it in a call to <code>set()</code>.</p>\n<h2>Set intersection</h2>\n<p>If you do the above and make <code>func_args</code> a set, then this:</p>\n<pre><code>for k in dict(kwargs) if k in func_args\n</code></pre>\n<p>can be replaced by <code>set(kwargs.keys()) &amp; func_args</code>.</p>\n<h2>Non-repeatable read</h2>\n<p>There's a potential issue with your use of <code>pop()</code>. This modifies your <code>kwargs</code> in a loop. Are you sure that you want a given <code>kwarg</code> to only apply to one function in your pipe, and not all of them?</p>\n<h2>Real tests</h2>\n<p>Convert this:</p>\n<pre><code>example_pipe= create_sequential_pipe([example_func_1, example_func_2, example_func_3])\n\nout = example_pipe(2)\nprint(out) # 2.0\n\nout = example_pipe(2, power=2, sum=1, divide=5)\nprint(out) # 1.0\n</code></pre>\n<p>into an actual unit test - you're already most of the way there, so you might as well.</p>\n<h2>Variadic function</h2>\n<pre><code>create_sequential_pipe(func_list):\n</code></pre>\n<p>is a good candidate for being turned into a variadic function, i.e. accepting <code>*func_list</code>. This will make invocation simpler in some cases, including the one you showed at the bottom - there will be no need for an inner list literal.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T16:07:39.030", "Id": "250429", "ParentId": "250360", "Score": "1" } } ]
{ "AcceptedAnswerId": "250429", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T10:23:50.843", "Id": "250360", "Score": "1", "Tags": [ "python" ], "Title": "Defining pipelines of functions when passing a main argument across multiple functions" }
250360
<p>I am working on a finite element (FE) code and want to provide multiple material models (20+). In FE applications, the computational domain is subdivided into a set of geometrically simple elements, e.g. tetrahedra or hexahedra. I use <code>Worker</code>s that carry elementwise computations sing a given material model. Depending on the used material (e.g. compressible vs incompressible) we might end up using different <code>Worker</code> classes, requiring different interface from the material models.</p> <p>Some of the used material models are meta models and internally use other material models. A good example is the so-called maxwell element which is composed of an elastic spring and a dashpot. We would model the spring using an already existing material model from our library. The problem is that such meta models require an interface of the material model which might be different to the one required by the <code>Worker</code>s.</p> <p>In my current attempt <strong>I am using multiple inheritance (MI)</strong> in order to implement the different interfaces. Usually I try to avoid MI, but I have't found a better solution.</p> <p>I use factories to create models and worker objects, returning the base classes <code>ModelABC</code> and <code>WorkerABC</code>, respectively. The concrete classes <code>Worker1</code> and <code>Worker2</code> define required interfaces from the material models, namely <code>Worker*::IModel</code>. Similarly, the <code>MetaModel</code> class also defines an interface <code>MetaModel::IModel</code>. Now, the elementary material models <code>Material1</code> and <code>Material2</code> inherit the interfaces which I want them to implement (sometimes it physically does not make sense for a model to implement a certain functions, e.g an anisotropic material should not use functions which require isotropy). Here is a <a href="https://godbolt.org/z/s5n8EG" rel="nofollow noreferrer">demo</a> of the code below.</p> <pre><code>#include &lt;memory&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cassert&gt; class ModelABC; class WorkerABC { public: virtual ~WorkerABC() = default; void evaluate_cell (/*args*/) const {this-&gt;evaluate_cell_impl(/*args*/);}; private: virtual void evaluate_cell_impl(/*args*/) const = 0; }; class Worker1: WorkerABC { public: class IModel { public: double get_stress (const double x) const {return this-&gt;get_stress_impl (x);} virtual ~IModel() = default; private: virtual double get_stress_impl (const double x) const = 0; }; Worker1 (ModelABC* m); virtual ~Worker1() = default; private: void evaluate_cell_impl (/*args*/) const override {/*uses get_stress*/} std::unique_ptr&lt;IModel&gt; model; }; class Worker2 : public WorkerABC { public: class IModel { public: double get_stress (const double x) const {return this-&gt;get_stress_impl (x);} double get_pressure (const double x) const {return this-&gt;get_pressure_impl (x);} virtual ~IModel() = default; private: virtual double get_stress_impl (const double x) const = 0; virtual double get_pressure_impl (const double x) const = 0; }; Worker2 (ModelABC* m); virtual ~Worker2() = default; private: void evaluate_cell_impl (/*args*/) const override {/*uses get_stress and get_pressure*/} std::unique_ptr&lt;IModel&gt; model; }; // Have to use this class. class ParameterHandler { public: ParameterHandler(const std::string &amp;s): id(s) {} virtual ~ParameterHandler () = default; const std::string&amp; get_id() const {return id;} // parse, declare, write parameters etc. private: std::string id; }; // Abstract Model base class needed for factories. class ModelABC: public ParameterHandler { public: // some common functions ModelABC(const std::string &amp;s): ParameterHandler(s) {} virtual ~ModelABC() = default; }; class MetaModel: public Worker2::IModel, public ModelABC { public: class IModel { public: double get_energy (const double x) const {return get_energy_impl(x);} virtual ~IModel() = default; private: virtual double get_energy_impl(const double) const = 0; }; MetaModel (const std::string &amp;s, ModelABC* m) : ModelABC(s), model(dynamic_cast&lt;IModel*&gt;(m)) { if (model == nullptr) throw; std::cout &lt;&lt; &quot;Meta model uses: &quot; &lt;&lt; m-&gt;get_id() &lt;&lt; std::endl; }; virtual ~MetaModel() = default; private: double get_stress_impl (const double x) const override {return x*x;}; double get_pressure_impl (const double x) const override {return model-&gt;get_energy(x)/x;}; std::unique_ptr&lt;IModel&gt; model; }; // Can only be used by Worker class Model1: public ModelABC, public Worker1::IModel { public: Model1(const std::string &amp;s): ModelABC(s) {} virtual ~Model1() = default; private: double get_stress_impl(const double x) const override {return x;} }; // Can be used by MetaModel, and Worker2 class Model2: public ModelABC, public Worker2::IModel, public MetaModel::IModel { public: Model2(const std::string&amp; s): ModelABC(s) {} virtual ~Model2() = default; private: double get_stress_impl(const double x) const override {return 2*x;} double get_pressure_impl(const double x) const override {return x;} double get_energy_impl(const double x) const override {return 4*x*x;} }; // example.cc inline Worker1::Worker1 (ModelABC* m) : model(dynamic_cast&lt;IModel*&gt;(m)) { if(model == nullptr) throw; std::cout &lt;&lt; &quot;Created Worker with ModelABC: &quot; &lt;&lt; m-&gt;get_id() &lt;&lt; std::endl; } inline Worker2::Worker2 (ModelABC* m) : model(dynamic_cast&lt;IModel*&gt;(m)) { if(model == nullptr) throw; std::cout &lt;&lt; &quot;Created Worker with ModelABC: &quot; &lt;&lt; m-&gt;get_id() &lt;&lt; std::endl; } </code></pre> <p>What do you think about the use of MI in the above case? Is it a bad design choice?</p>
[]
[ { "body": "<p>Incidentally, kudos to you for using the Non-Virtual Interface idiom! (For readers who don't know what it is, see <a href=\"https://quuxplusone.github.io/blog/2019/08/02/the-tough-guide-to-cpp-acronyms/#nvi\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://quuxplusone.github.io/blog/2019/10/18/quotable-cppcon-talks/#jon-kalb-back-to-basics-object-o\" rel=\"nofollow noreferrer\">here</a>.)</p>\n<p>To a first approximation, I would say that multiple inheritance is <em>usually</em> a bad design choice, so it probably is bad in this case as well.</p>\n<p>Looking a bit closer, I don't see the point of <code>ModelABC</code> in this architecture. You have <code>ModelABC</code> so that all models can inherit from a single base class... but inheritance should be used only when the base class is useful in its own right as a polymorphic interface. The reason to have an <code>AnimalABC</code> base class is that you're going to be writing a lot of polymorphic (generic) code that operates on polymorphic (generic) animals via that common <code>AnimalABC</code> API. If all your code is either specific to <code>Cat</code>s or specific to <code>Dog</code>s, then you don't need them to inherit from <code>AnimalABC</code> because that common API isn't buying you anything.</p>\n<hr />\n<p>Seems like the constructor <code>Worker1(ModelABC*)</code> should be <code>Worker1(Worker1::IModel*)</code> instead. Either you're calling it like</p>\n<pre><code>Model1 m1; // implements Worker1::IModel and also ModelABC\nWorker1 w1(&amp;m1);\n</code></pre>\n<p>in which case the conversion-to-base followed by <code>dynamic_cast</code>-back-to-<code>IModel</code> is harmless but slow; or else you're calling it like</p>\n<pre><code>ModelABC&amp; m = ...; // comes from somewhere else\nWorker1 w1(&amp;m);\n</code></pre>\n<p>in which case it's still arguably better to push the <code>dynamic_cast</code> into the caller:</p>\n<pre><code>ModelABC&amp; m = ...; // comes from somewhere else\nWorker1 w1(&amp;dynamic_cast&lt;Worker1::IModel&amp;&gt;(m)); // throw bad_cast on failure\n</code></pre>\n<p>This looks ugly, because it <em>should</em> look ugly: this caller has a model-it-doesn't-know-what-it-is, and it's trying to create a <code>Worker1</code> despite <code>Worker1</code> being unable to deal with certain kinds of models. We should deal with this ugliness by pushing the <code>dynamic_cast</code> even higher up. This relates to the mantra <strong>&quot;Make invalid states unrepresentable.&quot;</strong> If <code>Worker1</code> can't deal with anything but <code>Worker1::IModel*</code>, then you statically shouldn't be able to pass it anything but <code>Worker1::IModel*</code>.</p>\n<hr />\n<p>Ownership is unclear here. We create a <code>Worker</code> by passing it a pointer to a <code>Model</code>. From my background knowledge, I would assume that you'll have many workers all working on one model, and so no single worker <em>owns</em> the model; they all <em>observe</em> it. It seems reasonable to guess that perhaps the <em>model</em> should own its <em>workers!</em></p>\n<p>If that's the case, then the problem gets easy, because you can put the model in charge of creating the exact kind of workers it wants.</p>\n<pre><code>// Old code\nModel1 m1;\nm1.addWorker(std::make_unique&lt;Worker1&gt;(&amp;m1));\nm1.addWorker(std::make_unique&lt;Worker1&gt;(&amp;m1));\nModel2 m2;\nm2.addWorker(std::make_unique&lt;Worker2&gt;(&amp;m2));\nm2.addWorker(std::make_unique&lt;Worker2&gt;(&amp;m2));\n\n// New code\nModel1 m1;\nm1.addWorkers(2); // Model1::addWorkers knows to create workers of type Worker1\nModel2 m2;\nm2.addWorkers(2); // Model2::addWorkers knows to create workers of type Worker2\n</code></pre>\n<p>Don't bother <code>main</code> with decisions like &quot;what kind of Workers&quot; and then risk rejection in the <code>dynamic_cast</code>. Follow the classical OOP principle of <em>asking the object</em> to create workers, since <em>the object</em> is the one who understands how to do it.</p>\n<pre><code>class Model1 {\n void addWorker(std::unique_ptr&lt;Worker1&gt;);\npublic:\n void addWorkers(int n) {\n for (int i=0; i &lt; n; ++i) {\n addWorker(std::make_unique&lt;Worker1&gt;(this));\n }\n }\n};\nclass Model2 {\n void addWorker(std::unique_ptr&lt;Worker2&gt;);\npublic:\n void addWorkers(int n) {\n for (int i=0; i &lt; n; ++i) {\n addWorker(std::make_unique&lt;Worker2&gt;(this));\n }\n }\n};\n</code></pre>\n<p>Once you've done that, you <em>might</em> discover that &quot;creating some workers for yourself&quot; is an operation that would be useful in polymorphic contexts, when you don't know statically what kind of model you're dealing with. <em>That</em> would be the time to bring back the base class <code>ModelABC</code>, so that you could make <code>addWorkers</code> a virtual function:</p>\n<pre><code>class ModelABC {\n virtual void do_addWorkers(int);\npublic:\n void addWorkers(int n) { do_addWorkers(n); }\n};\n\nclass Model2 : public ModelABC {\n void addWorker(std::unique_ptr&lt;Worker2&gt;);\n void do_addWorkers(int n) override {\n for (int i=0; i &lt; n; ++i) {\n addWorker(std::make_unique&lt;Worker2&gt;(this));\n }\n }\n};\n</code></pre>\n<p>However, you should do that <em>only if you need to call <code>model.addWorkers(n)</code> in a polymorphic context!</em> If you are only ever calling <code>addWorkers</code> on an object whose dynamic type matches its static type — <code>Model1</code> or <code>Model2</code> — then you don't need polymorphism and <code>virtual</code> here.</p>\n<hr />\n<p>In fact, when I showed the new code as</p>\n<pre><code>// New code\nModel1 m1;\nm1.addWorkers(2); // Model1::addWorkers knows to create workers of type Worker1\nModel2 m2;\nm2.addWorkers(2); // Model2::addWorkers knows to create workers of type Worker2\n</code></pre>\n<p>maybe I should have said</p>\n<pre><code>Model1 m1;\nm1.addWorker1s(2);\nModel2 m2;\nm2.addWorker2s(2);\n</code></pre>\n<p>As shown, there is no reason for <code>Model1::addWorker1s</code> and <code>Model2::addWorker2s</code> to have the same function name. The only reason to give two things the same name is if you're planning to call them from <em>generic</em> (templated) code!</p>\n<pre><code>template&lt;class M&gt;\nstd::shared_ptr&lt;M&gt; createWithTwoWorkers() {\n auto model = std::make_shared&lt;M&gt;();\n model-&gt;addWorkers(2);\n return model;\n}\n\nstd::shared_ptr&lt;Model1&gt; m1 = createWithTwoWorkers&lt;Model1&gt;();\nstd::shared_ptr&lt;Model2&gt; m2 = createWithTwoWorkers&lt;Model2&gt;();\n</code></pre>\n<p>If you're not planning to send <code>Model1</code> and <code>Model2</code> down the same generic codepath like this, then there's really no reason for their APIs even to have any <em>names</em> in common.</p>\n<hr />\n<p>That last bit of advice might go too far for your taste. ;) But the point to take away is: Introduce polymorphism/genericity/overloading <em>when</em> it is useful, and <em>only</em> when it is useful. The reader should always be able to say, &quot;I understand why this base class is here,&quot; or &quot;I understand why these two classes' member functions have the same name,&quot; or &quot;I understand why these two functions are in an overload set.&quot; Which means, &quot;I understand <em>what would break</em> if this were changed.&quot;</p>\n<p>This relates to the mantra <strong>&quot;Keep it simple, stupid!&quot;</strong> Polymorphism/genericity/overloading are awesome tools for solving problems, but it's up to you-the-programmer to make sure that you are using them only when there <em>is</em> a problem to be solved.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:09:37.517", "Id": "250416", "ParentId": "250361", "Score": "3" } } ]
{ "AcceptedAnswerId": "250416", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T10:30:19.343", "Id": "250361", "Score": "4", "Tags": [ "c++", "inheritance", "interface" ], "Title": "multiple inheritance in c++ to implement different interfaces" }
250361
<p>I haven't a clue whether this works for every case, but it has in the ones I tried. If there are any optimizations that could happen anywhere please do comment on it. Regarding my code style, I'm sure there's something to fix there.</p> <p>In this game you are given a set of numbers and a target. You need to reach the target using only the given numbers and the operators (<span class="math-container">\$ + \$</span>, <span class="math-container">\$ - \$</span>, <span class="math-container">\$ / \$</span>, <span class="math-container">\$ \times \$</span>). You cannot use any number more than once, but every operator can be used as many times as necessary. You do not need to use every number/operator.</p> <pre><code>import itertools target = 225 numbers = [25, 1, 9, 9, 4, 2] math_functions = &quot;+-/*&quot; solution = None def generate_number_permutations(numbers, length): return list(itertools.permutations(numbers, length)) def generate_function_permutations(length): return list(itertools.product(math_functions, repeat=length)) for x in range(len(numbers)): number_permutations = generate_number_permutations(numbers, x+1) function_permutations = generate_function_permutations(x) if x == 0: for y in number_permutations: if y[0] == target: solution = y[0] break else: continue for permutation in number_permutations: for functions in function_permutations: value = permutation[0] for function in enumerate(functions): if function[1] == &quot;+&quot;: value += permutation[function[0]+1] elif function[1] == &quot;-&quot;: value -= permutation[function[0]+1] elif function[1] == &quot;/&quot;: value /= permutation[function[0]+1] else: value *= permutation[function[0]+1] if value == target: solution = permutation, functions break else: continue break if solution is not None: break print(solution) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:32:17.550", "Id": "491244", "Score": "0", "body": "Can you elaborate in the question body on what the program does?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:38:22.267", "Id": "491246", "Score": "0", "body": "@AryanParekh added" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T18:05:57.287", "Id": "491255", "Score": "0", "body": "To be 100% honest, the thing is it's difficult to write optimization tactics for this program without changing the logic a LOT." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T20:54:06.460", "Id": "491263", "Score": "4", "body": "Fails solving for example `target = 2; numbers = [3, 4, 14]`." } ]
[ { "body": "<h2>Globals</h2>\n<p>Since <code>target</code>, <code>numbers</code> and <code>math_functions</code> are global constants, they should be all-caps - e.g. <code>TARGET</code>. That said, you should refactor this so that the target and numbers are parametric, so that they can (eventually) be randomly generated.</p>\n<p>Solution does not belong as a global, since it is mutable - its presence prevents your program from being re-entrant.</p>\n<p>Likewise, the globally-scoped code starting with <code>for x</code> should be moved into a function.</p>\n<h2>Use of operators</h2>\n<p>This falls into the category of &quot;code as data&quot;. This block:</p>\n<pre><code> if function[1] == &quot;+&quot;:\n value += permutation[function[0]+1]\n elif function[1] == &quot;-&quot;:\n value -= permutation[function[0]+1]\n elif function[1] == &quot;/&quot;:\n value /= permutation[function[0]+1]\n else:\n value *= permutation[function[0]+1]\n</code></pre>\n<p>can be greatly simplified if you change your <code>math_functions</code> to be a tuple (or maybe dictionary) of character-operator pairs, where you import your operators from <a href=\"https://docs.python.org/3/library/operator.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/operator.html</a> .</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T15:29:17.210", "Id": "250425", "ParentId": "250368", "Score": "3" } }, { "body": "<h1>Operators</h1>\n<p>This is just to add on to @Reinderien answer. You can create a function, pass in the values you want to operate on and the operator you want to use, and return the calculation of those two numbers.</p>\n<pre><code>def perform_operator(op: str, a: int, b: int) -&gt; int:\n return { &quot;+&quot;: a + b, &quot;-&quot;: a - b, &quot;*&quot;: a * b, &quot;/&quot;: a / b }[op]\n</code></pre>\n<p>Here's how you would use this function</p>\n<pre><code>...\nfor function in enumerate(functions):\n value = perform_operator(function[1], value, permutation[function[0] + 1])\nif value == target:\n solution = permutation, functions\n break\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T22:33:26.697", "Id": "491386", "Score": "0", "body": "For this case the dictionary approach is fine, since the expressions are cheap. It doesn't scale, though, because it requires that every single possible expression is evaluated and then only one returned." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T22:24:14.923", "Id": "250451", "ParentId": "250368", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:12:00.230", "Id": "250368", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Countdown number game solver" }
250368
<p>This code reads barrel diameter and height from file, then, based on dimension make decisions and finally these decisions are printed out to a file. My pronbelm is how to avoid using the code wrtine on lines 70-101? Probably has to do with line 35, but I haven´t figured my way around it. Would be nice if there is a way (chance) to make this code shorter.</p> <p>P.S d - diameter, h - height</p> <pre><code> using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace TaaviSimsonTest { class Program { static void Main(string[] args) { //Reads values from an input file var numbersList = File.ReadAllLines(&quot;C:\\temp\\vaaditest07.txt&quot;) .Select(line =&gt; line.Split(' ')) .Select(barrels =&gt; new { diameter = int.Parse(barrels[0]), height = int.Parse(barrels[1]) }) .ToArray(); //Puts diameter and height values to arrays int[] d = numbersList.Select(x =&gt; x.diameter).ToArray(); int[] h = numbersList.Select(x =&gt; x.height).ToArray(); //Displays numbersList with line number, diameter and height for (int i = 0; i &lt; d.Length; i++) { Console.WriteLine(&quot;Line {0}: diameter: {1}, height: {2}&quot;, i, d[i], h[i]); } //comparing barrel sizes and making a decision List&lt;string&gt; output = new List&lt;string&gt;(); for (int j = 0; j &lt; (d.Length - 1); j++) { int a = j + 1; int b = j + 2; if (d[j] &gt; d[j + 1] &amp;&amp; h[j] &gt; h[j+1]) { string command = a + &quot;&lt;-&quot; + b; //1 &lt;- 2, if j = 0 output.Add(command); //puts command in array } else if (d[j] &lt; d[j + 1] &amp;&amp; h[j] &lt; h[j+1]) { string command = a + &quot;-&gt;&quot; + b; output.Add(command); } else if (d[j+1] &lt; h[j] &amp;&amp; ((d[j+1] * d[j+1] + h[j+1] * h[j+1]) &lt; d[j] * d[j])) { string command = a + &quot;&lt;-&quot; + b; // 2 &lt;- 3 output.Add(command); } else if(d[j] &lt; h[j+1] &amp;&amp; ((d[j] * d[j] + h[j] * h[j]) &lt; d[j+1] * d[j+1])) { string command = a + &quot;-&gt;&quot; + b; output.Add(command); } else { string command = a + &quot;--&quot; + b; output.Add(command); } } //how to avoid this cycle? int c = 1; int e = d.Length; if (d[0] &gt; d[d.Length - 1] &amp;&amp; h[0] &gt; h[d.Length - 1]) { string command = c + &quot;&lt;-&quot; + e; output.Add(command); } else if (d[0] &lt; d[d.Length - 1] &amp;&amp; h[0] &lt; h[d.Length-1]) { string command = c + &quot;-&gt;&quot; + e; output.Add(command); } else if (d[d.Length-1] &lt; h[0] &amp;&amp; ((d[d.Length-1] * d[d.Length-1] + h[d.Length-1] * h[d.Length-1]) &lt; d[0] * d[0])) { string command = c + &quot;&lt;-&quot; + e; output.Add(command); } else if (d[0] &lt; h[d.Length-1] &amp;&amp; ((d[0] * d[0] + h[0] * h[0]) &lt; d[d.Length-1]*d[d.Length-1])) { string command = c + &quot;-&gt;&quot; + e; output.Add(command); } else { string command = c + &quot;--&quot; + e; output.Add(command); } //Writes values of array to a new file String[] outputlist = output.ToArray(); File.WriteAllLines(@&quot;C:\Temp\barrelsOutput.txt&quot;, outputlist); //Displaying output in console Console.WriteLine(&quot;&quot;); foreach (var item in outputlist) { Console.WriteLine(item.ToString()); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T20:49:59.147", "Id": "491262", "Score": "1", "body": "Can you give a feedback to [this answer](https://codereview.stackexchange.com/a/250335/226545) or accept it?" } ]
[ { "body": "<p>I would advice starting with writing code that is actually readable. Also from your question I don't really know what your goal is.</p>\n<p>Do you want short code that get the job done? Then I'd say you are already there. If you want readable and maintainable code, then maybe try an OO approach where you encapsulate bits of code into objects which with their name and methods you document what you are actually doing.</p>\n<p>Because I'm waaaay too lazy to interpret what you are trying to do at lines 70-101. I wanna read the names and titles and know it.</p>\n<p>So, that is my two cents</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T20:27:06.323", "Id": "491259", "Score": "0", "body": "OP has fulfill the minimum requirement to have a valid question, if you have any confusion regarding OP question, feel free to use the comment section before posting an answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T18:53:14.007", "Id": "250376", "ParentId": "250371", "Score": "1" } }, { "body": "<p><strong>Some Notes :</strong></p>\n<ul>\n<li>you should make your code more readable more often. This would give your code more sense even for yourself, specially if you reviewed it in the future.</li>\n<li>you need to consider naming convention like using Pascal Casing for Properties, naming your variables with meaningful names.</li>\n<li>Don't split the string without validating first.</li>\n<li>Don't <code>Parse</code> values directly such as <code>int.Parse</code> unless you're sure it will be a valid value, instead use <code>int.TryParse</code> to avoid exceptions.</li>\n<li>Don't create an array from anonymous type (or any other type) array unless if is needed (in your case it's not needed) instead, use the array that you've created.</li>\n<li>Always if you see some redundancy in your code (repetitive code) move it to a method, this way you can reuse the method and your adjustments would be in one place.</li>\n<li><code>File.WriteAllLines</code> accepts <code>IEnumerable</code> this means, you can pass the <code>List&lt;string&gt;</code> directly, so no need to convert it to array.</li>\n<li><code>string.Join</code> can concatenate a <code>List</code> or <code>Array</code> into one <code>string</code> so use that to your advantage.</li>\n<li>Always validate your values as much as possible, this would give more stability to your code, and ensure your results.</li>\n</ul>\n<p>Your question regarding this part of code :</p>\n<pre><code>if (d[0] &gt; d[d.Length - 1] &amp;&amp; h[0] &gt; h[d.Length - 1]) \n{\n string command = c + &quot;&lt;-&quot; + e;\n output.Add(command);\n}\nelse if (d[0] &lt; d[d.Length - 1] &amp;&amp; h[0] &lt; h[d.Length-1]) \n{\n string command = c + &quot;-&gt;&quot; + e;\n output.Add(command);\n}\nelse if (d[d.Length-1] &lt; h[0] &amp;&amp; \n ((d[d.Length-1] * d[d.Length-1] + h[d.Length-1] * h[d.Length-1]) &lt; \n d[0] * d[0]))\n{\n string command = c + &quot;&lt;-&quot; + e;\n output.Add(command);\n}\nelse if (d[0] &lt; h[d.Length-1] &amp;&amp; \n ((d[0] * d[0] + h[0] * h[0]) &lt; \n d[d.Length-1]*d[d.Length-1]))\n{\n string command = c + &quot;-&gt;&quot; + e;\n output.Add(command);\n}\nelse\n{\n string command = c + &quot;--&quot; + e;\n output.Add(command);\n}\n</code></pre>\n<p>This part needs to be moved into a method and make it more generalized to be reused, like this :</p>\n<pre><code>private static string GetCommand(int currentDiameter , int nextDiameter , int currentHeight , int nextHeight)\n{\n var currentDiameterMultiplied = currentDiameter * currentDiameter;\n var nextDiameterMultiplied = nextDiameter * nextDiameter;\n var currentHeightMultiplied = currentHeight * currentHeight;\n var nextHeightMultiplied = nextHeight * nextHeight;\n\n if(currentDiameter &gt; nextDiameter &amp;&amp; currentHeight &gt; nextHeight)\n {\n return &quot;&lt;-&quot;;\n }\n\n if(currentDiameter &lt; nextDiameter &amp;&amp; currentHeight &lt; nextHeight)\n {\n return &quot;-&gt;&quot;;\n }\n\n if(nextDiameter &lt; currentHeight &amp;&amp; ( ( nextDiameterMultiplied + nextHeightMultiplied ) &lt; currentDiameterMultiplied ))\n {\n return &quot;&lt;-&quot;;\n }\n\n if(currentDiameter &lt; nextHeight &amp;&amp; ( ( currentDiameterMultiplied + currentHeightMultiplied ) &lt; nextDiameterMultiplied ))\n {\n return &quot;-&gt;&quot;;\n }\n\n return &quot;--&quot;;\n}\n</code></pre>\n<p>now you can reuse it in your code, here is the modified version of your code:</p>\n<pre><code>static void Main(string[] args)\n{\n //Reads values from an input file\n var path = &quot;C:\\\\temp\\\\vaaditest07.txt&quot;;\n \n if(!File.Exists(path)) { throw new FileNotFoundException(nameof(path)); }\n \n var data = File.ReadAllLines(path); \n \n if(data == null) { throw new ArgumentNullException(nameof(data)); }\n \n var numbersList = data\n .Select(line =&gt; \n line.Split(' ')\n .Select(barrels =&gt; new\n { \n Diameter = int.TryParse(barrels[0], out var diameter) ? diameter : 0,\n Height = int.TryParse(barrels[1], out var height) ? height : 0\n }).ToArray();\n\n //comparing barrel sizes and making a decision\n var output = new List&lt;string&gt;();\n\n var length = numbersList.Length;\n \n var command = string.Empty;\n \n for(int index = 0, nextIndex = 1; index &lt; length; index++, nextIndex++)\n { \n var current = numbersList[index];\n \n var next = numbersList[nextIndex];\n\n // Displays numbersList with line number, diameter and height\n Console.WriteLine(&quot;Line {0}: diameter: {1}, height: {2}&quot; , index , current.Diameter , current.Height);\n\n if(index != length - 1)\n { \n var commandSymbol = GetCommand(current.Diameter , next.Diameter , current.Height , next.Height);\n command = $&quot;{nextIndex}{commandSymbol}{nextIndex + 1}&quot;; \n }\n else \n {\n var commandSymbol = GetCommand(numbersList[0].Diameter , current.Diameter , numbersList[0].Height , current.Height);\n command = $&quot;{0}{commandSymbol}{length}&quot;; \n }\n \n output.Add(command);\n }\n \n // Writes values of array to a new file\n File.WriteAllLines(@&quot;C:\\Temp\\barrelsOutput.txt&quot; , output);\n\n //Displaying output in console\n Console.WriteLine();\n Console.WriteLine(string.Join(Environment.NewLine, output));\n}\n\n \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T06:46:31.907", "Id": "491497", "Score": "0", "body": "Thank you for the tips. At first I wrote diameter and height out, but then I changed it to d and h, to try and make it shorter. Though I understand it makes reading code harder, which is not good. I will try out your version at the next free moment and give you feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T07:10:37.323", "Id": "491498", "Score": "0", "body": "I tried your code, but for some reason it gives me four errors.\nLine 19. Argument 1: Cannot convert from string[] to string\nLine 21. string[] does not contain a definition for 'Split' and no accessible extension method 'Split' accepting a first argument of type string[] could be found\nLine 46: The name \"GetCommand\" does not exist in the current context\nLine 51: The name \"GetCommand\" does not exist in the current context" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T07:20:37.597", "Id": "491500", "Score": "0", "body": "I forgot to copy method part, but it still gives named errors on lines 19 and 21" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-11T12:59:25.417", "Id": "491524", "Score": "0", "body": "@TaaviSimson sorry, I didn't test the code, I just revised it outside the compiler. I've fixed the issue. `File.ReadAllLines` returns `string[]` so I should iterate over its elements and split them. Which I missed, I've fixed it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T20:00:26.757", "Id": "250377", "ParentId": "250371", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T15:43:46.077", "Id": "250371", "Score": "4", "Tags": [ "c#", "array" ], "Title": "Solving code without extra cycle outside for loop" }
250371
<p>I've written a script that gets a list of all groups in AD along with a few specific properties for each group (DistinguishedName, CN, Type, and Description). Then it goes through each group and, for each member of type &quot;user&quot; (to exclude computers, servers, etc.), it gets the user's full name, title, and their manager's full name. Finally, it combines the two using a PS Module called <a href="https://www.powershellgallery.com/packages/Join-Object/2.0.1" rel="nofollow noreferrer">Join-Object</a> to join the two lists together and output it as a CSV file.</p> <p>Getting the AD Groups at the beginning is quick enough; it takes less than a minute to run. Combining all the output at the end likewise is pretty quick; a minute or less and it's done.</p> <p>The slow part is the middle step of looping through each group. For ~1500 groups and a total of about ~75k to ~85k users across all groups (many users are in multiple AD groups, naturally), it takes <strong>7 hours</strong> to run. Is there some way I can improve on that 7 hour runtime (preferably drastically)? Extrapolating from the run-time of the other sections, I would expect the middle section to take an hour or less.</p> <p>I'm running PowerShell 5.1 on Win10 and querying Active Directory on Windows Server 2016. This script was requested by our security team so they could generally audit AD group membership information in a format familiar to them (a CSV file inside Excel).</p> <pre><code>Import-Module -Name ActiveDirectory -Force Import-Module -Name Join-Object -Force #Get list of AD Groups. Currently ~1500 rows $ADGroupsList = Get-ADGroup -Filter * -Properties * | Select-Object DistinguishedName,CN,GroupCategory,Description | Sort-Object CN #Declare ADUsersList object $ADUsersList = @() #Declare Record variable and set parameter schema. The [ordered] keyword ensures the data is entered in this order $Record = [ordered] @{ &quot;Group Name&quot; = &quot;&quot; &quot;Employee Name&quot; = &quot;&quot; &quot;Title&quot;= &quot;&quot; &quot;Manager&quot; = &quot;&quot; } #Loop through each group in the groups list. This is the really, really slow part. If the AD Web Service limit is ever set back to the default (5000), this will fail for any groups that have more than 5,000 users. foreach ($Group in $ADGroupsList) { #Get list of members of the current group in the loop who are of type &quot;user&quot; (excludes servers or other computers, for example) $ArrayofMembers = Get-ADGroupMember -Identity $Group.DistinguishedName | Where { $_.objectClass -eq &quot;user&quot; } #Loop through each member in the list of members from above foreach ($Member in $ArrayofMembers) { #Get detailed user info about the current user like title and manager that aren't available from Get-ADGroupMember $User = Get-ADUser -Identity $Member -Properties name,title,manager | Select-Object Name, Title, @{Label=&quot;Manager&quot;;Expression={(Get-ADUser (Get-ADUser $Member -Properties Manager).Manager).Name}} #Specifies what values to apply to each property of the $Record object $Record.&quot;Group Name&quot; = $Group.CN $Record.&quot;Employee Name&quot; = $Member.Name $Record.&quot;Title&quot; = $User.Title $Record.&quot;Manager&quot; = $User.Manager #Put all the stored information above in a 'copy' record $objRecord = New-Object PSObject -property $Record #Append that copy to the existing data in the ADUsersList object $ADUsersList += $objRecord } } #Combines data from the two objects into one. This uses the Join-Object module from https://www.powershellgallery.com/packages/Join-Object/2.0.1 Join-Object -Left $ADGroupsList -Right $ADUsersList -LeftJoinProperty &quot;CN&quot; -RightJoinProperty &quot;Group Name&quot; -Type AllInBoth -LeftMultiMode DuplicateLines -RightMultiMode DuplicateLines -ExcludeLeftProperties DistinguishedName | Export-Csv C:\CombinedADResults.csv -NoTypeInformation </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T17:33:22.787", "Id": "491254", "Score": "1", "body": "Appending to arrays: when the += operator is used, it's actually destroying the array and creating a new one. See e.g. [this answer](https://codereview.stackexchange.com/a/242404/88771) for a hint how to eliminate this performance issue…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T18:49:11.477", "Id": "491375", "Score": "0", "body": "@JosefZ Turning `$ADUsersList` into a `System.Collections.ArrayList` and replacing the `+=` operator with `[void]$ADUsersList.Add($objRecord)` still took about 7 hours to run. Good information about the cost of appending, though." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T16:37:46.197", "Id": "250372", "Score": "3", "Tags": [ "performance", "powershell", "active-directory" ], "Title": "Get specific properties for all Active Directory groups and all their users, then combine them into CSV" }
250372
<p>Here is my code:</p> <pre><code>add_hook('ClientAreaPageInvoices', 1, function($vars) { $user_id = $_SESSION[&quot;uid&quot;]; $today = Carbon::now()-&gt;format('Y-m-d'); $query_1 = Capsule::table('tblinvoices') -&gt;select(Capsule::raw('SUM(total) as total_aberto')) -&gt;where(array('userid' =&gt; $user_id, 'status' =&gt; 'Unpaid')) -&gt;get(); $query_2 = Capsule::table('tblinvoices') -&gt;select(Capsule::raw('SUM(total) as total_vencido')) -&gt;where(array('userid' =&gt; $user_id, 'status' =&gt; 'Unpaid')) -&gt;whereDate('duedate', '&lt;=', $today) -&gt;get(); $query_3 = Capsule::table('tblinvoices') -&gt;select(Capsule::raw('SUM(total) as total_pago')) -&gt;where(array('userid' =&gt; $user_id, 'status' =&gt; 'Paid')) -&gt;get(); $array_1 = json_decode(json_encode($query_1), True); $array_2 = json_decode(json_encode($query_2), True); $array_3 = json_decode(json_encode($query_3), True); $totalAberto = $array_1[0]['total_aberto']; $totalVencido = $array_2[0]['total_vencido']; $totalPago = $array_3[0]['total_pago']; return array ('totalAberto' =&gt; $totalAberto, 'totalVencido' =&gt; $totalVencido, 'totalPago' =&gt; $totalPago); }); </code></pre> <p>Is there any way to simplify the entire code in general?</p> <p>It works well - I just want to learn other practices to make this type of consultation in a more optimized, and simplified way.</p>
[]
[ { "body": "<p>There seems to be a section in your code that you repeat three times. This can probably be placed in a separate function. Something like this:</p>\n<pre><code>function getInvoiceTotal($status, $onlyOverdue = FALSE)\n{\n $query = Capsule::table('tblinvoices');\n $query-&gt;select(Capsule::raw('SUM(total) as total'))\n -&gt;where(['userid' =&gt; $_SESSION['uid'], \n 'status' =&gt; $status]);\n if ($onlyOverdue &amp;&amp; ($status == 'Unpaid')) {\n $query-&gt;whereDate('duedate', '&lt;=', Carbon::now()-&gt;format('Y-m-d'));\n } \n return $query-&gt;get()-&gt;total; \n}\n\n\nadd_hook('ClientAreaPageInvoices', 1, function($vars) {\n return ['totalAberto' =&gt; getInvoiceTotal('Unpaid'), \n 'totalVencido' =&gt; getInvoiceTotal('Unpaid', TRUE), \n 'totalPago' =&gt; getInvoiceTotal('Paid')];\n});\n</code></pre>\n<p>Regretably I don't have Laravel installed so I cannot test this code, but I think the general idea is clear. Perhaps someone with more knowledge of Laravel can add to this answer?</p>\n<p>Some notes:</p>\n<ul>\n<li>I changed <code>array(....)</code> to <code>[....]</code>.</li>\n<li>I didn't understand the <code>json_decode(json_encode())</code> bit. Perhaps to go from objects to arrays? I don't see what's wrong with using the actual objects. Here's where I have most doubt that my code is correct, since I haven't tested it.</li>\n<li>I left out a lot of variables you used. Using variables, with good names, can make code easier to read, but in really good code, when a variable is only used once, it shouldn't be necessary.</li>\n<li>I strongly advise you to write your code in English only. I had to find out what the meaning of 'Aberto', 'Vencido' and 'Pago' is. Not every programmer speaks Protuguese.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:22:03.270", "Id": "491269", "Score": "1", "body": "When I see `json_decode(json_encode())` used (deliberately, correctly), it is to ensure that the whole multi-dimensional iterable structure is all array-type or all object-type. ...but I don't know that this is useful here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:22:48.870", "Id": "491270", "Score": "2", "body": "@mickmackusa Yes, that's what I assumed, but why is that conversion needed? This has probably to do with my lack of Laravel knowledge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T01:09:04.437", "Id": "491289", "Score": "1", "body": "@KIKOSoftware Very cool your code, really with a separate function everything is simplified, however it did not work for me, it returned all zero (0,00) values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T07:47:34.343", "Id": "491311", "Score": "0", "body": "It needs some basic debugging. The idea is sound, but clearly there's still some kind of error in it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:19:25.340", "Id": "250381", "ParentId": "250373", "Score": "7" } }, { "body": "<h2>SUM aggregates</h2>\n<p>Instead of selecting the <code>SUM</code> aggregate manually:</p>\n<blockquote>\n<pre><code>-&gt;select(Capsule::raw('SUM(total) as total_aberto'))\n</code></pre>\n</blockquote>\n<p>The <a href=\"https://laravel.com/api/8.x/Illuminate/Database/Query/Builder.html#method_sum\" rel=\"nofollow noreferrer\"><code>Builder::sum()</code></a> aggregate method can be used:</p>\n<pre><code>-&gt;sum('total')\n</code></pre>\n<p>Is there a model defined like <code>Invoice</code>?</p>\n<pre><code>&lt;?php\n\nnamespace App\\Models;\n\nclass Invoice extends Model \n{\n\n protected $table = 'tblinvoices';\n\n}\n</code></pre>\n<p>Presuming such a model existed, the code like this:</p>\n<blockquote>\n<pre><code>$query_1 = Capsule::table('tblinvoices')\n -&gt;select(Capsule::raw('SUM(total) as total_aberto'))\n -&gt;where(array('userid' =&gt; $user_id, 'status' =&gt; 'Unpaid'))\n -&gt;get();\n</code></pre>\n</blockquote>\n<p>could be simplified to this, using the <a href=\"https://laravel.com/docs/8.x/eloquent#retrieving-single-models\" rel=\"nofollow noreferrer\">methods to retrieve Single Models / Aggregates</a>:</p>\n<pre><code>$totalAberto = App\\Models\\Invoice::where(['userid' =&gt; $user_id, 'status' =&gt; 'Unpaid'])\n -&gt;sum('total');\n \n</code></pre>\n<h3>Array syntax</h3>\n<p>There isn't anything wrong with using <code>array()</code> but as of the time of writing, <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">PHP has Active support for versions 8.0 and 7.4</a>, and since PHP 5.4 arrays can be declared with <a href=\"https://www.php.net/manual/en/migration54.new-features.php\" rel=\"nofollow noreferrer\">short array syntax (PHP 5.4)</a>, as was used in my sample at the end of the section above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T15:43:10.260", "Id": "250426", "ParentId": "250373", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T17:45:52.123", "Id": "250373", "Score": "5", "Tags": [ "php", "array", "laravel" ], "Title": "Queries to get unpaid and unpaid invoices" }
250373
<p>I'm a new Rustacean, decided to make a wrapper for the LeagueOfLegends API.</p> <p>Focus is on simplicity, being able to make any API call with a simple function.</p> <p>I have not finished all functions however it's currently in a working state, and the other function will be very similair.</p> <h2>Code</h2> <p><strong>Lib.rs</strong> - I've included this file as I'm new to Rust and may not be using the file properly</p> <pre><code>pub mod riot_api; pub use riot_api::*; pub mod api_structs { pub mod lol_api_key; pub mod lol_region; pub mod lol_account; } pub mod util { pub (crate) mod http_client; pub mod http_error; } </code></pre> <p><strong>src/riot_api.rs</strong> - This is the library main file, containing all public methods</p> <pre><code>use crate::api_structs::lol_api_key::LolApiKey; use crate::api_structs::lol_account::LeagueAccount; use crate::util::http_client::HttpClient; use crate::util::http_error::HttpError; pub struct RiotApi { } impl RiotApi { const SUMMONER_BY_NAME_URL: &amp;'static str = &quot;https://%region%.api.riotgames.com/lol/summoner/v4/summoners/by-name/%name%?api_key=%apikey%&quot;; const GET_STATUS_URL : &amp;'static str = &quot;https://%region%.api.riotgames.com/lol/status/v3/shard-data?api_key=%apikey%&quot;; fn get_url_from_api_key(original_url : &amp;str, lol_api_key : &amp;LolApiKey) -&gt; String { return original_url .replace(&quot;%region%&quot;, lol_api_key.region.get_code()) .replace(&quot;%apikey%&quot;, &amp;*lol_api_key.api_key); } fn get_url_from_api_key_with_name(original_url : &amp;str, lol_api_key : &amp;LolApiKey, name : String) -&gt; String { return Self::get_url_from_api_key(original_url, lol_api_key) .replace(&quot;%name%&quot;, name.as_str()); } pub fn get_status(lol_api_key : &amp;LolApiKey) -&gt; Result&lt;String, HttpError&gt; { let url : String = Self::get_url_from_api_key(RiotApi::GET_STATUS_URL, lol_api_key); return HttpClient::get(url); } pub fn get_summoner(summoner_name : String, lol_api_key : &amp;LolApiKey) -&gt; Result&lt;LeagueAccount, HttpError&gt; { let url : String = Self::get_url_from_api_key_with_name(RiotApi::SUMMONER_BY_NAME_URL, lol_api_key, summoner_name); let http_result = HttpClient::get(url); if http_result.is_ok() { let league_account : LeagueAccount = serde_json::from_str(&amp;http_result.unwrap()).unwrap(); return Ok(league_account); } else { return Err(http_result.unwrap_err()); } } } </code></pre> <p><strong>src/util/http_client.rs</strong> - This is a wrapper class for an http library. It shouldn't be used outside this project</p> <pre><code>use reqwest; use crate::util::http_error::HttpError; pub struct HttpClient { } /** * Class to handle HTTP calls. Basically just a wrapper for an external HTTP client, to make management/changes easier */ impl HttpClient { pub fn get(url : String) -&gt; Result&lt;String, HttpError&gt; { let http_result = Self::http_get_result(url); return match http_result { Ok(result) =&gt; { if result.status() == 200 { Result::Ok(String::from(result.text().unwrap())) } else if result.status() == 401 { Result::Err(HttpError{ error_message: String::from(&quot;Unauthorized access to application&quot;), http_response_code: Some(401) }) } else if result.status() == 403 { Result::Err(HttpError{ error_message: String::from(&quot;Forbidden access to application. Check if API key has expired&quot;), http_response_code: Some(403) }) }else { Result::Err(HttpError{ error_message: String::from(&quot;Error in http request&quot;), http_response_code: Some(result.status().as_u16()) }) } }, Err(error) =&gt; { Result::Err(HttpError { error_message: error.to_string(), http_response_code: None }) } }; } fn http_get_result(url : String) -&gt; Result&lt;reqwest::blocking::Response, reqwest::Error&gt; { return reqwest::blocking::get(&amp;url); } } </code></pre> <p><strong>http_error.rs</strong> - Used for http errors when making network class</p> <pre><code>#[derive(PartialEq)] #[derive(Debug)] pub struct HttpError { pub error_message : String, pub http_response_code : Option&lt;u16&gt; } impl HttpError { } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T00:05:27.893", "Id": "491285", "Score": "2", "body": "Use `pub(crate)` to make struct available for your lib only." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T14:54:20.583", "Id": "491347", "Score": "0", "body": "@outoftime Thanks, I updated it and realized 'http_error' needs to be public" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T21:12:09.577", "Id": "250379", "Score": "3", "Tags": [ "beginner", "rust", "api", "wrapper" ], "Title": "A wrapper library for League Of Legends API" }
250379
<p>This is a problem that is asked on leet code for a simple calculator. The problem is stated as follows -</p> <p>Implement a basic calculator to evaluate a simple expression string.</p> <p>The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.</p> <p>Example 1:</p> <pre><code>Input: &quot;3+2*2&quot; Output: 7 </code></pre> <p>Example 2:</p> <pre><code>Input: &quot; 3/2 &quot; Output: 1 </code></pre> <p>Example 3:</p> <pre><code>Input: &quot; 3+5 / 2 &quot; Output: 5 </code></pre> <p>Note: You may assume that the given expression is always valid. Do not use the eval built-in library function.</p> <p>This is the code I wrote in a short span of time, I did not design it for more complicated cases -</p> <pre><code>import java.util.Queue; import java.util.Stack; import java.util.concurrent.ArrayBlockingQueue; import java.lang.Exception; public class Solution{ Stack&lt;Integer&gt; numberStack = new Stack(); Stack&lt;Character&gt; operatorStack = new Stack(); //assuming op1 is in operator stack and op2 is to be inserted public boolean hasPrecedence(char op1, char op2){ if (op2 == '/' &amp;&amp; op1 != '/'){ return true; } if (op2 == '*' &amp;&amp; (op1 == '+' || op1 == '-')){ return true; } return false; } // -1 means invalid // 0 means number // 1 means an operator public int validate(char operand){ boolean isNumber = false; if (Character.isDigit(operand)){ isNumber = true; } boolean isOperator = false; if (operand != '/' || operand !='*' || operand !='+' || operand != '-'){ isOperator = true; } if (!(isNumber || isOperator)){ return -1; } if (isNumber){ return 0; } if (isOperator){ return 1; } return -1; } private void performOperation(){ if(operatorStack.empty() || numberStack.empty()){ return; } char operator = operatorStack.pop(); if(numberStack.size() &lt; 2){ return; } int num2 = numberStack.pop(); int num1 = numberStack.pop(); int result = 0; switch(operator){ case '/': result = num1/num2; numberStack.push(result); break; case '+': result = num1+num2; numberStack.push(result); break; case '*': result = num1*num2; numberStack.push(result); break; case '-': result = num1-num2; numberStack.push(result); break; } } private int calculate(String exp) throws Exception{ if (exp == null || exp.trim().length() == 0 ){ throw new Exception(&quot;Null or empty expression &quot;); } char[] operArray = exp.toCharArray(); StringBuffer numberBuffer = new StringBuffer(); char operand = '\0'; for (int i=0; i &lt; operArray.length ; i++){ operand = operArray[i]; if (Character.isWhitespace(operand)){ continue; } int opVal = -1; opVal = validate(operand); if (opVal == -1){ throw new Exception(&quot;Invalid inputs &quot;); } //current char is number if (opVal == 0){ numberBuffer.append(operand); continue; } if (opVal == 1){ numberStack.push(Integer.parseInt(numberBuffer.toString())); numberBuffer = new StringBuffer(); if (!operatorStack.empty()){ if(!hasPrecedence(operatorStack.peek(), operand)){ performOperation(); } } operatorStack.push(operand); } } numberStack.push(Integer.parseInt(numberBuffer.toString())); while(!operatorStack.isEmpty()){ performOperation(); } return numberStack.pop(); } public static void main(String []args) throws Exception{ Solution expparser = new Solution(); int result = expparser.calculate(&quot;3+2*2&quot;); System.out.println(&quot;result is &quot; + result); result = expparser.calculate(&quot; 3/2 &quot;); System.out.println(&quot;result is &quot; + result); result = expparser.calculate(&quot; 3+5 / 2 &quot;); System.out.println(&quot;result is &quot; + result); result = expparser.calculate(&quot;3+2-2&quot;); System.out.println(&quot;result is &quot; + result); result = expparser.calculate(&quot; 3/2-1 &quot;); System.out.println(&quot;result is &quot; + result); result = expparser.calculate(&quot; 3/5/2 &quot;); System.out.println(&quot;result is &quot; + result); result = expparser.calculate(&quot;3/5*2&quot;); System.out.println(&quot;result is &quot; + result); result = expparser.calculate(&quot;3*5*2&quot;); System.out.println(&quot;result is &quot; + result); result = expparser.calculate(&quot; 3+5+2 &quot;); System.out.println(&quot;result is &quot; + result); } } </code></pre> <p>Considering there are no negative numbers in the expression, this code works fine and the test cases have all passed. How can I improve this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T12:41:38.017", "Id": "491332", "Score": "0", "body": "Please take a look at GNU Coreutils \"expr\" program for an example of how to implement an infix calculator. It can be implemented very neatly using recursion. https://github.com/coreutils/coreutils/blob/master/src/expr.c" } ]
[ { "body": "<h2>Consider using the <code>Deque</code> instead of the <code>Stack</code></h2>\n<p>As stated in the <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Stack.html\" rel=\"nofollow noreferrer\">documentation</a>, the use of the <code>Deque</code> is preferred. You can have more information on <a href=\"https://stackoverflow.com/a/12524949/12511456\">SO</a>.</p>\n<h2>Replace the <code>for</code> loop with an enhanced 'for' loop</h2>\n<p>In your code, you don’t actually need the index provided by the loop, you can the enhanced version.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i &lt; operArray.length; i++) {\n //[...]\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (char c : operArray) {\n //[...]\n}\n</code></pre>\n<h2>Simplify the boolean conditions.</h2>\n<p>Generally, when you are returning both <code>true</code> and <code>false</code> surrounded by a condition, you know you can refactor the logic of the expression.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (op2 == '*' &amp;&amp; (op1 == '+' || op1 == '-')) {\n return true;\n}\n\nreturn false;\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>return op2 == '*' &amp;&amp; (op1 == '+' || op1 == '-');\n</code></pre>\n<h2><code>Solution#validate</code> method</h2>\n<ol>\n<li>I suggest that you extract the logic to check if the number is an operator / number is two separate methods; this will make the code shorter and easier to read.</li>\n<li>The logic can be simplified, you can remove the <code>!(isNumber || isOperator)</code> and if neither, the method will return <code>-1</code>.</li>\n<li>The <code>operand != '/' || operand !='*' || operand !='+' || operand != '-'</code> is flawed; will always return true.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>// -1 means invalid\n// 0 means number\n// 1 means an operator\npublic int validate(char operand) {\n boolean isNumber = isNumber(operand);\n boolean isOperator = isOperator(operand);\n\n if (isNumber) {\n return 0;\n } else if (isOperator) {\n return 1;\n }\n\n return -1;\n}\n\nprivate boolean isNumber(char operand) {\n return Character.isDigit(operand);\n}\n\nprivate boolean isOperator(char operand) {\n return operand == '/' || operand == '*' || operand == '+' || operand == '-';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T00:58:56.390", "Id": "250387", "ParentId": "250380", "Score": "5" } }, { "body": "<p>One additional remark on <code>validate()</code>.</p>\n<p>You have three output cases:</p>\n<ul>\n<li>invalid</li>\n<li>number</li>\n<li>operator</li>\n</ul>\n<p>Instead of encoding them as integers (which is not a natural natural choice, as you can't meaningfully add, subtract or multiply them), I'd introduce an enum:</p>\n<pre><code>enum Validation { INVALID, NUMBER, OPERATOR }\n</code></pre>\n<p>Then the <code>validate()</code> method reads</p>\n<pre><code>public Validation validate(char operand) {\n ...\n}\n</code></pre>\n<p>Hint: whenever you feel it necessary to explain the meaning of some numbers, consider introducing an enum instead. You get a lot of benefits without any significant downsides.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T09:15:59.830", "Id": "250406", "ParentId": "250380", "Score": "5" } }, { "body": "<p>Do you have considered to use only one stack ?</p>\n<p>You can wrap your numbers into a constant entry that returns the number. And create one operation entry for each valid operation. So that you can &quot;just&quot; reduce your stack until she has one item.</p>\n<pre><code>Stack&lt;Function&lt;Integer, Integer&gt;&gt; operations = new Stack&lt;&gt;();\n\n\npublic Integer resolve(final Integer x) {\n Integer right = x;\n while ( !operations.isEmpty() ) {\n right = operations.pop().apply(right);\n }\n return right;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T09:28:11.790", "Id": "250408", "ParentId": "250380", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:03:57.133", "Id": "250380", "Score": "4", "Tags": [ "java" ], "Title": "leet code calculator II code" }
250380
<p>Recently, I have been working on a College Football Manager game, in which you coach a team from the ground up. I have successfully made it to where you can win games, lose games, and change your team overall. Yet, I haven't worked out how to make a ranking system. I tried it with an Array, but got lost and had no idea what to do.</p> <p>Keep in mind, not only does the player need to be ranked, but the other teams in the league. idon't know whether I would need to be simulating their seasons in the background(probably).</p> <p>If possible, I would like it to be based off their overall. The overall is found under the team integer, for example.</p> <p><code>int Kentucky 65; </code></p> <p>Here is the project code, and I know, clunky, if you have any ideas on how to clean it up or shorten it, that would also be appreciated.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cstdlib&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;bits/stdc++.h&gt; using namespace std; int main() { string next; string teams[10] = {&quot;Clemson&quot; , &quot;Alabama&quot; , &quot;Georgia&quot; , &quot;Florida&quot; , &quot;Notre Dame&quot; , &quot;Auburn&quot; , &quot;Oklahoma&quot; , &quot;LSU&quot; , &quot;Miami FL&quot; , &quot;Oklahoma State&quot;}; int select, ranking, teamoverall, wins, losses; string team1, team2, userteam, nextgame; int Alabama = 92; int Clemson = 90; int Georgia = 93; int NotreDame = 88; int MiamiFL = 80; int Auburn = 86; int Oklahoma = 85; int LSU = 82; int Florida = 90; int OklahomaST = 78; int Kansas = 60; int Kentucky = 60; int TexasAM = 65; float score, oppscore; int final, oppfinal, random, random1; team1 = &quot;Arkanasas&quot;; team2 = &quot;Oklahoma State&quot;; wins = 0; losses = 0; cout &lt;&lt; &quot;COLLEGE FOOTBALL COACH - 2020&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1 - Manage&quot; &lt;&lt; endl; cout &lt;&lt; &quot;2 - Manual&quot; &lt;&lt; endl; cout &lt;&lt; &quot;3 - About&quot; &lt;&lt; endl; cin &gt;&gt; select; if(select == 1){ goto TeamSelect; } if(select ==2){ goto Manual; } if(select == 3){ goto About; } TeamSelect: cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;Choose a starting school to coach&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1- &quot; &lt;&lt; team1 &lt;&lt; endl &lt;&lt; &quot;2- &quot; &lt;&lt; team2 &lt;&lt; endl; cin &gt;&gt; select; if(select == 1){ userteam = &quot;Arkansas&quot;; ranking = 15; nextgame = &quot;Georgia&quot;; teamoverall = 55; }else{ userteam = &quot;Oklahoma State&quot;; ranking = 10; nextgame = &quot;Kansas&quot;; teamoverall = 78; } goto Dynasty; Dynasty: cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;Team - &quot; &lt;&lt; userteam &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Next Game - &quot; &lt;&lt; nextgame &lt;&lt; &quot; | Opponent Overall - &quot;; if(nextgame == &quot;Georgia&quot;){ cout &lt;&lt; Georgia &lt;&lt; endl &lt;&lt; endl; }else{ if(nextgame == &quot;Kansas&quot;){ cout &lt;&lt; Kansas &lt;&lt; endl &lt;&lt; endl; }else{ if(nextgame == &quot;Kentucky&quot;){ cout &lt;&lt; Kentucky &lt;&lt; endl &lt;&lt; endl; }else{ if(nextgame == &quot;Auburn&quot;){ cout &lt;&lt; Auburn &lt;&lt; endl &lt;&lt; endl; }else{ if(nextgame == &quot;LSU&quot;){ cout &lt;&lt; LSU &lt;&lt; endl &lt;&lt; endl; }else{ if(nextgame == &quot;Texas A&amp;M&quot;){ cout &lt;&lt; TexasAM &lt;&lt; endl &lt;&lt; endl; } } } } } } cout &lt;&lt; &quot;Ranking - &quot;; if(ranking &lt; 11){ cout &lt;&lt; ranking &lt;&lt; endl &lt;&lt; endl; }else{ cout &lt;&lt; &quot;UNRANKED&quot; &lt;&lt; endl &lt;&lt; endl; } cout &lt;&lt; &quot;Record&quot; &lt;&lt; &quot;(&quot; &lt;&lt; wins &lt;&lt; &quot; - &quot; &lt;&lt; losses &lt;&lt; &quot;)&quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Team Overall - &quot; &lt;&lt; teamoverall &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;1- Play Next Game&quot; &lt;&lt; endl; cout &lt;&lt; &quot;2- Recruting&quot; &lt;&lt; endl; cout &lt;&lt; &quot;3- Rankings&quot; &lt;&lt; endl; cin &gt;&gt; select; if(select == 3){ goto rankings; }else if(select ==1){ goto playgame; } playgame: cout &lt;&lt; string( 100, '\n' ); if(userteam == &quot;Arkansas&quot;){ if(nextgame == &quot;Georgia&quot;){ score = teamoverall * .5; srand (time(NULL)); random = rand() % 5 + -20; srand (time(NULL)); random1 = rand() % 20 + 1; random = random + random1; score = score + random; oppscore = Georgia * .5; srand (time(NULL)); random = rand() % 5 + -20; srand (time(NULL)); random1 = rand() % 25 + 1; random = random + random1; oppscore = oppscore + random; final = score; oppfinal = oppscore; if(final == oppfinal){ goto playgame; } if(final &lt; 0){ final = 0; } if(oppfinal &lt; 0){ oppfinal = 0; } if(final == 1){ final == 3; } if(final == 1){ final == 3; } if(oppfinal ==1){ oppfinal == 3; } if(score&gt;oppscore){ wins = wins + 1; teamoverall = teamoverall + 2; }else{ losses = losses +1; teamoverall = teamoverall - 2; } cout &lt;&lt; &quot;Arkansas scored &quot; &lt;&lt; final &lt;&lt; &quot; | Georgia scored &quot; &lt;&lt; oppfinal &lt;&lt; endl &lt;&lt; endl; nextgame = &quot;Kentucky&quot;; cout &lt;&lt; &quot;Type 1 and press enter to continue...&quot; &lt;&lt; endl; cin &gt;&gt; select; goto Dynasty; }else{ if(nextgame == &quot;Kentucky&quot;){ score = teamoverall * .5; srand (time(NULL)); random = rand() % 5 + -20; srand (time(NULL)); random1 = rand() % 20 + 1; random = random + random1; score = score + random; oppscore = Kentucky * .5; srand (time(NULL)); random = rand() % 10 + -25; srand (time(NULL)); random1 = rand() % 25 + 1; random = random + random1; oppscore = oppscore + random; final = score; oppfinal = oppscore; if(final == oppfinal){ goto playgame; } if(final &lt; 0){ final = 0; } if(oppfinal &lt; 0){ oppfinal = 0; } if(final == 1){ final == 3; } if(oppfinal ==1){ oppfinal ==3; } if(score&gt;oppscore){ wins = wins + 1; teamoverall = teamoverall + 2; }else{ losses = losses +1; teamoverall = teamoverall - 2; } cout &lt;&lt; &quot;Arkansas scored &quot; &lt;&lt; final &lt;&lt; &quot; | Kentucky scored &quot; &lt;&lt; oppfinal &lt;&lt; endl &lt;&lt; endl; nextgame = &quot;Auburn&quot;; cout &lt;&lt; &quot;Type 1 and press enter to continue...&quot; &lt;&lt; endl; cin &gt;&gt; select; goto Dynasty; }else{ if(nextgame == &quot;Auburn&quot;){ cout &lt;&lt; string( 100, '\n' ); score = teamoverall * .5; srand (time(NULL)); random = rand() % 5 + -25; srand (time(NULL)); random1 = rand() % 20 + 1; random = random + random1; score = score + random; oppscore = Auburn * .5; srand (time(NULL)); random = rand() % 1 + -20; srand (time(NULL)); random1 = rand() % 20 + 1; random = random + random1; oppscore = oppscore + random; final = score; oppfinal = oppscore; if(final &lt; 0){ final = 0; } if(oppfinal &lt; 0){ oppfinal = 0; } if(final == 1){ final == 3; } if(oppfinal ==1){ oppfinal == 3; } if(final == oppfinal){ goto playgame; } if(score&gt;oppscore){ wins = wins + 1; teamoverall = teamoverall + 2; }else{ losses = losses +1; teamoverall = teamoverall - 2; } cout &lt;&lt; &quot;Arkansas scored &quot; &lt;&lt; final &lt;&lt; &quot; | Auburn scored &quot; &lt;&lt; oppfinal &lt;&lt; endl &lt;&lt; endl; nextgame = &quot;LSU&quot;; cout &lt;&lt; &quot;Type 1 and press enter to continue...&quot; &lt;&lt; endl; cin &gt;&gt; select; goto Dynasty; }else{ if(nextgame == &quot;LSU&quot;){ cout &lt;&lt; string( 100, '\n' ); score = teamoverall * .5; srand (time(NULL)); random = rand() % 5 + -15; srand (time(NULL)); random1 = rand() % 25 + 1; random = random + random1; score = score + random; oppscore = LSU * .5; srand (time(NULL)); random = rand() % 1 + -20; srand (time(NULL)); random1 = rand() % 25 + 1; random = random + random1; oppscore = oppscore + random; final = score; oppfinal = oppscore; if(final &lt; 0){ final = 0; } if(oppfinal &lt; 0){ oppfinal = 0; } if(final == 1){ final == 3; } if(oppfinal ==1){ oppfinal ==3; } if(final == oppfinal){ goto playgame; } if(score&gt;oppscore){ wins = wins + 1; teamoverall = teamoverall + 2; }else{ losses = losses +1; teamoverall = teamoverall - 2; } cout &lt;&lt; &quot;Arkansas scored &quot; &lt;&lt; final &lt;&lt; &quot; | LSU scored &quot; &lt;&lt; oppfinal &lt;&lt; endl &lt;&lt; endl; nextgame = &quot;Texas A&amp;M&quot;; cout &lt;&lt; &quot;Type 1 and press enter to continue...&quot; &lt;&lt; endl; cin &gt;&gt; select; goto Dynasty; }else{ if(nextgame == &quot;Texas A&amp;M&quot;){ cout &lt;&lt; string( 100, '\n' ); score = teamoverall * .5; srand (time(NULL)); random = rand() % 10 + -20; srand (time(NULL)); random1 = rand() % 30 + 1; random = random + random1; score = score + random; oppscore = TexasAM * .5; srand (time(NULL)); random = rand() % 5 + -15; srand (time(NULL)); random1 = rand() % 20 + 1; random = random + random1; oppscore = oppscore + random; final = score; oppfinal = oppscore; if(final &lt; 0){ final = 0; } if(oppfinal &lt; 0){ oppfinal = 0; } if(final == 1){ final == 3; } if(oppfinal ==1){ oppfinal = 3; } if(final == oppfinal){ goto playgame; } if(score&gt;oppscore){ wins = wins + 1; teamoverall = teamoverall + 2; }else{ losses = losses +1; teamoverall = teamoverall - 2; } cout &lt;&lt; &quot;Arkansas scored &quot; &lt;&lt; final &lt;&lt; &quot; | Texas A&amp;M scored &quot; &lt;&lt; oppfinal &lt;&lt; endl &lt;&lt; endl; nextgame = &quot;Texas A&amp;M&quot;; cout &lt;&lt; &quot;Type 1 and press enter to continue...&quot; &lt;&lt; endl; cin &gt;&gt; select; goto Dynasty; } } } } } } rankings: cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;1- &quot; &lt;&lt; teams[0] &lt;&lt; endl; cout &lt;&lt; &quot;2- &quot; &lt;&lt; teams[1] &lt;&lt; endl; cout &lt;&lt; &quot;3- &quot; &lt;&lt; teams[2] &lt;&lt; endl; cout &lt;&lt; &quot;4- &quot; &lt;&lt; teams[3] &lt;&lt; endl; cout &lt;&lt; &quot;5- &quot; &lt;&lt; teams[4] &lt;&lt; endl; cout &lt;&lt; &quot;6- &quot; &lt;&lt; teams[5] &lt;&lt; endl; cout &lt;&lt; &quot;7- &quot; &lt;&lt; teams[6] &lt;&lt; endl; cout &lt;&lt; &quot;8- &quot; &lt;&lt; teams[7] &lt;&lt; endl; cout &lt;&lt; &quot;9- &quot; &lt;&lt; teams[8] &lt;&lt; endl; cout &lt;&lt; &quot;10- &quot; &lt;&lt; teams[9] &lt;&lt; endl; cout &lt;&lt; &quot;Type 1 and press enter to go back...&quot; &lt;&lt; endl; cin &gt;&gt; select; goto Dynasty; Manual: cin &gt;&gt; select; About: cin &gt;&gt; select; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T11:10:51.360", "Id": "491407", "Score": "0", "body": "consider accepting an answer" } ]
[ { "body": "<p>Your code doesn't compile due to the invalid use of <code>goto</code>. Nevertheless, I have put in my thoughts.</p>\n<h1>Dont <code>using namespace std</code> &amp; <code> #include &lt;bits/stdc++.h&gt;</code></h1>\n<p><strong><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why shouldn't I use using namespace std in C++</a></strong> <br>\n<strong><a href=\"https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.\">Why shouldn't I #include &lt;bits/stdc++.h&gt;?</a></strong></p>\n<p>You should always try to avoid these two statements.</p>\n<hr />\n<h1>Format your code properly</h1>\n<p>A very important part of writing clean code is that it is formatted properly. As it is currently, your code is extremely tough to read. Simply using a site like <a href=\"https://codebeautify.org/cpp-formatter-beautifier\" rel=\"nofollow noreferrer\">this one</a>\nto format your code can help a lot</p>\n<h1>What goes into <code>main()</code>?</h1>\n<p>I would <strong>highly</strong> suggest you to make use of <a href=\"https://www.w3schools.com/cpp/cpp_functions.asp\" rel=\"nofollow noreferrer\">functions</a> to split the work. Your <code>main()</code> typically <strong>shouldn't</strong> perform all of this. You need to again, split the work into different functions which will make your code 100x more readable</p>\n<p>An example of from your code can be</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>cout &lt;&lt; &quot;COLLEGE FOOTBALL COACH - 2020&quot; &lt;&lt; endl;\ncout &lt;&lt; &quot;1 - Manage&quot; &lt;&lt; endl;\ncout &lt;&lt; &quot;2 - Manual&quot; &lt;&lt; endl;\ncout &lt;&lt; &quot;3 - About&quot; &lt;&lt; endl;\n</code></pre>\n<p>Why not assign this to a function called <code>print_info()</code> ? This way whenever you would want to print this, you wouldn't have to copy-past this but merely call <code>print_info()</code></p>\n<p>Your main function should be able to <em>control the flow</em>.</p>\n<h1><code>goto</code>?</h1>\n<p>I see <code>goto</code> statements everywhere in the code. It is now becoming increasingly difficult to read your code as I need to do <code>Cntrl+f</code> in my IDE to find the goto tag from the huge block of code. A much better alternative to it should be to use <strong>functions</strong>. Where each choice would call the respective function.</p>\n<h1>Avoid the use of <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#:%7E:text=7%20References-,Unnamed%20numerical%20constants,1%20manuals%20of%20the%201960s.\" rel=\"nofollow noreferrer\">magic numbers</a></h1>\n<p>Magic numbers basically are <br></p>\n<blockquote>\n<p>Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants</p>\n</blockquote>\n<pre class=\"lang-cpp prettyprint-override\"><code>if(select == 1){...}\n</code></pre>\n<p>What is <code>1</code> to the reader? What if I could name the specific choices in a way that the functionality remains the same but the code is more readable?</p>\n<h2><a href=\"https://docs.microsoft.com/en-us/cpp/cpp/enumerations-cpp?view=vs-2019#:%7E:text=An%20enumeration%20is%20a%20user,introduced%20in%20C%2B%2B11.\" rel=\"nofollow noreferrer\">enums in C++</a></h2>\n<blockquote>\n<p>An enumeration is a user-defined type that consists of a set of named integral constants that are known as enumerators.</p>\n</blockquote>\n<p>How will we implement the idea of enumerations here?</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Choices{ manage = 1,manual,abort };\n</code></pre>\n<p>here when I set <code>manage = 1</code>, manual becomes <code>2</code>, abort becomes <code>3</code>...\nThis way I can replace the line</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if(select == 1){...}\n</code></pre>\n<p>Into</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if(select == manage){...}\n</code></pre>\n<p>Now it is clear to the reader that if the user's selection is <code>manage</code>, <em>do manage stuff</em>.</p>\n<h1>Use <code>const</code> or <code>constexpr</code></h1>\n<p>You have a set of teams, <code>std::string teams[10]</code>. If you don't want to change this value during the run-time, it is a good practice to declare it <code>const</code>. This ensures that you will never change the value of <code>teams</code>. Hence, it will remain <strong>constant</strong>. Now even if you accidentally try to change <code>teams</code>. The compiler will throw an error and you will save yourself a lot of time.</p>\n<h1><code>'\\n'</code> over <code>std::endl</code></h1>\n<p>This might look like a very small, and unnecessary change. Both of them will achieve your purpose, but <code>'\\n'</code> is much faster as <code>std::endl;</code> will flush the output buffer every time, which has performance issues.<br><br></p>\n<p><strong><a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\">'\\n' vs std::endl in C++</a></strong></p>\n<hr />\n<h1>Object-Oriented-Programming</h1>\n<p>I think you yourself have figured out that your project is <strong>clunky</strong>. This is because the design of the program itself isn't good. You have randomly declared variables, and used <code>goto</code> to move around the huge block of code in the <code>main()</code> function.</p>\n<p>There is a way that you can improve your code by a huge margin. And that is <a href=\"https://www.w3schools.com/cpp/cpp_oop.asp#:%7E:text=C%2B%2B%20What%20is%20OOP%3F,contain%20both%20data%20and%20functions.&amp;text=OOP%20provides%20a%20clear%20structure%20for%20the%20programs\" rel=\"nofollow noreferrer\">Object oriented programming</a>. <br></p>\n<p>You have a team, it has attributes like score, wins, losses, name, etc.</p>\n<p>Why can't you have a <a href=\"https://www.geeksforgeeks.org/c-classes-and-objects/#:%7E:text=Class%3A%20A%20class%20in%20C%2B%2B,a%20blueprint%20for%20an%20object.\" rel=\"nofollow noreferrer\">class</a> called <code>Team</code> that would have all these attributes and methods to manage the data properly? This way you would reduce a lot of the repetition in the code and make it faster.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Team\n{\npublic:\n std::string name;\n int wins;\n int losses;\n int teamoverall;\n\n}\n</code></pre>\n<p>With this class, you would create an array of <code>Team</code>s which would all have these attributes. For example</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Team new_team;\nnew_team.name = &quot;Kansas&quot;;\nnew_team.wins = 5\n// and the rest of the attributes\n</code></pre>\n<p>Note: I don't know the game of football nor am I American , I have just taken the key points from your code.</p>\n<p>This would make it 100x easier to keep a track of what was going on.</p>\n<p>Since you have multiple teams, you can create an array of objects this way.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Team all_teams[number_of_teams];\n</code></pre>\n<p>My example is a very basic class. Read <a href=\"https://www.geeksforgeeks.org/c-classes-and-objects/#:%7E:text=Class%3A%20A%20class%20in%20C%2B%2B,a%20blueprint%20for%20an%20object.\" rel=\"nofollow noreferrer\">this</a> to know more about classes.</p>\n<h2>About the ranking system</h2>\n<p>Since you directly have an array of teams, 1 loop through the array can get you the team with the max number of wins. It would look like this</p>\n<p>Assuming the array of objects is initialized</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::string highest_scoring_team;\nint max = 0;\nfor(auto const&amp; team:array_of_teams)\n{\n if (team.max &gt; max) \n {\n team.max = max;\n highest_scoring_team = team.name\n }\n}\n</code></pre>\n<p><strong>What's happening here?</strong> I have set the initial score to <code>0</code> (Hoping that is the lowest score possible). Now when go through the teams, if the score of any team is greater than <code>max</code>, <code>max</code> becomes that score. And at the same time i keep a record of the winning team. At the end <code>highest_scoring_team</code> will be the name of the team and <code>max</code> will be their score.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T23:34:10.877", "Id": "491279", "Score": "0", "body": "Thank you, this helped loads. Though, could you provide thoughts on a ranking system, and how I could get that to work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T23:43:56.680", "Id": "491280", "Score": "1", "body": "@TroyCox I'm glad you found it useful, consider upvoting the answer if you do. About the ranking system . As I said I don't know a thing about football, so it is quite difficult for me to think of something that would be suitable for it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T23:45:36.860", "Id": "491282", "Score": "0", "body": "I understand, but I just need like a key concept. Like, could that be done for a ray? Is it possible to move around the individual elements in a ray, like swap them back and forth?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T23:47:02.960", "Id": "491283", "Score": "1", "body": "@TroyCox Can you do me a favor and briefly explain the ranking system part so I can edit my question to address this. Is the rank based on the scores of the teams?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T23:58:58.423", "Id": "491284", "Score": "0", "body": "So the ranking system is based on team performance, so wins and losses pretty much. In real College Football, a committee interprets a team's performance, so it isn't just based off wins and losses, but also how they think they did. If we were to do that here, it would probably be really long, so just ranked off their wins would be great." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T08:45:41.143", "Id": "491316", "Score": "0", "body": "@TroyCox check out the answer" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T23:11:53.410", "Id": "250386", "ParentId": "250382", "Score": "5" } }, { "body": "<p>In addition to above</p>\n<h1>Do not initialise srand over and over againg</h1>\n<p><code>srand (time(NULL));</code> should be called once. <a href=\"https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once\">Details</a></p>\n<h1>Use standard containers instead of raw arrays</h1>\n<p><code>std::array</code> is excellent choice to store your data of known size. if you are using c++17 you don't even need to specify what or how many inside.</p>\n<h1>You probably need a queue or stack maybe</h1>\n<p>if I comprehend correctly tons of <code>goto</code>s in your code you need <code>std::queue</code> to work with matchmaking and stuff.</p>\n<h1>do not copy-paste thing when you can use cycle instead</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>cout &lt;&lt; &quot;1- &quot; &lt;&lt; teams[0] &lt;&lt; endl;\ncout &lt;&lt; &quot;2- &quot; &lt;&lt; teams[1] &lt;&lt; endl;\ncout &lt;&lt; &quot;3- &quot; &lt;&lt; teams[2] &lt;&lt; endl;\ncout &lt;&lt; &quot;4- &quot; &lt;&lt; teams[3] &lt;&lt; endl;\ncout &lt;&lt; &quot;5- &quot; &lt;&lt; teams[4] &lt;&lt; endl;\ncout &lt;&lt; &quot;6- &quot; &lt;&lt; teams[5] &lt;&lt; endl;\ncout &lt;&lt; &quot;7- &quot; &lt;&lt; teams[6] &lt;&lt; endl;\ncout &lt;&lt; &quot;8- &quot; &lt;&lt; teams[7] &lt;&lt; endl;\ncout &lt;&lt; &quot;9- &quot; &lt;&lt; teams[8] &lt;&lt; endl;\n</code></pre>\n<p>could be printed as</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>const size_t teamCount = 8;\nfor (size_t i = 0; i &lt; teamCount;++i) {\n std::cout &lt;&lt; (i+1) &lt;&lt; &quot;- &quot; &lt;&lt; teams[i] &lt;&lt; &quot;\\n&quot;; // note it's not endl\n}\nstd::cout &lt;&lt; std::endl; // push endl to flush data to IO-stream\n</code></pre>\n<p>It applies to other places where you render some menu for player. You can make some class out of it. And using <code>queue</code> also will require to use some loops as well</p>\n<h1>Don't use reserved words</h1>\n<p><code>final</code> is also cv-qualifier for virtual methods, so better name it something else.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T16:03:49.170", "Id": "491364", "Score": "1", "body": "Great answer! Try using `'\\n'` over `std::endl` as flushing the stream should only be done when absolutely required, `'\\n'` does the same job much faster." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T12:25:49.690", "Id": "250414", "ParentId": "250382", "Score": "1" } } ]
{ "AcceptedAnswerId": "250386", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:30:23.233", "Id": "250382", "Score": "2", "Tags": [ "c++", "beginner", "array", "sorting", "integer" ], "Title": "Football management game in C++" }
250382
<p>I've been working on an Aerodynamics calculator using python (which I'm relatively new at), In this program, a value can be calculated based on multiple different inputs <em>ie. a calculates b, b calculates c, or c can find b and b can find a</em>.</p> <p>To elaborate on the function of this program it will loop through it's logic until it has found all the things it could with the given input(s). The code is pretty long for it's function and that's why I'd like to see if it could be optimized or if I could do anything better. For the input method, the input is a string. The code is as follows:</p> <pre><code>def Find_Pressure(temp): pressure = (101.29 * (((temp + 273.1) / 288.08) ** 5.256)) return pressure def Find_Temp_Alt(alt, ground_temp): Temp = ground_temp - (0.00649 * alt) return Temp def Find_Density(pressure, temp): density = (pressure / (0.2869 * (temp + 273.1))) return density def Find_Alt_Temp(temp, ground_temp): Alt = ((ground_temp - temp) / 0.00649) return Alt def is_Valid(x): try: float(x) return True except ValueError: return False def Parser(ground_temp, temp, alt, pressure, density): a = t = p = d = False run = True Alt = Temp = Pressure = Density = &quot;N/A&quot; if is_Valid(alt): Alt = float(alt) a = True if is_Valid(temp): Temp = float(temp) if Temp &lt;= -273.1: t = False else: t = True if is_Valid(pressure): Pressure = float(pressure) p = True if is_Valid(density): Density = float(density) d = True if not is_Valid(ground_temp): print('Enter Ground Temp') else: G_T = float(ground_temp) while run: run = False if a and not t: Temp = Find_Temp_Alt(Alt, G_T) t = True run = True if t and not a: Alt = Find_Alt_Temp(Temp, G_T) a = True run = True if p and not t: Temp = ((288.08 * ((Pressure / 101.29) ** (1 / 5.256))) - 273.1) t = True run = True if t and not p: Pressure = Find_Pressure(Temp) p = True run = True if (p and t) and not d: Density = Find_Density(Pressure, Temp) d = True run = True if (d and t) and not p: Pressure = (Density * 0.2869 * (Temp + 273.1)) p = True run = True if (d and p) and not t: Temp = ((Pressure / Density * 0.2869) - 273.1) t = True run = True return Alt, Temp, Pressure, Density </code></pre> <p>I apricate any help/feedback, thanks in advance!</p>
[]
[ { "body": "<p>Just a couple notes about style</p>\n<ul>\n<li>Variable and function names should be in <code>snake_case</code></li>\n<li>You should add type hints to display what types of parameters you accept, and what value(s) your functions return.</li>\n</ul>\n<pre><code>def find_pressure(temp: float) -&gt; float:\n return (101.29 * (((temp + 273.1) / 288.08) ** 5.256))\n\n\ndef find_temp_alt(alt: float, ground_temp: float) -&gt; float:\n return ground_temp - (0.00649 * alt)\n\n\ndef find_density(pressure: float, temp: float) -&gt; float:\n return (pressure / (0.2869 * (temp + 273.1)))\n\n\ndef Find_Alt_Temp(temp: float, ground_temp: float) -&gt; float:\n return ((ground_temp - temp) / 0.00649)\n\n\ndef is_valid(x: str) -&gt; bool:\n try:\n float(x)\n return True\n except ValueError:\n return False\n</code></pre>\n<p>You don't need to create a variable for a calculation in order to return that calculation. Just return the expression itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T03:56:09.123", "Id": "250392", "ParentId": "250383", "Score": "2" } }, { "body": "<p>Welcome to Code Review! I'll be adding onto what @Linny has already said about type hints and variable naming. Variable naming is part of python's PEP-8 guidelines (see bottom).</p>\n<h2>Magic numbers</h2>\n<p>You have a lot of magic numbers in your code, which are really conversion constants, but appear with no such explanation.</p>\n<h2>Variable names</h2>\n<p>Since you're writing an aerodynamics calculator, it'd help if you use full names for various variables in your code. For eg. <code>altitude</code> instead of <code>alt</code>, <code>temperature</code> instead of just <code>temp</code> (<code>temp</code> is generally used as a temporary variable in code).</p>\n<h2>Ground temperature</h2>\n<p>Based on the flow of program, I assume that <code>ground_temperature</code> is essential for any calculations. Perhaps check for it at the very beginning and break early in case of invalid checks.</p>\n<h2>Optional arguments</h2>\n<p>From the above, only <code>ground_temperature</code> is needed to call the calculator. Everything else is optional, and can be computed. Perhaps a function which defaults other values to <code>None</code> might suit you better:</p>\n<pre><code>def aerodynamic_calculator(\n ground_temperature: float,\n temperature: float = None,\n altitude: float = None,\n pressure: float = None,\n density: float = None,\n):\n</code></pre>\n<h2>Booleans for each parameter</h2>\n<p>With the above approach, you can just validate for the value itself, without having to keep track of a boolean for those values.</p>\n<pre><code>if temperature and not altitude:\n altitude = compute_altitude_from_temperature(temperature, ground_temperature)\n</code></pre>\n<h2>PEP-8</h2>\n<p>In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.</p>\n<p>Functions and variables should be named in a <code>lower_snake_case</code>, classes as <code>UpperCamelCase</code>, and constants as <code>UPPER_SNAKE_CASE</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T06:52:40.583", "Id": "250397", "ParentId": "250383", "Score": "4" } } ]
{ "AcceptedAnswerId": "250397", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:40:34.397", "Id": "250383", "Score": "6", "Tags": [ "python", "python-3.x", "mathematics", "calculator" ], "Title": "Python - Input Filtering, Calculating with a Variable Amount of Inputs" }
250383
<p>Description of the <a href="https://leetcode.com/problems/design-parking-system/" rel="nofollow noreferrer">problem</a>:</p> <blockquote> <p>Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.</p> <p>Implement the ParkingSystem class:</p> <p><code>ParkingSystem(int big, int medium, int small)</code> Initializes object of the <code>ParkingSystem</code> class. The number of slots for each parking space are given as part of the constructor.</p> <p><code>bool addCar(int carType)</code> Checks whether there is a parking space of <code>carType</code> for the car that wants to get into the parking lot. <code>carType</code> can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its <code>carType</code>. If there is no space available, return false, else park the car in that size space and return true.</p> </blockquote> <p>Below is my code, I would appreciate any suggestions on how to improve the code.</p> <pre><code>#include &lt;iostream&gt; class ParkingSystem { public: ParkingSystem(int big, int medium, int small) : m_big_max(big), m_medium_max(medium), m_small_max(small), m_big_curr(0), m_medium_curr(0), m_small_curr(0) {} bool addCar(int carType) { if (carType == 1) { // big car if (m_big_curr == m_big_max) { return false; } else { m_big_curr++; } } else if (carType == 2) { // medium car if (m_medium_curr == m_medium_max) { return false; } else { m_medium_curr++; } } else { // small car if (m_small_curr == m_small_max) { return false; } else { m_small_curr++; } } return true; } private: int m_big_max; int m_medium_max; int m_small_max; int m_big_curr; int m_medium_curr; int m_small_curr; }; int main() { ParkingSystem parking_system(1, 1, 0); std::cout &lt;&lt; &quot;parking_system.addCar(1) &quot; &lt;&lt; parking_system.addCar(1) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;parking_system.addCar(2) &quot; &lt;&lt; parking_system.addCar(2) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;parking_system.addCar(3) &quot; &lt;&lt; parking_system.addCar(3) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;parking_system.addCar(1) &quot; &lt;&lt; parking_system.addCar(1) &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<h2>Observation</h2>\n<p>You can simplify this using arrays.</p>\n<p>You don't need two numbers for each type (max and current). Simply track the number of open spots (per type) and count down.</p>\n<p>if you are not using arrays consider a switch statement.</p>\n<h2>Code Review:</h2>\n<p>Prefer <code>&quot;\\n&quot;</code> over <code>std::endl</code>.</p>\n<p>If your <code>main()</code> does not return anything but <code>0</code> at the end.<br />\nThen leave out the return. It is auto added by the compiler.</p>\n<h2>Re-Design</h2>\n<pre><code>template&lt;std::size_t typeCount = 3&gt;\nclass ParkingSystem\n{\n int openSlots[typeCount];\n \n public:\n template&lt;typename... Args&gt;\n ParkingSystem(Args... args)\n : openSlots{args...}\n {}\n \n bool addCar(int type)\n {\n if (openSlots[type - 1] == 0) {\n return false;\n }\n --openSlots[type - 1];\n return true;\n }\n};\n\nint main() \n{\n \n ParkingSystem parking_system(1, 1, 0);\n \n std::cout\n &lt;&lt; &quot;parking_system.addCar(1) &quot; &lt;&lt; parking_system.addCar(1) &lt;&lt; &quot;\\n&quot;\n &lt;&lt; &quot;parking_system.addCar(2) &quot; &lt;&lt; parking_system.addCar(2) &lt;&lt; &quot;\\n&quot;\n &lt;&lt; &quot;parking_system.addCar(3) &quot; &lt;&lt; parking_system.addCar(3) &lt;&lt; &quot;\\n&quot;\n &lt;&lt; &quot;parking_system.addCar(1) &quot; &lt;&lt; parking_system.addCar(1) &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T10:12:36.387", "Id": "491322", "Score": "0", "body": "is there any advantage in using a template for the size, compared to a `constexpr` variable?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T02:08:35.950", "Id": "250389", "ParentId": "250385", "Score": "4" } }, { "body": "<h1>General observations</h1>\n<p>If you notice your Parking class, you see that there are too many member variables. The first way to improve would be to try to reduce the extra variables. And that could be done by improving the code logic. But before I get into the logic part, I would like to point out.</p>\n<h2>Use <code>enum</code> for clarity</h2>\n<pre class=\"lang-cpp prettyprint-override\"><code>if (cartype == 1)\nif (cartype == 2)\n</code></pre>\n<p>These are called <strong><a href=\"https://help.semmle.com/wiki/display/CCPPOBJ/Magic+numbers#:%7E:text=A%20magic%20number%20is%20a,using%20the%20named%20constants%20instead.\" rel=\"nofollow noreferrer\">Magic Numbers</a></strong> <br>\nIt's not clear as to what <code>1</code> or <code>2</code> here. Unless you read the question thoroughly, it can get confusing.</p>\n<p>The solution is to use an <code>enum</code>. <br>\n<a href=\"https://docs.microsoft.com/en-us/cpp/cpp/enumerations-cpp?view=vs-2019#:%7E:text=An%20enumeration%20is%20a%20user,introduced%20in%20C%2B%2B11.\" rel=\"nofollow noreferrer\">enums in C++</a> <br></p>\n<blockquote>\n<p>An enumeration is a user-defined type that consists of a set of named integral constants\nthat are known as enumerators.</p>\n</blockquote>\n<p>This way you can give a <em>name</em> to numeric constants, which in this case are 1, 2, and 3.</p>\n<p>The syntax would look like <br></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum CarType{ BIG= 1, MEDIUM, SMALL};\n</code></pre>\n<p>This will set <code>MEDIUM</code> and <code>SMALL</code> to <code>2</code> and <code>3</code> respectively. Now your if statement will look like<br></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if (cartype == BIG)\nif (cartype == MEDIUM)\n</code></pre>\n<p>Sure you type a little more, but this way it is much clearer as to what the if statement checks for.</p>\n<h2>The Logic</h2>\n<p>The code asks us to keep track of 3 types of cars. Hence, all we really need is <strong>3</strong> variables. Even better, an array of car types.</p>\n<ul>\n<li>Every time we add a car, we do <code>--car_type</code></li>\n<li>If it is already 0, that means that the parking space of that type is full.</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum CarType{BIG = 1, MEDIUM, SMALL};\n\nconstexpr int nb_car_type = 3;\n\nclass Parking{\n private:\n int m_Big;\n int m_Medium;\n int m_Small;\n\n public:\n Parking(int big,int medium,int small)\n : m_Big{big}, m_Medium{medium}, m_Small{small}\n {}\n\n};\n</code></pre>\n<h2>With an array</h2>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;array&gt;\n\nconstexpr int nb_car_type = 3;\n\nclass Parking{\n private:\n std::array&lt; int , nb_car_type &gt; space;\n\n public:\n Parking(int big,int medium,int small)\n : space{big,medium,small}\n {}\n\n};\n</code></pre>\n<p><strong>Since we use an array, we will not need to use an <code>enum</code> since we won't be making any checks</strong> <br>\nThe advantage you have when using an array is that your <code>addcar()</code> function will be slightly smaller.</p>\n<h2>Adding the car</h2>\n<ul>\n<li>Check whether <code>space[car_type]</code> is 0</li>\n<li>If true, return false as parking space is 0</li>\n<li>If false, return true and decrement. <code>--space[car_type]</code></li>\n</ul>\n<p>Implementation.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;array&gt;\n\n\nconstexpr int nb_car_type = 3;\n\nclass Parking{\n private:\n std::array&lt; int , nb_car_type &gt; space;\n\n public:\n Parking(int big,int medium,int small)\n : space{big,medium,small}\n {}\n bool addcar(int type)\n {\n if (space[type-1] == 0) \n {\n return false;\n }\n --space[type-1];\n return true;\n }\n\n};\n</code></pre>\n<h2>What's happening here?</h2>\n<p>Since we have an array, we can directly slice the array by <code>type</code> and get the correct value. The reason it is not <code>type</code>, but <code>type-1</code> is because counting starts from 0. The 1st element of an array is <code>array[0]</code>.</p>\n<p>All we do is check whether that value is <code>0</code>. If it isn't that means more space is left, and we can derement that value. If it is then just <code>return false</code> as parking is full.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T10:05:37.483", "Id": "250410", "ParentId": "250385", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-08T22:57:34.117", "Id": "250385", "Score": "3", "Tags": [ "c++", "object-oriented" ], "Title": "Leetcode 1603. Design Parking System" }
250385
<pre><code>int combiset(int ism,int inarr[],int inpth){ int r1,r2,r3,r4; for(int i=0;i&lt;inpth;i++){ r1 = inarr[i]+inarr[i+1]; r2 = r1+inarr[i+2]; r3 = r2+inarr[i+3]; r4 = r3+inarr[i+4]; if(r4==ism){ printf(&quot;%d %d %d %d %d\n&quot;,inarr[i],inarr[i+1],inarr[i+2],inarr[i+3],inarr[i+4]);} if(r3==ism){ printf(&quot;%d %d %d %d\n&quot;,inarr[i],inarr[i+1],inarr[i+2],inarr[i+3]);} if(r2==ism){ printf(&quot;%d %d %d\n&quot;, inarr[i], inarr[i+1], inarr[i+2]);} if(r1==ism){ printf(&quot;%d %d\n&quot;, inarr[i], inarr[i+1]);} } } </code></pre> <p>I am currently designing a function which will calculate and display out the possible combinations of sets from the user input. User will inputs the value of sum that they want to target and the array data such as length and integers inside. For example, if user inputs</p> <pre><code>array length:10 array data:9 1 5 5 8 9 7 3 1 6 target sum:10 </code></pre> <p>then the result output should look like</p> <pre><code>9 1 5 5 7 3 3 1 6 </code></pre> <p>Hereby, answer should follow the input array order and answers should be linked, so 1 5 3 1 cannot be an answer.</p> <p>In my opinion, function which I have designed is too inefficient because user may input the array length as 100 then I have to make r1 until r100 to check whether there is possible combination of sets but with my method, the codes will get tremendously longer. Thus I am thinking of simpler code but I have no idea for it. How can I make my function better to find possible combinations of set?</p>
[]
[ { "body": "<h1>Avoid repetition</h1>\n<p>Whenever you are repeating yourself twice or more often, you should immediately find some way to get rid of the repetition. You probably already know how to do this. For example, in this case, just add more <code>for</code>-loops: one to calculate the sum, and another to print all the elements once you have found a set of consecutive elements that sums up to the desired value:</p>\n<pre><code>for (int i = 0; i &lt; inpth; i++) {\n int sum = 0;\n\n for (int j = i; j &lt; inpth &amp;&amp; sum &lt; ism; j++) {\n sum += inarr[j];\n\n if (sum == ism) {\n // Now I know that the sum of element i to j equals ism\n for (int k = i; k &lt;= j; k++) {\n printf(&quot;%d &quot;, inarr[k]);\n }\n\n printf(&quot;\\n&quot;);\n }\n }\n}\n</code></pre>\n<h1>Create functions to solve smaller problems</h1>\n<p>Try to split up your problem in smaller problems, and write functions to solve the smaller problems. This allows you to focus on the smaller problems, and the code usually becomes more readable as well. For example:</p>\n<pre><code>/* Print out a single subset */\nstatic void print_subset(int subarr[], int len) {\n for (int i = 0; i &lt; len; i++) {\n printf(&quot;%d &quot;, subarr[i]);\n }\n\n printf(&quot;\\n&quot;);\n}\n\n/* Check if summing from the start of the subarray will get us the desired value */\nstatic void check_subset(int ism, int subarr[], int len) {\n int sum = 0;\n\n for (int i = 0; i &lt; len &amp;&amp; sum &lt; ism; i++) {\n sum += subarr[i];\n\n if (sum == ism) {\n print_subset(subarr, i + 1);\n }\n }\n}\n\n/* Check all possible subsets of the input array */\nint combiset(int ism, int inarr[], int inpth) {\n for (int i = 0; i &lt; inpth; i++) {\n check_subset(ism, inarr + i, inpth - i);\n }\n}\n</code></pre>\n<p>In the above, each function only has a single <code>for</code>-loop, which makes them much easier to reason about than the three nested <code>for</code>-loops in the first example I gave.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T07:18:34.083", "Id": "250398", "ParentId": "250391", "Score": "6" } } ]
{ "AcceptedAnswerId": "250398", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T03:29:57.580", "Id": "250391", "Score": "4", "Tags": [ "c" ], "Title": "Finding possible subset combination from the user input" }
250391
<p>its a practice project from &quot;Automate the Boring stuff with Python&quot; book. i am an intermediate level Python programmer and i tried to solve this problem with less code as possible. This code will not take any wrong date into consideration eg: 29-02-2002 will not be selected because 2002 is not a leap year and only leap years have 29th of feb. i did not add code to also detect dates with months written in words, i could do that too but i want to keep things simple for now and i also did not use pyperclip module to detect dates from copied text to clipboard because i dont want to confuse any beginner who also want to learn from watching my code. I want master programmers to review my code and if their is another way possible to detect dates then please post your solutions. Also i would appreciate any advice and positive criticism, so i know where i am standing right now and what i need to improve. Thanks. Code is as follows:</p> <pre class="lang-py prettyprint-override"><code> import re def date_detector(text): date_pattern = re.compile(''' ([12][0-9]|3[0-1]|0?[1-9]) # to detect days from 1 to 31 ([./-]) # to detect different separations (1[0-2]|0?[1-9]) # to detect number of months ([./-]) # to detect different seperations (2?1?[0-9][0-9][0-9]) # to detect number of years from 1000-2999 years ''', re.VERBOSE) days = [] months = [] years = [] dates = [] for date in date_pattern.findall(text): days.append(int(date[0])) months.append(int(date[2])) years.append(int(date[4])) for num in range(len(days)): # appending dates in a list that dont need any filtering to detect wrong dates if months[num] not in (2, 4, 6, 9, 11): dates.append([days[num], months[num], years[num]]) # detecting those dates with months that have only 30 days elif days[num] &lt; 31 and months[num] in (4, 6, 9, 11): dates.append([days[num], months[num], years[num]]) # filtering leap years with Feb months that have 29 days elif months[num] == 2 and days[num] == 29: if years[num] % 4 == 0: if years[num] % 100 == 0: if years[num] % 400 == 0: dates.append([days[num], months[num], years[num]]) else: dates.append([days[num], months[num], years[num]]) # appending Feb dates that have less than 29 days elif months[num] == 2 and days[num] &lt; 29: dates.append([days[num], months[num], years[num]]) if len(dates) &gt; 0: for date in dates: print(date) data = '30-06-2012, 31-12-2012, 15-02-2002, 29-02-2004, 29-02-2002, 31-02-2004, 31-06-2012' date_detector(data) <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>I suggest some minor improvements in the regular expression:</p>\n<ul>\n<li>make sure that the same separator is used between day and month and between month and year with a backreference <code>(?P=sep)</code>,</li>\n<li>replace numbered capture groups with named, and make non-needed groups, if there wer any, non-capturing with <code>?:</code>. Consequently, <code>finditer</code> and <code>groupdict</code> are used, and the day is obtained from the match with <code>int(date['day'])</code>, etc. This will make the code somewhat more human.</li>\n</ul>\n<p>More importantly, I suggest that you get rid of <code>days</code>, <code>months</code> and <code>years</code> lists altogether. These data can be stored in dictionaries in <code>dates</code> list and filtered prior to appending to <code>dates</code>.</p>\n<p>As a consequence, you won't need a loop over <code>range(len(days))</code>.</p>\n<p>The validation conditions can be OR'ed together without losing clarity, and I propose to make it a separate function <code>date_is_valid(day: int, month: int, year: int) -&gt; bool</code>.</p>\n<p>Also, the only parametre in <code>date_detector</code> can be made typed: <code>def date_detector(text: str):</code>.</p>\n<p>To sum suggested modifications up:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\n\ndef date_is_valid(day: int, month: int, year: int) -&gt; bool:\n return (month not in (2, 4, 6, 9, 11) # 31 days in month (Jan, Mar, May, Jul, Aug, Oct, Dec).\n or day &lt; 31 and month in (4, 6, 9, 11) # 30 days in month (Feb, Apr, Jun, Sep, Nov).\n or month == 2 and day == 29 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n # February, 29th in a Gregorian leap year.\n or month == 2 and day &lt; 29) # February, 1st-28th.\n\ndef date_detector(text: str):\n date_pattern = re.compile('''\n (?P&lt;day&gt;[12][0-9]|3[0-1]|0?[1-9]) # to detect days from 1 to 31\n (?P&lt;sep&gt;[./-]) # to detect different separations\n (?P&lt;month&gt;1[0-2]|0?[1-9]) # to detect number of months\n (?P=sep) # to detect different seperations\n (?P&lt;year&gt;2?1?[0-9][0-9][0-9]) # to detect number of years from 1000-2999 years\n ''', re.VERBOSE)\n\n dates = []\n for match in date_pattern.finditer(text):\n date = match.groupdict() # convert Match object to dictionary.\n del date['sep'] # we don't need the separator any more.\n date = {key: int(val) for key, val in date.items()} # apply int() to all items.\n \n if date_is_valid(date['day'], date['month'], date['year']):\n dates.append(date)\n\n if len(dates) &gt; 0:\n for date in dates:\n print(date)\n\ndata = '30-06-2012, 31-12-2012, 15-02-2002, 29-02-2004, 29-02-2002, 31-02-2004, 31-06-2012'\n\ndate_detector(data)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T07:56:23.397", "Id": "250400", "ParentId": "250395", "Score": "2" } }, { "body": "<p>I know this is a part of an exercise, but it feels like a lot of wheel reinventing where you can leverage builtin Python capabilities for date validation:</p>\n<pre><code>from datetime import date\n\n&gt;&gt;&gt; date(2020, 2, 29) # leap year date works\ndatetime.date(2020, 2, 29)\n\n&gt;&gt;&gt; date(2002, 2, 29) # non-leap year will raise ValueError\nValueError: day is out of range for month\n\n&gt;&gt;&gt; date(2002, 9, 31) # 31th day will raise ValueError\nValueError: day is out of range for month\n</code></pre>\n<ul>\n<li><p>instead of creating 3 separate lists for <strong>years</strong>, <strong>months</strong> and <strong>days</strong>, you can create only one list, since you always access these parts at the same index. That also simplifies the <code>for</code> loop which gives you the values directly instead of giving you an index you want to access in these lists.</p>\n</li>\n<li><p>Python is a dynamic language where empty collections are evaluated to <code>False</code>, so when you want to check if a list has any items, you don't have to do it explicitly via <code>if len(list) &gt; 0</code>, but you can do <code>if list:</code>. For purpose of printing items in list, you can take it one step further and omit the condition completely as iterating through an empty list wont print anything. Snippet before/after:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code># before\nif len(dates) &gt; 0:\n for date in dates:\n print(date)\n\n# after\nfor date in dates:\n print(date)\n</code></pre>\n<p>all suggestion applied:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\nfrom datetime import date\n\ndef date_detector(text):\n date_pattern = re.compile('''\n ([12][0-9]|3[0-1]|0?[1-9]) # to detect days from 1 to 31\n ([./-]) # to detect different separations\n (1[0-2]|0?[1-9]) # to detect number of months\n ([./-]) # to detect different seperations\n (2?1?[0-9][0-9][0-9]) # to detect number of years from 1000-2999 years\n ''', re.VERBOSE)\n\n # use only one list for storing all parts of match together\n parsed = []\n for match in date_pattern.findall(text):\n # year, month, day for easier passing to date()\n parsed.append([ int(match[4]), int(match[2]), int(match[0])] )\n\n valid = [] \n for item in parsed:\n try:\n # pass list of [year, month, day] to date() and let it check its validity for us\n date(*item)\n except ValueError as e:\n pass # invalid date, dont do anything\n else:\n valid.append(item)\n\n for item in valid:\n print(item)\n\n\ndata = '30-06-2012, 31-12-2012, 15-02-2002, 29-02-2004, 29-02-2002, 31-02-2004, 31-06-2012'\n\ndate_detector(data)\n</code></pre>\n<ul>\n<li>this can be simplified further by merging both <code>for</code> loops together, so you it does not iterate through the collection of data twice needlessly.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T08:33:02.013", "Id": "250404", "ParentId": "250395", "Score": "2" } } ]
{ "AcceptedAnswerId": "250400", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T05:56:54.057", "Id": "250395", "Score": "2", "Tags": [ "python-3.x", "datetime", "regex", "object-detection" ], "Title": "Date Detection with Python RegEx" }
250395
<p>My goal with the below piece of POSIX shell code was to address the more platforms the better with <strong>shell <code>tput</code> colors</strong>. With this code, I now start all of my scripts, and so it's time to review it for some things I overlooked, did not think of too well, and such. Note: I start my scripts with <code>set -u</code>, which is why I set all empty in unspecified cases. Thanks.</p> <hr /> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh set -u if tput setaf &gt; /dev/null 2&gt;&amp;1; then # Linux-like tput_number_of_colors=$(tput colors 2&gt; /dev/null) tput_bold=$(tput bold 2&gt; /dev/null) tput_reset=$(tput sgr0 2&gt; /dev/null) tput_cmd_set_fg_color='tput setaf' elif tput AF &gt; /dev/null 2&gt;&amp;1; then # BSD-like tput_number_of_colors=$(tput Co 2&gt; /dev/null) tput_bold=$(tput md 2&gt; /dev/null) tput_reset=$(tput me 2&gt; /dev/null) tput_cmd_set_fg_color='tput AF' else # Console-like tput_number_of_colors=2 tput_cmd_set_fg_color= tput_bold= tput_reset= fi tput_test () { [ -n &quot;$tput_number_of_colors&quot; ] &amp;&amp; [ -n &quot;$tput_bold&quot; ] &amp;&amp; [ -n &quot;$tput_reset&quot; ] &amp;&amp; { [ &quot;$tput_number_of_colors&quot; -ge 8 ] &amp;&amp; printf '%s' &quot;$tput_bold&quot; &amp;&amp; $tput_cmd_set_fg_color 1; } &gt; /dev/null 2&gt;&amp;1 } if tput_test; then color_red=$tput_bold$($tput_cmd_set_fg_color 1) color_green=$tput_bold$($tput_cmd_set_fg_color 2) color_yellow=$tput_bold$($tput_cmd_set_fg_color 3) color_blue=$tput_bold$($tput_cmd_set_fg_color 4) color_magenta=$tput_bold$($tput_cmd_set_fg_color 5) color_cyan=$tput_bold$($tput_cmd_set_fg_color 6) color_white=$tput_bold$($tput_cmd_set_fg_color 7) else color_red=; color_green=; color_yellow=; color_blue=; color_magenta=; color_cyan=; color_white= fi </code></pre>
[]
[ { "body": "<h1>Self-review</h1>\n<p>Since no one replied thus far, I decided to re-think and re-write the code myself this morning.</p>\n<hr />\n<h2><code>terminfo</code> (*nix) vs <code>termcap</code> (*bsd)</h2>\n<p>I never really thought about how important to make note of this actually is. For searching info online, one needs to know these keywords. So, I added them as comments.</p>\n<h2>Structure into functions</h2>\n<p>I believe this code should be structured into suitable functions where available.</p>\n<h2>Find a way for an exit code from those functions</h2>\n<p>It's needed to simply chain (<code>&amp;&amp;</code>) the commands like <code>tput_bold=$(tput bold 2&gt; /dev/null) &amp;&amp; tput_reset=$(tput sgr0 2&gt; /dev/null)</code> in order for the imagined functions to return a reliable exit code.</p>\n<h2>The most basic test missing</h2>\n<p><code>command -v tput</code> was missing in my code, which is remedied now.</p>\n<h2>No unset variables</h2>\n<p>Since I use <code>set -u</code> in my scripts, it's necessary to set variables empty in case of failure. This feature has been enhanced.</p>\n<hr />\n<h2>Modified code</h2>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\nset -u\n\ntput_setup_nix ()\n{\n # terminfo\n tput_cmd_set_fg_color='tput setaf'\n tput_number_of_colors=$(tput colors 2&gt; /dev/null) &amp;&amp;\n tput_bold=$(tput bold 2&gt; /dev/null) &amp;&amp;\n tput_reset=$(tput sgr0 2&gt; /dev/null)\n}\n\ntput_setup_bsd ()\n{\n # termcap\n tput_cmd_set_fg_color='tput AF'\n tput_number_of_colors=$(tput Co 2&gt; /dev/null) &amp;&amp;\n tput_bold=$(tput md 2&gt; /dev/null) &amp;&amp;\n tput_reset=$(tput me 2&gt; /dev/null)\n}\n\ntput_setup_none ()\n{\n # no unset variables\n tput_cmd_set_fg_color=\n tput_number_of_colors=\n tput_bold=\n tput_reset=\n}\n\nif command -v tput &gt; /dev/null 2&gt;&amp;1; then\n\n if tput setaf &gt; /dev/null 2&gt;&amp;1; then\n\n if ! tput_setup_nix; then tput_setup_none; fi\n\n elif tput AF &gt; /dev/null 2&gt;&amp;1; then\n\n if ! tput_setup_bsd; then tput_setup_none; fi\n\n else\n tput_setup_none\n fi\n\nelse\n tput_setup_none\nfi\n\ntput_capability_test ()\n{\n [ -n &quot;$tput_cmd_set_fg_color&quot; ] &amp;&amp; [ -n &quot;$tput_number_of_colors&quot; ] &amp;&amp; [ -n &quot;$tput_bold&quot; ] &amp;&amp; [ -n &quot;$tput_reset&quot; ] &amp;&amp;\n [ &quot;$tput_number_of_colors&quot; -ge 8 ] &amp;&amp; { $tput_cmd_set_fg_color 1 &amp;&amp; printf '%s' &quot;$tput_bold$tput_reset&quot;; } &gt; /dev/null 2&gt;&amp;1\n\n}\n\nif tput_capability_test; then\n color_red=$tput_bold$($tput_cmd_set_fg_color 1)\n color_green=$tput_bold$($tput_cmd_set_fg_color 2)\n color_yellow=$tput_bold$($tput_cmd_set_fg_color 3)\n color_blue=$tput_bold$($tput_cmd_set_fg_color 4)\n color_magenta=$tput_bold$($tput_cmd_set_fg_color 5)\n color_cyan=$tput_bold$($tput_cmd_set_fg_color 6)\n color_white=$tput_bold$($tput_cmd_set_fg_color 7)\nelse\n color_red=\n color_green=\n color_yellow=\n color_blue=\n color_magenta=\n color_cyan=\n color_white=\nfi\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-22T05:40:07.937", "Id": "250998", "ParentId": "250396", "Score": "1" } } ]
{ "AcceptedAnswerId": "250998", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T06:15:03.177", "Id": "250396", "Score": "2", "Tags": [ "linux", "portability", "posix", "sh", "color" ], "Title": "*nix, *bsd, etc basic `tput` color setup" }
250396
<p>I'm trying to get my code to conform to java formatting convention, I think I've spaced and indented the right way, however, your peer review would be much appreciated.</p> <pre><code>/** * @author Nad Deb * Date: 10/10/2020 * This program is used to play two words games * It will work on input from the keyboard to workout suffix/infix/prefix from words * derived from a dictionary text file. */ package wordgames; //importing classes for method reading files, CLI input and, exception handling import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException; public class WordGames { /** * This method is used to declare and initialize a constant class variable * dictionary. create scanner object class, declare string and int variables also */ private static final File FILEREADER = new File(&quot;DICTIONARY.txt&quot;); private static String[] wordCollect; private static int wordCounter = 0; public static Scanner keyboardInput = new Scanner(System.in); /** * This main method is used to check for file exists with exception handling. * dictionary. create scanner object class, declare string and int variables also */ public static void main(String[] args) throws FileNotFoundException { //method for checking if file exists if (FILEREADER.exists() == false) { System.out.println(&quot;File doesn't exist. Exiting.&quot;); System.exit(0); } wordCollect = new String[100]; Scanner fileScanner = new Scanner(FILEREADER); while(fileScanner.hasNextLine()) { String line = fileScanner.nextLine(); wordCollect[wordCounter] = line; wordCounter++; } getSelection(); } /** * This get selection method is used to handle input from keyboard against a * list of options from the menu, which are linked to methods using switch * case. */ static String getSelection() throws FileNotFoundException { System.out.println(&quot;Welcome to the Word Games program menu.&quot;); System.out.println(&quot;Select from one of the following options.&quot;); System.out.println(&quot;1. Substring problem.&quot;); System.out.println(&quot;2. Points problem.&quot;); System.out.println(&quot;3. Exit.&quot;); System.out.println(&quot;Enter your selections: &quot;); String selection = keyboardInput.next(); //case switch for handling menu option input switch(selection) { case &quot;1&quot;: subStringProblem(); break; case &quot;2&quot;: pointsProblem(); break; case &quot;3&quot;: System.out.println(&quot;Good Bye!&quot;); System.exit(0); break; default: System.out.println(&quot;Invalid option. Try again.&quot;); getSelection(); } return null; } /** * This substring method is used to concatenate *fix to end of string temp * which is a string variable input from reading from lines in file via * wordCollect variable and checks if wordCollect starts with keyboard input * substring. */ static void subStringProblem() throws FileNotFoundException { System.out.println(&quot;Substring problem.&quot;); System.out.println(&quot;Enter a Substring:&quot;); String subString = keyboardInput.next(); String notFound = &quot; - not found&quot;; String infixFound = &quot; - infix&quot;; String prefixFound = &quot; - prefix&quot;; String suffixFound = &quot; - suffix&quot;; for(int i = 0; i &lt; wordCounter; i++) { String temp = wordCollect[i]; boolean found = false; if(wordCollect[i].startsWith(subString)) { found = true; temp = temp + prefixFound; } if(wordCollect[i].endsWith(subString)) { found = true; temp = temp + suffixFound; } if(wordCollect[i].contains(subString)) { found = true; temp = temp + infixFound; } if(!found) { System.out.printf(&quot; &quot; + wordCollect[i] + notFound + &quot;\n&quot;); } else { System.out.printf(&quot; &quot; + temp + &quot;\n&quot;); } } getSelection(); } /** * This points problem method is used to read file lines from scanner input. * switch case will check characters= (c) position in word string which is * input from nextLine, int l is the word length, for statement checks * the characters as it goes along the world. */ private static void pointsProblem() throws FileNotFoundException { System.out.println(&quot;Points problem.&quot;); Scanner input = new Scanner(FILEREADER); while (input.hasNext()) { String word = input.nextLine(); int l = word.length(); int point = 0; for (int x = 0; x &lt; 0; x++) { //checks the letters as it increments char c = word.charAt(x); //checks the letter at position x switch (c) { case 'a': case 'e': case 'i': case 'l': case 'n': case 'o': case 'r': case 's': case 't': case 'u': point += 1; break; case 'd': case 'g': point += 2; break; case 'b': case 'c': case 'm': case 'p': point += 3; break; case 'f': case 'h': case 'v': case 'w': case 'y': point += 4; break; case 'k': point += 5; break; case 'j': case 'x': point += 8; break; case 'q': case 'z': point += 10; break; } } System.out.println(word + &quot;is worth &quot; + point + &quot; points.&quot; ); } getSelection(); } </code></pre> <p>}</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T08:17:09.417", "Id": "491312", "Score": "4", "body": "Please make sure the preformatted code block correctly shows all of your code, indented the way you expect. Your class's final '}' is shown outside the code block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T08:18:21.190", "Id": "491313", "Score": "8", "body": "Regarding indentation: use your IDE's auto-indent or auto-format feature. Nobody does it by hand nowadays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:48:23.607", "Id": "491341", "Score": "0", "body": "WRT your title: please read https://codereview.stackexchange.com/help/how-to-ask ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T12:56:39.837", "Id": "491627", "Score": "1", "body": "As you haven't edited your question yet, you're probably not interested in a review any more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-14T14:01:23.570", "Id": "496577", "Score": "0", "body": "Once a question has been answered, please do not edit the question, especially code that was mentioned in the review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T04:07:08.897", "Id": "496961", "Score": "0", "body": "@pacmaninbw I didn't edit in such a way that would alter what the answer addresses. It was to make the } fit in the code block, which was recommended before an answer." } ]
[ { "body": "<p>You should use an automatic formatter like suggested in a comment, or an online one such as this <a href=\"https://www.tutorialspoint.com/online_java_formatter.htm\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/online_java_formatter.htm</a> or <a href=\"https://codebeautify.org/javaviewer\" rel=\"nofollow noreferrer\">https://codebeautify.org/javaviewer</a></p>\n<p>Some changes that we get are</p>\n<p>Before</p>\n<pre><code> switch(selection) {\n case &quot;1&quot;: subStringProblem();\n break;\n case &quot;2&quot;: pointsProblem();\n break;\n</code></pre>\n<p>After</p>\n<pre><code> switch (selection) {\n case &quot;1&quot;:\n subStringProblem();\n break;\n case &quot;2&quot;:\n pointsProblem();\n break;\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T04:12:26.517", "Id": "496963", "Score": "0", "body": "Thank you, I have already learnt to use the format function in Netbeans to format my code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T09:17:26.273", "Id": "250407", "ParentId": "250401", "Score": "3" } }, { "body": "<pre class=\"lang-java prettyprint-override\"><code>/**\n * @author Nad Deb\n * Date: 10/10/2020\n * This program is used to play two words games\n * It will work on input from the keyboard to workout suffix/infix/prefix \n from words\n * derived from a dictionary text file.\n */\n</code></pre>\n<p>I'd skip such file headers altogether. There are package-level Javadoc, but ideally infomration about author, date etc. would be available through the version control.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>package wordgames;\n</code></pre>\n<p>Ideally, <a href=\"https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html\" rel=\"nofollow noreferrer\">the package names associate</a> with the origin of the software, for example <code>com.company.application</code> or <code>com.github.username.project</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>//importing classes for method reading files, CLI input and, exception handling\n</code></pre>\n<p>Do not comment what you're doing, comment why and how you're doing it. Such comments are unnecessary as it tells me nothing beyond what I can read from the next three lines.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>/**\n* This method is used to declare and initialize a constant class variable \n* dictionary. create scanner object class, declare string and int variables also\n*/\n</code></pre>\n<p>Same here, it is even misleading, as there is no method to be seen.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private static String[] wordCollect;\nprivate static int wordCounter = 0;\n</code></pre>\n<p>You most likely want to use a <code>List</code>/<code>ArrayList</code> and call it simply <code>words</code>. Using a <code>List</code> would also allow you to remove the counter.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private static final File FILEREADER = new File(&quot;DICTIONARY.txt&quot;);\n// ...\npublic static Scanner keyboardInput = new Scanner(System.in);\n</code></pre>\n<p>Ideally the file would be passed to an instance of your class, and you'd open the <code>Scanner</code> only in a scope as needed.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if (FILEREADER.exists() == false) {\n System.out.println(&quot;File doesn't exist. Exiting.&quot;);\n System.exit(0);\n }\n</code></pre>\n<p><code>System.exit</code> is a a last resort to exiting a JVM. Returning from <code>main</code> would mean the JVM is shutting down, <code>System.exit</code> means that the JVM process is being terminated.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> wordCollect = new String[100];\nScanner fileScanner = new Scanner(FILEREADER);\n while(fileScanner.hasNextLine()) {\n String line = fileScanner.nextLine();\n wordCollect[wordCounter] = line;\n wordCounter++;\n }\n</code></pre>\n<p>Using a <code>List</code> here would remove most of the complexity, additionally, reading a file could be done through <code>java.nio.Files.readAllLines</code>, which returns a <code>List</code> of all lines. You also might need to think about the encoding that is used by the content.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> default:\n System.out.println(&quot;Invalid option. Try again.&quot;);\n getSelection();\n</code></pre>\n<p>Instead of recursing, you should loop until a valid option is given.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>static String getSelection() throws FileNotFoundException {\n</code></pre>\n<p>Why does this return <code>String</code>?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for(int i = 0; i &lt; wordCounter; i++) {\n String temp = wordCollect[i];\n</code></pre>\n<p>Could be replaced with a for-each loop when a <code>List</code> is being used.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> String temp = wordCollect[i];\n \n boolean found = false;\n \n if(wordCollect[i].startsWith(subString)) {\n found = true;\n temp = temp + prefixFound;\n }\n if(wordCollect[i].endsWith(subString)) {\n found = true;\n temp = temp + suffixFound;\n }\n if(wordCollect[i].contains(subString)) {\n found = true;\n temp = temp + infixFound;\n }\n if(!found) {\n System.out.printf(&quot; &quot; + wordCollect[i] + \n notFound + &quot;\\n&quot;);\n }\n else {\n System.out.printf(&quot; &quot; + temp + &quot;\\n&quot;);\n }\n</code></pre>\n<p>As an improved exercise, encode the state in a class of its own. The constructor accepts a <code>String</code> as value, and there are three <code>HasPrefix</code>/<code>HasSuffix</code>/<code>HasInfix</code> methods which are returning whether these are present. Additionally, the <code>toString</code> could be overridden to have it return the wanted String representation.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int x = 0; x &lt; 0; x++)\n</code></pre>\n<p>First, I'm a stubborn advocate that one should never user one-letter variable names, the only exception being dimensions.</p>\n<p>Second, choosing <code>x</code> as a variable name is misleading, as most of the time one would think it would have something to do with a dimension.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int x = 0; x &lt; 0; x++) {\n</code></pre>\n<p>That's not even working, at all, the condition is wrong.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-14T14:18:43.713", "Id": "252108", "ParentId": "250401", "Score": "1" } } ]
{ "AcceptedAnswerId": "250407", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T08:12:18.950", "Id": "250401", "Score": "4", "Tags": [ "java" ], "Title": "Checking indentation, header/class/inline comments, spacing convention" }
250401
<p>I've been learning about about how to use <a href="https://reactjs.org/docs/context.html#before-you-use-context" rel="nofollow noreferrer">context</a>, and how to make a <a href="https://reactjs.org/docs/higher-order-components.html" rel="nofollow noreferrer">higher order component</a> to provide context values through props.</p> <p>So, I've created my HOC to pass down the props, and it looks like this, in a file called <code>ConsumerWrapper.jsx</code>:</p> <pre><code>import React from &quot;react&quot;; import {ThemeContext} from &quot;../context/fakeContext&quot;; import hoistNonReactStatic from 'hoist-non-react-statics'; export function ConsumerWrapper(WrappedComponent) { const EndComponent = props =&gt; { return ( &lt;ThemeContext.Consumer&gt; {({theme, toggleTheme}) =&gt; ( &lt;WrappedComponent {...props} theme={theme} toggleTheme={toggleTheme}/&gt; )} &lt;/ThemeContext.Consumer&gt; ) }; EndComponent.displayName = `ConsumerWrapper(${getDisplayName(WrappedComponent)})`; hoistNonReactStatic(EndComponent, WrappedComponent); return EndComponent; } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } </code></pre> <p>Then I made a component which was made to be Wrapped, in <code>WC.jsx</code>:</p> <pre><code>import React from &quot;react&quot;; import {ConsumerWrapper} from &quot;./ConsumerWrapper&quot;; function WC(props) { const {theme, toggleTheme} = props; return ( &lt;div style={{color: theme.foreground, background:theme.background }}&gt; &lt;p&gt;hello world from WC&lt;/p&gt; &lt;p&gt;{props.secondaryMessage}&lt;/p&gt; &lt;/div&gt; ) } export default ConsumerWrapper(WC); </code></pre> <p>As you can see, in that file I export the component already pre-wrapped. That way, in my other files, I can just use it like so:</p> <pre><code>import WC from &quot;./components/WC&quot;; ... return (&lt;WC secondaryMessage=&quot;second message here&quot;/&gt;) ... </code></pre> <hr /> <p>HOWEVER, it occurs to me that there's an alternative: that instead of exporting the wrapped component in WC, I wrap it in the files that use it. So my <code>WC.jsx</code> would look like this:</p> <pre><code>import React from &quot;react&quot;; export default function WC(props) { const {theme, toggleTheme} = props; return ( &lt;div style={{color: theme.foreground, background:theme.background }}&gt; &lt;p&gt;hello world from WC&lt;/p&gt; &lt;p&gt;{props.secondaryMessage}&lt;/p&gt; &lt;/div&gt; ) } </code></pre> <p>And then when I want to use it, I have to wrap it first:</p> <pre><code>import WC from &quot;./components/WC&quot;; import {ConsumerWrapper} from &quot;./ConsumerWrapper&quot;; const WrappedWC = ConsumerWrapper(WC); ... return (&lt;WrappedWC secondaryMessage=&quot;second message here&quot;/&gt;) ... </code></pre> <p>In general, is the second one preferred to the first? The second one allows me, in the future, to provide alternative (maybe even non-context related) props for <code>theme</code> and <code>toggleTheme</code>, so in the second one, the component seems less &quot;bound to the implementation&quot; so to speak, less coupled.</p> <p>Was hoping I could get some advice on this. Thanks.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T08:14:28.967", "Id": "250402", "Score": "3", "Tags": [ "comparative-review", "react.js", "jsx" ], "Title": "React Higher Order Components - export wrapped component or wrap it in parent?" }
250402
<p>I am writing unit tests for a NestJS service, which imports and instantiates a class (OAuth2Client) from an external module (google-auth-library) and uses one of its functions (verifyIdToken).</p> <p>I am mocking the class to override that function as follows:</p> <pre><code>// service.test.ts jest.mock('google-auth-library', () =&gt; { return { OAuth2Client: jest.fn(), }; }); import { OAuth2Client } from 'google-auth-library'; describe('test', () =&gt; { it ('test1', () =&gt; { OAuth2Client.mockImplementation(() =&gt; { return { verifyIdToken: () =&gt; true } }); }); it('test2', () =&gt; { OAuth2Client.mockImplementation(() =&gt; { return { verifyIdToken: () =&gt; false } }); }); }); </code></pre> <p>This works correctly and the test passes, but I am seeing a Typescript error saying that mockImplementation does not exist on OAuth2Client and am wondering if this approach is the best way to achieve what I want or is there an alternative. I was reading around and saw that an option is to use <code>jest.spyOn</code> as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T15:18:32.533", "Id": "491350", "Score": "1", "body": "Welcome to Code Review! When you state \"_but I am seeing a Typescript error saying that mockImplementation does not exist on OAuth2Client_\" is that an error that shows in an IDE, the test output, or elsewhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T06:42:24.007", "Id": "491596", "Score": "0", "body": "It shows in the IDE and its produced by the Typescript extension (I'm using VS Code). The tests pass normally regardless, I'm just mostly wondering whether my approach is considered good practice." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T08:30:34.753", "Id": "250403", "Score": "3", "Tags": [ "javascript", "unit-testing" ], "Title": "Jest - mocking a class function from an external node module" }
250403
<p>problem statement: using React and Redux build an interest calculator that, given a principal, rate of annual interest, and number of years, will display the total principal plus interest using the formula <code>TOTAL = principal * (1 + (rate * years))</code></p> <p>Any feedback welcome on the style, approach, etc.</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt;&lt;body&gt; &lt;section&gt;&lt;/section&gt; &lt;script src=&quot;https://unpkg.com/react/umd/react.production.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://unpkg.com/react-dom/umd/react-dom.production.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://unpkg.com/redux&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://unpkg.com/react-redux&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://unpkg.com/htm&quot;&gt;&lt;/script&gt; &lt;script&gt; const jsx = htm.bind(React.createElement); function reducer(model={ total: 0, }, action={type:'', payload: null}){ let store; switch(action.type){ case 'TOTAL_COST': store = { total: action.payload.total }; break; default: store = model; } return store; } const actions = { updateTotal: function({ principal, years, rate }){ return { type: 'TOTAL_COST', payload: {total: principal * (1 + (rate * years))} } } }; const store = Redux.createStore(reducer); class App extends React.Component{ constructor(props){ super(props); this.state = { principal: 1000, years: 7, rate: 0.025 }; this.submit = this.submit.bind(this); this.update = this.update.bind(this); } componentWillMount(){ this.submit(new CustomEvent('init')); } update(e){ //const val = e.target.value * 1; let { valueAsNumber, value, name } = e.target; const state = {...this.state}; if(isNaN(valueAsNumber)){ valueAsNumber = 0; } state[ name ] = valueAsNumber; this.props.dispatch( actions.updateTotal(state) ); this.setState({[name]: valueAsNumber}); } submit(e){ e.preventDefault(); this.props.dispatch( actions.updateTotal(this.state) ); } //TOTAL = principal * (1 + (rate * years)) render(){ const { principal, years, rate } = this.state; return jsx`&lt;form onSubmit=${ this.submit }&gt; &lt;style&gt; label{display:block;} &lt;/style&gt; &lt;h2&gt;interest calculator&lt;/h2&gt; &lt;h1&gt;&lt;label&gt; total &lt;span&gt;${ this.props.total.toFixed(2) }&lt;/span&gt; &lt;/label&gt;&lt;/h1&gt; &lt;fieldset&gt; &lt;label&gt; principal &lt;input name=principal onInput=${ this.update } type=&quot;number&quot; min=1 defaultValue=${ principal } /&gt; &lt;/label&gt; &lt;label&gt; years &lt;input name=years onInput=${ this.update }type=&quot;number&quot; min=1 max=300 defaultValue=${ years } /&gt; &lt;/label&gt; &lt;label&gt; rate &lt;input name=rate onInput=${ this.update } type=&quot;number&quot; min=0 max=100 defaultValue=${ rate } step=0.0001 /&gt; &lt;/label&gt; &lt;/fieldset&gt; &lt;button&gt;calculate&lt;/button&gt; &lt;/form&gt;`; } } const ConnectedApp = ReactRedux.connect((store)=&gt;{return {total:store.total}})(App); ReactDOM.render( jsx`&lt;${ReactRedux.Provider} store=${ store }&gt; &lt;${ ConnectedApp } key=${ Date.now() }&gt; &lt;//&gt; &lt;//&gt;`, document.querySelector('section') ); requestAnimationFrame(()=&gt;{ console.log(` tests running → any failures will be shown below`); requestAnimationFrame(()=&gt;{ console.log(` tests done → any failures are shown above`); }); const { updateTotal } = actions; let result = updateTotal({principal: 5000, years: 5, rate: 0.025}).payload; let expected = 5625; console.assert(Math.round(result.total) === expected, `expected total ${ result.total } to be ${ expected }`, result); }); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p><strong>Everything's on the front-end</strong> You're using <a href=\"https://github.com/developit/htm\" rel=\"nofollow noreferrer\">HTM</a> to interpret the JSX by putting the JSX through a template literal. It's quite an interesting option, but for a professional project, I think compiling the JSX beforehand in a build process would be a better choice:</p>\n<ul>\n<li>It's very easy to make syntactical typos in the template literal, and you have to run the script in order to see them. If something gets conditionally rendered, you may not see problems with your syntax until the component gets rendered, which may be uncommon; the potential bugs will be significantly harder to encounter and fix. In contrast, if you put the JSX inside a JSX file, and use a syntax-aware IDE like VSCode, you'll be able to spot such mistakes on sight and fix them immediately.</li>\n<li>Transpiling the script ahead of time also makes things much easier if you decide to make the project larger. For example, if you have component A and notice that something isn't working right with it, you could have a standalone <code>A.jsx</code> file that you could go to and debug. (In contrast, if you have, say, 200 or 400 or 1000 lines of code in a single file without a build process, it gets more difficult to navigate around than it should be)</li>\n<li>Having standalone <code>.js</code> / <code>.jsx</code> files also allows for linting, which I consider to be absolutely essential to enforcing code style and quality, and which can turn difficult-to-debug runtime errors into trivially fixable compile-time errors.</li>\n<li>It also allows you to transpile ES2020+ syntax down to ES2015 or ES5 or whatever you prefer, which can make code easier to read and write while remaining compatible with as many browsers as possible.</li>\n</ul>\n<p>It's just an option to consider. If you're not happy at the amount of setup it requires, you can use boilerplate like <a href=\"https://reactjs.org/docs/create-a-new-react-app.html\" rel=\"nofollow noreferrer\">create-react-app</a> so that it's nearly ready to go out of the box.</p>\n<p><strong>Avoid <code>let</code> and reassignment</strong> When variable names are permitted to be reassigned, it can make code more difficult to understand at a glance, when you always have to keep in mind &quot;This variable was declared with <code>let</code>, so I need to be on the lookout for when it may be reassigned.&quot; (Linting rule: <a href=\"https://eslint.org/docs/rules/prefer-const\" rel=\"nofollow noreferrer\"><code>prefer-const</code></a>). See <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">this post on softwareengineering</a> about the topic. There are a number of other places in the code where you're using <code>let</code> where <code>const</code> can be used instead.</p>\n<p>In the reducer, rather than reassign <code>store</code> and then return it at the bottom of the <code>switch</code>, you can return it immediately. (You could also consider avoiding the <code>switch</code> here, since it requires a lot of unnecessary boilerplate).</p>\n<pre><code>// When an argument list requires multiple lines,\n// I think it's easier to read to put each argument on a separate line like this:\nfunction reducer(\n model={total: 0},\n action={type:'', payload: null}\n) {\n switch(action.type){\n case 'TOTAL_COST':\n return { total: action.payload.total };\n default:\n return model;\n }\n}\n</code></pre>\n<p>or, if the reducer won't be expanded in the future:</p>\n<pre><code>function reducer(\n model={total: 0},\n action={type:'', payload: null}\n) {\n return action.type === 'TOTAL_COST'\n ? { total: action.payload.total };\n : model;\n}\n</code></pre>\n<p><strong><code>this</code> binding and mount actions</strong> You do:</p>\n<pre><code>constructor(props){\n super(props);\n this.state = {\n principal: 1000,\n years: 7,\n rate: 0.025\n };\n this.submit = this.submit.bind(this);\n this.update = this.update.bind(this);\n this.submit(new CustomEvent('init'));\n}\n</code></pre>\n<p>There are 2 improvements that can be made here: first, consider using class fields to define the methods instead of using <code>.bind</code> in the constructor, to be more concise and avoid boilerplate. Secondly, populating the component initially with <code>this.submit(new CustomEvent('init'));</code>, an event that is passed only so that calling <code>e.preventDefault</code> on it later doesn't throw is weird. How about using optional chaining in <code>submit</code> instead of passing a parameter?</p>\n<pre><code>class App extends React.Component{\n state = {\n principal: 1000,\n years: 7,\n rate: 0.025\n };\n constructor(props){\n super(props);\n this.submit();\n }\n submit = (e) =&gt; {\n e?.preventDefault();\n this.props.dispatch( actions.updateTotal(this.state) );\n }\n update = (e) =&gt; {\n</code></pre>\n<p>You could also consider using functional components instead; React <a href=\"https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both\" rel=\"nofollow noreferrer\">recommends using them</a> instead of class components for new code - they make code a bit easier to understand and maintain.</p>\n<p><strong>Update</strong> You have:</p>\n<pre><code>update(e){\n let { valueAsNumber, value, name } = e.target;\n const state = {...this.state};\n if(isNaN(valueAsNumber)){\n valueAsNumber = 0;\n }\n state[ name ] = valueAsNumber;\n this.props.dispatch( actions.updateTotal(state) );\n this.setState({[name]: valueAsNumber});\n}\n</code></pre>\n<p>When using React, seeing something like</p>\n<pre><code>state[ name ] = valueAsNumber;\n</code></pre>\n<p>should look scary, because it looks very close to mutating state, and state should <em>never</em> be mutated in React - see <a href=\"https://www.google.com/search?q=why+don%27t+mutate+state\" rel=\"nofollow noreferrer\">here</a> for lots of articles on the subject. While your current method <em>works</em>, it may well be worrying at a glance. Consider using a more functional approach, to construct the new state all at once, without mutation:</p>\n<pre><code>update = (e) =&gt; {\n const { valueAsNumber, value, name } = e.target\n const newState = {\n ...this.state,\n [name]: valueAsNumber || 0\n };\n this.props.dispatch( actions.updateTotal(newState) );\n this.setState(newState);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T04:33:43.923", "Id": "491397", "Score": "0", "body": "thanks @CertainPerformance The feedback related to what is unclear and clearer is useful. Much of the feedback echoes and refers specifically to community and framework norms without a reason. If you are able to explicitly and concisely articulate reasons for these comments that would be useful. I don't expect it however it's worth mentioning for those who aren't a part of the cultural React-Redux phenomenon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T04:44:19.233", "Id": "491398", "Score": "0", "body": "I added a couple links, is there anything in particular that doesn't seem well-grounded enough?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T06:35:52.427", "Id": "496735", "Score": "0", "body": "Nothing additional needed--thanks again. This is very helpful. It's worth noting that many of these assertions are simply preferences without substantive reason. To be clear, stating something is clearer is a reason, stating something is better without more detail or because someone else recommends is not a reason. These are logical fallacies until substantiated and are common methods of economizing and normalizing behavior in software development. There's no need to add more, this is simply a point of reflection. Thank you again, appreciate the time and articulation. It is useful." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T14:46:01.947", "Id": "250423", "ParentId": "250405", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T08:36:33.187", "Id": "250405", "Score": "3", "Tags": [ "calculator", "react.js", "redux" ], "Title": "interest calculator with React+Redux" }
250405
<p>Very new to OOP with Python - and feel like I still don't totally get OOP. However I thought I'd put together a personal online book library to practice inheritance, methods, docstrings etc.</p> <p>Program allows one to add books (comics or novels - with comics inheriting from novels) to one's own library, and create a custom reading lists.</p> <p>There are a few different methods. For example, a library method which will return all books over a specified length.</p> <p>Note that I've removed quite a lot from this, just so it's not 5 pages long! I would normally have several different types of books, attributes such as Author etc. But hopefully from the below you get a good idea of the structure.</p> <p>Speaking of structure, I would just like to know if mine is any good. Also there is an issue whereby if you remove a book from the library, it will still show up in any reading lists I created. I don't know if there's a way to deal with this, or if I'm thinking about this the wrong way.</p> <pre><code>class Library: def __init__(self, books = None): if books is None: self.books = [] else: self.books = books def add_book(self, book): self.books.append(book) def remove_book(self, book): self.books.remove(book) def pages_over_n(self, number): &quot;&quot;&quot;Returns books that have more than specified number of pages&quot;&quot;&quot; return [book for book in self.books if book.pages &gt; number] def get_library(self): &quot;&quot;&quot;Returns all books in Library&quot;&quot;&quot; return self.books def __repr__(self): return f&quot;Library({self.books})&quot; def __str__(self): return f&quot;Library has {len(self.books)}&quot; class Novel: def __init__(self, title, pages, publicationDate): self.title = title self.pages = pages self.publicationDate = publicationDate def __repr__(self): return f&quot;Novel({self.title}, {self.pages}, {self.publicationDate})&quot; def __str__(self): return f&quot;Media: {self.title}&quot; class ComicBook(Novel): def __init__(self, title, pages, publicationDate, artist): super().__init__(title, pages, publicationDate) self.artist = artist def get_artist(self): return f&quot;Artist: {self.artist}&quot; def __repr__(self): return (f&quot;ComicBook({self.title}, {self.pages}, &quot; f&quot;{self.publicationDate}, {self.artist})&quot;) class ReadingList: def __init__(self): self.list = [] def add_book(self, book): &quot;&quot;&quot;Add book to reading list&quot;&quot;&quot; self.list.append(book) def remove_book(self, book): &quot;&quot;&quot;Remove book from reading list&quot;&quot;&quot; self.list.remove(book) def total_pages(self): &quot;&quot;&quot;Returns total pages in reading list&quot;&quot;&quot; total = 0 for book in self.list: total += book.pages return total def __repr__(self): return f&quot;ReadingList({self.list})&quot; def __str__(self): return f&quot;Reading list of size {len(self.list)}&quot; # Initialise Library library = Library() # Create a few books novel1 = Novel(&quot;Harry Potter&quot;, 500, 1991) novel2 = Novel(&quot;LotR&quot;, 1000, 1960) novel3 = Novel(&quot;Game of Thrones&quot;, 2000, 2018) comic1 = ComicBook(&quot;Batman&quot;, 100, 2020, &quot;Stan Lee&quot;) # Add books to library. library.add_book(novel1) library.add_book(novel2) library.add_book(novel3) library.add_book(comic1) # Create a new reading list. readingListOne = ReadingList() # Add a couple of books to reading list. readingListOne.add_book(novel1) readingListOne.add_book(comic1) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T10:07:59.007", "Id": "491320", "Score": "8", "body": "Long code is not frowned upon in [codereview.se]. For a big-ish project, you can also put the code on git(hub/lab) etc and include the specific file/code you want reviewed in the post here, linking to the project for further reference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T10:10:49.547", "Id": "491321", "Score": "0", "body": "Thanks for the info. I had the feeling that people would only be interested in looking over short code. There isn't too much more to add at the moment (still working through it) - jus wanted to check I was on the right lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T03:32:26.193", "Id": "491393", "Score": "0", "body": "@AaronWright Do you have to do OOP? A lot of people (including myself) don't like it, and would prefer to do a functional style." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T07:09:38.990", "Id": "491399", "Score": "0", "body": "There is no persistence of data yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T09:55:59.390", "Id": "491402", "Score": "1", "body": "@dwjohnston You don't like OOP and your top tag is java?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T09:58:35.550", "Id": "491403", "Score": "0", "body": "@AryanParekh I don't have an especially active profile on Code Review. I mostly use JavaScript." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T18:55:06.913", "Id": "491457", "Score": "0", "body": "@AaronWright Consider accepting any answer :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-14T02:29:10.063", "Id": "492860", "Score": "0", "body": "OOP and functional \"style\" are not mutually exclusive. A lot of the encapsulation, scope, composition goals look very OOPish to me. As for JavaScript, it is an \"object based\" language and its features allow a very OO design approach. Breaking down complexity into interacting objects is a powerful paradigm." } ]
[ { "body": "<h1>General Observations</h1>\n<p>I'm being 100% honest here, When I just give a glance at your code there is nothing that is immediately horrifying with it.</p>\n<ul>\n<li>You shouldn't use variable/function names that are already defined in Python. Your class <code>ReadingList</code> has an attribute <code>list</code>. This is a bad idea as there is already a <code>list</code> keyword that can clash with your definition</li>\n</ul>\n<h1>Code Structure</h1>\n<p>You have tried to implement the idea of inheritance, although it is fine, it will be much better to have your base class as <code>Book</code>.\n<a href=\"https://i.stack.imgur.com/fr2Yo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fr2Yo.png\" alt=\"b\" /></a></p>\n<p>This makes more sense due to the fact that novels, and comic books <strong>are types of books</strong>. And hence can share attributes and methods.</p>\n<p>Your <code>Book</code> class can have attributes and methods like</p>\n<ul>\n<li>Author</li>\n<li>Name</li>\n<li>Stuff which is common in all types of books</li>\n</ul>\n<p>And your child class <code>Novel</code> can have</p>\n<ul>\n<li>Sutff which is special in Novel</li>\n</ul>\n<p>A very very basic implementation</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Book():\n def __init__(self,author,name):\n self.author = author\n self.name = name\n\n def print_book(self):\n print(f&quot;{self.name} by {self.author}&quot;)\n\n\n\n\nclass Novel(Book):\n def __init__(self,author,name):\n Book.__init__(self,author,name)\n\n def display(self):\n print(f&quot;The Novel {self.name}&quot;)\n # Novel stuff which isn't common in all books\n\nclass Comic(Book):\n def __init__(self,author,name):\n Book.__init__(self,author,name)\n\n def display(self):\n print(f&quot;The comic book {self.name}&quot;)\n # Comic book stuff which isn't common in all books\n \n\nnov = Novel(&quot;J.K Rowling&quot;,&quot;Harry Potter&quot;)\nnov.print_book()\n</code></pre>\n<p>The point is that your <code>Novel</code> class is basically a <code>Book</code> which as an author, pages, etc. But it also has something which other books like <code>Comic</code> don't. This way you don't need to create an entirely new class, but you can simply inherit the common from the <code>Book</code> class and add the extra stuff in <code>Novel</code></p>\n<hr />\n<h1>Creating a library</h1>\n<p>You can stop here if you want to, and consider your <code>Book</code> class as a library. But if you want to get crazier, you can have another class called <code>Magazine</code> and that would be the child class of parent <code>Library</code>. Here is what that would look like.\n<a href=\"https://i.stack.imgur.com/hhgT9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hhgT9.png\" alt=\"lib\" /></a></p>\n<p>But this would get quite complicated, moreover, it wouldn't make a lot of sense to inherit <code>Book</code> from <code>Library</code>. Hence it is a good idea to keep <code>Library</code> as a separate that will merely control the books.</p>\n<pre class=\"lang-py prettyprint-override\"><code>\n\nclass Library():\n def __init__(self,book_list = []):\n self.book_list = book_list\n\n def new_book(self,book):\n self.book_list.append(book)\n\n def remove_book(self,name): # book is the name of the book\n for book in self.book_list:\n if book.name == name:\n self.book_list.remove(book)\n break\n\n\n def print_books(self):\n for book in self.book_list:\n print(f&quot;Book {book.name} by {book.author}&quot;)\n\n\nclass Book():\n def __init__(self,author,name):\n self.author = author\n self.name = name\n\n def print_book(self):\n print(f&quot;{self.name} by {self.author}&quot;)\n\n\n\n\nclass Novel(Book):\n def __init__(self,author,name):\n Book.__init__(self,author,name)\n\n def display(self):\n print(f&quot;The Novel {self.name}&quot;)\n # Novel stuff which isn't common in all books\n\nclass Comic(Book):\n def __init__(self,author,name):\n Book.__init__(self,author,name)\n\n def display(self):\n print(f&quot;The comic book {self.name}&quot;)\n # Comic book stuff which isn't common in all books\n\n\nmy_lib = Library()\nmy_lib.new_book(Novel(&quot;J.K Rowling&quot;,&quot;Harry Potter&quot;))\nmy_lib.new_book(Novel(&quot;Aryan Parekh&quot;,&quot;Stack&quot;))\n\nmy_lib.remove_book(&quot;Stack&quot;)\n\nmy_lib.print_books()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T11:23:07.317", "Id": "491325", "Score": "0", "body": "Thank you. Yes having Book as the parent class would make more sense now I think about it. I'll be sure to change list as well. Regarding having magazine and book as child classes of library, I'm not quite sure how this would work. However this is probably just down to me not being that knowledgable regarding inheritance. What kind of methods would the parent class Library have in this instance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:01:56.430", "Id": "491333", "Score": "1", "body": "@AaronWright It is not absolutely necessary that it would need to be a parent. In fact, I would recommend `Library` to be a separate class which would create a list of `Book` objects" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:22:50.330", "Id": "491336", "Score": "0", "body": "Ah I see. Thank you. I think this is similar to what I have, but just having subclasses of books which inherit from `Book`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:24:15.410", "Id": "491338", "Score": "0", "body": "@AaronWright Inheritance is useful, but if you ask me, I would say no to use it in this scenario" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T08:21:02.107", "Id": "491400", "Score": "1", "body": "Small suggestion/nitpick: it is common to just use `books` instead of `book_list`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-16T22:34:46.217", "Id": "493329", "Score": "0", "body": "@GrajdeanuAlex. Thank you! I'll add that in. I'm actually trying to convert this into a GUI application which would allow one to add songs, remove songs, etc with buttons. Do you happen to know if this is possible with the current design I have?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T11:01:23.223", "Id": "250412", "ParentId": "250409", "Score": "8" } }, { "body": "<h1>Simplify the constructor of <code>class Library</code></h1>\n<p>You have a default value of <code>None</code> for the parameter <code>books</code>, but then immediately proceed to convert that <code>None</code> to an empty list. Why not use <code>[]</code> as the default value?</p>\n<pre><code>class Library:\n def __init__(self, books = []):\n self.books = list(books)\n\n ...\n</code></pre>\n<p>Note that to prevent the issue of <a href=\"https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments\" rel=\"noreferrer\">mutable default arguments</a> as mentioned by ojdo, you should make a copy of the initial list.</p>\n<h1>Be consistent</h1>\n<p>You take an optional list of books in the constructor of <code>class Library</code>, but there is no such thing in <code>class ReadingList</code>. That is a bit surprising.</p>\n<p>Also be consistent with naming things. In <code>class Library</code>, the list of books is called <code>books</code>, but in <code>class ReadlingList</code> you named it <code>list</code>. I would name it <code>books</code> in both cases.</p>\n<p>Also be consistent with the names of functions:</p>\n<ul>\n<li><code>get_library()</code> should be <code>get_books()</code>, since it only returns the list of books, not an object of type <code>Library</code>.</li>\n<li><code>pages_over_n()</code> should be <code>get_books_with_over_n_pages()</code> or something similar, to indicate that it returns <code>Book</code>s, not pages.</li>\n<li><code>total_pages()</code> should be renamed <code>get_total_pages()</code> or <code>calculate_total_pages()</code>. Prefer using verbs for function names, and nouns for variables.</li>\n</ul>\n<p>And I also wonder why a <code>ComicBook</code> has an <code>artist</code>, but a <code>Novel</code> has no <code>author</code>? And why is there a <code>get_artist()</code> but no <code>get_title()</code>, <code>get_publication_date()</code> and so on? Making everything consistent will make using your classes much easier.</p>\n<h1>Removing books from the Library</h1>\n<p>As you noticed, you can remove a book from the library, but it won't be removed from any reading lists. But that is fine. Why would a book magically disappear from a real life reading list if your library removes that book? Note that your code is perfectly fine, Python won't actually delete the <code>Book</code> object from memory until the last reference to it is gone.</p>\n<p>However, if you want a book to disappear from the <code>ReadingList</code> when it is removed from the <code>Library</code>, then somehow there needs to be some communications between those two objects. There are two options:</p>\n<ol>\n<li><p>A <code>Library</code> keeps a list of <code>ReadingList</code>s that reference its <code>Book</code>s, and when you call <code>remove_book()</code> on a <code>Library</code>, it will in turn iterate over all the <code>ReadingList</code>s and call <code>remove_book()</code> on them as well.</p>\n</li>\n<li><p>A <code>ReadingList</code> keeps a reference to the <code>Library</code> whose <code>Book</code>s it contains. Whenever you call a member function that accesses the list of books on the reading list, this member function first has to filter out all the books that are no longer in the <code>Library</code>.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T11:16:57.717", "Id": "491324", "Score": "0", "body": "Perfect thank you! This helps a lot. Your first point makes a lot more sense than what I've done. Regarding the lack of get methods, this is something I plan on adding in. For the reading list, my thinking was that if you remove a book from the Library, then you would also want it removed from the reading list. Sort of like removing a song from Spotify's library would remove it from a playlists (I would presume). Again, this is just a vague idea I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T11:49:10.263", "Id": "491328", "Score": "7", "body": "I fear the first recommendation [would backfire](https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments), or do you know that this behaves differently within instance methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T12:19:51.840", "Id": "491330", "Score": "0", "body": "I would need to check. All I was looking for was to have an option whereby I can initialise class with either nothing, or initialise it with an array of books (rather than adding each one separately using the add_book method)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T12:25:44.357", "Id": "491331", "Score": "1", "body": "@ojdo You are right. But actually, even when you provide the argument you have to be aware that the list you provide might be modified by subsequent calls to `add_book()` and `remove_book()`, so I guess it's best to always create a copy of the list. I'll modify my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:01:56.867", "Id": "491334", "Score": "0", "body": "@G.Sliepen Thank you for the update. I think number 1 on that list is what I initially tried, but ended up confusing myself. Logic I started with was that if a book was added to `ReadingList` using `add_book`, add the reading list to a predefined list in `Library` - however I just got myself in a jumble. Hopefully I'll better understand OOP the more I spend with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:38:40.647", "Id": "491340", "Score": "1", "body": "@AaronWright This has not much to do with OOP, but rather how variables work in Python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T17:23:21.633", "Id": "491369", "Score": "4", "body": "I personally would a) not opt to do perform a copy operation and b) prefer the `books=None` idiom like in the question, but in total a helpful answer, +1." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T11:01:41.490", "Id": "250413", "ParentId": "250409", "Score": "8" } }, { "body": "<p>Since <code>Library</code> and <code>ReadingList</code> are just different types of lists of books, I would opt for define a generic <code>BookList</code> as a base class from which <code>Library</code> and <code>ReadingList</code> both inherit.</p>\n<p>Doing this saves you from the repetition of having to define common methods like the following, which both of your classes already do. Here are some methods from the <code>Library</code> class.</p>\n<pre><code>def __init__(self, books = None):\n if books is None:\n self.books = []\n else:\n self.books = books\n\ndef add_book(self, book):\n self.books.append(book)\n \ndef remove_book(self, book):\n self.books.remove(book)\n</code></pre>\n<p>And here are the analogous methods from the <code>ReadingList</code> class.</p>\n<pre><code>def __init__(self):\n self.list = []\n\ndef add_book(self, book):\n &quot;&quot;&quot;Add book to reading list&quot;&quot;&quot;\n self.list.append(book)\n \ndef remove_book(self, book):\n &quot;&quot;&quot;Remove book from reading list&quot;&quot;&quot;\n self.list.remove(book)\n</code></pre>\n<p>As <a href=\"https://codereview.stackexchange.com/questions/250409/personal-book-library-with-python#answer-250413\">G. Sliepen</a> said, you should simplify the <code>Library</code> constructor to match the <code>ReadingList</code> constructor. After you do this, the methods are exactly the same.</p>\n<p>By defining a generic book list class, not only do you not have to keep redefining common functionality, you can also take advantage of polymorphic functions.</p>\n<p>For example, rather than making each class responsible for outputting a string representation of itself, you could define a <code>BookListHTMLWriter</code> that takes a book list item (either a <code>ReadingList</code> or a <code>Library</code>, both are fine when they're derived from the same <code>BookList</code> object), and outputs an HTML table representation.</p>\n<p>Likewise, you could also define a <code>BookListXMLWriter</code> that outputs the XML representation of a <code>BookList</code> object or a subclass thereof. You could take this OOP-refactoring even further by then refactoring the functionality common to the <code>BookListHTMLWriter</code> and <code>BookListXMLWriter</code> classes and derive them from a base <code>BookListWriter</code> base class.</p>\n<p>Optimistically, object-oriented programming can be a bit of an acquired taste (and an esoteric one, at that), but once you start thinking in these terms it's a useful mental model, even if it's not your only one. Or you preferred one, even.</p>\n<hr />\n<p>Regarding your point about how removing a book from your library does not remove it from your reading list(s), I agree with previous responses that this makes sense. I think the problem that you're alluding to might be the question of referential integrity, which I noticed, too.</p>\n<p>You've obviously already noticed that <code>Library</code> and <code>ReadingList</code> are both lists of <code>Book</code>s. When reading over code, I always start picturing the corresponding database schema, and the problem I think you're referring to is that there should be a main list of already created books from which you can add to a personal library and/or reading list, presumably depending on whether you own the book. I would call this main list a &quot;catalog&quot; or something to differentiate this main list from a list of a particular type belonging to a particular user.</p>\n<p>Moreover, this catalog would simply be all of the records in a <code>books</code> table in your database.</p>\n<p>To implement a database for this program, you could start by creating the <code>books</code> and <code>users</code> tables, and then creating a third table consisting only of a user's id and a book's id. Querying this link table for a given user id would give you all of the books this person owns.</p>\n<p>If you wanted users to be able to create arbitrary libraries based not just on whether they own a book, you would only need to create a <code>reading_lists</code> table with a user id as a field to indicate the owner, and then create another link table using a list id and a book id.</p>\n<p>This would solve your referential integrity problem by preventing the deletion of a book record unless you specify an appropriate <code>ON DELETE</code> action in the <code>books</code> table schema.</p>\n<p>Subclassing <code>Book</code>s into <code>Novel</code>s and <code>Magazine</code>s complicates things because if the inheritance hierarchy imbues complex enough differences on your subclasses, your objects no longer map nicely into single tables (assuming you want a reasonably-normalizable schema).</p>\n<p>If you hit this point, a good entity-relational mapping tool can save you hours of frustration.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:10:44.577", "Id": "491335", "Score": "0", "body": "Thank you! I'll give some of this a go. Some of it may be a little advanced for me, however sounds like a good learning opportunity. Even defining `BookListXMLWriter` sounds like something I'll need to do a bit of research into." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:58:13.827", "Id": "491343", "Score": "0", "body": "Do you know where I could look to learn a bit more about implementing databases etc, or a link to something that has done something similar? It's a bit beyond my knowledge, but sounds interesting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T18:58:00.313", "Id": "491376", "Score": "0", "body": "If you've never worked with databases before, I can't recommend [Beginning Databases with PostgreSQL](https://www.amazon.com/Beginning-Databases-PostgreSQL-Novice-Professional/dp/1590594789/ref=sr_1_4?crid=1UHQS185PLIG9&dchild=1&keywords=postgresql&qid=1602269514&s=books&sprefix=postgresql%2Caps%2C172&sr=1-4) enough. It was published years ago, but the content is still current. It walks you through the setup, designing a database, why even bother, etc. It's one of my favorite books of all time, I love it. (It's also only 11 bucks used) It's the book that got me started" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T20:50:17.930", "Id": "491384", "Score": "0", "body": "Perfect thank you! I'll definitely take a look. I'm doing a course which includes databases and SQL - which I think starts in a couple months, but I'll try get a head start with that book!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T12:37:19.513", "Id": "250415", "ParentId": "250409", "Score": "6" } } ]
{ "AcceptedAnswerId": "250412", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T09:28:33.913", "Id": "250409", "Score": "11", "Tags": [ "python" ], "Title": "Personal book library" }
250409
<p>I know that there is a generic data structure <code>System.Array</code> could be used to create customized type array. I want to focus on the two dimensional data structure that something like plane with concatenate methods. The following code is my implementation of a generic two dimensional data structure <code>Plane&lt;T&gt;</code>.</p> <p>Is there any possible improvement of this code?</p> <pre class="lang-cs prettyprint-override"><code>public class Plane&lt;T&gt; { private Array PlaneArray; public Plane() { this.PlaneArray = Array.CreateInstance(typeof(T), 1, 1); } public Plane(Plane&lt;T&gt; ObjectInput) { this.PlaneArray = ObjectInput.PlaneArray; } public Plane(uint SizeXInput, uint SizeYInput) { if (SizeXInput &lt; 0 || SizeYInput &lt; 0) { this.PlaneArray = Array.CreateInstance(typeof(T), 1, 1); } else { this.PlaneArray = Array.CreateInstance(typeof(T), SizeXInput + 1, SizeYInput + 1); } } public Plane&lt;T&gt; ConcatenateHorizontal(Plane&lt;T&gt; PlaneInput) { if (this.GetSizeY().Equals(PlaneInput.GetSizeY()).Equals(false)) { return default; } var ReturnObject = new Plane&lt;T&gt;(this.GetSizeX() + PlaneInput.GetSizeX(), this.GetSizeY()); Parallel.For(0, this.GetSizeY(), (LoopNumberY, stateY) =&gt; { Parallel.For(0, this.GetSizeX(), (LoopNumberX, stateX) =&gt; { ReturnObject.SetElement(this.GetElement((uint)LoopNumberX, (uint)LoopNumberY), (uint)LoopNumberX, (uint)LoopNumberY); }); }); Parallel.For(0, PlaneInput.GetSizeY(), (LoopNumberY, stateY) =&gt; { Parallel.For(0, PlaneInput.GetSizeX(), (LoopNumberX, stateX) =&gt; { ReturnObject.SetElement(PlaneInput.GetElement((uint)LoopNumberX, (uint)LoopNumberY), (uint)(LoopNumberX + this.GetSizeX()), (uint)LoopNumberY); }); }); return ReturnObject; } public Plane&lt;T&gt; ConcatenateHorizontalInverse(Plane&lt;T&gt; PlaneInput) { return PlaneInput.ConcatenateHorizontal(this); } public Plane&lt;T&gt; ConcatenateVertical(Plane&lt;T&gt; PlaneInput) { if (this.GetSizeX().Equals(PlaneInput.GetSizeX()).Equals(false)) { return new Plane&lt;T&gt;(); } var ReturnObject = new Plane&lt;T&gt;(this.GetSizeX(), this.GetSizeY() + PlaneInput.GetSizeY()); Parallel.For(0, this.GetSizeY(), (LoopNumberY, stateY) =&gt; { Parallel.For(0, this.GetSizeX(), (LoopNumberX, stateX) =&gt; { ReturnObject.SetElement(this.GetElement((uint)LoopNumberX, (uint)LoopNumberY), (uint)LoopNumberX, (uint)LoopNumberY); }); }); Parallel.For(0, PlaneInput.GetSizeY(), (LoopNumberY, stateY) =&gt; { Parallel.For(0, PlaneInput.GetSizeX(), (LoopNumberX, stateX) =&gt; { ReturnObject.SetElement(PlaneInput.GetElement((uint)LoopNumberX, (uint)LoopNumberY), (uint)LoopNumberX, (uint)(LoopNumberY + this.GetSizeY())); }); }); return ReturnObject; } public Plane&lt;T&gt; ConcatenateVerticalInverse(Plane&lt;T&gt; BlockStructureInput) { return BlockStructureInput.ConcatenateVertical(this); } public T GetElement(uint LocationX, uint LocationY) { if (LocationX &lt;= this.PlaneArray.GetUpperBound(0) &amp;&amp; LocationX &gt;= this.PlaneArray.GetLowerBound(0) &amp;&amp; LocationY &lt;= this.PlaneArray.GetUpperBound(1) &amp;&amp; LocationY &gt;= this.PlaneArray.GetLowerBound(1)) { return (T)this.PlaneArray.GetValue(LocationX, LocationY); } Console.WriteLine(&quot;Index invalid&quot;); return default(T); } public uint GetSizeX() { return (uint)(this.PlaneArray.GetUpperBound(0) - this.PlaneArray.GetLowerBound(0)); } public uint GetSizeY() { return (uint)(this.PlaneArray.GetUpperBound(1) - this.PlaneArray.GetLowerBound(1)); } public Tuple&lt;bool, Plane&lt;T&gt;&gt; SetElement(T NewElement, uint LocationX, uint LocationY) { if (LocationX &lt;= this.PlaneArray.GetUpperBound(0) &amp;&amp; LocationX &gt;= this.PlaneArray.GetLowerBound(0) &amp;&amp; LocationY &lt;= this.PlaneArray.GetUpperBound(1) &amp;&amp; LocationY &gt;= this.PlaneArray.GetLowerBound(1)) { this.PlaneArray.SetValue(NewElement, LocationX, LocationY); return new Tuple&lt;bool, Plane&lt;T&gt;&gt;(true, this); } else { return new Tuple&lt;bool, Plane&lt;T&gt;&gt;(false, this); ; } } public override string ToString() { string ReturnString = &quot;&quot;; for (uint LoopNumberY = 0; LoopNumberY &lt; this.GetSizeY(); LoopNumberY++) { for (uint LoopNumberX = 0; LoopNumberX &lt; this.GetSizeX(); LoopNumberX++) { ReturnString = ReturnString + this.GetElement(LoopNumberX, LoopNumberY).ToString() + &quot;\t&quot;); } ReturnString = ReturnString + System.Environment.NewLine; } return ReturnString.ToString(); } } </code></pre> <p>The usage of this <code>Plane&lt;T&gt;</code> class:</p> <pre class="lang-cs prettyprint-override"><code>Plane&lt;string&gt; plane = new Plane&lt;string&gt;(5, 5); for (uint LoopNumberY = 0; LoopNumberY &lt; plane.GetSizeY(); LoopNumberY++) { for (uint LoopNumberX = 0; LoopNumberX &lt; plane.GetSizeX(); LoopNumberX++) { plane.SetElement(&quot;(&quot; + LoopNumberX.ToString() + &quot;, &quot; + LoopNumberY.ToString() + &quot;)&quot;, LoopNumberX, LoopNumberY); } } Console.WriteLine(plane.ToString()); var ConcatenateHRetult = plane.ConcatenateHorizontal(plane); Console.WriteLine(ConcatenateHRetult.ToString()); var ConcatenateVRetult = plane.ConcatenateVertical(plane); Console.WriteLine(ConcatenateVRetult.ToString()); </code></pre> <p><strong>Oct 16, 2020 Update</strong></p> <p>In order to test this Plane class, the customized method <code>Equals</code> is needed. Here's my implementation. First, the size comparison is performed, and the next step is checking the content equivalent.</p> <pre><code>public override bool Equals(object obj) { var objForTesting = obj as Plane&lt;T&gt;; if (this.GetSizeX().Equals(objForTesting.GetSizeX()).Equals(false) || this.GetSizeY().Equals(objForTesting.GetSizeY()).Equals(false) ) // If size is different { return false; } // Content comparison for (uint y = 0; y &lt; this.GetSizeY(); y++) { for (uint x = 0; x &lt; this.GetSizeX(); x++) { if (this.GetElement(x, y).Equals(objForTesting.GetElement(x, y)).Equals(false)) { return false; } } } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:55:57.210", "Id": "491342", "Score": "0", "body": "If you're concatenating strings and aren't using StringBuilder, you're likely doing it wrong: https://docs.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T14:05:26.677", "Id": "491344", "Score": "0", "body": "@BCdotWEB Thank you for the suggestion. The code has been updated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T16:35:06.187", "Id": "491366", "Score": "0", "body": "@JimmyHu you shouldn't update the code posted in your question (unless it's missing something or there's typo), please revert the changes you've made." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T16:56:53.230", "Id": "491367", "Score": "1", "body": "@cliesens Thank you for the comments. The code has been reverted to the origin version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T19:14:10.587", "Id": "491377", "Score": "1", "body": "@cliesens as long as no answer is posted, they can update the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-13T20:34:02.877", "Id": "492832", "Score": "0", "body": "See my updated answer regarding C# Indexer to replace `GetElement` and `SetElement`." } ]
[ { "body": "<p>This:</p>\n<pre><code> Console.WriteLine(&quot;Index invalid&quot;);\n return default(T);\n</code></pre>\n<p>is dangerous. Having out-of-bounds indices is dangerous enough that you should probably just raise an exception here, rather than returning a default that will probably be wrong from the perspective of the caller. If this is a feature that you're really going to use, wrap it in a second function (<code>TryGetElement</code>) that follows the same pattern as other methods in C#: have an output parameter that might be set, and return a boolean that is only true if the call succeeded.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T16:49:42.927", "Id": "250433", "ParentId": "250418", "Score": "4" } }, { "body": "<p>Welcome to Code Review!</p>\n<p>I don't have much time to write a full review right now, but I'll give you a concise list of things you could do to improve your code (in my opinion).</p>\n<h1>Naming</h1>\n<p>Use <code>camelCase</code> instead of <code>PascalCase</code> for local variables, class variables &amp; method arguments. In addition to making your code a lot more readable (I don't have to wonder, &quot;is this a variable? a method? a static class?&quot;), it also ensures other people who are familiar with C# will be able to understand and work with your code, as this is the convention followed by most (if not all) C# programmers.</p>\n<p>I'm also not a very big fan of super long names for the <code>for</code> loop iterating variable. I generally stick to <code>i</code>, <code>j</code> and sometimes <code>k</code>, or use other descriptive names when I'm not simply iterating over indices. But to me, <code>LoopNumberX</code> is really way too long and actually makes the code harder to read. What does <code>LoopNumberX</code> even mean? Again, this is a personal preference, but I don't think there's many people who would argue <code>LoopNumberX</code> is a good name. If you know what a <code>for</code> loop is, then whenever you see <code>i</code> or <code>j</code>, you'll know exactly what is going on.</p>\n<h1>Properties</h1>\n<p>You could make your code even more maintainable &amp; easy to understand by using properties. You should use <code>PascalCase</code> when naming properties. Here are some examples of using properties in various ways:</p>\n<pre><code>private int x;\n\npublic int X\n{\n public get \n {\n return x;\n }\n\n public set \n {\n x = value;\n }\n}\n</code></pre>\n<p>Which you can shorten to :</p>\n<pre><code>private int x;\n\npublic int X\n{\n public get =&gt; x;\n\n public set =&gt; x = value;\n}\n</code></pre>\n<p>As there is only a single statement is the getter/setter. You can go even further and remove the private field entirely like this :</p>\n<pre><code>public int X { get; private set; }\n</code></pre>\n<p>This is called an auto-property. This example also shows how you can give the property, its setter and getter different access modifiers. You can also add logic inside the getter/setter like this :</p>\n<pre><code>private int x;\n\npublic int X\n{\n public get { return x; }\n\n public set \n {\n if (x &lt; 0) {\n throw new Exception(&quot;X should be larger than 0!&quot;);\n }\n\n x = value;\n }\n}\n</code></pre>\n<p>Properties are great, use them whenever you can (though they shouldn't replace all your methods of course, only when appropriate)!</p>\n<h1><code>uint</code></h1>\n<p>I'd recommend against using <code>uint</code> everywhere as you do, even though it may seem like a good idea. If you'd like more information on this subject, I recommend taking a quick look at <a href=\"https://stackoverflow.com/questions/2013116/should-i-use-uint-in-c-sharp-for-values-that-cant-be-negative\">https://stackoverflow.com/questions/2013116/should-i-use-uint-in-c-sharp-for-values-that-cant-be-negative</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T18:50:47.703", "Id": "250439", "ParentId": "250418", "Score": "5" } }, { "body": "<p>First I would like to re-iterate the points made by @cliesens regarding naming and avoid <code>uint</code>.</p>\n<p>Keep in mind the most number of elements you may have in an array is <code>int.MaxValue</code>. Theoretically, with your use of <code>unit</code>, someone could try to create an array that is 3 billion wide by 3 billion deep, which would throw exceptions. And your code doesn't handle exceptions very well.</p>\n<p>UPDATED: Was it intentional that your constructor accepting a <code>Plane</code> copies the source plane by reference? That would mean that anyone changing something in the copy would also be changing it in the original and vice versa. I personally would think this should be a cloned copy, instead of a reference copy.</p>\n<p>The <code>ToString()</code> is a bad idea, not because of the lack of <code>StringBuilder</code> but because it could be a very long process. Let's say I had a plane that is 40K across and 50K tall, for 2 billion elements. Then I must wait a really long time for <code>ToString()</code> to fully render a result. Since the debugger and other things use <code>ToString()</code> to quickly display information, you should have <code>ToString()</code> be as fast as it can be.</p>\n<p>Thus, I would suggest changing it, and moving your current logic into its own method. I do find it odd that you choose to display the array by Y and then X (or by Height first then Width) since most people working with a 2D geometric plane tend to think in terms of X first, then Y. Perhaps you chose to do this so that as it prints down a page it would almost textually mirror the plane rotated around the X-axis. If so, this would be predicated upon the elements in the X dimension printing neatly across 1 row in the Console window.</p>\n<p>I would suggest you may want to have 2 different methods so that one has a choice of the display order.</p>\n<p>I would also suggest there could be properties in your class for <code>Width</code> and <code>Height</code>, which seem more natural to use rather than <code>GetSizeX()</code> or <code>GetSizeY()</code>.</p>\n<p>You employ <code>System.Array</code> even though you have a generic class. All of your calls to <code>CreateInstance</code> create a typically 0-indexed array, so calling <code>GetUpperBound(0) - GetLowerBound(0) + 1</code> could be replaced with <code>GetLength(0)</code>.</p>\n<p>Here is my take on a partial design:</p>\n<pre><code>public class PlaneV2&lt;T&gt;\n{\n public int Width { get; } = 0;\n public int Height { get; } = 0;\n private T[,] Grid = null;\n public int Length =&gt; Width * Height;\n\n public PlaneV2() : this(1, 1) { }\n\n public PlaneV2(int width, int height)\n {\n Width = Math.Max(width, 0);\n Height = Math.Max(height, 0);\n Grid = new T[width, height];\n }\n\n public PlaneV2(PlaneV2&lt;T&gt; plane) : this(plane?.Grid) { }\n\n public PlaneV2(T[,] sourceGrid)\n {\n if (sourceGrid == null)\n {\n return;\n }\n\n Width = sourceGrid.GetLength(0);\n Height = sourceGrid.GetLength(1);\n Grid = new T[Width, Height];\n Array.Copy(sourceGrid, Grid, sourceGrid.Length);\n }\n\n // SNIPPED\n\n public override string ToString() =&gt; $&quot;{nameof(PlaneV2&lt;T&gt;)}&lt;{typeof(T).Name}&gt;[{Width}, {Height}]&quot;;\n\n public string ToDelimitedStringByHeightThenWidth(string separator = &quot;\\t&quot;)\n {\n StringBuilder lines = new StringBuilder();\n for (int y = 0; y &lt; Height; y++)\n {\n StringBuilder columns = new StringBuilder();\n string columnDelimiter = &quot;&quot;;\n for (int x = 0; x &lt; Width; x++)\n {\n columns.Append(columnDelimiter + Grid[x, y].ToString());\n if (columnDelimiter == &quot;&quot;)\n {\n columnDelimiter = separator;\n }\n }\n lines.AppendLine(columns.ToString());\n }\n return lines.ToString();\n }\n\n public string ToDelimitedStringByWidthThenHeight(string separator = &quot;\\t&quot;)\n {\n StringBuilder lines = new StringBuilder();\n for (int x = 0; x &lt; Width; x++)\n {\n StringBuilder columns = new StringBuilder();\n string columnDelimiter = &quot;&quot;;\n for (int y = 0; y &lt; Height; y++)\n {\n columns.Append(columnDelimiter + Grid[x, y].ToString());\n if (columnDelimiter == &quot;&quot;)\n {\n columnDelimiter = separator;\n }\n }\n lines.AppendLine(columns.ToString());\n }\n return lines.ToString();\n }\n\n} // class\n\n} // namespace\n</code></pre>\n<p>That's about all I can do since I must get back to my daytime job. To summarize:</p>\n<ol>\n<li>Consider using properties to your advantage</li>\n<li>Employ suggested C# naming guidelines</li>\n<li>Use short, simple naming for loop variables</li>\n<li>Avoid <code>unit</code> for array indexing</li>\n<li>Have a Width and Height property</li>\n<li>Consider using a generic array</li>\n<li>ToString should be short, sweet and FAST</li>\n<li>Offer a choice to display (X by Y) or (Y by X)</li>\n</ol>\n<p>Given that an array can hold int.MaxValue elements, then your biggest <strong>square</strong> plane would be 46_340 X 46_340. If you wanted to offer HUGE planes, then you would need to change the guts of the class to support an array of arrays.</p>\n<p>Other things to consider:</p>\n<ol>\n<li>Should you implement IEquatable or IComparable?</li>\n<li>Do you want any constraints, such as struct, on T?</li>\n</ol>\n<p><strong>UPDATE #2 : C# INDEXERS</strong></p>\n<p>I find having GetElement and SetElement methods cumbersome. I prefer to interact with the object more like an array, and that's where <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/\" rel=\"nofollow noreferrer\">C# Indexers</a> come in handy. Here is a way you can get rid of both GetElement and SetElement, while maintaining the same functionality:</p>\n<pre><code>public T this[int x, int y]\n{\n get\n {\n if (x &lt; 0 || x &gt;= Width)\n {\n throw new ArgumentOutOfRangeException(nameof(x));\n }\n if (y &lt; 0 || y &gt;= Height)\n {\n throw new ArgumentOutOfRangeException(nameof(y));\n }\n return Grid[x, y];\n }\n set\n {\n if (x &lt; 0 || x &gt;= Width)\n {\n throw new ArgumentOutOfRangeException(nameof(x));\n }\n if (y &lt; 0 || y &gt;= Height)\n {\n throw new ArgumentOutOfRangeException(nameof(y));\n }\n Grid[x, y] = value;\n }\n}\n</code></pre>\n<p>And here is a quick example of how to use it:</p>\n<pre><code>var width = 3;\nvar height = 5;\nvar plane = new PlaneV2&lt;int&gt;(width, height);\n\nfor (var x = 0; x &lt; width; x++)\nfor (var y = 0; y &lt; height; y++)\n{\n //NOTICE how I use plane like a 2D array\n plane[x, y] = ((x + 1) * 100) + y;\n}\n\nConsole.WriteLine(&quot;ToString() Example: &quot; + plane.ToString());\n\nConsole.WriteLine(&quot;\\nTAB DELIMITED BY X THEN Y&quot;);\nConsole.WriteLine(plane.ToDelimitedStringByWidthThenHeight());\n\nConsole.WriteLine(&quot;\\nSEMI-COLON DELIMITED BY Y THEN X&quot;);\nConsole.WriteLine(plane.ToDelimitedStringByHeightThenWidth(&quot; ; &quot;));\n</code></pre>\n<p><strong>CONSOLE OUTPUT</strong></p>\n<pre><code>ToString() Example: PlaneV2&lt;Int32&gt;[3, 5]\n\nTAB DELIMITED BY X THEN Y\n100 101 102 103 104\n200 201 202 203 204\n300 301 302 303 304\n\nSEMI-COLON DELIMITED BY Y THEN X\n100 ; 200 ; 300\n101 ; 201 ; 301\n102 ; 202 ; 302\n103 ; 203 ; 303\n104 ; 204 ; 304\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-16T02:04:32.667", "Id": "493215", "Score": "0", "body": "Thank you for answering. Is it better to use T[,] than `System.Array` object?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-16T10:21:04.827", "Id": "493243", "Score": "0", "body": "@JimmyHu I personally think its better to use T[,] because the underlying array is now strong-typed, and you may access individual elements without type casting. For a large plane with millions of elements, it would perform better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-12T14:08:43.453", "Id": "250546", "ParentId": "250418", "Score": "4" } } ]
{ "AcceptedAnswerId": "250546", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:35:01.197", "Id": "250418", "Score": "6", "Tags": [ "c#", "object-oriented", "generics", "classes" ], "Title": "Generic Two Dimensional Data Plane with Manipulation Methods For C#" }
250418
<p>I have started with C and I made this code and as the title suggests this program can calculate the average score of a given number of scores. Now my major concern is, is it more efficient to get the number of scores as a Command Line Argument or is the current approach better incase if sometime in the future someone designs a Interactive Front-End for it?</p> <p>Also I am using the cs50 library I am not sure if it is allowed here please tell me if it's not so I'll keep that in mind in the future.</p> <pre><code>#include &lt;cs50.h&gt; #include &lt;stdio.h&gt; float average(int length, int array[]); int main(void) { int i, j; printf(&quot;This Program will Help you Compute the Average Score \n&quot;); //Welcome Message int Total = get_int(&quot;How Many Scores do you wish to Use: &quot;); //Asks User for How Many Scores int scores[Total]; //Stores Scores in an Array for (i=0; i &lt; Total; i++) //A Loop to keep Asking for Scores { scores[i]=get_int(&quot;Enter Score %d \n&quot;, i+1); //i+1 is used as it would be better to start asking from Score 1 so that it avoids confusion } printf(&quot;The Average score is %f&quot;, average(Total, scores)); } float average(int length, int array[]) { int sum = 0; for (int j=0; j &lt; length; j++) { sum += array[j]; } return sum/(float)length; } </code></pre>
[]
[ { "body": "<h2>Reduce the number of loops</h2>\n<p>The most time-consuming part of your program is to loop through the array. Notice that you have done this twice, why can't you keep a track of the total sum while taking the input?</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt; \n\nfloat average(int sum,int number);\n\nint main(void)\n{\n int number_of_integers,number,sum = 0;\n printf(&quot;Enter the number of integers: &quot;);\n scanf(&quot;%d&quot;,&amp;number_of_integers);\n for(int i = 0;i &lt; number_of_integers;i++)\n {\n printf(&quot;Enter: &quot;);\n scanf(&quot;%d&quot;,&amp;number);\n sum+=number;\n }\n printf(&quot;Average = %d&quot;,average(sum,number_of_integers));\n}\n\nfloat average(int sum, int number)\n{\n return sum/(float)number;\n}\n</code></pre>\n<p>This reduces the number of loops from <code>2</code> into <code>1</code>. And completely removes the need of having an array of integers. Making your program both memory efficient and fast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T15:31:57.960", "Id": "491351", "Score": "0", "body": "Thanks a lot understood :) Also this is probably the best welcome I have ever received on any SE so many upvotes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T15:39:07.153", "Id": "491353", "Score": "0", "body": "i just checked you github profile and man you learnt coding at such a young age can you refer to some resources which you used? I am totally new to coding" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T15:49:30.733", "Id": "491358", "Score": "1", "body": "Thanks a lot as a side question how long did it take you to master C++? I am studying C as I was following the cs50 course and they started with this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T15:51:46.793", "Id": "491359", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/113926/discussion-between-foundabettername-and-aryan-parekh)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T16:09:37.287", "Id": "491432", "Score": "0", "body": "\"The most time-consuming part of your program is to loop through the array.\" --> The most time consuming is the execution of complex functions like `scanf()` and `printf()`, dwarfing the concern about using a separate `average(int length, int array[])`. Better to focus on reducing O(n) ( which was done here with memory usage) than concerns about \"number of loops from 2 into 1\"`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T16:12:39.577", "Id": "491433", "Score": "0", "body": "@chux-ReinstateMonica What if the size of the input is `100,000`, would having 2 loops instead of 1 still be minimal compared to `printf()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T16:42:16.900", "Id": "491435", "Score": "0", "body": "Having 2 loops vs 1 would not impact the time performance. I/O still dominates. There are still `n` i/o calls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:15:45.790", "Id": "491436", "Score": "0", "body": "@chux-ReinstateMonica what ??!. OP's code already has `n` I/O calls, plus another iteration through the array to get the average, how will removing the second loop completely not make a difference?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:29:01.880", "Id": "491438", "Score": "0", "body": "[Profile](https://en.wikipedia.org/wiki/Profiling_(computer_programming)) the 2 approaches. Even with automated input the time spent will be 1.000000 vs 1.000001 of the other - no practical difference. With the knitted approach here, code does have a memory savings, yet now pieces are intertwined and not readily available for code re-use as separate modules. Code re-use is the valuable asset in long term effective programming." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T14:36:03.890", "Id": "250422", "ParentId": "250419", "Score": "3" } }, { "body": "<blockquote>\n<p>... major concern is, is it more efficient to get the number of scores as a Command Line Argument or is the current approach better in case if sometime in the future someone designs a Interactive Front-End for it?</p>\n</blockquote>\n<p>&quot;more efficient&quot; needs to focus on <strong><a href=\"https://en.wikipedia.org/wiki/Big_O_notation\" rel=\"nofollow noreferrer\">order of complexity</a></strong>, else one wastes valuable coding effort in <a href=\"https://softwareengineering.stackexchange.com/a/80092/94903\">premature optimizations</a>. OP's code run-time is O(n). It does not get better in run-time using using 1 loop or 2.</p>\n<blockquote>\n<p>current approach better incase if sometime in the future someone designs a Interactive Front-End for it?</p>\n</blockquote>\n<p>Current is better.</p>\n<p>Code architecture <strong>designed for growth</strong> is a good idea. A good strategy is to separate input, processing and output.</p>\n<p>In OP's small code, loops can be combined (saves memory), yet for growth and real larger code, and portability, maintain separations.</p>\n<pre><code>// Pseudo code\nmain()\n setup()\n input()\n process_data()\n output()\n cleanup()\n</code></pre>\n<p>Set aside small linear time improvement concerns and look to proper <strong>full range functionality</strong></p>\n<ul>\n<li>Below code can readily overflow <code>sum += array[j]</code>.</li>\n<li><code>float</code> in C is rarely the preferred type. Use <code>double</code> and reduce precision loss.</li>\n<li>Array sizing best done with <code>size_t</code>.</li>\n<li>Consider <a href=\"https://en.wikipedia.org/wiki/C2x#Features\" rel=\"nofollow noreferrer\">future trends</a> with function signatures (which OP followed with <code>length</code> 1st).</li>\n<li>Use <code>const</code> when referenced data is not changed. Allows wider usage and conveys intent.</li>\n<li>Consider alternatives to casting.</li>\n<li>Trust your compiler to make at least basic optimizations. Code for clarity.</li>\n</ul>\n<p>OP's</p>\n<pre><code>float average(int length, int array[]) { // length more than INT_MAX?\n int sum = 0;\n for (int j=0; j &lt; length; j++) {\n sum += array[j]; // Overflow ?\n }\n return sum/(float)length; // low precision FP\n}\n</code></pre>\n<p>Alternative</p>\n<pre><code>double average(size_t length, const int array[]) {\n long long sum = 0; // or double sum = 0.0 is very large input expected.\n for (size_t j=0; j &lt; length; j++) {\n sum += array[j];\n }\n double avg = sum;\n return avg/length;\n}\n</code></pre>\n<p><strong>Minor: Output improvements</strong></p>\n<p><code>&quot;%f&quot;</code> is weak. Consider <code>&quot;%g&quot;</code>. It is more informative when the value is smaller and not so noisy when the value is large.</p>\n<p>No need for spaces before <code>&quot;\\n&quot;</code>. Such spaces are surprising to find in output. Avoids surprising effects.</p>\n<pre><code>// Enter Score %d \\n&quot;\nEnter Score %d\\n&quot;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:29:53.780", "Id": "491439", "Score": "0", "body": "I performed your `get_average()` *1000000* times, with the size of the array as 1000. The input of the method being the same, your code slowed down a lot whereas my solution had the sum pre-calculated so **it was instantaneous**. I am really confused because I'm sure you have way more knowledge than me, can you explain?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:35:15.700", "Id": "491440", "Score": "0", "body": "@AryanParekh `average()` is only called once in OP's code. Why call 1000000 times? Looks like you are trying to assess different `average(size_t length, const int array[])` versus different `main()`. Profile the whole, not the pieces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:38:03.087", "Id": "491441", "Score": "0", "body": "I really think that is a bad excuse, But, What about memory? It is extremely in-efficient if you look into it form that side" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:41:44.050", "Id": "491443", "Score": "0", "body": "You are hanging on the exception that the `get_average()` function will be called only once as the question does the same, yet you talk about long term code re-use" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:43:13.473", "Id": "491444", "Score": "0", "body": "@AryanParekh \"I really think that is a bad excuse\" --> Perhaps your insight into programming exceeds mine . Re: memory in-efficiency. Answers already covers that with \"saves memory\". Coding to optimize trivial programs prevents larger concerns about code re-use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:45:53.577", "Id": "491445", "Score": "0", "body": "please tell me *larger concerns about code re-use*, that are completely worth trading with memory and speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T19:42:21.303", "Id": "491459", "Score": "0", "body": "@AryanParekh These excess concerns about performance neglected the _functional_ error in your code. `printf(\"Average = %d\",average(...` should have been `printf(\"Average = %g\",average(.. ` and is part of the larger concerns. Your valuable programmer time needs to be spent in various ways. Code correctness comes first before optimizations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T19:42:32.360", "Id": "491460", "Score": "0", "body": "@AryanParekh With OP's narrow usage it is true the O(1) memory is needed and not O(n). Processing data as it arrives is good for these select issues. Should code expand and re-used to cover other statistics like mode and sort, O(n), or more, is needed. It is likely the problem is already O(n) memory as `n` is known _a priori_. Further your speed assessment lacks a fair compare as the compare done in your input code is not counted (it too takes time) whereas OP's compare in the read loop is 0 (as it is not there)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T20:43:06.153", "Id": "491464", "Score": "0", "body": "My speed assesment lacks no fair, it's you that refuse to believe it as being fair. You agree that your function **will be much slower**, your only argument is that it is fine if the function is slow as it is only being called once, and hence it does not make a difference. As for the measuring part, I have used **the same** input and output for both test cases. Plus their time isn't considered because I measured using an external library where I could place the start and end points carefully. This should end at, \"we both think differently\", " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T20:51:05.953", "Id": "491465", "Score": "0", "body": "Just to point out, as you say \"should code expand\".Is there no possibility that `average()` can be called more than once if the code *expands*? The time taken for your average function at best is `O(n)`. Due to the design of my function, it can even be inlined if it's called frequently having a clear advantage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T20:58:48.777", "Id": "491470", "Score": "0", "body": "@AryanParekh Given you have comment _after_ \"This should end at\", I'll add one. Consider a more pragmatic approach to solving differences. Look for common ground rather than incite. You have decades of programming in front of you and good programming involves teams. Our differences in advice are not that far apart. What is optimal is involves many more aspects than what is presented here and so depending on those, the optimal path for OP could go left or right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T21:07:34.673", "Id": "491472", "Score": "0", "body": "I agree with you 100% on this, I think our argument boils down to what the code is actually being used for. Currently, I am working on my chess engine, spending 24 hours to create a single, CPU-efficient function, and then another 24 hours to optimize it even more.If the purpose was different, then my approach would be different too. Possible that your coding style is different than mine, I'd say it's similar to how some people loathe OOP and other's don't. Opinions‍♂️" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T21:23:24.613", "Id": "491473", "Score": "0", "body": "@AryanParekh My first big program was for 2 to play chess - and not cheat. I even had en passant checking, check, checkmate and castling - almost. My castling checked if the king, rook had never been moved by that color and nothing in between, king not in check, not across check or into check. The corner case missed was: \"is the rook there\" (i.e. it could have been taken/moved by the opposition) yet my castling with the ghost rook was allowed and resurrected the piece. Such is the fun of chess rules." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-10T17:07:34.597", "Id": "250473", "ParentId": "250419", "Score": "1" } } ]
{ "AcceptedAnswerId": "250422", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T13:57:27.997", "Id": "250419", "Score": "4", "Tags": [ "c" ], "Title": "Calculates the Average Score of Given Number of Scores in C" }
250419
<p>I am writing a function that can be used in a ruby script that will match the parameter and values together so the script can use them in an intelligent way. The idea is if you were to run a script with this function it would output the key value pairs of the parameters passed to the script.</p> <p>For example</p> <pre><code>my_script.rb -user Jeff -key /path/to/key -config /path/to/config </code></pre> <p>The expected output would be an array with the key value pairs like</p> <pre><code>[ {:arg =&gt; 'user', :val =&gt; 'Jeff'}, {:arg =&gt; 'key', :val =&gt; '/path/to/key'}, {:arg =&gt; 'config', :val =&gt; '/path/to/config'} ] </code></pre> <p>This then could be used in any Ruby script that takes command line arguments and organizes it for them in a consistent way. Then the script can decide what to do with the output and act on those key value pairs passed.</p> <p><strong>My Question:</strong></p> <p>Are there are enhancements that can be made for this script and / or is there simpler ways to do this in Ruby? The function is below:</p> <pre><code>#!/usr/bin/env ruby class Script_Helper def self.get_params (ary) args = Array.new unless ARGV.empty? for i in 0..ARGV.size-1 if ARGV[i].start_with?('-') and i &lt; ARGV.size + 1 args.push ({:arg =&gt; ARGV[i], :val =&gt; ARGV[i+1]}) end end end return args end end </code></pre>
[]
[ { "body": "<h1>Consistency</h1>\n<p>Sometimes you are using whitespace around operators, sometimes you don't. Sometimes you are using whitespace between the message name and the argument list of a message send, sometimes you don't.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).</p>\n<p>In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing <em>IFF</em> you actually <em>want</em> to convey some extra information.</p>\n<p>For example, some people always use parentheses for defining and calling purely functional side-effect free methods, and never use parentheses for defining and calling impure methods. That is a <em>good</em> reason to use two different styles (parentheses and no parentheses) for doing the same thing (defining methods).</p>\n<h1>Whitespace around operators</h1>\n<p>There should be 1 space either side of an operator.</p>\n<h1>Whitespace in hash literals</h1>\n<p>In a hash literal, there should be one space after the opening curly brace and one space before the closing curly brace.</p>\n<h1>New-style hash literals</h1>\n<p>Well, they are called &quot;new-style&quot; or &quot;Ruby 1.9&quot; hash literals, but really, they were introduced in 2007, and we have Ruby 3.0 soon, so we should really simply be calling them &quot;hash literals&quot; at this point. They are neither new anymore nor is Ruby 1.9 still relevant.</p>\n<p>Ruby 1.9 introduced a shortcut syntax for hash literals where keys are symbols, inspired by ECMAScript.</p>\n<p>So, this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>{:arg =&gt; ARGV[i], :val =&gt; ARGV[i+1]}\n</code></pre>\n<p>should be this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>{ arg: ARGV[i], val: ARGV[i+1] }\n</code></pre>\n<h1>Frozen string literals</h1>\n<p>Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n</code></pre>\n<p>It is generally preferred to add this comment to all your files.</p>\n<h1>No space before parameter list</h1>\n<p>In a method definition, there should be no whitespace between the method name and the parameter list, e.g. this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def self.get_params (ary)\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def self.get_params(ary)\n</code></pre>\n<p>Ruby allows you to specify a parameter list either in parentheses or with whitespace. If you combine the two, it could get confusing, because Ruby also allows <em>array destructuring</em> in parameter lists:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def foo(((first_of_first, second_of_first), second))\n second_of_first\nend\n\nfoo([[23, 42], 'Hello'])\n#=&gt; 42\n</code></pre>\n<p>Array destructuring is performed by adding an additional set of parentheses. Now, if you have a method with two parameters, you can write it like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def foo(bar, baz)\nend\n</code></pre>\n<p>or like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def foo bar, baz\nend\n</code></pre>\n<p>If you write it like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def foo (bar, baz)\nend\n</code></pre>\n<p>A reader <em>might</em> think that this is a <em>single</em> parameter that uses array destructuring. In fact, Ruby even prints a warning that tells you exactly that:</p>\n<pre class=\"lang-none prettyprint-override\"><code>warning: parentheses after method name is interpreted as an argument list, not a decomposed argument\n</code></pre>\n<h1>No space before argument list</h1>\n<p>In a message send, there should be no whitespace between the message and the argument list, e.g. this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>args.push ({:arg =&gt; ARGV[i], :val =&gt; ARGV[i+1]})\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>args.push({:arg =&gt; ARGV[i], :val =&gt; ARGV[i+1]})\n</code></pre>\n<p>This will bite you as soon as you have more than one argument. Ruby allows you to write the argument list to a message send without parentheses like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>foo.bar baz, quux\n</code></pre>\n<p>instead of</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>foo.bar(baz, quux)\n</code></pre>\n<p>The problem arises because the whitespace triggers the first mode, so</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>foo.bar (baz, quux)\n</code></pre>\n<p>is <em>not</em> interpreted as <em>two</em> arguments <code>baz</code> and <code>quux</code> but as passing arguments with whitespace <em>instead of parentheses</em> and thus as a <em>single argument</em> <code>(baz, quux)</code>. Except <code>(baz, quux)</code> is not legal Ruby code, and thus you get an error.</p>\n<h1>Warnings</h1>\n<p>The Ruby developers work hard on providing helpful warning messages. You should read them and investigate them. They almost always point to problems or at least potential problems in your code.</p>\n<p>For example, running your code generates the following warning message:</p>\n<pre class=\"lang-none prettyprint-override\"><code>warning: parentheses after method name is interpreted as an argument list, not a decomposed argument\n</code></pre>\n<h1>Unused parameter</h1>\n<p>Your <code>get_params</code> method is defined with one parameter <code>ary</code>, but you are not using this parameter anywhere. It is completely useless.</p>\n<p>If you have a parameter or a local variable that is <em>intentionally</em> unused, the Ruby community standard is to name it with a leading underscore, e.g. <code>_ary</code> or even just <code>_</code>.</p>\n<p>However, in this case, it serves absolutely no purpose and should simply be removed altogether.</p>\n<h1>Empty literals</h1>\n<p>Instead of using the <code>new</code> method to create instances of core classes, you should prefer to use literals. E.g. use <code>''</code> or <code>&quot;&quot;</code> instead of <code>String.new</code>, <code>[]</code> instead of <code>Array.new</code>, and so forth.</p>\n<p>This is <em>especially</em> true for <em>empty</em> objects.</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>args = Array.new\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>args = []\n</code></pre>\n<h1>Prefer <code>each</code> over <code>for</code> / <code>in</code></h1>\n<p>Nobody in Ruby uses <code>for</code> / <code>in</code>. In fact, we hardly use any loops at all. I would go so far as to say, when you are using a loop, you are doing it wrong.</p>\n<p>The idiomatic way would be to use <a href=\"https://ruby-doc.org/core/Range.html#method-i-each\" rel=\"nofollow noreferrer\"><code>Range#each</code></a> instead. Not only is <code>each</code> more idiomatic, but <code>for</code> / <code>in</code> has this weird scoping rule where the loop variable escapes into the surrounding scope, which is almost always not what you want.</p>\n<p>So, this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>for i in 0..ARGV.size-1\n if ARGV[i].start_with?('-') and i &lt; ARGV.size + 1\n args.push ({:arg =&gt; ARGV[i], :val =&gt; ARGV[i+1]})\n end\nend\n</code></pre>\n<p>should become this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>(0..ARGV.size-1).each do |i|\n if ARGV[i].start_with?('-') and i &lt; ARGV.size + 1\n args.push ({:arg =&gt; ARGV[i], :val =&gt; ARGV[i+1]})\n end\nend\n</code></pre>\n<p>Actually, there is a lot more that can be improved about that, but we will stick with the purely mechanical transformations for now, and keep our brain switched off.</p>\n<h1>Modifier <code>if</code></h1>\n<p>If you have a conditional expression with only a single expression in the body and no <code>else</code>, it is generally preferred to use the modifier form.</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>if ARGV[i].start_with?('-') and i &lt; ARGV.size + 1\n args.push ({:arg =&gt; ARGV[i], :val =&gt; ARGV[i+1]})\nend\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>args.push ({:arg =&gt; ARGV[i], :val =&gt; ARGV[i+1]}) if ARGV[i].start_with?('-') and i &lt; ARGV.size + 1\n</code></pre>\n<h1>Prefer symbolic operators <code>||</code>, <code>&amp;&amp;</code>, <code>!</code> over keywords <code>and</code>, <code>or</code>, <code>not</code></h1>\n<p>In a boolean expression, you should prefer the symbolic operators over the keywords. The keywords have doubly-unexpected precedence: not only is the precedence of the keywords <code>and</code> and <code>or</code> much lower than the precedence of <code>&amp;&amp;</code> and <code>||</code>, but also <code>and</code> and <code>or</code> both have the <em>same</em> precedence while <code>&amp;&amp;</code> has higher precedence than <code>||</code>. This can be very confusing.</p>\n<p>Idiomatic Ruby community standard is to always use the symbolic operators, <em>except</em> for when you actually use boolean logic for control flow, as in</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>do_something and exit\n</code></pre>\n<p>So,</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>ARGV[i].start_with?('-') and i &lt; ARGV.size + 1\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>ARGV[i].start_with?('-') &amp;&amp; i &lt; ARGV.size + 1\n</code></pre>\n<h1>Redundant <code>return</code></h1>\n<p>The return value of a method is the value of the last expression that was evaluated inside the method. Unless you want an early <code>return</code>, it is generally not necessary to use <code>return</code> at all.</p>\n<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect all of the style violations I pointed out above (plus some more), and also was able to autocorrect all of the ones I listed.</p>\n<p>Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can <em>actually</em> correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit &quot;save&quot;.</p>\n<p>In particular, running Rubocop on your code, it detects 19 offenses, of which it can automatically correct 17. This leaves you with 2 offenses, both of which are very simple.</p>\n<p>Here's what the result of the auto-fix looks like:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>#!/usr/bin/env ruby\n# frozen_string_literal: true\n\nclass Script_Helper\n def self.get_params(_ary)\n args = []\n unless ARGV.empty?\n (0..ARGV.size - 1).each do |i|\n args.push({ arg: ARGV[i], val: ARGV[i + 1] }) if ARGV[i].start_with?('-') &amp;&amp; (i &lt; ARGV.size + 1)\n end\n end\n args\n end\nend\n</code></pre>\n<p>And here are the offenses that Rubocop could not automatically correct:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Offenses:\n\nscript_helper.rb:4:1: C: Style/Documentation: Missing top-level class documentation comment.\nclass Script_Helper\n^^^^^\n\nscript_helper.rb:4:7: C: Naming/ClassAndModuleCamelCase: Use CamelCase for classes and modules.\nclass Script_Helper\n ^^^^^^^^^^^^^\n\n1 file inspected, 2 offenses detected\n</code></pre>\n<p>Let's look at the simple one first.</p>\n<h1>Naming</h1>\n<p>Class names should be <code>PascalCase</code>, constants should be <code>SCREAMING_SNAKE_CASE</code>, everything else should be <code>snake_case</code>. Files should be named after the primary module or class they define, and they should be named in <code>snake_case</code> as well.</p>\n<p>So, the name of your class should be <code>ScriptHelper</code>, not <code>Script_Helper</code>.</p>\n<h1>Unused parameter, take 2</h1>\n<p>As mentioned above, the parameter should be removed. Rubocop only automatically renamed it, because removing it could break code that calls this method with an argument.</p>\n<p>But since it isn't used, it should simply be removed and all callers fixed to not pass an argument.</p>\n<h1>Vertical whitespace</h1>\n<p>Your method could use some vertical whitespace to give the code more room to breathe. I would suggest at least separating the initialization at the beginning of the method, and the return at the end:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def self.get_params(_ary)\n args = []\n\n unless ARGV.empty?\n (0..ARGV.size - 1).each do |i|\n args.push({ arg: ARGV[i], val: ARGV[i + 1] }) if ARGV[i].start_with?('-') &amp;&amp; (i &lt; ARGV.size + 1)\n end\n end\n\n args\nend\n</code></pre>\n<h1>&quot;Reader&quot; methods</h1>\n<p>I re-run Rubocop every time I change something in my code. In fact, I have it set up to run automatically when I save my code, when I commit my code, etc.</p>\n<p>Since we now have removed the parameter from the method, it now tells us something new: &quot;Reader&quot; methods or &quot;getter methods&quot; that don't take any arguments and simply return a value should not be named with a <code>get_</code> prefix. This is unlike Java, for example.</p>\n<p>So, the method should simply be named <code>params</code>.</p>\n<h1>Redundant check</h1>\n<p>If <code>ARGV</code> is empty, its size will be <code>0</code>, which means that the range <code>0..ARGV.size - 1</code> will be the range <code>0..-1</code>, which is empty. Iterating over an empty range doesn't do anything, so we can just delete the check for <code>ARGV.empty?</code></p>\n<h1>Redundant check 2</h1>\n<p>You are iterating from 0 to size-1, therefore <code>i</code> will <em>never</em> be greater than size. The check <code>i &lt; ARGV.size + 1</code> will always be true, and is thus redundant and can be deleted.</p>\n<h1>Iterators, take 2</h1>\n<p>We already converted the <code>for</code> loop into an <code>each</code> iterator. However, you are iterating over the <em>indices</em> of <code>ARGV</code> and then pull out the elements using the indices. This is a very FORTRAN way of writing that code. It is much easier to iterate over the <em>elements</em> directly.</p>\n<p>Even better, since you always need the to look at the current and the next element, we can iterate over a <em>sliding window of 2 consecutive elements</em>. That's exactly what <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-each_cons\" rel=\"nofollow noreferrer\"><code>Enumerable#each_cons</code></a> does:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>ARGV.each_cons(2) do |param, arg|\n args.push({ arg: param, val: arg }) if param.start_with?('-')\nend\n</code></pre>\n<p>As above, if <code>ARGV</code> is empty, <code>each_cons</code> will simply not do anything, so we don't need to check.</p>\n<h1>The &quot;shovel&quot; operator <code>&lt;&lt;</code></h1>\n<p>And while we are looking at this code: <a href=\"https://ruby-doc.org/core/Array.html#method-i-push\" rel=\"nofollow noreferrer\"><code>Array#push</code></a> is not idiomatic. More precisely, it is <em>only</em> idiomatic if you are using the array as a <em>stack</em>, then you would use <code>Array#push</code> and <a href=\"https://ruby-doc.org/core/Array.html#method-i-pop\" rel=\"nofollow noreferrer\"><code>Array#pop</code></a>, since those are the standard names for the stack operations.</p>\n<p>The idiomatic way of appending something to something else is the shovel operator, in this case <a href=\"https://ruby-doc.org/core/Array.html#method-i-3C-3C\" rel=\"nofollow noreferrer\"><code>Array#&lt;&lt;</code></a>, so that should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>args &lt;&lt; { arg: param, val: arg }\n</code></pre>\n<h1>Iterators, take 3</h1>\n<p>We are still doing a lot of stuff manually. Initialize the empty array, loop over <code>ARGV</code>, append to the array, etc.</p>\n<p>Whenever you have the pattern of &quot;Initialize a result, loop over a collection appending to the result, return result&quot;, that is a <a href=\"https://wikipedia.org/wiki/Fold_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>fold</em></a>. There are two implementations of <em>fold</em> in the Ruby core library, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-inject\" rel=\"nofollow noreferrer\"><code>inject</code></a> and <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-each_with_object\" rel=\"nofollow noreferrer\"><code>each_with_object</code></a>. <code>inject</code> is the more functional one, <code>each_with_object</code> is the more imperative one. So, for now, we will use <code>each_with_object</code> here, since the code is still pretty imperative, and that makes the relationship between the old and new code more clear:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>args = []\n\nARGV.each_cons(2) do |param, arg|\n args &lt;&lt; { arg: param, val: arg } if param.start_with?('-')\nend\n\nargs\n</code></pre>\n<p>becomes</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>ARGV.each_cons(2).each_with_object([]) do |(param, arg), args|\n args &lt;&lt; { arg: param, val: arg } if param.start_with?('-')\nend\n</code></pre>\n<p>Now, if we want to make it purely functional, it would look like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>ARGV.each_cons(2).inject([]) do |args, (param, arg)|\n if param.start_with?('-') then args + [{ arg: param, val: arg }] else args end\nend\n</code></pre>\n<h1>Iterators, take 4</h1>\n<p>Instead of filtering inside the iteration, we could instead <em>chain</em> iterators and filter first. This works for both our variations:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>ARGV\n .each_cons(2)\n .select { |param, _| param.start_with?('-') }\n .each_with_object([]) { |(param, arg), args| args &lt;&lt; { arg: param, val: arg } }\n\nARGV\n .each_cons(2)\n .select { |param, _| param.start_with?('-') }\n .inject([]) { |args, (param, arg)| args + [{ arg: param, val: arg }] }\n</code></pre>\n<h1>Excursion: Generality of <em>fold</em> (<code>inject</code> / <code>each_with_object</code>)</h1>\n<p>When I wrote above that you can rewrite this iteration with <code>inject</code> or <code>each_with_object</code>, that was actually a tautological statement. I didn't even have to read the code to make this statement.</p>\n<p>It turns out that <em>fold</em> is &quot;general&quot;. <a href=\"https://wikipedia.org/wiki/Fold_(higher-order_function)#Universality\" rel=\"nofollow noreferrer\"><em>Every</em> iteration over a collection can be expressed using <em>fold</em></a>. This means, if we were to delete <em>every method</em> from <code>Enumerable</code>, except <code>inject</code>, then we could re-implement the entire <code>Enumerable</code> module again, using nothing but <code>inject</code>. As long as we have <code>inject</code>, we can do anything.</p>\n<h1>Iterators, take 5</h1>\n<p>So, what we did until now was replace the loop with a low-level iterator, replace the low-level iterator with a higher-level iterator, and decompose the iteration into two chained higher-level iterators.</p>\n<p>However, we are still not done. What we are now doing is we take each element from our filtered sliding window collection, modifying it, and putting it into a new collection. So, really, what we are doing is <em>transforming</em> each element, or &quot;mapping&quot; each element to a new element.</p>\n<p>This is called <a href=\"https://wikipedia.org/wiki/Map_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>map</em></a> and is also available in Ruby as <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-map\" rel=\"nofollow noreferrer\"><code>Enumerable#map</code></a>.</p>\n<p>So, finally, our code looks like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>ARGV\n .each_cons(2)\n .select { |param, _| param.start_with?('-') }\n .map { |param, arg| { arg: param, val: arg } }\nend\n</code></pre>\n<p>What we did here, was to replace the <em>general</em> high-level iterator <em>fold</em> (which can do <em>anything</em>) with a more restricted, more specialized high-level iterator <em>map</em>. By using a more specialized iterator, we are able to better convey our semantics to the reader. Instead of thinking &quot;Okay, so here we have an accumulator, and an element, and we do something with the element, and then append it to the accumulator … ah, I see, we are transforming each element&quot;, the reader just sees <code>map</code> and instantly <em>knows</em> that <code>map</code> transforms the elements.</p>\n<h1>Classes and modules</h1>\n<p>In your code, you are using a class. However, your class cannot sensibly be instantiated. Therefore, it shouldn't be a class.</p>\n<p>It makes more sense for it to be a module instead. Here's how I would write your entire file:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>#!/usr/bin/env ruby\n# frozen_string_literal: true\n\nmodule ScriptHelper\n module_function def params\n ARGV\n .each_cons(2)\n .select { |param, _| param.start_with?('-') }\n .map { |param, arg| { arg: param, val: arg } }\n end\nend\n</code></pre>\n<h1>Linter, revisited</h1>\n<p>Rubocop actually complains about my inline use of <a href=\"https://ruby-doc.org/core/Module.html#method-i-module_function\" rel=\"nofollow noreferrer\"><code>Module#module_function</code></a>. It wants me to write this instead:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>#!/usr/bin/env ruby\n# frozen_string_literal: true\n\nmodule ScriptHelper\n def params\n ARGV\n .each_cons(2)\n .select { |param, _| param.start_with?('-') }\n .map { |param, arg| { arg: param, val: arg } }\n end\n\n module_function :params\nend\n</code></pre>\n<p>I disagree. You should not be afraid to disable or re-configure rules in your linter to fit your style.</p>\n<p>However, note that programming is a team sport. If you are <em>modifying</em> code, adopt the existing style. If you are part of a team, adopt the team's style. If you write open source code, adopt the project's style. If you start your own project, adopt the community's style (do <em>not</em> create your own style for your project, until your project is big and successful enough to have its own independent community).</p>\n<h1>Speaking of community …</h1>\n<p>Of course, the <em>really correct</em> solution to your problem is to use one of the many, already existing, well-maintained, well-tested, well-documented, well-known command line option parser libraries. Ruby ships with <a href=\"https://ruby-doc.org/stdlib/libdoc/optparse/rdoc/\" rel=\"nofollow noreferrer\"><code>optparse</code></a> in the standard library, but there are many, many others with some amazing features:</p>\n<ul>\n<li><a href=\"https://github.com/mdub/clamp\" rel=\"nofollow noreferrer\">Clamp</a></li>\n<li><a href=\"https://github.com/commander-rb/commander\" rel=\"nofollow noreferrer\">Commander</a></li>\n<li><a href=\"https://github.com/chef/mixlib-cli\" rel=\"nofollow noreferrer\"><code>Mixlib::CLI</code></a></li>\n<li><a href=\"https://manageiq.org/optimist/\" rel=\"nofollow noreferrer\">Optimist</a></li>\n<li><a href=\"https://github.com/leejarvis/slop\" rel=\"nofollow noreferrer\">slop</a></li>\n</ul>\n<p>Don't re-invent the wheel.</p>\n<p><a href=\"https://nasa.gov/specials/wheels/\" rel=\"nofollow noreferrer\">It is true that NASA has (kind-of) re-invented the wheel for the Perseverance rover</a>, but most of us are not NASA. We don't face the unique challenge of sending a rover to Mars that needs to autonomously drive over rough, unknown terrain, and needs to be as light while at the same time as robust as possible. We just want to get from A to B on a paved road. There are plenty of wheels available off-the-shelf that do that.</p>\n<p>Always remember: we are not NASA. It is highly unlikely that a problem we are encountering has never before been seen in the history of humankind. Parsing command line arguments is not a highly-specialized, complex, unique problem, it is a problem that has been solved with standardized libraries over 30 years ago.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T21:37:04.727", "Id": "250447", "ParentId": "250420", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-09T14:29:52.643", "Id": "250420", "Score": "1", "Tags": [ "ruby" ], "Title": "What changes can I make to simply this function that groups parameter key value pairs" }
250420